remote_internal.c 202.6 KB
Newer Older
1 2 3 4
/*
 * remote_internal.c: driver to provide access to libvirtd running
 *   on a remote machine
 *
5
 * Copyright (C) 2007-2008 Red Hat, Inc.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Richard Jones <rjones@redhat.com>
 */

24
#include <config.h>
25

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

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

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

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

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

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

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

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

71 72
#include <poll.h>

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

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

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


96 97
static int inside_daemon = 0;

98 99 100 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
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;
};

129
struct private_data {
130 131
    virMutex lock;

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

143 144
#if HAVE_SASL
    sasl_conn_t *saslconn;      /* SASL context */
145

146 147 148
    const char *saslDecoded;
    unsigned int saslDecodedLength;
    unsigned int saslDecodedOffset;
149 150 151 152

    const char *saslEncoded;
    unsigned int saslEncodedLength;
    unsigned int saslEncodedOffset;
153
#endif
154 155 156 157 158 159

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

160 161 162 163 164 165 166
    /* 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;
167 168 169 170 171 172 173

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

    /* List of threads currently waiting for dispatch */
    struct remote_thread_call *waitDispatch;
174 175
};

176 177 178 179 180 181
enum {
    REMOTE_CALL_IN_OPEN = 1,
    REMOTE_CALL_QUIET_MISSING_RPC = 2,
};


182 183 184 185 186 187 188 189 190 191
static void remoteDriverLock(struct private_data *driver)
{
    virMutexLock(&driver->lock);
}

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

192 193 194 195
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);
196 197
static int remoteAuthenticate (virConnectPtr conn, struct private_data *priv, int in_open,
                               virConnectAuthPtr auth, const char *authtype);
198
#if HAVE_SASL
199 200
static int remoteAuthSASL (virConnectPtr conn, struct private_data *priv, int in_open,
                           virConnectAuthPtr auth, const char *mech);
201
#endif
202
#if HAVE_POLKIT
203 204
static int remoteAuthPolkit (virConnectPtr conn, struct private_data *priv, int in_open,
                             virConnectAuthPtr auth);
205
#endif /* HAVE_POLKIT */
206
static void error (virConnectPtr conn, virErrorNumber code, const char *info);
207 208
static void errorf (virConnectPtr conn, virErrorNumber code,
                     const char *fmt, ...) ATTRIBUTE_FORMAT(printf, 3, 4);
209 210 211
static void server_error (virConnectPtr conn, remote_error *err);
static virDomainPtr get_nonnull_domain (virConnectPtr conn, remote_nonnull_domain domain);
static virNetworkPtr get_nonnull_network (virConnectPtr conn, remote_nonnull_network network);
212 213
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);
214
static virNodeDevicePtr get_nonnull_node_device (virConnectPtr conn, remote_nonnull_node_device dev);
215 216
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);
217 218
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);
219
void remoteDomainEventFired(int watch, int fd, int event, void *data);
220 221
static void remoteDomainQueueEvent(virConnectPtr conn, XDR *xdr);
void remoteDomainEventQueueFlush(int timer, void *opaque);
222 223 224 225 226 227 228
/*----------------------------------------------------------------------*/

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

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

A
Atsushi SAKAI 已提交
231
#ifdef WITH_LIBVIRTD
232 233 234 235 236 237 238 239 240
static int
remoteStartup(void)
{
    /* Mark that we're inside the daemon so we can avoid
     * re-entering ourselves
     */
    inside_daemon = 1;
    return 0;
}
A
Atsushi SAKAI 已提交
241
#endif
242

243
#ifndef WIN32
244 245 246 247
/**
 * remoteFindServerPath:
 *
 * Tries to find the path to the libvirtd binary.
248
 *
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
 * 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.
 */
280
static int
281 282 283
remoteForkDaemon(virConnectPtr conn)
{
    const char *daemonPath = remoteFindDaemonPath();
284
    const char *const daemonargs[] = { daemonPath, "--timeout=30", NULL };
285 286
    int ret, status;
    pid_t pid;
287 288

    if (!daemonPath) {
289
        error(conn, VIR_ERR_INTERNAL_ERROR, _("failed to find libvirtd binary"));
290
        return -1;
291 292
    }

293 294 295
    if (virExec(NULL, daemonargs, NULL, NULL,
                &pid, -1, NULL, NULL, VIR_EXEC_DAEMON) < 0)
        return -1;
296 297 298 299 300 301 302 303 304 305
    /*
     * do a waitpid on the intermediate process to avoid zombies.
     */
 retry_wait:
    ret = waitpid(pid, &status, 0);
    if (ret < 0) {
        if (errno == EINTR)
            goto retry_wait;
    }

306
    return 0;
307
}
308
#endif
309

310
enum virDrvOpenRemoteFlags {
311 312 313 314
    VIR_DRV_OPEN_REMOTE_RO = (1 << 0),
    VIR_DRV_OPEN_REMOTE_UNIX = (1 << 1),
    VIR_DRV_OPEN_REMOTE_USER = (1 << 2),
    VIR_DRV_OPEN_REMOTE_AUTOSTART = (1 << 3),
315
};
316

317 318 319 320 321 322 323 324 325 326
/* What transport? */
enum {
    trans_tls,
    trans_unix,
    trans_ssh,
    trans_ext,
    trans_tcp,
} transport;


327
static int
328 329 330 331
doRemoteOpen (virConnectPtr conn,
              struct private_data *priv,
              virConnectAuthPtr auth ATTRIBUTE_UNUSED,
              int flags)
332
{
333
    int wakeupFD[2];
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
    char *transport_str = NULL;

    if (conn->uri) {
        if (!conn->uri->scheme)
            return VIR_DRV_OPEN_DECLINED;

        transport_str = get_transport_from_scheme (conn->uri->scheme);

        if (!transport_str || 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;
        }
358 359
    }

360 361 362
    if (!transport_str) {
        if ((!conn->uri || !conn->uri->server) &&
            (flags & VIR_DRV_OPEN_REMOTE_UNIX))
363 364 365 366
            transport = trans_unix;
        else
            return VIR_DRV_OPEN_DECLINED; /* Decline - not a remote URL. */
    }
367

368 369 370
    /* Local variables which we will initialise. These can
     * get freed in the failed: path.
     */
371
    char *name = 0, *command = 0, *sockname = 0, *netcat = 0, *username = 0;
372
    char *port = 0, *authtype = 0;
373
    int no_verify = 0, no_tty = 0;
374
    char **cmd_argv = NULL;
375

376 377 378
    /* Return code from this function, and the private data. */
    int retcode = VIR_DRV_OPEN_ERROR;

379
    /* Remote server defaults to "localhost" if not specified. */
380
    if (conn->uri && conn->uri->port != 0) {
381
        if (virAsprintf(&port, "%d", conn->uri->port) == -1) goto out_of_memory;
382 383 384 385 386 387 388 389 390 391 392 393
    } 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 if (transport == trans_ssh) {
        port = strdup ("22");
        if (!port) goto out_of_memory;
    } else
        port = NULL;           /* Port not used for unix, ext. */

394

395 396
    priv->hostname = strdup (conn->uri && conn->uri->server ?
                             conn->uri->server : "localhost");
397 398
    if (!priv->hostname)
        goto out_of_memory;
399 400
    if (conn->uri && conn->uri->user) {
        username = strdup (conn->uri->user);
401 402
        if (!username)
            goto out_of_memory;
403 404
    }

405 406 407 408 409
    /* 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).
     */
410 411 412
    struct qparam_set *vars;
    struct qparam *var;
    int i;
413 414
    char *query;

415
    if (conn->uri) {
416
#ifdef HAVE_XMLURI_QUERY_RAW
417
        query = conn->uri->query_raw;
418
#else
419
        query = conn->uri->query;
420
#endif
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
        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);
        }
462

463 464
        /* Construct the original name. */
        if (!name) {
465 466 467 468 469 470 471
            if (STREQ(conn->uri->scheme, "remote") ||
                STRPREFIX(conn->uri->scheme, "remote+")) {
                /* Allow remote serve to probe */
                name = strdup("");
            } else {
                xmlURI tmpuri = {
                    .scheme = conn->uri->scheme,
472
#ifdef HAVE_XMLURI_QUERY_RAW
473
                    .query_raw = qparam_get_query (vars),
474
#else
475
                    .query = qparam_get_query (vars),
476
#endif
477 478 479 480 481 482 483 484 485
                    .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';
                }
486

487
                name = (char *) xmlSaveUri (&tmpuri);
488

489 490 491 492 493 494 495 496 497 498
#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] = '+';
            }
499 500
        }

501 502 503 504 505
        free_qparam_set (vars);
    } else {
        /* Probe URI server side */
        name = strdup("");
    }
506

507 508 509
    if (!name) {
        error(conn, VIR_ERR_NO_MEMORY, NULL);
        goto failed;
510 511
    }

512
    DEBUG("proceeding with name = %s", name);
513

514 515 516 517 518 519 520
    /* 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;
    }

521 522 523 524
    /* Connect to the remote service. */
    switch (transport) {
    case trans_tls:
        if (initialise_gnutls (conn) == -1) goto failed;
525
        priv->uses_tls = 1;
526 527 528 529 530 531

        /*FALLTHROUGH*/
    case trans_tcp: {
        // http://people.redhat.com/drepper/userapi-ipv6.html
        struct addrinfo *res, *r;
        struct addrinfo hints;
532
        int saved_errno = EINVAL;
533 534 535
        memset (&hints, 0, sizeof hints);
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_flags = AI_ADDRCONFIG;
536
        int e = getaddrinfo (priv->hostname, port, &hints, &res);
537
        if (e != 0) {
538 539 540
            errorf (conn, VIR_ERR_SYSTEM_ERROR,
                    _("unable to resolve hostname '%s': %s"),
                    priv->hostname, gai_strerror (e));
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
            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;

558 559
            priv->sock = socket (r->ai_family, SOCK_STREAM, 0);
            if (priv->sock == -1) {
J
Jim Meyering 已提交
560
                saved_errno = errno;
561 562 563 564
                continue;
            }

            /* Disable Nagle - Dan Berrange. */
565
            setsockopt (priv->sock,
566 567 568
                        IPPROTO_TCP, TCP_NODELAY, (void *)&no_slow_start,
                        sizeof no_slow_start);

569
            if (connect (priv->sock, r->ai_addr, r->ai_addrlen) == -1) {
J
Jim Meyering 已提交
570
                saved_errno = errno;
571
                close (priv->sock);
572 573 574
                continue;
            }

575 576
            if (priv->uses_tls) {
                priv->session =
577
                    negotiate_gnutls_on_connection
578
                      (conn, priv, no_verify);
579 580 581
                if (!priv->session) {
                    close (priv->sock);
                    priv->sock = -1;
582 583 584 585 586 587 588
                    continue;
                }
            }
            goto tcp_connected;
        }

        freeaddrinfo (res);
589 590 591
        errorf (conn, VIR_ERR_SYSTEM_ERROR,
                _("unable to connect to '%s': %s"),
                priv->hostname, strerror (saved_errno));
592 593 594 595 596 597 598 599 600 601
        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;
    }

602
#ifndef WIN32
603 604
    case trans_unix: {
        if (!sockname) {
605
            if (flags & VIR_DRV_OPEN_REMOTE_USER) {
606 607
                struct passwd *pw;
                uid_t uid = getuid();
608

609
                if (!(pw = getpwuid(uid))) {
610 611 612
                    errorf (conn, VIR_ERR_SYSTEM_ERROR,
                            _("unable to lookup user '%d': %s"),
                            uid, strerror (errno));
613 614
                    goto failed;
                }
615

616
                if (virAsprintf(&sockname, "@%s" LIBVIRTD_USER_UNIX_SOCKET, pw->pw_dir) < 0)
617
                    goto out_of_memory;
618

619
            } else {
620
                if (flags & VIR_DRV_OPEN_REMOTE_RO)
621 622 623
                    sockname = strdup (LIBVIRTD_PRIV_UNIX_SOCKET_RO);
                else
                    sockname = strdup (LIBVIRTD_PRIV_UNIX_SOCKET);
624 625
                if (sockname == NULL)
                    goto out_of_memory;
626
            }
627 628 629 630 631 632
        }

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

635 636 637
        memset (&addr, 0, sizeof addr);
        addr.sun_family = AF_UNIX;
        strncpy (addr.sun_path, sockname, UNIX_PATH_MAX (addr));
638 639
        if (addr.sun_path[0] == '@')
            addr.sun_path[0] = '\0';
640

641 642 643
      autostart_retry:
        priv->sock = socket (AF_UNIX, SOCK_STREAM, 0);
        if (priv->sock == -1) {
644 645 646
            errorf (conn, VIR_ERR_SYSTEM_ERROR,
                    _("unable to create socket %s"),
                    strerror (errno));
647 648
            goto failed;
        }
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667
        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 &&
                trials < 5) {
                close(priv->sock);
                priv->sock = -1;
                if (remoteForkDaemon(conn) == 0) {
                    trials++;
                    usleep(5000 * trials * trials);
                    goto autostart_retry;
                }
            }
668 669 670
            errorf (conn, VIR_ERR_SYSTEM_ERROR,
                    _("unable to connect to '%s': %s"),
                    sockname, strerror (errno));
671 672 673 674 675 676 677
            goto failed;
        }

        break;
    }

    case trans_ssh: {
678 679 680 681
        int j, nr_args = 8;

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

683
        command = command ? command : strdup ("ssh");
684 685
        if (command == NULL)
            goto out_of_memory;
686 687 688

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

692 693 694 695 696 697 698 699
        j = 0;
        cmd_argv[j++] = strdup (command);
        cmd_argv[j++] = strdup ("-p");
        cmd_argv[j++] = strdup (port);
        if (username) {
            cmd_argv[j++] = strdup ("-l");
            cmd_argv[j++] = strdup (username);
        }
700 701 702 703 704 705 706
        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");
        }
707
        cmd_argv[j++] = strdup (priv->hostname);
708 709
        cmd_argv[j++] = strdup (netcat ? netcat : "nc");
        cmd_argv[j++] = strdup ("-U");
710
        cmd_argv[j++] = strdup (sockname ? sockname : LIBVIRTD_PRIV_UNIX_SOCKET);
711 712
        cmd_argv[j++] = 0;
        assert (j == nr_args);
713 714 715
        for (j = 0; j < (nr_args-1); j++)
            if (cmd_argv[j] == NULL)
                goto out_of_memory;
716 717 718 719
    }

        /*FALLTHROUGH*/
    case trans_ext: {
720
        pid_t pid;
721 722 723 724 725 726 727
        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) {
728 729 730
            errorf (conn, VIR_ERR_SYSTEM_ERROR,
                    _("unable to create socket pair %s"),
                    strerror (errno));
731 732 733
            goto failed;
        }

734 735
        if (virExec(conn, (const char**)cmd_argv, NULL, NULL,
                    &pid, sv[1], &(sv[1]), NULL, VIR_EXEC_NONE) < 0)
736 737 738 739
            goto failed;

        /* Parent continues here. */
        close (sv[1]);
740
        priv->sock = sv[0];
741
        priv->pid = pid;
742
    }
743 744 745 746 747 748 749
#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"));
750
        goto failed;
751 752 753

#endif /* WIN32 */

754 755
    } /* switch (transport) */

756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
    if (virSetNonBlock(priv->sock) < 0) {
        errorf (conn, VIR_ERR_SYSTEM_ERROR,
                _("unable to make socket non-blocking %s"),
                strerror(errno));
        goto failed;
    }

    if (pipe(wakeupFD) < 0) {
        errorf (conn, VIR_ERR_SYSTEM_ERROR,
                _("unable to make pipe %s"),
                strerror(errno));
        goto failed;
    }
    priv->wakeupReadFD = wakeupFD[0];
    priv->wakeupSendFD = wakeupFD[1];
771 772

    /* Try and authenticate with server */
773
    if (remoteAuthenticate(conn, priv, 1, auth, authtype) == -1)
774 775
        goto failed;

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

779
    if (call (conn, priv, REMOTE_CALL_IN_OPEN, REMOTE_PROC_OPEN,
780 781 782 783
              (xdrproc_t) xdr_remote_open_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto failed;

784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
    /* 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) {
            error (conn, VIR_ERR_NO_MEMORY, NULL);
            goto failed;
        }
    }

816 817 818 819 820 821 822 823 824 825 826 827
    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 */
828
    if ((priv->watch = virEventAddHandle(priv->sock,
829
                                         VIR_EVENT_HANDLE_READABLE,
830
                                         remoteDomainEventFired,
831
                                         conn, NULL)) < 0) {
832 833 834 835 836 837
        DEBUG0("virEventAddHandle failed: No addHandleImpl defined."
               " continuing without events.");
    } else {

        DEBUG0("Adding Timeout for remote event queue flushing");
        if ( (priv->eventFlushTimer = virEventAddTimeout(-1,
838 839
                                                         remoteDomainEventQueueFlush,
                                                         conn, NULL)) < 0) {
840 841
            DEBUG0("virEventAddTimeout failed: No addTimeoutImpl defined. "
                    "continuing without events.");
842
            virEventRemoveHandle(priv->watch);
843
            priv->watch = -1;
844 845
        }
    }
846 847 848
    /* Successful. */
    retcode = VIR_DRV_OPEN_SUCCESS;

849
 cleanup:
850
    /* Free up the URL and strings. */
851 852 853 854 855 856 857
    free (name);
    free (command);
    free (sockname);
    free (authtype);
    free (netcat);
    free (username);
    free (port);
858 859 860 861 862 863 864 865 866 867
    if (cmd_argv) {
        char **cmd_argv_ptr = cmd_argv;
        while (*cmd_argv_ptr) {
            free (*cmd_argv_ptr);
            cmd_argv_ptr++;
        }
        free (cmd_argv);
    }

    return retcode;
868 869

 out_of_memory:
870
    error (conn, VIR_ERR_NO_MEMORY, NULL);
871 872 873 874 875 876 877 878 879

 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);
880
#ifndef WIN32
881 882 883 884 885 886 887 888
        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);
        }
889
#endif
890 891 892 893 894 895 896 897
    }

    if (priv->hostname) {
        free (priv->hostname);
        priv->hostname = NULL;
    }

    goto cleanup;
898 899
}

900
static virDrvOpenStatus
901 902 903
remoteOpen (virConnectPtr conn,
            virConnectAuthPtr auth,
            int flags)
904
{
905
    struct private_data *priv;
906 907
    int ret, rflags = 0;

908 909 910
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

911
    if (VIR_ALLOC(priv) < 0) {
912
        error (conn, VIR_ERR_NO_MEMORY, _("struct private_data"));
913 914 915
        return VIR_DRV_OPEN_ERROR;
    }

916 917 918 919 920 921 922 923
    if (virMutexInit(&priv->lock) < 0) {
        error(conn, VIR_ERR_INTERNAL_ERROR,
              _("cannot initialize mutex"));
        VIR_FREE(priv);
        return VIR_DRV_OPEN_ERROR;
    }
    remoteDriverLock(priv);
    priv->localUses = 1;
924
    priv->watch = -1;
925

926
    if (flags & VIR_CONNECT_RO)
927 928
        rflags |= VIR_DRV_OPEN_REMOTE_RO;

929 930 931 932 933 934 935
    /*
     * If no servername is given, and no +XXX
     * transport is listed, then force to a
     * local UNIX socket connection
     */
    if (conn->uri &&
        !conn->uri->server &&
D
Daniel P. Berrange 已提交
936
        conn->uri->scheme &&
937 938
        !strchr(conn->uri->scheme, '+')) {
        DEBUG0("Auto-remote UNIX socket");
939 940
        rflags |= VIR_DRV_OPEN_REMOTE_UNIX;
    }
941 942 943 944 945 946 947 948 949 950

    /*
     * 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 已提交
951
        conn->uri->scheme &&
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
        ((strchr(conn->uri->scheme, '+') == 0)||
         (strstr(conn->uri->scheme, "+unix") != NULL)) &&
        STREQ(conn->uri->path, "/session") &&
        getuid() > 0) {
        DEBUG0("Auto-spawn user daemon instance");
        rflags |= VIR_DRV_OPEN_REMOTE_USER;
        rflags |= VIR_DRV_OPEN_REMOTE_AUTOSTART;
    }

    /*
     * If URI is NULL, then do a UNIX connection
     * possibly auto-spawning unprivileged server
     * and probe remote server for URI
     */
    if (!conn->uri) {
        DEBUG0("Auto-probe remote URI");
968
        rflags |= VIR_DRV_OPEN_REMOTE_UNIX;
969 970 971 972 973
        if (getuid() > 0) {
            DEBUG0("Auto-spawn user daemon instance");
            rflags |= VIR_DRV_OPEN_REMOTE_USER;
            rflags |= VIR_DRV_OPEN_REMOTE_AUTOSTART;
        }
974
    }
975 976

    priv->sock = -1;
977
    ret = doRemoteOpen(conn, priv, auth, rflags);
978 979
    if (ret != VIR_DRV_OPEN_SUCCESS) {
        conn->privateData = NULL;
980
        remoteDriverUnlock(priv);
981
        VIR_FREE(priv);
982 983
    } else {
        conn->privateData = priv;
984
        remoteDriverUnlock(priv);
985 986 987 988 989
    }
    return ret;
}


990 991 992 993 994 995 996 997 998 999 1000
/* 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;

1001 1002

static int
1003
check_cert_file (virConnectPtr conn, const char *type, const char *file)
1004 1005 1006
{
    struct stat sb;
    if (stat(file, &sb) < 0) {
1007 1008 1009
        errorf(conn, VIR_ERR_RPC,
               _("Cannot access %s '%s': %s (%d)"),
               type, file, strerror(errno), errno);
1010 1011 1012 1013 1014 1015
        return -1;
    }
    return 0;
}


1016
static int
1017
initialise_gnutls (virConnectPtr conn)
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
{
    static int initialised = 0;
    int err;

    if (initialised) return 0;

    gnutls_global_init ();

    /* X509 stuff */
    err = gnutls_certificate_allocate_credentials (&x509_cred);
    if (err) {
1029 1030 1031
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to allocate TLS credentials: %s"),
                gnutls_strerror (err));
1032 1033 1034
        return -1;
    }

1035

1036
    if (check_cert_file(conn, "CA certificate", LIBVIRT_CACERT) < 0)
1037
        return -1;
1038
    if (check_cert_file(conn, "client key", LIBVIRT_CLIENTKEY) < 0)
1039
        return -1;
1040
    if (check_cert_file(conn, "client certificate", LIBVIRT_CLIENTCERT) < 0)
1041 1042
        return -1;

1043
    /* Set the trusted CA cert. */
1044
    DEBUG("loading CA file %s", LIBVIRT_CACERT);
1045 1046 1047 1048
    err =
        gnutls_certificate_set_x509_trust_file (x509_cred, LIBVIRT_CACERT,
                                                GNUTLS_X509_FMT_PEM);
    if (err < 0) {
1049 1050 1051
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to load CA certificate: %s"),
                gnutls_strerror (err));
1052 1053 1054 1055
        return -1;
    }

    /* Set the client certificate and private key. */
1056 1057
    DEBUG("loading client cert and key from files %s and %s",
          LIBVIRT_CLIENTCERT, LIBVIRT_CLIENTKEY);
1058 1059 1060 1061 1062 1063
    err =
        gnutls_certificate_set_x509_key_file (x509_cred,
                                              LIBVIRT_CLIENTCERT,
                                              LIBVIRT_CLIENTKEY,
                                              GNUTLS_X509_FMT_PEM);
    if (err < 0) {
1064 1065 1066
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to load private key/certificate: %s"),
                gnutls_strerror (err));
1067 1068 1069 1070 1071 1072 1073
        return -1;
    }

    initialised = 1;
    return 0;
}

1074
static int verify_certificate (virConnectPtr conn, struct private_data *priv, gnutls_session_t session);
1075 1076 1077

static gnutls_session_t
negotiate_gnutls_on_connection (virConnectPtr conn,
1078 1079
                                struct private_data *priv,
                                int no_verify)
1080 1081 1082 1083 1084 1085 1086 1087 1088
{
    const int cert_type_priority[3] = {
        GNUTLS_CRT_X509,
        GNUTLS_CRT_OPENPGP,
        0
    };
    int err;
    gnutls_session_t session;

1089
    /* Initialize TLS session
1090 1091 1092
     */
    err = gnutls_init (&session, GNUTLS_CLIENT);
    if (err) {
1093 1094 1095
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to initialize TLS client: %s"),
                gnutls_strerror (err));
1096 1097 1098 1099 1100 1101
        return NULL;
    }

    /* Use default priorities */
    err = gnutls_set_default_priority (session);
    if (err) {
1102 1103 1104
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to set TLS algorithm priority: %s"),
                gnutls_strerror (err));
1105 1106 1107 1108 1109 1110
        return NULL;
    }
    err =
        gnutls_certificate_type_set_priority (session,
                                              cert_type_priority);
    if (err) {
1111 1112 1113
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to set certificate priority: %s"),
                gnutls_strerror (err));
1114 1115 1116 1117 1118 1119 1120
        return NULL;
    }

    /* put the x509 credentials to the current session
     */
    err = gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, x509_cred);
    if (err) {
1121 1122 1123
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to set session credentials: %s"),
                gnutls_strerror (err));
1124 1125 1126 1127
        return NULL;
    }

    gnutls_transport_set_ptr (session,
1128
                              (gnutls_transport_ptr_t) (long) priv->sock);
1129 1130 1131 1132 1133 1134 1135

    /* Perform the TLS handshake. */
 again:
    err = gnutls_handshake (session);
    if (err < 0) {
        if (err == GNUTLS_E_AGAIN || err == GNUTLS_E_INTERRUPTED)
            goto again;
1136 1137 1138
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to complete TLS handshake: %s"),
                gnutls_strerror (err));
1139 1140 1141 1142
        return NULL;
    }

    /* Verify certificate. */
1143
    if (verify_certificate (conn, priv, session) == -1) {
1144 1145 1146
        DEBUG0("failed to verify peer's certificate");
        if (!no_verify) return NULL;
    }
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

    /* 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;
1158 1159 1160
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to complete TLS initialization: %s"),
                gnutls_strerror (len));
1161 1162 1163
        return NULL;
    }
    if (len != 1 || buf[0] != '\1') {
1164
        error (conn, VIR_ERR_RPC,
1165
               _("server verification (of our certificate or IP address) failed\n"));
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
        return NULL;
    }

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

    return session;
}

static int
verify_certificate (virConnectPtr conn ATTRIBUTE_UNUSED,
1179 1180
                    struct private_data *priv,
                    gnutls_session_t session)
1181 1182 1183 1184 1185 1186 1187 1188
{
    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) {
1189 1190 1191
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to verify server certificate: %s"),
                gnutls_strerror (ret));
1192 1193
        return -1;
    }
1194

1195
    if ((now = time(NULL)) == ((time_t)-1)) {
1196 1197 1198
        errorf (conn, VIR_ERR_SYSTEM_ERROR,
                _("cannot get current time: %s"),
                strerror (errno));
1199 1200 1201 1202
        return -1;
    }

    if (status != 0) {
1203
        const char *reason = _("Invalid certificate");
1204 1205

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

1208
        if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1209
            reason = _("The certificate hasn't got a known issuer.");
1210

1211
        if (status & GNUTLS_CERT_REVOKED)
1212
            reason = _("The certificate has been revoked.");
1213 1214

#ifndef GNUTLS_1_0_COMPAT
1215
        if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1216
            reason = _("The certificate uses an insecure algorithm");
1217
#endif
1218

1219 1220 1221
        errorf (conn, VIR_ERR_RPC,
                _("server certificate failed validation: %s"),
                reason);
1222 1223 1224 1225
        return -1;
    }

    if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509) {
1226
        error (conn, VIR_ERR_RPC, _("Certificate type is not X.509"));
1227 1228
        return -1;
    }
1229

1230
    if (!(certs = gnutls_certificate_get_peers(session, &nCerts))) {
1231
        error (conn, VIR_ERR_RPC, _("gnutls_certificate_get_peers failed"));
1232 1233
        return -1;
    }
1234

1235 1236 1237 1238 1239
    for (i = 0 ; i < nCerts ; i++) {
        gnutls_x509_crt_t cert;

        ret = gnutls_x509_crt_init (&cert);
        if (ret < 0) {
1240 1241 1242
            errorf (conn, VIR_ERR_GNUTLS_ERROR,
                    _("unable to initialize certificate: %s"),
                    gnutls_strerror (ret));
1243 1244
            return -1;
        }
1245

1246 1247
        ret = gnutls_x509_crt_import (cert, &certs[i], GNUTLS_X509_FMT_DER);
        if (ret < 0) {
1248 1249 1250
            errorf (conn, VIR_ERR_GNUTLS_ERROR,
                    _("unable to import certificate: %s"),
                    gnutls_strerror (ret));
1251 1252 1253
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1254

1255
        if (gnutls_x509_crt_get_expiration_time (cert) < now) {
1256
            error (conn, VIR_ERR_RPC, _("The certificate has expired"));
1257 1258 1259
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1260

1261
        if (gnutls_x509_crt_get_activation_time (cert) > now) {
1262
            error (conn, VIR_ERR_RPC, _("The certificate is not yet activated"));
1263 1264 1265
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1266

1267
        if (i == 0) {
1268
            if (!gnutls_x509_crt_check_hostname (cert, priv->hostname)) {
1269 1270 1271
                errorf(conn, VIR_ERR_RPC,
                       _("Certificate's owner does not match the hostname (%s)"),
                       priv->hostname);
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
                gnutls_x509_crt_deinit (cert);
                return -1;
            }
        }
    }

    return 0;
}

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

1283

1284
static int
1285
doRemoteClose (virConnectPtr conn, struct private_data *priv)
1286 1287 1288 1289 1290 1291
{
    if (call (conn, priv, 0, REMOTE_PROC_CLOSE,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        return -1;

1292 1293 1294 1295 1296
    if (priv->eventFlushTimer >= 0) {
        /* Remove timeout */
        virEventRemoveTimeout(priv->eventFlushTimer);
        /* Remove handle for remote events */
        virEventRemoveHandle(priv->watch);
1297
        priv->watch = -1;
1298
    }
1299

1300
    /* Close socket. */
1301
    if (priv->uses_tls && priv->session) {
1302
        gnutls_bye (priv->session, GNUTLS_SHUT_RDWR);
1303 1304 1305 1306 1307 1308
        gnutls_deinit (priv->session);
    }
#if HAVE_SASL
    if (priv->saslconn)
        sasl_dispose (&priv->saslconn);
#endif
1309 1310
    close (priv->sock);

1311
#ifndef WIN32
1312 1313 1314 1315 1316 1317 1318 1319
    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);
    }
1320
#endif
1321

1322
    /* Free hostname copy */
1323
    free (priv->hostname);
1324

1325
    /* See comment for remoteType. */
1326
    free (priv->type);
1327

1328 1329 1330 1331 1332 1333
    /* Free callback list */
    virDomainEventCallbackListFree(priv->callbackList);

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

1334 1335 1336
    return 0;
}

1337 1338 1339
static int
remoteClose (virConnectPtr conn)
{
1340
    int ret = 0;
1341
    struct private_data *priv = conn->privateData;
1342

1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
    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);
1354 1355 1356 1357

    return ret;
}

1358 1359 1360
static int
remoteSupportsFeature (virConnectPtr conn, int feature)
{
1361
    int rv = -1;
1362 1363
    remote_supports_feature_args args;
    remote_supports_feature_ret ret;
1364
    struct private_data *priv = conn->privateData;
1365

1366 1367
    remoteDriverLock(priv);

1368
    /* VIR_DRV_FEATURE_REMOTE* features are handled directly. */
1369 1370 1371 1372
    if (feature == VIR_DRV_FEATURE_REMOTE) {
        rv = 1;
        goto done;
    }
1373 1374 1375 1376 1377 1378 1379

    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)
1380 1381 1382
        goto done;

    rv = ret.supported;
1383

1384
done:
1385
    remoteDriverUnlock(priv);
1386
    return rv;
1387 1388
}

1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
/* 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)
{
1400
    char *rv = NULL;
1401
    remote_get_type_ret ret;
1402
    struct private_data *priv = conn->privateData;
1403

1404 1405
    remoteDriverLock(priv);

1406
    /* Cached? */
1407 1408 1409 1410
    if (priv->type) {
        rv = priv->type;
        goto done;
    }
1411 1412 1413 1414 1415

    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)
1416
        goto done;
1417 1418

    /* Stash. */
1419 1420 1421
    rv = priv->type = ret.type;

done:
1422
    remoteDriverUnlock(priv);
1423
    return rv;
1424 1425 1426
}

static int
1427
remoteGetVersion (virConnectPtr conn, unsigned long *hvVer)
1428
{
1429
    int rv = -1;
1430
    remote_get_version_ret ret;
1431
    struct private_data *priv = conn->privateData;
1432

1433 1434
    remoteDriverLock(priv);

1435 1436 1437 1438
    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)
1439
        goto done;
1440 1441

    if (hvVer) *hvVer = ret.hv_ver;
1442 1443 1444
    rv = 0;

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

1449 1450 1451
static char *
remoteGetHostname (virConnectPtr conn)
{
1452
    char *rv = NULL;
1453
    remote_get_hostname_ret ret;
1454
    struct private_data *priv = conn->privateData;
1455

1456 1457
    remoteDriverLock(priv);

1458 1459 1460 1461
    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)
1462
        goto done;
1463 1464

    /* Caller frees this. */
1465 1466 1467
    rv = ret.hostname;

done:
1468
    remoteDriverUnlock(priv);
1469
    return rv;
1470 1471
}

1472 1473 1474
static int
remoteGetMaxVcpus (virConnectPtr conn, const char *type)
{
1475
    int rv = -1;
1476 1477
    remote_get_max_vcpus_args args;
    remote_get_max_vcpus_ret ret;
1478
    struct private_data *priv = conn->privateData;
1479

1480 1481
    remoteDriverLock(priv);

1482
    memset (&ret, 0, sizeof ret);
1483
    args.type = type == NULL ? NULL : (char **) &type;
1484 1485 1486
    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)
1487 1488 1489
        goto done;

    rv = ret.max_vcpus;
1490

1491
done:
1492
    remoteDriverUnlock(priv);
1493
    return rv;
1494 1495 1496 1497 1498
}

static int
remoteNodeGetInfo (virConnectPtr conn, virNodeInfoPtr info)
{
1499
    int rv = -1;
1500
    remote_node_get_info_ret ret;
1501
    struct private_data *priv = conn->privateData;
1502

1503 1504
    remoteDriverLock(priv);

1505 1506 1507 1508
    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)
1509
        goto done;
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519

    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;
1520 1521 1522
    rv = 0;

done:
1523
    remoteDriverUnlock(priv);
1524
    return rv;
1525 1526 1527 1528 1529
}

static char *
remoteGetCapabilities (virConnectPtr conn)
{
1530
    char *rv = NULL;
1531
    remote_get_capabilities_ret ret;
1532
    struct private_data *priv = conn->privateData;
1533

1534 1535
    remoteDriverLock(priv);

1536 1537 1538 1539
    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)
1540
        goto done;
1541 1542

    /* Caller frees this. */
1543 1544 1545
    rv = ret.capabilities;

done:
1546
    remoteDriverUnlock(priv);
1547
    return rv;
1548 1549
}

1550 1551 1552 1553 1554 1555
static int
remoteNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
1556
    int rv = -1;
1557 1558 1559
    remote_node_get_cells_free_memory_args args;
    remote_node_get_cells_free_memory_ret ret;
    int i;
1560
    struct private_data *priv = conn->privateData;
1561

1562 1563
    remoteDriverLock(priv);

1564 1565 1566 1567 1568
    if (maxCells > REMOTE_NODE_MAX_CELLS) {
        errorf (conn, VIR_ERR_RPC,
                _("too many NUMA cells: %d > %d"),
                maxCells,
                REMOTE_NODE_MAX_CELLS);
1569
        goto done;
1570 1571 1572 1573 1574 1575 1576 1577 1578
    }

    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)
1579
        goto done;
1580 1581 1582 1583 1584 1585

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

1586 1587 1588
    rv = ret.freeMems.freeMems_len;

done:
1589
    remoteDriverUnlock(priv);
1590
    return rv;
1591 1592 1593 1594 1595
}

static unsigned long long
remoteNodeGetFreeMemory (virConnectPtr conn)
{
1596
    unsigned long long rv = 0; /* 0 is error value this special function*/
1597
    remote_node_get_free_memory_ret ret;
1598
    struct private_data *priv = conn->privateData;
1599

1600 1601
    remoteDriverLock(priv);

1602 1603 1604 1605
    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)
1606 1607 1608
        goto done;

    rv = ret.freeMem;
1609

1610
done:
1611
    remoteDriverUnlock(priv);
1612
    return rv;
1613 1614 1615
}


1616 1617 1618
static int
remoteListDomains (virConnectPtr conn, int *ids, int maxids)
{
1619
    int rv = -1;
1620 1621 1622
    int i;
    remote_list_domains_args args;
    remote_list_domains_ret ret;
1623
    struct private_data *priv = conn->privateData;
1624

1625 1626
    remoteDriverLock(priv);

1627
    if (maxids > REMOTE_DOMAIN_ID_LIST_MAX) {
1628 1629 1630
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain IDs: %d > %d"),
                maxids, REMOTE_DOMAIN_ID_LIST_MAX);
1631
        goto done;
1632 1633 1634 1635 1636 1637 1638
    }
    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)
1639
        goto done;
1640 1641

    if (ret.ids.ids_len > maxids) {
1642 1643 1644
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain IDs: %d > %d"),
                ret.ids.ids_len, maxids);
1645
        goto cleanup;
1646 1647 1648 1649 1650
    }

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

1651 1652 1653
    rv = ret.ids.ids_len;

cleanup:
1654 1655
    xdr_free ((xdrproc_t) xdr_remote_list_domains_ret, (char *) &ret);

1656
done:
1657
    remoteDriverUnlock(priv);
1658
    return rv;
1659 1660 1661 1662 1663
}

static int
remoteNumOfDomains (virConnectPtr conn)
{
1664
    int rv = -1;
1665
    remote_num_of_domains_ret ret;
1666
    struct private_data *priv = conn->privateData;
1667

1668 1669
    remoteDriverLock(priv);

1670 1671 1672 1673
    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)
1674 1675 1676
        goto done;

    rv = ret.num;
1677

1678
done:
1679
    remoteDriverUnlock(priv);
1680
    return rv;
1681 1682 1683
}

static virDomainPtr
1684
remoteDomainCreateXML (virConnectPtr conn,
1685 1686 1687
                         const char *xmlDesc,
                         unsigned int flags)
{
1688
    virDomainPtr dom = NULL;
1689 1690
    remote_domain_create_xml_args args;
    remote_domain_create_xml_ret ret;
1691
    struct private_data *priv = conn->privateData;
1692

1693 1694
    remoteDriverLock(priv);

1695 1696 1697 1698
    args.xml_desc = (char *) xmlDesc;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
1699 1700 1701
    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)
1702
        goto done;
1703 1704

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

1707
done:
1708
    remoteDriverUnlock(priv);
1709 1710 1711 1712 1713 1714
    return dom;
}

static virDomainPtr
remoteDomainLookupByID (virConnectPtr conn, int id)
{
1715
    virDomainPtr dom = NULL;
1716 1717
    remote_domain_lookup_by_id_args args;
    remote_domain_lookup_by_id_ret ret;
1718
    struct private_data *priv = conn->privateData;
1719

1720 1721
    remoteDriverLock(priv);

1722 1723 1724 1725 1726 1727
    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)
1728
        goto done;
1729 1730 1731 1732

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

1733
done:
1734
    remoteDriverUnlock(priv);
1735 1736 1737 1738 1739 1740
    return dom;
}

static virDomainPtr
remoteDomainLookupByUUID (virConnectPtr conn, const unsigned char *uuid)
{
1741
    virDomainPtr dom = NULL;
1742 1743
    remote_domain_lookup_by_uuid_args args;
    remote_domain_lookup_by_uuid_ret ret;
1744
    struct private_data *priv = conn->privateData;
1745

1746 1747
    remoteDriverLock(priv);

1748 1749 1750 1751 1752 1753
    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)
1754
        goto done;
1755 1756 1757

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

done:
1760
    remoteDriverUnlock(priv);
1761 1762 1763 1764 1765 1766
    return dom;
}

static virDomainPtr
remoteDomainLookupByName (virConnectPtr conn, const char *name)
{
1767
    virDomainPtr dom = NULL;
1768 1769
    remote_domain_lookup_by_name_args args;
    remote_domain_lookup_by_name_ret ret;
1770
    struct private_data *priv = conn->privateData;
1771

1772 1773
    remoteDriverLock(priv);

1774 1775 1776 1777 1778 1779
    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)
1780
        goto done;
1781 1782 1783 1784

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

1785
done:
1786
    remoteDriverUnlock(priv);
1787 1788 1789 1790 1791 1792
    return dom;
}

static int
remoteDomainSuspend (virDomainPtr domain)
{
1793
    int rv = -1;
1794
    remote_domain_suspend_args args;
1795
    struct private_data *priv = domain->conn->privateData;
1796

1797 1798
    remoteDriverLock(priv);

1799 1800 1801 1802 1803
    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)
1804
        goto done;
1805

1806 1807 1808
    rv = 0;

done:
1809
    remoteDriverUnlock(priv);
1810
    return rv;
1811 1812 1813 1814 1815
}

static int
remoteDomainResume (virDomainPtr domain)
{
1816
    int rv = -1;
1817
    remote_domain_resume_args args;
1818
    struct private_data *priv = domain->conn->privateData;
1819

1820 1821
    remoteDriverLock(priv);

1822 1823 1824 1825 1826
    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)
1827
        goto done;
1828

1829 1830 1831
    rv = 0;

done:
1832
    remoteDriverUnlock(priv);
1833
    return rv;
1834 1835 1836 1837 1838
}

static int
remoteDomainShutdown (virDomainPtr domain)
{
1839
    int rv = -1;
1840
    remote_domain_shutdown_args args;
1841
    struct private_data *priv = domain->conn->privateData;
1842

1843 1844
    remoteDriverLock(priv);

1845 1846 1847 1848 1849
    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)
1850
        goto done;
1851

1852 1853 1854
    rv = 0;

done:
1855
    remoteDriverUnlock(priv);
1856
    return rv;
1857 1858 1859 1860 1861
}

static int
remoteDomainReboot (virDomainPtr domain, unsigned int flags)
{
1862
    int rv = -1;
1863
    remote_domain_reboot_args args;
1864
    struct private_data *priv = domain->conn->privateData;
1865

1866 1867
    remoteDriverLock(priv);

1868 1869 1870 1871 1872 1873
    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)
1874
        goto done;
1875

1876 1877 1878
    rv = 0;

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

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

1890 1891
    remoteDriverLock(priv);

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

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

1899 1900 1901
    rv = 0;

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

static char *
remoteDomainGetOSType (virDomainPtr domain)
{
1909
    char *rv = NULL;
1910 1911
    remote_domain_get_os_type_args args;
    remote_domain_get_os_type_ret ret;
1912
    struct private_data *priv = domain->conn->privateData;
1913

1914 1915
    remoteDriverLock(priv);

1916 1917 1918 1919 1920 1921
    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)
1922
        goto done;
1923 1924

    /* Caller frees. */
1925 1926 1927
    rv = ret.type;

done:
1928
    remoteDriverUnlock(priv);
1929
    return rv;
1930 1931 1932 1933 1934
}

static unsigned long
remoteDomainGetMaxMemory (virDomainPtr domain)
{
1935
    unsigned long rv = 0;
1936 1937
    remote_domain_get_max_memory_args args;
    remote_domain_get_max_memory_ret ret;
1938
    struct private_data *priv = domain->conn->privateData;
1939

1940 1941
    remoteDriverLock(priv);

1942 1943 1944 1945 1946 1947
    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)
1948 1949 1950
        goto done;

    rv = ret.memory;
1951

1952
done:
1953
    remoteDriverUnlock(priv);
1954
    return rv;
1955 1956 1957 1958 1959
}

static int
remoteDomainSetMaxMemory (virDomainPtr domain, unsigned long memory)
{
1960
    int rv = -1;
1961
    remote_domain_set_max_memory_args args;
1962
    struct private_data *priv = domain->conn->privateData;
1963

1964 1965
    remoteDriverLock(priv);

1966 1967 1968 1969 1970 1971
    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)
1972
        goto done;
1973

1974 1975 1976
    rv = 0;

done:
1977
    remoteDriverUnlock(priv);
1978
    return rv;
1979 1980 1981 1982 1983
}

static int
remoteDomainSetMemory (virDomainPtr domain, unsigned long memory)
{
1984
    int rv = -1;
1985
    remote_domain_set_memory_args args;
1986
    struct private_data *priv = domain->conn->privateData;
1987

1988 1989
    remoteDriverLock(priv);

1990 1991 1992 1993 1994 1995
    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)
1996
        goto done;
1997

1998 1999 2000
    rv = 0;

done:
2001
    remoteDriverUnlock(priv);
2002
    return rv;
2003 2004 2005 2006 2007
}

static int
remoteDomainGetInfo (virDomainPtr domain, virDomainInfoPtr info)
{
2008
    int rv = -1;
2009 2010
    remote_domain_get_info_args args;
    remote_domain_get_info_ret ret;
2011
    struct private_data *priv = domain->conn->privateData;
2012

2013 2014
    remoteDriverLock(priv);

2015 2016 2017 2018 2019 2020
    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)
2021
        goto done;
2022 2023 2024 2025 2026 2027

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

2029 2030 2031
    rv = 0;

done:
2032
    remoteDriverUnlock(priv);
2033
    return rv;
2034 2035 2036 2037 2038
}

static int
remoteDomainSave (virDomainPtr domain, const char *to)
{
2039
    int rv = -1;
2040
    remote_domain_save_args args;
2041
    struct private_data *priv = domain->conn->privateData;
2042

2043 2044
    remoteDriverLock(priv);

2045 2046 2047 2048 2049 2050
    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)
2051
        goto done;
2052

2053 2054 2055
    rv = 0;

done:
2056
    remoteDriverUnlock(priv);
2057
    return rv;
2058 2059 2060 2061 2062
}

static int
remoteDomainRestore (virConnectPtr conn, const char *from)
{
2063
    int rv = -1;
2064
    remote_domain_restore_args args;
2065
    struct private_data *priv = conn->privateData;
2066

2067 2068
    remoteDriverLock(priv);

2069 2070 2071 2072 2073
    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)
2074
        goto done;
2075

2076 2077 2078
    rv = 0;

done:
2079
    remoteDriverUnlock(priv);
2080
    return rv;
2081 2082 2083 2084 2085
}

static int
remoteDomainCoreDump (virDomainPtr domain, const char *to, int flags)
{
2086
    int rv = -1;
2087
    remote_domain_core_dump_args args;
2088
    struct private_data *priv = domain->conn->privateData;
2089

2090 2091
    remoteDriverLock(priv);

2092 2093 2094 2095 2096 2097 2098
    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)
2099
        goto done;
2100

2101 2102 2103
    rv = 0;

done:
2104
    remoteDriverUnlock(priv);
2105
    return rv;
2106 2107 2108 2109 2110
}

static int
remoteDomainSetVcpus (virDomainPtr domain, unsigned int nvcpus)
{
2111
    int rv = -1;
2112
    remote_domain_set_vcpus_args args;
2113
    struct private_data *priv = domain->conn->privateData;
2114

2115 2116
    remoteDriverLock(priv);

2117 2118 2119 2120 2121 2122
    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)
2123
        goto done;
2124

2125 2126 2127
    rv = 0;

done:
2128
    remoteDriverUnlock(priv);
2129
    return rv;
2130 2131 2132 2133 2134 2135 2136 2137
}

static int
remoteDomainPinVcpu (virDomainPtr domain,
                     unsigned int vcpu,
                     unsigned char *cpumap,
                     int maplen)
{
2138
    int rv = -1;
2139
    remote_domain_pin_vcpu_args args;
2140
    struct private_data *priv = domain->conn->privateData;
2141

2142 2143
    remoteDriverLock(priv);

2144
    if (maplen > REMOTE_CPUMAP_MAX) {
2145 2146 2147
        errorf (domain->conn, VIR_ERR_RPC,
                _("map length greater than maximum: %d > %d"),
                maplen, REMOTE_CPUMAP_MAX);
2148
        goto done;
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
    }

    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)
2159
        goto done;
2160

2161 2162 2163
    rv = 0;

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

static int
remoteDomainGetVcpus (virDomainPtr domain,
                      virVcpuInfoPtr info,
                      int maxinfo,
                      unsigned char *cpumaps,
                      int maplen)
{
2175
    int rv = -1;
2176 2177 2178
    int i;
    remote_domain_get_vcpus_args args;
    remote_domain_get_vcpus_ret ret;
2179
    struct private_data *priv = domain->conn->privateData;
2180

2181 2182
    remoteDriverLock(priv);

2183
    if (maxinfo > REMOTE_VCPUINFO_MAX) {
2184 2185 2186
        errorf (domain->conn, VIR_ERR_RPC,
                _("vCPU count exceeds maximum: %d > %d"),
                maxinfo, REMOTE_VCPUINFO_MAX);
2187
        goto done;
2188
    }
2189
    if (maxinfo * maplen > REMOTE_CPUMAPS_MAX) {
2190 2191 2192
        errorf (domain->conn, VIR_ERR_RPC,
                _("vCPU map buffer length exceeds maximum: %d > %d"),
                maxinfo * maplen, REMOTE_CPUMAPS_MAX);
2193
        goto done;
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
    }

    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)
2204
        goto done;
2205 2206

    if (ret.info.info_len > maxinfo) {
2207 2208 2209
        errorf (domain->conn, VIR_ERR_RPC,
                _("host reports too many vCPUs: %d > %d"),
                ret.info.info_len, maxinfo);
2210
        goto cleanup;
2211
    }
2212
    if (ret.cpumaps.cpumaps_len > maxinfo * maplen) {
2213 2214 2215
        errorf (domain->conn, VIR_ERR_RPC,
                _("host reports map buffer length exceeds maximum: %d > %d"),
                ret.cpumaps.cpumaps_len, maxinfo * maplen);
2216
        goto cleanup;
2217 2218
    }

2219 2220 2221
    memset (info, 0, sizeof (virVcpuInfo) * maxinfo);
    memset (cpumaps, 0, maxinfo * maplen);

2222 2223 2224 2225 2226 2227 2228 2229 2230 2231
    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];

2232 2233 2234
    rv = ret.info.info_len;

cleanup:
2235
    xdr_free ((xdrproc_t) xdr_remote_domain_get_vcpus_ret, (char *) &ret);
2236 2237

done:
2238
    remoteDriverUnlock(priv);
2239
    return rv;
2240 2241 2242 2243 2244
}

static int
remoteDomainGetMaxVcpus (virDomainPtr domain)
{
2245
    int rv = -1;
2246 2247
    remote_domain_get_max_vcpus_args args;
    remote_domain_get_max_vcpus_ret ret;
2248
    struct private_data *priv = domain->conn->privateData;
2249

2250 2251
    remoteDriverLock(priv);

2252 2253 2254
    make_nonnull_domain (&args.dom, domain);

    memset (&ret, 0, sizeof ret);
2255
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_MAX_VCPUS,
2256 2257
              (xdrproc_t) xdr_remote_domain_get_max_vcpus_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_max_vcpus_ret, (char *) &ret) == -1)
2258
        goto done;
2259

2260 2261 2262
    rv = ret.num;

done:
2263
    remoteDriverUnlock(priv);
2264
    return rv;
2265 2266 2267 2268 2269
}

static char *
remoteDomainDumpXML (virDomainPtr domain, int flags)
{
2270
    char *rv = NULL;
2271 2272
    remote_domain_dump_xml_args args;
    remote_domain_dump_xml_ret ret;
2273
    struct private_data *priv = domain->conn->privateData;
2274

2275 2276
    remoteDriverLock(priv);

2277 2278 2279 2280 2281 2282 2283
    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)
2284
        goto done;
2285 2286

    /* Caller frees. */
2287 2288 2289
    rv = ret.xml;

done:
2290
    remoteDriverUnlock(priv);
2291
    return rv;
2292 2293
}

2294 2295 2296 2297 2298 2299 2300
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)
{
2301
    int rv = -1;
2302 2303
    remote_domain_migrate_prepare_args args;
    remote_domain_migrate_prepare_ret ret;
2304
    struct private_data *priv = dconn->privateData;
2305

2306 2307
    remoteDriverLock(priv);

2308 2309 2310 2311 2312 2313 2314 2315 2316
    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)
2317
        goto done;
2318 2319 2320 2321 2322 2323 2324 2325

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

2326 2327 2328
    rv = 0;

done:
2329
    remoteDriverUnlock(priv);
2330
    return rv;
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
}

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

2346 2347
    remoteDriverLock(priv);

2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358
    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)
2359
        goto done;
2360

2361 2362 2363
    rv = 0;

done:
2364
    remoteDriverUnlock(priv);
2365
    return rv;
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
}

static virDomainPtr
remoteDomainMigrateFinish (virConnectPtr dconn,
                           const char *dname,
                           const char *cookie,
                           int cookielen,
                           const char *uri,
                           unsigned long flags)
{
2376
    virDomainPtr ddom = NULL;
2377 2378
    remote_domain_migrate_finish_args args;
    remote_domain_migrate_finish_ret ret;
2379
    struct private_data *priv = dconn->privateData;
2380

2381 2382
    remoteDriverLock(priv);

2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
    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)
2393
        goto done;
2394 2395 2396 2397

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

2398
done:
2399
    remoteDriverUnlock(priv);
2400 2401 2402
    return ddom;
}

D
Daniel Veillard 已提交
2403 2404 2405 2406 2407 2408 2409 2410
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)
{
2411
    int rv = -1;
D
Daniel Veillard 已提交
2412 2413
    remote_domain_migrate_prepare2_args args;
    remote_domain_migrate_prepare2_ret ret;
2414
    struct private_data *priv = dconn->privateData;
D
Daniel Veillard 已提交
2415

2416 2417
    remoteDriverLock(priv);

D
Daniel Veillard 已提交
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427
    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)
2428
        goto done;
D
Daniel Veillard 已提交
2429 2430 2431 2432 2433 2434 2435 2436

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

2437 2438 2439
    rv = 0;

done:
2440
    remoteDriverUnlock(priv);
2441
    return rv;
D
Daniel Veillard 已提交
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452
}

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

2458 2459
    remoteDriverLock(priv);

D
Daniel Veillard 已提交
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
    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)
2471
        goto done;
D
Daniel Veillard 已提交
2472 2473 2474 2475

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

2476
done:
2477
    remoteDriverUnlock(priv);
D
Daniel Veillard 已提交
2478 2479 2480
    return ddom;
}

2481 2482 2483
static int
remoteListDefinedDomains (virConnectPtr conn, char **const names, int maxnames)
{
2484
    int rv = -1;
2485 2486 2487
    int i;
    remote_list_defined_domains_args args;
    remote_list_defined_domains_ret ret;
2488
    struct private_data *priv = conn->privateData;
2489

2490 2491
    remoteDriverLock(priv);

2492
    if (maxnames > REMOTE_DOMAIN_NAME_LIST_MAX) {
2493 2494 2495
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain names: %d > %d"),
                maxnames, REMOTE_DOMAIN_NAME_LIST_MAX);
2496
        goto done;
2497 2498 2499 2500 2501 2502 2503
    }
    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)
2504
        goto done;
2505 2506

    if (ret.names.names_len > maxnames) {
2507 2508 2509
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain names: %d > %d"),
                ret.names.names_len, maxnames);
2510
        goto cleanup;
2511 2512 2513 2514 2515 2516 2517 2518 2519 2520
    }

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

2521 2522 2523
    rv = ret.names.names_len;

cleanup:
2524 2525
    xdr_free ((xdrproc_t) xdr_remote_list_defined_domains_ret, (char *) &ret);

2526
done:
2527
    remoteDriverUnlock(priv);
2528
    return rv;
2529 2530 2531 2532 2533
}

static int
remoteNumOfDefinedDomains (virConnectPtr conn)
{
2534
    int rv = -1;
2535
    remote_num_of_defined_domains_ret ret;
2536
    struct private_data *priv = conn->privateData;
2537

2538 2539
    remoteDriverLock(priv);

2540 2541 2542 2543
    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)
2544
        goto done;
2545

2546 2547 2548
    rv = ret.num;

done:
2549
    remoteDriverUnlock(priv);
2550
    return rv;
2551 2552 2553 2554 2555
}

static int
remoteDomainCreate (virDomainPtr domain)
{
2556
    int rv = -1;
2557
    remote_domain_create_args args;
2558
    struct private_data *priv = domain->conn->privateData;
2559

2560 2561
    remoteDriverLock(priv);

2562 2563 2564 2565 2566
    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)
2567
        goto done;
2568

2569 2570 2571
    rv = 0;

done:
2572
    remoteDriverUnlock(priv);
2573
    return rv;
2574 2575 2576 2577 2578
}

static virDomainPtr
remoteDomainDefineXML (virConnectPtr conn, const char *xml)
{
2579
    virDomainPtr dom = NULL;
2580 2581
    remote_domain_define_xml_args args;
    remote_domain_define_xml_ret ret;
2582
    struct private_data *priv = conn->privateData;
2583

2584 2585
    remoteDriverLock(priv);

2586 2587 2588 2589 2590 2591
    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)
2592
        goto done;
2593 2594 2595 2596

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

2597
done:
2598
    remoteDriverUnlock(priv);
2599 2600 2601 2602 2603 2604
    return dom;
}

static int
remoteDomainUndefine (virDomainPtr domain)
{
2605
    int rv = -1;
2606
    remote_domain_undefine_args args;
2607
    struct private_data *priv = domain->conn->privateData;
2608

2609 2610
    remoteDriverLock(priv);

2611 2612 2613 2614 2615
    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)
2616
        goto done;
2617

2618 2619 2620
    rv = 0;

done:
2621
    remoteDriverUnlock(priv);
2622
    return rv;
2623 2624 2625
}

static int
2626
remoteDomainAttachDevice (virDomainPtr domain, const char *xml)
2627
{
2628
    int rv = -1;
2629
    remote_domain_attach_device_args args;
2630
    struct private_data *priv = domain->conn->privateData;
2631

2632 2633
    remoteDriverLock(priv);

2634
    make_nonnull_domain (&args.dom, domain);
2635
    args.xml = (char *) xml;
2636 2637 2638 2639

    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)
2640
        goto done;
2641

2642 2643 2644
    rv = 0;

done:
2645
    remoteDriverUnlock(priv);
2646
    return rv;
2647 2648 2649
}

static int
2650
remoteDomainDetachDevice (virDomainPtr domain, const char *xml)
2651
{
2652
    int rv = -1;
2653
    remote_domain_detach_device_args args;
2654
    struct private_data *priv = domain->conn->privateData;
2655

2656 2657
    remoteDriverLock(priv);

2658
    make_nonnull_domain (&args.dom, domain);
2659
    args.xml = (char *) xml;
2660 2661 2662 2663

    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)
2664
        goto done;
2665

2666 2667 2668
    rv = 0;

done:
2669
    remoteDriverUnlock(priv);
2670
    return rv;
2671 2672 2673 2674 2675
}

static int
remoteDomainGetAutostart (virDomainPtr domain, int *autostart)
{
2676
    int rv = -1;
2677 2678
    remote_domain_get_autostart_args args;
    remote_domain_get_autostart_ret ret;
2679
    struct private_data *priv = domain->conn->privateData;
2680

2681 2682
    remoteDriverLock(priv);

2683 2684 2685 2686 2687 2688
    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)
2689
        goto done;
2690 2691

    if (autostart) *autostart = ret.autostart;
2692 2693 2694
    rv = 0;

done:
2695
    remoteDriverUnlock(priv);
2696
    return rv;
2697 2698 2699 2700 2701
}

static int
remoteDomainSetAutostart (virDomainPtr domain, int autostart)
{
2702
    int rv = -1;
2703
    remote_domain_set_autostart_args args;
2704
    struct private_data *priv = domain->conn->privateData;
2705

2706 2707
    remoteDriverLock(priv);

2708 2709 2710 2711 2712 2713
    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)
2714
        goto done;
2715

2716 2717 2718
    rv = 0;

done:
2719
    remoteDriverUnlock(priv);
2720
    return rv;
2721 2722
}

2723 2724 2725
static char *
remoteDomainGetSchedulerType (virDomainPtr domain, int *nparams)
{
2726
    char *rv = NULL;
2727 2728
    remote_domain_get_scheduler_type_args args;
    remote_domain_get_scheduler_type_ret ret;
2729
    struct private_data *priv = domain->conn->privateData;
2730

2731 2732
    remoteDriverLock(priv);

2733 2734 2735 2736 2737 2738
    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)
2739
        goto done;
2740 2741 2742 2743

    if (nparams) *nparams = ret.nparams;

    /* Caller frees this. */
2744 2745 2746
    rv = ret.type;

done:
2747
    remoteDriverUnlock(priv);
2748
    return rv;
2749 2750 2751 2752 2753 2754
}

static int
remoteDomainGetSchedulerParameters (virDomainPtr domain,
                                    virSchedParameterPtr params, int *nparams)
{
2755
    int rv = -1;
2756 2757
    remote_domain_get_scheduler_parameters_args args;
    remote_domain_get_scheduler_parameters_ret ret;
2758
    int i = -1;
2759
    struct private_data *priv = domain->conn->privateData;
2760

2761 2762
    remoteDriverLock(priv);

2763 2764 2765 2766 2767 2768 2769
    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)
2770
        goto done;
2771 2772 2773 2774

    /* Check the length of the returned list carefully. */
    if (ret.params.params_len > REMOTE_DOMAIN_SCHEDULER_PARAMETERS_MAX ||
        ret.params.params_len > *nparams) {
2775 2776 2777
        error (domain->conn, VIR_ERR_RPC,
               _("remoteDomainGetSchedulerParameters: "
                 "returned number of parameters exceeds limit"));
2778
        goto cleanup;
2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
    }
    *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:
2802 2803 2804
            error (domain->conn, VIR_ERR_RPC,
                   _("remoteDomainGetSchedulerParameters: "
                     "unknown parameter type"));
2805
            goto cleanup;
2806 2807 2808
        }
    }

2809 2810 2811
    rv = 0;

cleanup:
2812
    xdr_free ((xdrproc_t) xdr_remote_domain_get_scheduler_parameters_ret, (char *) &ret);
2813
done:
2814
    remoteDriverUnlock(priv);
2815
    return rv;
2816 2817 2818 2819 2820 2821
}

static int
remoteDomainSetSchedulerParameters (virDomainPtr domain,
                                    virSchedParameterPtr params, int nparams)
{
2822
    int rv = -1;
2823 2824
    remote_domain_set_scheduler_parameters_args args;
    int i, do_error;
2825
    struct private_data *priv = domain->conn->privateData;
2826

2827 2828
    remoteDriverLock(priv);

2829 2830 2831 2832
    make_nonnull_domain (&args.dom, domain);

    /* Serialise the scheduler parameters. */
    args.params.params_len = nparams;
2833
    if (VIR_ALLOC_N(args.params.params_val, nparams) < 0) {
2834
        error (domain->conn, VIR_ERR_RPC, _("out of memory allocating array"));
2835
        goto done;
2836 2837 2838 2839 2840 2841 2842
    }

    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) {
2843
            error (domain->conn, VIR_ERR_NO_MEMORY, _("out of memory"));
2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860
            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:
2861
            error (domain->conn, VIR_ERR_RPC, _("unknown parameter type"));
2862 2863 2864 2865 2866 2867
            do_error = 1;
        }
    }

    if (do_error) {
        xdr_free ((xdrproc_t) xdr_remote_domain_set_scheduler_parameters_args, (char *) &args);
2868
        goto done;
2869 2870 2871 2872 2873
    }

    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)
2874
        goto done;
2875

2876 2877 2878
    rv = 0;

done:
2879
    remoteDriverUnlock(priv);
2880
    return rv;
2881 2882
}

2883 2884 2885 2886
static int
remoteDomainBlockStats (virDomainPtr domain, const char *path,
                        struct _virDomainBlockStats *stats)
{
2887
    int rv = -1;
2888 2889
    remote_domain_block_stats_args args;
    remote_domain_block_stats_ret ret;
2890
    struct private_data *priv = domain->conn->privateData;
2891

2892 2893
    remoteDriverLock(priv);

2894 2895 2896 2897 2898 2899 2900 2901
    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)
2902
        goto done;
2903 2904 2905 2906 2907 2908 2909

    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;

2910 2911 2912
    rv = 0;

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

static int
remoteDomainInterfaceStats (virDomainPtr domain, const char *path,
                            struct _virDomainInterfaceStats *stats)
{
2921
    int rv = -1;
2922 2923
    remote_domain_interface_stats_args args;
    remote_domain_interface_stats_ret ret;
2924
    struct private_data *priv = domain->conn->privateData;
2925

2926 2927
    remoteDriverLock(priv);

2928 2929 2930 2931 2932 2933 2934 2935 2936
    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)
2937
        goto done;
2938 2939 2940 2941 2942 2943 2944 2945 2946 2947

    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;

2948 2949 2950
    rv = 0;

done:
2951
    remoteDriverUnlock(priv);
2952
    return rv;
2953 2954
}

2955 2956 2957 2958 2959 2960 2961 2962
static int
remoteDomainBlockPeek (virDomainPtr domain,
                       const char *path,
                       unsigned long long offset,
                       size_t size,
                       void *buffer,
                       unsigned int flags)
{
2963
    int rv = -1;
2964 2965
    remote_domain_block_peek_args args;
    remote_domain_block_peek_ret ret;
2966
    struct private_data *priv = domain->conn->privateData;
2967

2968 2969
    remoteDriverLock(priv);

2970 2971 2972 2973
    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);
2974
        goto done;
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988
    }

    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)
2989
        goto done;
2990 2991

    if (ret.buffer.buffer_len != size) {
2992 2993 2994
        errorf (domain->conn, VIR_ERR_RPC,
                "%s", _("returned buffer is not same size as requested"));
        goto cleanup;
2995 2996 2997
    }

    memcpy (buffer, ret.buffer.buffer_val, size);
2998 2999 3000
    rv = 0;

cleanup:
3001 3002
    free (ret.buffer.buffer_val);

3003
done:
3004
    remoteDriverUnlock(priv);
3005
    return rv;
3006 3007
}

R
Richard W.M. Jones 已提交
3008 3009 3010 3011 3012 3013 3014
static int
remoteDomainMemoryPeek (virDomainPtr domain,
                        unsigned long long offset,
                        size_t size,
                        void *buffer,
                        unsigned int flags)
{
3015
    int rv = -1;
R
Richard W.M. Jones 已提交
3016 3017
    remote_domain_memory_peek_args args;
    remote_domain_memory_peek_ret ret;
3018
    struct private_data *priv = domain->conn->privateData;
R
Richard W.M. Jones 已提交
3019

3020 3021
    remoteDriverLock(priv);

R
Richard W.M. Jones 已提交
3022 3023 3024 3025
    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);
3026
        goto done;
R
Richard W.M. Jones 已提交
3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
    }

    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)
3040
        goto done;
R
Richard W.M. Jones 已提交
3041 3042

    if (ret.buffer.buffer_len != size) {
3043 3044 3045
        errorf (domain->conn, VIR_ERR_RPC,
                "%s", _("returned buffer is not same size as requested"));
        goto cleanup;
R
Richard W.M. Jones 已提交
3046 3047 3048
    }

    memcpy (buffer, ret.buffer.buffer_val, size);
3049 3050 3051
    rv = 0;

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

3054
done:
3055
    remoteDriverUnlock(priv);
3056
    return rv;
R
Richard W.M. Jones 已提交
3057 3058
}

3059 3060
/*----------------------------------------------------------------------*/

3061
static virDrvOpenStatus
3062
remoteNetworkOpen (virConnectPtr conn,
3063
                   virConnectAuthPtr auth,
3064
                   int flags)
3065
{
3066 3067 3068
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

3069 3070
    if (conn &&
        conn->driver &&
3071
        STREQ (conn->driver->name, "remote")) {
3072 3073 3074
        struct private_data *priv;

       /* If we're here, the remote driver is already
3075 3076 3077
         * in use due to a) a QEMU uri, or b) a remote
         * URI. So we can re-use existing connection
         */
3078 3079 3080 3081 3082
        priv = conn->privateData;
        remoteDriverLock(priv);
        priv->localUses++;
        conn->networkPrivateData = priv;
        remoteDriverUnlock(priv);
3083
        return VIR_DRV_OPEN_SUCCESS;
3084 3085 3086
    } else {
        /* Using a non-remote driver, so we need to open a
         * new connection for network APIs, forcing it to
3087 3088
         * use the UNIX transport. This handles Xen driver
         * which doesn't have its own impl of the network APIs.
3089
         */
3090
        struct private_data *priv;
3091
        int ret, rflags = 0;
3092
        if (VIR_ALLOC(priv) < 0) {
3093
            error (conn, VIR_ERR_NO_MEMORY, _("struct private_data"));
3094 3095
            return VIR_DRV_OPEN_ERROR;
        }
3096 3097 3098 3099 3100 3101
        if (virMutexInit(&priv->lock) < 0) {
            error(conn, VIR_ERR_INTERNAL_ERROR,
                  _("cannot initialize mutex"));
            VIR_FREE(priv);
            return VIR_DRV_OPEN_ERROR;
        }
3102
        if (flags & VIR_CONNECT_RO)
3103
            rflags |= VIR_DRV_OPEN_REMOTE_RO;
D
Daniel P. Berrange 已提交
3104
        rflags |= VIR_DRV_OPEN_REMOTE_UNIX;
3105 3106

        priv->sock = -1;
3107
        ret = doRemoteOpen(conn, priv, auth, rflags);
3108 3109
        if (ret != VIR_DRV_OPEN_SUCCESS) {
            conn->networkPrivateData = NULL;
3110
            VIR_FREE(priv);
3111
        } else {
3112
            priv->localUses = 1;
3113 3114 3115 3116
            conn->networkPrivateData = priv;
        }
        return ret;
    }
3117 3118 3119
}

static int
3120 3121
remoteNetworkClose (virConnectPtr conn)
{
3122
    int rv = 0;
3123 3124
    struct private_data *priv = conn->networkPrivateData;

3125 3126 3127 3128 3129 3130 3131 3132
    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        rv = doRemoteClose(conn, priv);
        conn->networkPrivateData = NULL;
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
3133
    }
3134 3135
    if (priv)
        remoteDriverUnlock(priv);
3136
    return rv;
3137 3138 3139 3140 3141
}

static int
remoteNumOfNetworks (virConnectPtr conn)
{
3142
    int rv = -1;
3143
    remote_num_of_networks_ret ret;
3144
    struct private_data *priv = conn->networkPrivateData;
3145

3146 3147
    remoteDriverLock(priv);

3148 3149 3150 3151
    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)
3152 3153 3154
        goto done;

    rv = ret.num;
3155

3156
done:
3157
    remoteDriverUnlock(priv);
3158
    return rv;
3159 3160 3161 3162 3163
}

static int
remoteListNetworks (virConnectPtr conn, char **const names, int maxnames)
{
3164
    int rv = -1;
3165 3166 3167
    int i;
    remote_list_networks_args args;
    remote_list_networks_ret ret;
3168
    struct private_data *priv = conn->networkPrivateData;
3169

3170 3171
    remoteDriverLock(priv);

3172
    if (maxnames > REMOTE_NETWORK_NAME_LIST_MAX) {
3173 3174 3175
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                maxnames, REMOTE_NETWORK_NAME_LIST_MAX);
3176
        goto done;
3177 3178 3179 3180 3181 3182 3183
    }
    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)
3184
        goto done;
3185 3186

    if (ret.names.names_len > maxnames) {
3187 3188 3189
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                ret.names.names_len, maxnames);
3190
        goto cleanup;
3191 3192 3193 3194 3195 3196 3197 3198 3199 3200
    }

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

3201 3202 3203
    rv = ret.names.names_len;

cleanup:
3204 3205
    xdr_free ((xdrproc_t) xdr_remote_list_networks_ret, (char *) &ret);

3206
done:
3207
    remoteDriverUnlock(priv);
3208
    return rv;
3209 3210 3211 3212 3213
}

static int
remoteNumOfDefinedNetworks (virConnectPtr conn)
{
3214
    int rv = -1;
3215
    remote_num_of_defined_networks_ret ret;
3216
    struct private_data *priv = conn->networkPrivateData;
3217

3218 3219
    remoteDriverLock(priv);

3220 3221 3222 3223
    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)
3224 3225 3226
        goto done;

    rv = ret.num;
3227

3228
done:
3229
    remoteDriverUnlock(priv);
3230
    return rv;
3231 3232 3233 3234 3235 3236
}

static int
remoteListDefinedNetworks (virConnectPtr conn,
                           char **const names, int maxnames)
{
3237
    int rv = -1;
3238 3239 3240
    int i;
    remote_list_defined_networks_args args;
    remote_list_defined_networks_ret ret;
3241
    struct private_data *priv = conn->networkPrivateData;
3242

3243 3244
    remoteDriverLock(priv);

3245
    if (maxnames > REMOTE_NETWORK_NAME_LIST_MAX) {
3246 3247 3248
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                maxnames, REMOTE_NETWORK_NAME_LIST_MAX);
3249
        goto done;
3250 3251 3252 3253 3254 3255 3256
    }
    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)
3257
        goto done;
3258 3259

    if (ret.names.names_len > maxnames) {
3260 3261 3262
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                ret.names.names_len, maxnames);
3263
        goto cleanup;
3264 3265 3266 3267 3268 3269 3270 3271 3272 3273
    }

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

3274 3275 3276
    rv = ret.names.names_len;

cleanup:
3277 3278
    xdr_free ((xdrproc_t) xdr_remote_list_defined_networks_ret, (char *) &ret);

3279
done:
3280
    remoteDriverUnlock(priv);
3281
    return rv;
3282 3283 3284 3285 3286 3287
}

static virNetworkPtr
remoteNetworkLookupByUUID (virConnectPtr conn,
                           const unsigned char *uuid)
{
3288
    virNetworkPtr net = NULL;
3289 3290
    remote_network_lookup_by_uuid_args args;
    remote_network_lookup_by_uuid_ret ret;
3291
    struct private_data *priv = conn->networkPrivateData;
3292

3293 3294
    remoteDriverLock(priv);

3295 3296 3297 3298 3299 3300
    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)
3301
        goto done;
3302 3303 3304 3305

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

3306
done:
3307
    remoteDriverUnlock(priv);
3308 3309 3310 3311 3312 3313 3314
    return net;
}

static virNetworkPtr
remoteNetworkLookupByName (virConnectPtr conn,
                           const char *name)
{
3315
    virNetworkPtr net = NULL;
3316 3317
    remote_network_lookup_by_name_args args;
    remote_network_lookup_by_name_ret ret;
3318
    struct private_data *priv = conn->networkPrivateData;
3319

3320 3321
    remoteDriverLock(priv);

3322 3323 3324 3325 3326 3327
    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)
3328
        goto done;
3329 3330 3331 3332

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

3333
done:
3334
    remoteDriverUnlock(priv);
3335 3336 3337 3338 3339 3340
    return net;
}

static virNetworkPtr
remoteNetworkCreateXML (virConnectPtr conn, const char *xmlDesc)
{
3341
    virNetworkPtr net = NULL;
3342 3343
    remote_network_create_xml_args args;
    remote_network_create_xml_ret ret;
3344
    struct private_data *priv = conn->networkPrivateData;
3345

3346 3347
    remoteDriverLock(priv);

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

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

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

static virNetworkPtr
remoteNetworkDefineXML (virConnectPtr conn, const char *xml)
{
3367
    virNetworkPtr net = NULL;
3368 3369
    remote_network_define_xml_args args;
    remote_network_define_xml_ret ret;
3370
    struct private_data *priv = conn->networkPrivateData;
3371

3372 3373
    remoteDriverLock(priv);

3374 3375 3376 3377 3378 3379
    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)
3380
        goto done;
3381 3382 3383 3384

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

3385
done:
3386
    remoteDriverUnlock(priv);
3387 3388 3389 3390 3391 3392
    return net;
}

static int
remoteNetworkUndefine (virNetworkPtr network)
{
3393
    int rv = -1;
3394
    remote_network_undefine_args args;
3395
    struct private_data *priv = network->conn->networkPrivateData;
3396

3397 3398
    remoteDriverLock(priv);

3399 3400 3401 3402 3403
    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)
3404
        goto done;
3405

3406 3407 3408
    rv = 0;

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

static int
remoteNetworkCreate (virNetworkPtr network)
{
3416
    int rv = -1;
3417
    remote_network_create_args args;
3418
    struct private_data *priv = network->conn->networkPrivateData;
3419

3420 3421
    remoteDriverLock(priv);

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

3429 3430 3431
    rv = 0;

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

static int
remoteNetworkDestroy (virNetworkPtr network)
{
3439
    int rv = -1;
3440
    remote_network_destroy_args args;
3441
    struct private_data *priv = network->conn->networkPrivateData;
3442

3443 3444
    remoteDriverLock(priv);

3445 3446 3447 3448 3449
    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)
3450
        goto done;
3451

3452 3453 3454
    rv = 0;

done:
3455
    remoteDriverUnlock(priv);
3456
    return rv;
3457 3458 3459 3460 3461
}

static char *
remoteNetworkDumpXML (virNetworkPtr network, int flags)
{
3462
    char *rv = NULL;
3463 3464
    remote_network_dump_xml_args args;
    remote_network_dump_xml_ret ret;
3465
    struct private_data *priv = network->conn->networkPrivateData;
3466

3467 3468
    remoteDriverLock(priv);

3469 3470 3471 3472 3473 3474 3475
    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)
3476
        goto done;
3477 3478

    /* Caller frees. */
3479 3480 3481
    rv = ret.xml;

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

static char *
remoteNetworkGetBridgeName (virNetworkPtr network)
{
3489
    char *rv = NULL;
3490 3491
    remote_network_get_bridge_name_args args;
    remote_network_get_bridge_name_ret ret;
3492
    struct private_data *priv = network->conn->networkPrivateData;
3493

3494 3495
    remoteDriverLock(priv);

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

    /* Caller frees. */
3505 3506 3507
    rv = ret.name;

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

static int
remoteNetworkGetAutostart (virNetworkPtr network, int *autostart)
{
3515
    int rv = -1;
3516 3517
    remote_network_get_autostart_args args;
    remote_network_get_autostart_ret ret;
3518
    struct private_data *priv = network->conn->networkPrivateData;
3519

3520 3521
    remoteDriverLock(priv);

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

    if (autostart) *autostart = ret.autostart;

3532 3533 3534
    rv = 0;

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

static int
remoteNetworkSetAutostart (virNetworkPtr network, int autostart)
{
3542
    int rv = -1;
3543
    remote_network_set_autostart_args args;
3544
    struct private_data *priv = network->conn->networkPrivateData;
3545

3546 3547
    remoteDriverLock(priv);

3548 3549 3550 3551 3552 3553
    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)
3554
        goto done;
3555

3556 3557 3558
    rv = 0;

done:
3559
    remoteDriverUnlock(priv);
3560
    return rv;
3561 3562
}

3563 3564 3565 3566 3567



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

3568
static virDrvOpenStatus
3569 3570 3571 3572 3573 3574 3575 3576 3577 3578
remoteStorageOpen (virConnectPtr conn,
                   virConnectAuthPtr auth,
                   int flags)
{
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

    if (conn &&
        conn->driver &&
        STREQ (conn->driver->name, "remote")) {
3579
        struct private_data *priv = conn->privateData;
3580 3581 3582 3583
        /* 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
         */
3584 3585 3586 3587
        remoteDriverLock(priv);
        priv->localUses++;
        conn->storagePrivateData = priv;
        remoteDriverUnlock(priv);
3588 3589 3590
        return VIR_DRV_OPEN_SUCCESS;
    } else if (conn->networkDriver &&
               STREQ (conn->networkDriver->name, "remote")) {
3591 3592 3593 3594 3595
        struct private_data *priv = conn->networkPrivateData;
        remoteDriverLock(priv);
        conn->storagePrivateData = priv;
        priv->localUses++;
        remoteDriverUnlock(priv);
3596 3597 3598 3599 3600 3601 3602
        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.
         */
3603
        struct private_data *priv;
3604
        int ret, rflags = 0;
3605
        if (VIR_ALLOC(priv) < 0) {
3606 3607 3608
            error (NULL, VIR_ERR_NO_MEMORY, _("struct private_data"));
            return VIR_DRV_OPEN_ERROR;
        }
3609 3610 3611 3612 3613 3614
        if (virMutexInit(&priv->lock) < 0) {
            error(conn, VIR_ERR_INTERNAL_ERROR,
                  _("cannot initialize mutex"));
            VIR_FREE(priv);
            return VIR_DRV_OPEN_ERROR;
        }
3615 3616 3617 3618 3619
        if (flags & VIR_CONNECT_RO)
            rflags |= VIR_DRV_OPEN_REMOTE_RO;
        rflags |= VIR_DRV_OPEN_REMOTE_UNIX;

        priv->sock = -1;
3620
        ret = doRemoteOpen(conn, priv, auth, rflags);
3621 3622
        if (ret != VIR_DRV_OPEN_SUCCESS) {
            conn->storagePrivateData = NULL;
3623
            VIR_FREE(priv);
3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635
        } else {
            priv->localUses = 1;
            conn->storagePrivateData = priv;
        }
        return ret;
    }
}

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

3638 3639 3640 3641 3642 3643 3644 3645
    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        ret = doRemoteClose(conn, priv);
        conn->storagePrivateData = NULL;
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
3646
    }
3647 3648
    if (priv)
        remoteDriverUnlock(priv);
3649

3650 3651 3652 3653 3654 3655
    return ret;
}

static int
remoteNumOfStoragePools (virConnectPtr conn)
{
3656
    int rv = -1;
3657
    remote_num_of_storage_pools_ret ret;
3658
    struct private_data *priv = conn->storagePrivateData;
3659

3660 3661
    remoteDriverLock(priv);

3662 3663 3664 3665
    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)
3666 3667 3668
        goto done;

    rv = ret.num;
3669

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

static int
remoteListStoragePools (virConnectPtr conn, char **const names, int maxnames)
{
3678
    int rv = -1;
3679 3680 3681
    int i;
    remote_list_storage_pools_args args;
    remote_list_storage_pools_ret ret;
3682
    struct private_data *priv = conn->storagePrivateData;
3683

3684 3685
    remoteDriverLock(priv);

3686 3687
    if (maxnames > REMOTE_STORAGE_POOL_NAME_LIST_MAX) {
        error (conn, VIR_ERR_RPC, _("too many storage pools requested"));
3688
        goto done;
3689 3690 3691 3692 3693 3694 3695
    }
    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)
3696
        goto done;
3697 3698 3699

    if (ret.names.names_len > maxnames) {
        error (conn, VIR_ERR_RPC, _("too many storage pools received"));
3700
        goto cleanup;
3701 3702 3703 3704 3705 3706 3707 3708 3709 3710
    }

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

3711 3712 3713
    rv = ret.names.names_len;

cleanup:
3714 3715
    xdr_free ((xdrproc_t) xdr_remote_list_storage_pools_ret, (char *) &ret);

3716
done:
3717
    remoteDriverUnlock(priv);
3718
    return rv;
3719 3720 3721 3722 3723
}

static int
remoteNumOfDefinedStoragePools (virConnectPtr conn)
{
3724
    int rv = -1;
3725
    remote_num_of_defined_storage_pools_ret ret;
3726
    struct private_data *priv = conn->storagePrivateData;
3727

3728 3729
    remoteDriverLock(priv);

3730 3731 3732 3733
    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)
3734
        goto done;
3735

3736 3737 3738
    rv = ret.num;

done:
3739
    remoteDriverUnlock(priv);
3740
    return rv;
3741 3742 3743 3744 3745 3746
}

static int
remoteListDefinedStoragePools (virConnectPtr conn,
                               char **const names, int maxnames)
{
3747
    int rv = -1;
3748 3749 3750
    int i;
    remote_list_defined_storage_pools_args args;
    remote_list_defined_storage_pools_ret ret;
3751
    struct private_data *priv = conn->storagePrivateData;
3752

3753 3754
    remoteDriverLock(priv);

3755 3756
    if (maxnames > REMOTE_STORAGE_POOL_NAME_LIST_MAX) {
        error (conn, VIR_ERR_RPC, _("too many storage pools requested"));
3757
        goto done;
3758 3759 3760 3761 3762 3763 3764
    }
    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)
3765
        goto done;
3766 3767 3768

    if (ret.names.names_len > maxnames) {
        error (conn, VIR_ERR_RPC, _("too many storage pools received"));
3769
        goto cleanup;
3770 3771 3772 3773 3774 3775 3776 3777 3778 3779
    }

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

3780 3781 3782
    rv = ret.names.names_len;

cleanup:
3783 3784
    xdr_free ((xdrproc_t) xdr_remote_list_defined_storage_pools_ret, (char *) &ret);

3785
done:
3786
    remoteDriverUnlock(priv);
3787
    return rv;
3788 3789
}

3790 3791 3792 3793 3794 3795
static char *
remoteFindStoragePoolSources (virConnectPtr conn,
                              const char *type,
                              const char *srcSpec,
                              unsigned int flags)
{
3796
    char *rv = NULL;
3797 3798
    remote_find_storage_pool_sources_args args;
    remote_find_storage_pool_sources_ret ret;
3799
    struct private_data *priv = conn->storagePrivateData;
3800 3801
    const char *emptyString = "";

3802 3803
    remoteDriverLock(priv);

3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822
    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)
3823
        goto done;
3824

3825
    rv = ret.xml;
3826 3827 3828 3829
    ret.xml = NULL; /* To stop xdr_free free'ing it */

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

3830
done:
3831
    remoteDriverUnlock(priv);
3832
    return rv;
3833 3834
}

3835 3836 3837 3838
static virStoragePoolPtr
remoteStoragePoolLookupByUUID (virConnectPtr conn,
                               const unsigned char *uuid)
{
3839
    virStoragePoolPtr pool = NULL;
3840 3841
    remote_storage_pool_lookup_by_uuid_args args;
    remote_storage_pool_lookup_by_uuid_ret ret;
3842
    struct private_data *priv = conn->storagePrivateData;
3843

3844 3845
    remoteDriverLock(priv);

3846 3847 3848 3849 3850 3851
    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)
3852
        goto done;
3853 3854 3855 3856

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

3857
done:
3858
    remoteDriverUnlock(priv);
3859 3860 3861 3862 3863 3864 3865
    return pool;
}

static virStoragePoolPtr
remoteStoragePoolLookupByName (virConnectPtr conn,
                               const char *name)
{
3866
    virStoragePoolPtr pool = NULL;
3867 3868
    remote_storage_pool_lookup_by_name_args args;
    remote_storage_pool_lookup_by_name_ret ret;
3869
    struct private_data *priv = conn->storagePrivateData;
3870

3871 3872
    remoteDriverLock(priv);

3873 3874 3875 3876 3877 3878
    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)
3879
        goto done;
3880 3881 3882 3883

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

3884
done:
3885
    remoteDriverUnlock(priv);
3886 3887 3888 3889 3890 3891
    return pool;
}

static virStoragePoolPtr
remoteStoragePoolLookupByVolume (virStorageVolPtr vol)
{
3892
    virStoragePoolPtr pool = NULL;
3893 3894
    remote_storage_pool_lookup_by_volume_args args;
    remote_storage_pool_lookup_by_volume_ret ret;
3895
    struct private_data *priv = vol->conn->storagePrivateData;
3896

3897 3898
    remoteDriverLock(priv);

3899 3900 3901 3902 3903 3904
    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)
3905
        goto done;
3906 3907 3908 3909

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

3910
done:
3911
    remoteDriverUnlock(priv);
3912 3913 3914 3915 3916 3917 3918
    return pool;
}


static virStoragePoolPtr
remoteStoragePoolCreateXML (virConnectPtr conn, const char *xmlDesc, unsigned int flags)
{
3919
    virStoragePoolPtr pool = NULL;
3920 3921
    remote_storage_pool_create_xml_args args;
    remote_storage_pool_create_xml_ret ret;
3922
    struct private_data *priv = conn->storagePrivateData;
3923

3924 3925
    remoteDriverLock(priv);

3926 3927 3928 3929 3930 3931 3932
    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)
3933
        goto done;
3934 3935 3936 3937

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

3938
done:
3939
    remoteDriverUnlock(priv);
3940 3941 3942 3943 3944 3945
    return pool;
}

static virStoragePoolPtr
remoteStoragePoolDefineXML (virConnectPtr conn, const char *xml, unsigned int flags)
{
3946
    virStoragePoolPtr pool = NULL;
3947 3948
    remote_storage_pool_define_xml_args args;
    remote_storage_pool_define_xml_ret ret;
3949
    struct private_data *priv = conn->storagePrivateData;
3950

3951 3952
    remoteDriverLock(priv);

3953 3954 3955 3956 3957 3958 3959
    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)
3960
        goto done;
3961 3962 3963 3964

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

3965
done:
3966
    remoteDriverUnlock(priv);
3967 3968 3969 3970 3971 3972
    return pool;
}

static int
remoteStoragePoolUndefine (virStoragePoolPtr pool)
{
3973
    int rv = -1;
3974
    remote_storage_pool_undefine_args args;
3975
    struct private_data *priv = pool->conn->storagePrivateData;
3976

3977 3978
    remoteDriverLock(priv);

3979 3980 3981 3982 3983
    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)
3984
        goto done;
3985

3986 3987 3988
    rv = 0;

done:
3989
    remoteDriverUnlock(priv);
3990
    return rv;
3991 3992 3993 3994 3995
}

static int
remoteStoragePoolCreate (virStoragePoolPtr pool, unsigned int flags)
{
3996
    int rv = -1;
3997
    remote_storage_pool_create_args args;
3998
    struct private_data *priv = pool->conn->storagePrivateData;
3999

4000 4001
    remoteDriverLock(priv);

4002 4003 4004 4005 4006 4007
    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)
4008
        goto done;
4009

4010 4011 4012
    rv = 0;

done:
4013
    remoteDriverUnlock(priv);
4014
    return rv;
4015 4016 4017 4018 4019 4020
}

static int
remoteStoragePoolBuild (virStoragePoolPtr pool,
                        unsigned int flags)
{
4021
    int rv = -1;
4022
    remote_storage_pool_build_args args;
4023
    struct private_data *priv = pool->conn->storagePrivateData;
4024

4025 4026
    remoteDriverLock(priv);

4027 4028 4029 4030 4031 4032
    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)
4033
        goto done;
4034

4035 4036 4037
    rv = 0;

done:
4038
    remoteDriverUnlock(priv);
4039
    return rv;
4040 4041 4042 4043 4044
}

static int
remoteStoragePoolDestroy (virStoragePoolPtr pool)
{
4045
    int rv = -1;
4046
    remote_storage_pool_destroy_args args;
4047
    struct private_data *priv = pool->conn->storagePrivateData;
4048

4049 4050
    remoteDriverLock(priv);

4051 4052 4053 4054 4055
    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)
4056
        goto done;
4057

4058 4059 4060
    rv = 0;

done:
4061
    remoteDriverUnlock(priv);
4062
    return rv;
4063 4064 4065 4066 4067 4068
}

static int
remoteStoragePoolDelete (virStoragePoolPtr pool,
                         unsigned int flags)
{
4069
    int rv = -1;
4070
    remote_storage_pool_delete_args args;
4071
    struct private_data *priv = pool->conn->storagePrivateData;
4072

4073 4074
    remoteDriverLock(priv);

4075 4076 4077 4078 4079 4080
    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)
4081
        goto done;
4082

4083 4084 4085
    rv = 0;

done:
4086
    remoteDriverUnlock(priv);
4087
    return rv;
4088 4089 4090 4091 4092 4093
}

static int
remoteStoragePoolRefresh (virStoragePoolPtr pool,
                          unsigned int flags)
{
4094
    int rv = -1;
4095
    remote_storage_pool_refresh_args args;
4096
    struct private_data *priv = pool->conn->storagePrivateData;
4097

4098 4099
    remoteDriverLock(priv);

4100 4101 4102 4103 4104 4105
    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)
4106
        goto done;
4107

4108 4109 4110
    rv = 0;

done:
4111
    remoteDriverUnlock(priv);
4112
    return rv;
4113 4114 4115 4116 4117
}

static int
remoteStoragePoolGetInfo (virStoragePoolPtr pool, virStoragePoolInfoPtr info)
{
4118
    int rv = -1;
4119 4120
    remote_storage_pool_get_info_args args;
    remote_storage_pool_get_info_ret ret;
4121
    struct private_data *priv = pool->conn->storagePrivateData;
4122

4123 4124
    remoteDriverLock(priv);

4125 4126 4127 4128 4129 4130
    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)
4131
        goto done;
4132 4133 4134 4135 4136 4137

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

4138 4139 4140
    rv = 0;

done:
4141
    remoteDriverUnlock(priv);
4142
    return rv;
4143 4144 4145 4146 4147 4148
}

static char *
remoteStoragePoolDumpXML (virStoragePoolPtr pool,
                          unsigned int flags)
{
4149
    char *rv = NULL;
4150 4151
    remote_storage_pool_dump_xml_args args;
    remote_storage_pool_dump_xml_ret ret;
4152
    struct private_data *priv = pool->conn->storagePrivateData;
4153

4154 4155
    remoteDriverLock(priv);

4156 4157 4158 4159 4160 4161 4162
    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)
4163
        goto done;
4164 4165

    /* Caller frees. */
4166 4167 4168
    rv = ret.xml;

done:
4169
    remoteDriverUnlock(priv);
4170
    return rv;
4171 4172 4173 4174 4175
}

static int
remoteStoragePoolGetAutostart (virStoragePoolPtr pool, int *autostart)
{
4176
    int rv = -1;
4177 4178
    remote_storage_pool_get_autostart_args args;
    remote_storage_pool_get_autostart_ret ret;
4179
    struct private_data *priv = pool->conn->storagePrivateData;
4180

4181 4182
    remoteDriverLock(priv);

4183 4184 4185 4186 4187 4188
    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)
4189
        goto done;
4190 4191 4192

    if (autostart) *autostart = ret.autostart;

4193 4194 4195
    rv = 0;

done:
4196
    remoteDriverUnlock(priv);
4197
    return rv;
4198 4199 4200 4201 4202
}

static int
remoteStoragePoolSetAutostart (virStoragePoolPtr pool, int autostart)
{
4203
    int rv = -1;
4204
    remote_storage_pool_set_autostart_args args;
4205
    struct private_data *priv = pool->conn->storagePrivateData;
4206

4207 4208
    remoteDriverLock(priv);

4209 4210 4211 4212 4213 4214
    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)
4215
        goto done;
4216

4217 4218 4219
    rv = 0;

done:
4220
    remoteDriverUnlock(priv);
4221
    return rv;
4222 4223 4224 4225 4226 4227
}


static int
remoteStoragePoolNumOfVolumes (virStoragePoolPtr pool)
{
4228
    int rv = -1;
4229 4230
    remote_storage_pool_num_of_volumes_args args;
    remote_storage_pool_num_of_volumes_ret ret;
4231
    struct private_data *priv = pool->conn->storagePrivateData;
4232

4233 4234
    remoteDriverLock(priv);

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

    rv = ret.num;
4244

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

static int
remoteStoragePoolListVolumes (virStoragePoolPtr pool, char **const names, int maxnames)
{
4253
    int rv = -1;
4254 4255 4256
    int i;
    remote_storage_pool_list_volumes_args args;
    remote_storage_pool_list_volumes_ret ret;
4257
    struct private_data *priv = pool->conn->storagePrivateData;
4258

4259 4260
    remoteDriverLock(priv);

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

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

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

4287 4288 4289
    rv = ret.names.names_len;

cleanup:
4290 4291
    xdr_free ((xdrproc_t) xdr_remote_storage_pool_list_volumes_ret, (char *) &ret);

4292
done:
4293
    remoteDriverUnlock(priv);
4294
    return rv;
4295 4296 4297 4298 4299 4300 4301 4302
}



static virStorageVolPtr
remoteStorageVolLookupByName (virStoragePoolPtr pool,
                              const char *name)
{
4303
    virStorageVolPtr vol = NULL;
4304 4305
    remote_storage_vol_lookup_by_name_args args;
    remote_storage_vol_lookup_by_name_ret ret;
4306
    struct private_data *priv = pool->conn->storagePrivateData;
4307

4308 4309
    remoteDriverLock(priv);

4310 4311 4312 4313 4314 4315 4316
    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)
4317
        goto done;
4318 4319 4320 4321

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

4322
done:
4323
    remoteDriverUnlock(priv);
4324 4325 4326 4327 4328 4329 4330
    return vol;
}

static virStorageVolPtr
remoteStorageVolLookupByKey (virConnectPtr conn,
                             const char *key)
{
4331
    virStorageVolPtr  vol = NULL;
4332 4333
    remote_storage_vol_lookup_by_key_args args;
    remote_storage_vol_lookup_by_key_ret ret;
4334
    struct private_data *priv = conn->storagePrivateData;
4335

4336 4337
    remoteDriverLock(priv);

4338 4339 4340 4341 4342 4343
    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)
4344
        goto done;
4345 4346 4347 4348

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

4349
done:
4350
    remoteDriverUnlock(priv);
4351 4352 4353 4354 4355 4356 4357
    return vol;
}

static virStorageVolPtr
remoteStorageVolLookupByPath (virConnectPtr conn,
                              const char *path)
{
4358
    virStorageVolPtr vol = NULL;
4359 4360
    remote_storage_vol_lookup_by_path_args args;
    remote_storage_vol_lookup_by_path_ret ret;
4361
    struct private_data *priv = conn->storagePrivateData;
4362

4363 4364
    remoteDriverLock(priv);

4365 4366 4367 4368 4369 4370
    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)
4371
        goto done;
4372 4373 4374 4375

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

4376
done:
4377
    remoteDriverUnlock(priv);
4378 4379 4380 4381 4382 4383 4384
    return vol;
}

static virStorageVolPtr
remoteStorageVolCreateXML (virStoragePoolPtr pool, const char *xmlDesc,
                           unsigned int flags)
{
4385
    virStorageVolPtr vol = NULL;
4386 4387
    remote_storage_vol_create_xml_args args;
    remote_storage_vol_create_xml_ret ret;
4388
    struct private_data *priv = pool->conn->storagePrivateData;
4389

4390 4391
    remoteDriverLock(priv);

4392 4393 4394 4395 4396 4397 4398 4399
    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)
4400
        goto done;
4401 4402 4403 4404

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

4405
done:
4406
    remoteDriverUnlock(priv);
4407 4408 4409 4410 4411 4412 4413
    return vol;
}

static int
remoteStorageVolDelete (virStorageVolPtr vol,
                        unsigned int flags)
{
4414
    int rv = -1;
4415
    remote_storage_vol_delete_args args;
4416
    struct private_data *priv = vol->conn->storagePrivateData;
4417

4418 4419
    remoteDriverLock(priv);

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

4428 4429 4430
    rv = 0;

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

static int
remoteStorageVolGetInfo (virStorageVolPtr vol, virStorageVolInfoPtr info)
{
4438
    int rv = -1;
4439 4440
    remote_storage_vol_get_info_args args;
    remote_storage_vol_get_info_ret ret;
4441
    struct private_data *priv = vol->conn->storagePrivateData;
4442

4443 4444
    remoteDriverLock(priv);

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

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

4457 4458 4459
    rv = 0;

done:
4460
    remoteDriverUnlock(priv);
4461
    return rv;
4462 4463 4464 4465 4466 4467
}

static char *
remoteStorageVolDumpXML (virStorageVolPtr vol,
                         unsigned int flags)
{
4468
    char *rv = NULL;
4469 4470
    remote_storage_vol_dump_xml_args args;
    remote_storage_vol_dump_xml_ret ret;
4471
    struct private_data *priv = vol->conn->storagePrivateData;
4472

4473 4474
    remoteDriverLock(priv);

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

    /* Caller frees. */
4485 4486 4487
    rv = ret.xml;

done:
4488
    remoteDriverUnlock(priv);
4489
    return rv;
4490 4491 4492 4493 4494
}

static char *
remoteStorageVolGetPath (virStorageVolPtr vol)
{
4495
    char *rv = NULL;
4496 4497
    remote_storage_vol_get_path_args args;
    remote_storage_vol_get_path_ret ret;
4498
    struct private_data *priv = vol->conn->storagePrivateData;
4499

4500 4501
    remoteDriverLock(priv);

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

    /* Caller frees. */
4511 4512 4513
    rv = ret.name;

done:
4514
    remoteDriverUnlock(priv);
4515
    return rv;
4516 4517 4518
}


4519 4520 4521 4522 4523 4524 4525
/*----------------------------------------------------------------------*/

static virDrvOpenStatus
remoteDevMonOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 int flags ATTRIBUTE_UNUSED)
{
4526 4527 4528
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

4529 4530 4531
    if (conn &&
        conn->driver &&
        STREQ (conn->driver->name, "remote")) {
4532
        struct private_data *priv = conn->privateData;
4533 4534 4535 4536
        /* 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
         */
4537 4538 4539 4540
        remoteDriverLock(priv);
        priv->localUses++;
        conn->devMonPrivateData = priv;
        remoteDriverUnlock(priv);
4541
        return VIR_DRV_OPEN_SUCCESS;
4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570
    } 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;
        int ret, rflags = 0;
        if (VIR_ALLOC(priv) < 0) {
            error (NULL, VIR_ERR_NO_MEMORY, _("struct private_data"));
            return VIR_DRV_OPEN_ERROR;
        }
        if (virMutexInit(&priv->lock) < 0) {
            error(conn, VIR_ERR_INTERNAL_ERROR,
                  _("cannot initialize mutex"));
            VIR_FREE(priv);
            return VIR_DRV_OPEN_ERROR;
        }
        if (flags & VIR_CONNECT_RO)
            rflags |= VIR_DRV_OPEN_REMOTE_RO;
        rflags |= VIR_DRV_OPEN_REMOTE_UNIX;
4571

4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582
        priv->sock = -1;
        ret = doRemoteOpen(conn, priv, auth, rflags);
        if (ret != VIR_DRV_OPEN_SUCCESS) {
            conn->devMonPrivateData = NULL;
            VIR_FREE(priv);
        } else {
            priv->localUses = 1;
            conn->devMonPrivateData = priv;
        }
        return ret;
    }
4583 4584 4585 4586 4587
}

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

4590 4591 4592 4593 4594 4595 4596 4597
    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        ret = doRemoteClose(conn, priv);
        conn->devMonPrivateData = NULL;
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
4598
    }
4599 4600
    if (priv)
        remoteDriverUnlock(priv);
4601 4602 4603 4604 4605 4606 4607
    return ret;
}

static int remoteNodeNumOfDevices(virConnectPtr conn,
                                  const char *cap,
                                  unsigned int flags)
{
4608
    int rv = -1;
4609 4610
    remote_node_num_of_devices_args args;
    remote_node_num_of_devices_ret ret;
4611
    struct private_data *priv = conn->devMonPrivateData;
4612

4613 4614
    remoteDriverLock(priv);

4615 4616 4617 4618 4619 4620 4621
    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)
4622 4623 4624
        goto done;

    rv = ret.num;
4625

4626
done:
4627
    remoteDriverUnlock(priv);
4628
    return rv;
4629 4630 4631 4632 4633 4634 4635 4636 4637
}


static int remoteNodeListDevices(virConnectPtr conn,
                                 const char *cap,
                                 char **const names,
                                 int maxnames,
                                 unsigned int flags)
{
4638
    int rv = -1;
4639 4640 4641
    int i;
    remote_node_list_devices_args args;
    remote_node_list_devices_ret ret;
4642
    struct private_data *priv = conn->devMonPrivateData;
4643

4644 4645
    remoteDriverLock(priv);

4646 4647
    if (maxnames > REMOTE_NODE_DEVICE_NAME_LIST_MAX) {
        error (conn, VIR_ERR_RPC, _("too many device names requested"));
4648
        goto done;
4649 4650 4651 4652 4653 4654 4655 4656 4657
    }
    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)
4658
        goto done;
4659 4660 4661

    if (ret.names.names_len > maxnames) {
        error (conn, VIR_ERR_RPC, _("too many device names received"));
4662
        goto cleanup;
4663 4664 4665 4666 4667 4668 4669 4670 4671 4672
    }

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

4673 4674 4675
    rv = ret.names.names_len;

cleanup:
4676 4677
    xdr_free ((xdrproc_t) xdr_remote_node_list_devices_ret, (char *) &ret);

4678
done:
4679
    remoteDriverUnlock(priv);
4680
    return rv;
4681 4682 4683 4684 4685 4686 4687 4688
}


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

4692 4693
    remoteDriverLock(priv);

4694 4695 4696 4697 4698 4699
    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)
4700
        goto done;
4701 4702 4703 4704 4705

    dev = get_nonnull_node_device(conn, ret.dev);

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

4706
done:
4707
    remoteDriverUnlock(priv);
4708 4709 4710 4711 4712 4713
    return dev;
}

static char *remoteNodeDeviceDumpXML(virNodeDevicePtr dev,
                                     unsigned int flags)
{
4714
    char *rv = NULL;
4715 4716
    remote_node_device_dump_xml_args args;
    remote_node_device_dump_xml_ret ret;
4717
    struct private_data *priv = dev->conn->devMonPrivateData;
4718

4719 4720
    remoteDriverLock(priv);

4721 4722 4723 4724 4725 4726 4727
    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)
4728
        goto done;
4729 4730

    /* Caller frees. */
4731 4732 4733
    rv = ret.xml;

done:
4734
    remoteDriverUnlock(priv);
4735
    return rv;
4736 4737 4738 4739
}

static char *remoteNodeDeviceGetParent(virNodeDevicePtr dev)
{
4740
    char *rv = NULL;
4741 4742
    remote_node_device_get_parent_args args;
    remote_node_device_get_parent_ret ret;
4743
    struct private_data *priv = dev->conn->devMonPrivateData;
4744

4745 4746
    remoteDriverLock(priv);

4747 4748 4749 4750 4751 4752
    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)
4753
        goto done;
4754 4755

    /* Caller frees. */
4756 4757 4758
    rv = ret.parent ? *ret.parent : NULL;

done:
4759
    remoteDriverUnlock(priv);
4760
    return rv;
4761 4762 4763 4764
}

static int remoteNodeDeviceNumOfCaps(virNodeDevicePtr dev)
{
4765
    int rv = -1;
4766 4767
    remote_node_device_num_of_caps_args args;
    remote_node_device_num_of_caps_ret ret;
4768
    struct private_data *priv = dev->conn->devMonPrivateData;
4769

4770 4771
    remoteDriverLock(priv);

4772 4773 4774 4775 4776 4777
    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)
4778 4779 4780
        goto done;

    rv = ret.num;
4781

4782
done:
4783
    remoteDriverUnlock(priv);
4784
    return rv;
4785 4786 4787 4788 4789 4790
}

static int remoteNodeDeviceListCaps(virNodeDevicePtr dev,
                                    char **const names,
                                    int maxnames)
{
4791
    int rv = -1;
4792 4793 4794
    int i;
    remote_node_device_list_caps_args args;
    remote_node_device_list_caps_ret ret;
4795
    struct private_data *priv = dev->conn->devMonPrivateData;
4796

4797 4798
    remoteDriverLock(priv);

4799 4800
    if (maxnames > REMOTE_NODE_DEVICE_CAPS_LIST_MAX) {
        error (dev->conn, VIR_ERR_RPC, _("too many capability names requested"));
4801
        goto done;
4802 4803 4804 4805 4806 4807 4808 4809
    }
    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)
4810
        goto done;
4811 4812 4813

    if (ret.names.names_len > maxnames) {
        error (dev->conn, VIR_ERR_RPC, _("too many capability names received"));
4814
        goto cleanup;
4815 4816 4817 4818 4819 4820 4821 4822 4823 4824
    }

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

4825 4826 4827
    rv = ret.names.names_len;

cleanup:
4828 4829
    xdr_free ((xdrproc_t) xdr_remote_node_device_list_caps_ret, (char *) &ret);

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


4836 4837
/*----------------------------------------------------------------------*/

4838
static int
4839
remoteAuthenticate (virConnectPtr conn, struct private_data *priv, int in_open,
4840 4841 4842 4843 4844 4845
                    virConnectAuthPtr auth
#if !HAVE_SASL && !HAVE_POLKIT
                    ATTRIBUTE_UNUSED
#endif
                    ,
                    const char *authtype)
4846 4847
{
    struct remote_auth_list_ret ret;
4848
    int err, type = REMOTE_AUTH_NONE;
4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864

    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;

4865 4866 4867 4868 4869 4870 4871 4872
    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 {
4873
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4874 4875 4876
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                             NULL, NULL, NULL, 0, 0,
                             _("unknown authentication type %s"), authtype);
4877 4878 4879 4880 4881 4882 4883
            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) {
4884
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4885
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4886 4887
                             _("requested authentication type %s rejected"),
                             authtype);
4888 4889 4890 4891 4892 4893 4894
            return -1;
        }
    } else {
        type = ret.types.types_val[0];
    }

    switch (type) {
4895
#if HAVE_SASL
4896 4897 4898 4899 4900 4901 4902
    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) {
4903
            VIR_FREE(ret.types.types_val);
4904 4905 4906
            return -1;
        }
        break;
4907
    }
4908 4909
#endif

4910 4911
#if HAVE_POLKIT
    case REMOTE_AUTH_POLKIT:
4912
        if (remoteAuthPolkit(conn, priv, in_open, auth) < 0) {
4913
            VIR_FREE(ret.types.types_val);
4914 4915 4916 4917 4918
            return -1;
        }
        break;
#endif

4919 4920 4921 4922 4923
    case REMOTE_AUTH_NONE:
        /* Nothing todo, hurrah ! */
        break;

    default:
4924
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4925 4926 4927 4928
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                         NULL, NULL, NULL, 0, 0,
                         _("unsupported authentication type %d"),
                         ret.types.types_val[0]);
4929
        VIR_FREE(ret.types.types_val);
4930 4931 4932
        return -1;
    }

4933
    VIR_FREE(ret.types.types_val);
4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953

    return 0;
}



#if HAVE_SASL
/*
 * NB, keep in sync with similar method in qemud/remote.c
 */
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) {
4954
        virRaiseError (NULL, NULL, NULL, VIR_FROM_REMOTE,
4955 4956 4957 4958
                         VIR_ERR_NO_MEMORY, VIR_ERR_ERROR,
                         NULL, NULL, NULL, 0, 0,
                         _("Cannot resolve address %d: %s"),
                         err, gai_strerror(err));
4959 4960 4961
        return NULL;
    }

4962
    if (VIR_ALLOC_N(addr, strlen(host) + 1 + strlen(port) + 1) < 0) {
4963
        virRaiseError (NULL, NULL, NULL, VIR_FROM_REMOTE,
4964 4965
                         VIR_ERR_NO_MEMORY, VIR_ERR_ERROR,
                         NULL, NULL, NULL, 0, 0,
4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976
                         "address");
        return NULL;
    }

    strcpy(addr, host);
    strcat(addr, ";");
    strcat(addr, port);
    return addr;
}


4977 4978 4979 4980 4981 4982 4983 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 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054
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)
{
5055
    sasl_callback_t *cbs;
5056
    int i, n;
5057
    if (VIR_ALLOC_N(cbs, ncredtype+1) < 0) {
5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076
        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
5077
 *
5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091
 * 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 */

5092
    if (VIR_ALLOC_N(*cred, ninteract) < 0)
5093 5094 5095 5096 5097
        return -1;

    for (ninteract = 0 ; interact[ninteract].id != 0 ; ninteract++) {
        (*cred)[ninteract].type = remoteAuthCredSASL2Vir(interact[ninteract].id);
        if (!(*cred)[ninteract].type) {
5098
            VIR_FREE(*cred);
5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116
            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++)
5117 5118
        VIR_FREE(cred[i].result);
    VIR_FREE(cred);
5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139
}


/*
 * @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
5140 5141
 */
static int
5142 5143
remoteAuthSASL (virConnectPtr conn, struct private_data *priv, int in_open,
                virConnectAuthPtr auth, const char *wantmech)
5144 5145
{
    sasl_conn_t *saslconn = NULL;
5146
    sasl_security_properties_t secprops;
5147 5148 5149 5150 5151 5152
    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;
5153
    char *serverin = NULL;
5154 5155 5156 5157 5158
    unsigned int clientoutlen, serverinlen;
    const char *mech;
    int err, complete;
    struct sockaddr_storage sa;
    socklen_t salen;
5159
    char *localAddr = NULL, *remoteAddr = NULL;
5160 5161
    const void *val;
    sasl_ssf_t ssf;
5162 5163 5164 5165 5166 5167
    sasl_callback_t *saslcb = NULL;
    sasl_interact_t *interact = NULL;
    virConnectCredentialPtr cred = NULL;
    int ncred = 0;
    int ret = -1;
    const char *mechlist;
5168

5169
    DEBUG0("Client initialize SASL authentication");
5170 5171 5172
    /* Sets up the SASL library as a whole */
    err = sasl_client_init(NULL);
    if (err != SASL_OK) {
5173
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5174
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5175
                         _("failed to initialize SASL library: %d (%s)"),
5176
                         err, sasl_errstring(err, NULL, NULL));
5177
        goto cleanup;
5178 5179 5180 5181 5182
    }

    /* Get local address in form  IPADDR:PORT */
    salen = sizeof(sa);
    if (getsockname(priv->sock, (struct sockaddr*)&sa, &salen) < 0) {
5183
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5184
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5185
                         _("failed to get sock address %d (%s)"),
J
Jim Meyering 已提交
5186
                         errno, strerror(errno));
5187
        goto cleanup;
5188
    }
5189 5190
    if ((localAddr = addrToString(&sa, salen)) == NULL)
        goto cleanup;
5191 5192 5193 5194

    /* Get remote address in form  IPADDR:PORT */
    salen = sizeof(sa);
    if (getpeername(priv->sock, (struct sockaddr*)&sa, &salen) < 0) {
5195
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5196
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5197
                         _("failed to get peer address %d (%s)"),
J
Jim Meyering 已提交
5198
                         errno, strerror(errno));
5199
        goto cleanup;
5200
    }
5201 5202 5203
    if ((remoteAddr = addrToString(&sa, salen)) == NULL)
        goto cleanup;

5204 5205 5206 5207 5208 5209
    if (auth) {
        if ((saslcb = remoteAuthMakeCallbacks(auth->credtype, auth->ncredtype)) == NULL)
            goto cleanup;
    } else {
        saslcb = NULL;
    }
5210 5211 5212 5213 5214 5215

    /* Setup a handle for being a client */
    err = sasl_client_new("libvirt",
                          priv->hostname,
                          localAddr,
                          remoteAddr,
5216
                          saslcb,
5217 5218
                          SASL_SUCCESS_DATA,
                          &saslconn);
5219

5220
    if (err != SASL_OK) {
5221
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5222
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5223
                         _("Failed to create SASL client context: %d (%s)"),
5224
                         err, sasl_errstring(err, NULL, NULL));
5225
        goto cleanup;
5226 5227
    }

5228 5229 5230 5231 5232 5233
    /* 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))) {
5234
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5235
                             VIR_ERR_INTERNAL_ERROR, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5236
                             "%s", _("invalid cipher size for TLS session"));
5237
            goto cleanup;
5238 5239 5240
        }
        ssf *= 8; /* key size is bytes, sasl wants bits */

5241
        DEBUG("Setting external SSF %d", ssf);
5242 5243
        err = sasl_setprop(saslconn, SASL_SSF_EXTERNAL, &ssf);
        if (err != SASL_OK) {
5244
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5245
                             VIR_ERR_INTERNAL_ERROR, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5246
                             _("cannot set external SSF %d (%s)"),
5247
                             err, sasl_errstring(err, NULL, NULL));
5248
            goto cleanup;
5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262
        }
    }

    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) {
5263
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5264
                         VIR_ERR_INTERNAL_ERROR, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5265
                         _("cannot set security props %d (%s)"),
5266
                         err, sasl_errstring(err, NULL, NULL));
5267
        goto cleanup;
5268 5269
    }

5270 5271 5272 5273
    /* 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,
5274 5275
              (xdrproc_t) xdr_remote_auth_sasl_init_ret, (char *) &iret) != 0)
        goto cleanup;
5276 5277


5278 5279 5280
    mechlist = iret.mechlist;
    if (wantmech) {
        if (strstr(mechlist, wantmech) == NULL) {
5281
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5282 5283 5284 5285
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                             NULL, NULL, NULL, 0, 0,
                             _("SASL mechanism %s not supported by server"),
                             wantmech);
5286
            VIR_FREE(iret.mechlist);
5287 5288 5289 5290 5291
            goto cleanup;
        }
        mechlist = wantmech;
    }
 restart:
5292
    /* Start the auth negotiation on the client end first */
5293
    DEBUG("Client start negotiation mechlist '%s'", mechlist);
5294
    err = sasl_client_start(saslconn,
5295 5296
                            mechlist,
                            &interact,
5297 5298 5299
                            &clientout,
                            &clientoutlen,
                            &mech);
5300
    if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
5301
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5302
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5303
                         _("Failed to start SASL negotiation: %d (%s)"),
5304
                         err, sasl_errdetail(saslconn));
5305
        VIR_FREE(iret.mechlist);
5306 5307 5308 5309 5310
        goto cleanup;
    }

    /* Need to gather some credentials from the client */
    if (err == SASL_INTERACT) {
5311
        const char *msg;
5312 5313 5314 5315 5316 5317
        if (cred) {
            remoteAuthFreeCredentials(cred, ncred);
            cred = NULL;
        }
        if ((ncred =
             remoteAuthMakeCredentials(interact, &cred)) < 0) {
5318
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5319 5320 5321
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                             NULL, NULL, NULL, 0, 0,
                             "%s", _("Failed to make auth credentials"));
5322
            VIR_FREE(iret.mechlist);
5323 5324 5325
            goto cleanup;
        }
        /* Run the authentication callback */
5326
        if (auth && auth->cb) {
5327 5328 5329
            if ((*(auth->cb))(cred, ncred, auth->cbdata) >= 0) {
                remoteAuthFillInteract(cred, interact);
                goto restart;
5330
            }
5331
            msg = "Failed to collect auth credentials";
5332
        } else {
5333
            msg = "No authentication callback available";
5334
        }
5335
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5336
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL,
5337
                         0, 0, "%s", msg);
5338
        goto cleanup;
5339
    }
5340
    VIR_FREE(iret.mechlist);
5341 5342

    if (clientoutlen > REMOTE_AUTH_SASL_DATA_MAX) {
5343
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5344
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5345 5346
                         _("SASL negotiation data too long: %d bytes"),
                         clientoutlen);
5347
        goto cleanup;
5348 5349 5350 5351 5352 5353 5354
    }
    /* 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;
5355
    DEBUG("Server start negotiation with mech %s. Data %d bytes %p", mech, clientoutlen, clientout);
5356 5357 5358 5359 5360

    /* 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,
5361 5362
              (xdrproc_t) xdr_remote_auth_sasl_start_ret, (char *) &sret) != 0)
        goto cleanup;
5363 5364 5365 5366 5367

    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;
5368 5369
    DEBUG("Client step result complete: %d. Data %d bytes %p",
          complete, serverinlen, serverin);
5370 5371 5372

    /* Loop-the-loop...
     * Even if the server has completed, the client must *always* do at least one step
D
Daniel Veillard 已提交
5373
     * in this loop to verify the server isn't lying about something. Mutual auth */
5374
    for (;;) {
5375
    restep:
5376 5377 5378
        err = sasl_client_step(saslconn,
                               serverin,
                               serverinlen,
5379
                               &interact,
5380 5381
                               &clientout,
                               &clientoutlen);
5382
        if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
5383
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5384
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5385
                             _("Failed SASL step: %d (%s)"),
5386
                             err, sasl_errdetail(saslconn));
5387 5388 5389 5390
            goto cleanup;
        }
        /* Need to gather some credentials from the client */
        if (err == SASL_INTERACT) {
5391
            const char *msg;
5392 5393 5394 5395 5396
            if (cred) {
                remoteAuthFreeCredentials(cred, ncred);
                cred = NULL;
            }
            if ((ncred = remoteAuthMakeCredentials(interact, &cred)) < 0) {
5397
                virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5398
                                 VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5399
                                 "%s", _("Failed to make auth credentials"));
5400 5401 5402
                goto cleanup;
            }
            /* Run the authentication callback */
5403
            if (auth && auth->cb) {
5404 5405 5406
                if ((*(auth->cb))(cred, ncred, auth->cbdata) >= 0) {
                    remoteAuthFillInteract(cred, interact);
                    goto restep;
5407
                }
5408
                msg = "Failed to collect auth credentials";
5409
            } else {
5410
                msg = "No authentication callback available";
5411
            }
5412
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5413
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL,
5414
                             0, 0, "%s", msg);
5415
            goto cleanup;
5416 5417 5418
        }

        if (serverin) {
5419
            VIR_FREE(serverin);
5420
        }
5421
        DEBUG("Client step result %d. Data %d bytes %p", err, clientoutlen, clientout);
5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432

        /* 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;
5433
        DEBUG("Server step with %d bytes %p", clientoutlen, clientout);
5434 5435 5436 5437

        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,
5438 5439
                  (xdrproc_t) xdr_remote_auth_sasl_step_ret, (char *) &pret) != 0)
            goto cleanup;
5440 5441 5442 5443 5444 5445

        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;

5446 5447
        DEBUG("Client step result complete: %d. Data %d bytes %p",
              complete, serverinlen, serverin);
5448 5449 5450

        /* This server call shows complete, and earlier client step was OK */
        if (complete && err == SASL_OK) {
5451
            VIR_FREE(serverin);
5452 5453 5454 5455
            break;
        }
    }

5456 5457 5458 5459
    /* Check for suitable SSF if non-TLS */
    if (!priv->uses_tls) {
        err = sasl_getprop(saslconn, SASL_SSF, &val);
        if (err != SASL_OK) {
5460
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5461
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5462
                             _("cannot query SASL ssf on connection %d (%s)"),
5463
                             err, sasl_errstring(err, NULL, NULL));
5464
            goto cleanup;
5465 5466
        }
        ssf = *(const int *)val;
5467
        DEBUG("SASL SSF value %d", ssf);
5468
        if (ssf < 56) { /* 56 == DES level, good for Kerberos */
5469
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5470
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
5471
                             _("negotiation SSF %d was not strong enough"), ssf);
5472
            goto cleanup;
5473 5474 5475
        }
    }

5476
    DEBUG0("SASL authentication complete");
5477
    priv->saslconn = saslconn;
5478 5479 5480
    ret = 0;

 cleanup:
5481 5482 5483
    VIR_FREE(localAddr);
    VIR_FREE(remoteAddr);
    VIR_FREE(serverin);
5484

5485
    VIR_FREE(saslcb);
5486 5487 5488
    remoteAuthFreeCredentials(cred, ncred);
    if (ret != 0 && saslconn)
        sasl_dispose(&saslconn);
5489

5490
    return ret;
5491 5492 5493
}
#endif /* HAVE_SASL */

5494 5495 5496 5497 5498 5499 5500 5501 5502

#if HAVE_POLKIT
/* Perform the PolicyKit authentication process
 */
static int
remoteAuthPolkit (virConnectPtr conn, struct private_data *priv, int in_open,
                  virConnectAuthPtr auth)
{
    remote_auth_polkit_ret ret;
5503
    int i, allowcb = 0;
5504 5505 5506 5507 5508 5509 5510 5511
    virConnectCredential cred = {
        VIR_CRED_EXTERNAL,
        conn->flags & VIR_CONNECT_RO ? "org.libvirt.unix.monitor" : "org.libvirt.unix.manage",
        "PolicyKit",
        NULL,
        NULL,
        0,
    };
5512
    DEBUG0("Client initialize PolicyKit authentication");
5513

5514
    if (auth && auth->cb) {
5515
        /* Check if the necessary credential type for PolicyKit is supported */
5516 5517 5518 5519
        for (i = 0 ; i < auth->ncredtype ; i++) {
            if (auth->credtype[i] == VIR_CRED_EXTERNAL)
                allowcb = 1;
        }
5520

5521 5522 5523
        if (allowcb) {
            /* Run the authentication callback */
            if ((*(auth->cb))(&cred, 1, auth->cbdata) < 0) {
5524
                virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
5525
                                 VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
J
Jim Meyering 已提交
5526
                                 "%s", _("Failed to collect auth credentials"));
5527 5528
                return -1;
            }
5529
        } else {
5530
            DEBUG0("Client auth callback does not support PolicyKit");
5531 5532
        }
    } else {
5533
        DEBUG0("No auth callback provided");
5534 5535 5536 5537 5538 5539 5540 5541 5542
    }

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

5543
    DEBUG0("PolicyKit authentication complete");
5544 5545 5546
    return 0;
}
#endif /* HAVE_POLKIT */
5547 5548 5549
/*----------------------------------------------------------------------*/

static int remoteDomainEventRegister (virConnectPtr conn,
5550 5551
                                      virConnectDomainEventCallback callback,
                                      void *opaque,
5552
                                      virFreeCallback freecb)
5553
{
5554
    int rv = -1;
5555 5556
    struct private_data *priv = conn->privateData;

5557 5558
    remoteDriverLock(priv);

5559 5560
    if (priv->eventFlushTimer < 0) {
         error (conn, VIR_ERR_NO_SUPPORT, _("no event support"));
5561
         goto done;
5562
    }
5563
    if (virDomainEventCallbackListAdd(conn, priv->callbackList,
5564
                                      callback, opaque, freecb) < 0) {
5565
         error (conn, VIR_ERR_RPC, _("adding cb to list"));
5566
         goto done;
5567 5568 5569 5570 5571 5572 5573
    }

    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)
5574
            goto done;
5575 5576
    }

5577 5578 5579
    rv = 0;

done:
5580
    remoteDriverUnlock(priv);
5581
    return rv;
5582 5583 5584
}

static int remoteDomainEventDeregister (virConnectPtr conn,
5585
                                        virConnectDomainEventCallback callback)
5586 5587
{
    struct private_data *priv = conn->privateData;
5588
    int rv = -1;
5589

5590 5591
    remoteDriverLock(priv);

5592
    if (virDomainEventCallbackListRemove(conn, priv->callbackList,
5593
                                         callback) < 0) {
5594
         error (conn, VIR_ERR_RPC, _("removing cb fron list"));
5595
         goto done;
5596 5597 5598 5599 5600 5601 5602
    }

    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)
5603
            goto done;
5604 5605
    }

5606 5607 5608
    rv = 0;

done:
5609
    remoteDriverUnlock(priv);
5610
    return rv;
5611
}
5612

5613 5614
/*----------------------------------------------------------------------*/

5615

5616 5617 5618 5619 5620 5621 5622 5623
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)
{
5624
    XDR xdr;
5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637
    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;
    }
5638 5639

    /* Get a unique serial number for this message. */
5640 5641 5642 5643
    rv->serial = priv->counter++;
    rv->proc_nr = proc_nr;
    rv->ret_filter = ret_filter;
    rv->ret = ret;
5644 5645 5646 5647 5648

    hdr.prog = REMOTE_PROGRAM;
    hdr.vers = REMOTE_PROTOCOL_VERSION;
    hdr.proc = proc_nr;
    hdr.direction = REMOTE_CALL;
5649
    hdr.serial = rv->serial;
5650 5651 5652
    hdr.status = REMOTE_OK;

    /* Serialise header followed by args. */
5653
    xdrmem_create (&xdr, rv->buffer+4, REMOTE_MESSAGE_MAX, XDR_ENCODE);
5654
    if (!xdr_remote_message_header (&xdr, &hdr)) {
5655
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
5656
               VIR_ERR_RPC, _("xdr_remote_message_header failed"));
5657
        goto error;
5658 5659 5660
    }

    if (!(*args_filter) (&xdr, args)) {
5661 5662
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn, VIR_ERR_RPC,
               _("marshalling args"));
5663
        goto error;
5664 5665 5666
    }

    /* Get the length stored in buffer. */
5667
    rv->bufferLength = xdr_getpos (&xdr);
5668 5669 5670 5671 5672
    xdr_destroy (&xdr);

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

    /* Encode the length word. */
5676 5677
    xdrmem_create (&xdr, rv->buffer, 4, XDR_ENCODE);
    if (!xdr_int (&xdr, (int *)&rv->bufferLength)) {
5678 5679
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn, VIR_ERR_RPC,
               _("xdr_int (length word)"));
5680
        goto error;
5681 5682 5683
    }
    xdr_destroy (&xdr);

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 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947
    return rv;

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



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

            error (in_open ? NULL : conn,
                   VIR_ERR_SYSTEM_ERROR, strerror (errno));
            return -1;

        }
    }

    return ret;
}


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

                errorf (in_open ? NULL : conn,
                        VIR_ERR_SYSTEM_ERROR,
                        _("failed to read from socket %s"),
                        strerror (errno));
            } else {
                errorf (in_open ? NULL : conn,
                        VIR_ERR_SYSTEM_ERROR,
                        "%s", _("server closed connection"));
            }
            return -1;
        }
    }

    return ret;
}


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

        ret = processCallWrite(conn, priv, in_open,
                               priv->saslEncoded + priv->saslEncodedOffset,
                               priv->saslEncodedLength - priv->saslEncodedOffset);
        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;
        ret = processCallWrite(conn, priv, in_open,
                               thecall->buffer + thecall->bufferOffset,
                               thecall->bufferLength - thecall->bufferOffset);
        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
processCallSend(virConnectPtr conn, struct private_data *priv,
                int in_open) {
    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) {
        int ret = processCallSendOne(conn, priv, in_open, thecall);
        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
processCallRecvSome(virConnectPtr conn, struct private_data *priv,
                    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;
            ret = processCallRead(conn, priv, in_open,
                                  encoded, encodedLen);
            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;

        ret = processCallRead(conn, priv, in_open,
                              priv->buffer + priv->bufferOffset,
                              wantData);
        if (ret < 0)
            return -1;
        if (ret == 0)
            return 0;

        priv->bufferOffset += ret;

        return ret;
#if HAVE_SASL
    }
#endif
}
5948 5949


5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979
static void
processCallAsyncEvent(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;
    }

    if (hdr->proc == REMOTE_PROC_DOMAIN_EVENT) {
        remoteDomainQueueEvent(conn, xdr);
        virEventUpdateTimeout(priv->eventFlushTimer, 0);
    } else {
        DEBUG("Unexpected event proc %d", hdr->proc);
    }
}

static int
processCallRecvLen(virConnectPtr conn, struct private_data *priv,
                   int in_open) {
    XDR xdr;
    int len;

    xdrmem_create (&xdr, priv->buffer, priv->bufferLength, XDR_DECODE);
5980
    if (!xdr_int (&xdr, &len)) {
5981
        error (in_open ? NULL : conn,
5982
               VIR_ERR_RPC, _("xdr_int (length word, reply)"));
5983 5984 5985 5986 5987 5988 5989 5990
        return -1;
    }
    xdr_destroy (&xdr);

    /* Length includes length word - adjust to real length to read. */
    len -= 4;

    if (len < 0 || len > REMOTE_MESSAGE_MAX) {
5991
        error (in_open ? NULL : conn,
5992
               VIR_ERR_RPC, _("packet received from server too large"));
5993 5994 5995
        return -1;
    }

5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010
    /* 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
processCallRecvMsg(virConnectPtr conn, struct private_data *priv,
                   int in_open) {
    XDR xdr;
    struct remote_message_header hdr;
    int len = priv->bufferLength - 4;
    struct remote_thread_call *thecall;
6011 6012

    /* Deserialise reply header. */
6013
    xdrmem_create (&xdr, priv->buffer + 4, len, XDR_DECODE);
6014
    if (!xdr_remote_message_header (&xdr, &hdr)) {
6015
        error (in_open ? NULL : conn,
6016
               VIR_ERR_RPC, _("invalid header in reply"));
6017 6018 6019 6020 6021
        return -1;
    }

    /* Check program, version, etc. are what we expect. */
    if (hdr.prog != REMOTE_PROGRAM) {
6022 6023 6024 6025 6026
        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);
6027 6028 6029
        return -1;
    }
    if (hdr.vers != REMOTE_PROTOCOL_VERSION) {
6030 6031 6032 6033 6034
        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);
6035 6036 6037
        return -1;
    }

6038 6039 6040 6041 6042 6043 6044
    /* Async events from server need special handling */
    if (hdr.direction == REMOTE_MESSAGE) {
        processCallAsyncEvent(conn, priv, in_open,
                              &hdr, &xdr);
        xdr_destroy(&xdr);
        return 0;
    }
6045

6046 6047 6048 6049 6050 6051 6052
    if (hdr.direction != REMOTE_REPLY) {
        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);
        xdr_destroy(&xdr);
6053 6054
        return -1;
    }
6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070

    /* Ok, definitely got an RPC reply now find
       out who's been waiting for it */

    thecall = priv->waitDispatch;
    while (thecall &&
           thecall->serial != hdr.serial)
        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"),
                       hdr.serial);
        xdr_destroy(&xdr);
6071 6072
        return -1;
    }
6073 6074 6075 6076 6077 6078 6079 6080

    if (hdr.proc != thecall->proc_nr) {
        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)"),
                       hdr.proc, thecall->proc_nr);
        xdr_destroy (&xdr);
6081 6082 6083 6084 6085 6086 6087 6088 6089
        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).
     */
    switch (hdr.status) {
    case REMOTE_OK:
6090 6091
        if (!(*thecall->ret_filter) (&xdr, thecall->ret)) {
            error (in_open ? NULL : conn, VIR_ERR_RPC,
6092
                   _("unmarshalling ret"));
6093 6094
            return -1;
        }
6095
        thecall->mode = REMOTE_MODE_COMPLETE;
6096 6097 6098 6099
        xdr_destroy (&xdr);
        return 0;

    case REMOTE_ERROR:
6100 6101 6102
        memset (&thecall->err, 0, sizeof thecall->err);
        if (!xdr_remote_error (&xdr, &thecall->err)) {
            error (in_open ? NULL : conn,
6103
                   VIR_ERR_RPC, _("unmarshalling remote_error"));
6104 6105 6106
            return -1;
        }
        xdr_destroy (&xdr);
6107 6108
        thecall->mode = REMOTE_MODE_ERROR;
        return 0;
6109 6110

    default:
6111 6112 6113 6114
        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)"),
                       hdr.status);
6115 6116 6117 6118 6119
        xdr_destroy (&xdr);
        return -1;
    }
}

6120 6121

static int
6122 6123 6124 6125 6126 6127
processCallRecv(virConnectPtr conn, struct private_data *priv,
                int in_open) {
    int ret;

    /* Read as much data as is available, until we get
     * EGAIN
6128
     */
6129 6130
    for (;;) {
        ret = processCallRecvSome(conn, priv, in_open);
6131

6132 6133 6134 6135
        if (ret < 0)
            return -1;
        if (ret == 0)
            return 0;  /* Blocking on read */
6136

6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148
        /* Check for completion of our goal */
        if (priv->bufferOffset == priv->bufferLength) {
            if (priv->bufferOffset == 4) {
                ret = processCallRecvLen(conn, priv, in_open);
            } else {
                ret = processCallRecvMsg(conn, priv, in_open);
                priv->bufferOffset = priv->bufferLength = 0;
            }
            if (ret < 0)
                return -1;
        }
    }
6149 6150
}

6151 6152 6153 6154 6155
/*
 * Process all calls pending dispatch/receive until we
 * get a reply to our own call. Then quit and pass the buck
 * to someone else.
 */
6156
static int
6157 6158 6159 6160
processCalls(virConnectPtr conn,
             struct private_data *priv,
             int in_open,
             struct remote_thread_call *thiscall)
6161
{
6162 6163
    struct pollfd fds[2];
    int ret;
6164

6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210
    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;
            errorf (in_open ? NULL : conn, VIR_ERR_INTERNAL_ERROR,
                    _("poll on socket failed %s"), strerror(errno));
            return -1;
        }

        if (fds[0].revents & POLLOUT) {
            if (processCallSend(conn, priv, in_open) < 0)
6211 6212
                return -1;
        }
6213 6214 6215

        if (fds[0].revents & POLLIN) {
            if (processCallRecv(conn, priv, in_open) < 0)
6216
                return -1;
6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240
        }

        /* 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);
6241
            }
6242 6243
            prev = tmp;
            tmp = tmp->next;
6244 6245
        }

6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261
        /* 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;
        }
6262

6263 6264 6265 6266 6267 6268 6269

        if (fds[0].revents & (POLLHUP | POLLERR)) {
            errorf(in_open ? NULL : conn, VIR_ERR_INTERNAL_ERROR,
                   "%s", _("received hangup / error event on socket"));
            return -1;
        }
    }
6270 6271
}

6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304
/*
 * This function performs a remote procedure call to procedure PROC_NR.
 *
 * 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!
 */
6305
static int
6306 6307 6308 6309 6310
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)
6311
{
6312 6313
    int rv;
    struct remote_thread_call *thiscall;
6314

6315 6316 6317 6318 6319 6320 6321 6322
    DEBUG("Doing call %d %p", proc_nr, priv->waitDispatch);
    thiscall = prepareCall(conn, priv, flags, proc_nr,
                           args_filter, args,
                           ret_filter, ret);

    if (!thiscall) {
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
               VIR_ERR_NO_MEMORY, NULL);
6323 6324 6325
        return -1;
    }

6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336
    /* 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;
6337

6338 6339
        /* Force other thread to wakup from poll */
        safewrite(priv->wakeupSendFD, &ignore, sizeof(ignore));
6340

6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358
        DEBUG("Going to sleep %d %p %p", proc_nr, priv->waitDispatch, thiscall);
        /* 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);
6359
            return -1;
6360
        }
6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376

        DEBUG("Wokeup from sleep %d %p %p", proc_nr, priv->waitDispatch, thiscall);
        /* 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;
6377
        }
6378 6379 6380

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

6381
    } else {
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
        /* We're first to catch the buck */
        priv->waitDispatch = thiscall;
    }

    DEBUG("We have the buck %d %p %p", proc_nr, priv->waitDispatch, thiscall);
    /*
     * 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);

    rv = processCalls(conn, priv,
                      flags & REMOTE_CALL_IN_OPEN ? 1 : 0,
                      thiscall);

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

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

cleanup:
    DEBUG("All done with our call %d %p %p", proc_nr, priv->waitDispatch, thiscall);
    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 &&
            STRPREFIX(*thiscall->err.message, "unknown procedure")) {
            rv = -2;
        } else {
            server_error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
                          &thiscall->err);
            rv = -1;
6431
        }
6432 6433
    } else {
        rv = 0;
6434
    }
6435 6436 6437
    VIR_FREE(thiscall);
    return rv;
}
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
/**
 * remoteDomainReadEvent
 *
 * Read the event data off the wire
 */
static virDomainEventPtr
remoteDomainReadEvent(virConnectPtr conn, XDR *xdr)
{
    remote_domain_event_ret ret;
    virDomainPtr dom;
    virDomainEventPtr event = NULL;
    memset (&ret, 0, sizeof ret);

    /* unmarshall parameters, and process it*/
    if (! xdr_remote_domain_event_ret(xdr, &ret) ) {
        error (conn, VIR_ERR_RPC,
               _("remoteDomainProcessEvent: unmarshalling ret"));
        return NULL;
    }

    dom = get_nonnull_domain(conn,ret.dom);
    if (!dom)
        return NULL;

    event = virDomainEventNewFromDom(dom, ret.event, ret.detail);

    virDomainFree(dom);
    return event;
6467 6468
}

6469 6470
static void
remoteDomainQueueEvent(virConnectPtr conn, XDR *xdr)
6471
{
6472 6473
    struct private_data *priv = conn->privateData;
    virDomainEventPtr event;
6474

6475 6476 6477
    event = remoteDomainReadEvent(conn, xdr);
    if (!event)
        return;
6478

6479 6480 6481 6482 6483
    if (virDomainEventQueuePush(priv->domainEvents,
                                event) < 0) {
        DEBUG0("Error adding event to queue");
        virDomainEventFree(event);
    }
6484 6485
}

6486 6487 6488 6489 6490 6491 6492 6493 6494 6495
/** remoteDomainEventFired:
 *
 * The callback for monitoring the remote socket
 * for event data
 */
void
remoteDomainEventFired(int watch,
                       int fd,
                       int event,
                       void *opaque)
6496
{
6497 6498
    virConnectPtr        conn = opaque;
    struct private_data *priv = conn->privateData;
6499

6500
    remoteDriverLock(priv);
6501

6502 6503 6504
    /* This should be impossible, but it doesn't hurt to check */
    if (priv->waitDispatch)
        goto done;
6505

6506
    DEBUG("Event fired %d %d %d %X", watch, fd, event, event);
6507

6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526
    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;
    }

    if (processCallRecv(conn, priv, 0) < 0)
        DEBUG0("Something went wrong during async message processing");

done:
    remoteDriverUnlock(priv);
6527 6528
}

6529 6530
void
remoteDomainEventQueueFlush(int timer ATTRIBUTE_UNUSED, void *opaque)
6531
{
6532 6533 6534 6535 6536 6537 6538 6539 6540 6541
    virConnectPtr conn = opaque;
    struct private_data *priv = conn->privateData;

    remoteDriverLock(priv);

    virDomainEventQueueDispatch(priv->domainEvents, priv->callbackList,
                                virDomainEventDispatchDefaultFunc, NULL);
    virEventUpdateTimeout(priv->eventFlushTimer, -1);

    remoteDriverUnlock(priv);
6542 6543
}

6544

6545 6546 6547 6548 6549 6550
/* For errors internal to this library. */
static void
error (virConnectPtr conn, virErrorNumber code, const char *info)
{
    const char *errmsg;

6551 6552
    errmsg = virErrorMsg (code, info);
    virRaiseError (conn, NULL, NULL, VIR_FROM_REMOTE,
6553 6554 6555 6556
                     code, VIR_ERR_ERROR, errmsg, info, NULL, 0, 0,
                     errmsg, info);
}

6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573
/* For errors internal to this library.
   Identical to the above, but with a format string and optional params.  */
static void
errorf (virConnectPtr conn, virErrorNumber code, const char *fmt, ...)
{
    const char *errmsg;
    va_list args;
    char errorMessage[256];

    if (fmt) {
        va_start(args, fmt);
        vsnprintf(errorMessage, sizeof errorMessage - 1, fmt, args);
        va_end(args);
    } else {
        errorMessage[0] = '\0';
    }

6574 6575
    errmsg = virErrorMsg (code, errorMessage);
    virRaiseError (conn, NULL, NULL, VIR_FROM_REMOTE,
6576 6577 6578
                     code, VIR_ERR_ERROR,
                     errmsg, errorMessage, NULL, -1, -1,
                     errmsg, errorMessage);
6579 6580
}

6581 6582 6583 6584 6585 6586 6587
/* For errors generated on the server side and sent back to us. */
static void
server_error (virConnectPtr conn, remote_error *err)
{
    virDomainPtr dom;
    virNetworkPtr net;

6588
    /* Get the domain and network, if set. */
6589 6590 6591
    dom = err->dom ? get_nonnull_domain (conn, *err->dom) : NULL;
    net = err->net ? get_nonnull_network (conn, *err->net) : NULL;

6592
    virRaiseError (conn, dom, net,
6593
                     err->domain, err->code, err->level,
D
Daniel P. Berrange 已提交
6594 6595 6596
                     err->str1 ? *err->str1 : NULL,
                     err->str2 ? *err->str2 : NULL,
                     err->str3 ? *err->str3 : NULL,
6597
                     err->int1, err->int2,
D
Daniel P. Berrange 已提交
6598
                     "%s", err->message ? *err->message : NULL);
6599 6600 6601 6602
    if (dom)
        virDomainFree(dom);
    if (net)
        virNetworkFree(net);
6603 6604 6605 6606
}

/* get_nonnull_domain and get_nonnull_network turn an on-wire
 * (name, uuid) pair into virDomainPtr or virNetworkPtr object.
6607
 * These can return NULL if underlying memory allocations fail,
6608
 * but if they do then virterror_internal.has been set.
6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624
 */
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);
}

6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636
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);
}

6637 6638 6639 6640 6641 6642
static virNodeDevicePtr
get_nonnull_node_device (virConnectPtr conn, remote_nonnull_node_device dev)
{
    return virGetNodeDevice(conn, dev.name);
}

6643 6644 6645 6646
/* Make remote_nonnull_domain and remote_nonnull_network. */
static void
make_nonnull_domain (remote_nonnull_domain *dom_dst, virDomainPtr dom_src)
{
6647
    dom_dst->id = dom_src->id;
6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658
    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);
}

6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673
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;
}

6674 6675
/*----------------------------------------------------------------------*/

6676 6677 6678 6679 6680
unsigned long remoteVersion(void)
{
    return REMOTE_PROTOCOL_VERSION;
}

6681 6682 6683 6684 6685
static virDriver driver = {
    .no = VIR_DRV_REMOTE,
    .name = "remote",
    .open = remoteOpen,
    .close = remoteClose,
6686
    .supports_feature = remoteSupportsFeature,
6687
        .type = remoteType,
6688
        .version = remoteGetVersion,
6689
    .getHostname = remoteGetHostname,
6690 6691
        .getMaxVcpus = remoteGetMaxVcpus,
        .nodeGetInfo = remoteNodeGetInfo,
6692 6693 6694
    .getCapabilities = remoteGetCapabilities,
    .listDomains = remoteListDomains,
    .numOfDomains = remoteNumOfDomains,
6695
    .domainCreateXML = remoteDomainCreateXML,
6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725
    .domainLookupByID = remoteDomainLookupByID,
    .domainLookupByUUID = remoteDomainLookupByUUID,
    .domainLookupByName = remoteDomainLookupByName,
    .domainSuspend = remoteDomainSuspend,
    .domainResume = remoteDomainResume,
    .domainShutdown = remoteDomainShutdown,
    .domainReboot = remoteDomainReboot,
    .domainDestroy = remoteDomainDestroy,
    .domainGetOSType = remoteDomainGetOSType,
    .domainGetMaxMemory = remoteDomainGetMaxMemory,
    .domainSetMaxMemory = remoteDomainSetMaxMemory,
    .domainSetMemory = remoteDomainSetMemory,
    .domainGetInfo = remoteDomainGetInfo,
    .domainSave = remoteDomainSave,
    .domainRestore = remoteDomainRestore,
    .domainCoreDump = remoteDomainCoreDump,
    .domainSetVcpus = remoteDomainSetVcpus,
    .domainPinVcpu = remoteDomainPinVcpu,
    .domainGetVcpus = remoteDomainGetVcpus,
    .domainGetMaxVcpus = remoteDomainGetMaxVcpus,
    .domainDumpXML = remoteDomainDumpXML,
    .listDefinedDomains = remoteListDefinedDomains,
    .numOfDefinedDomains = remoteNumOfDefinedDomains,
    .domainCreate = remoteDomainCreate,
    .domainDefineXML = remoteDomainDefineXML,
    .domainUndefine = remoteDomainUndefine,
    .domainAttachDevice = remoteDomainAttachDevice,
    .domainDetachDevice = remoteDomainDetachDevice,
    .domainGetAutostart = remoteDomainGetAutostart,
    .domainSetAutostart = remoteDomainSetAutostart,
6726 6727 6728
    .domainGetSchedulerType = remoteDomainGetSchedulerType,
    .domainGetSchedulerParameters = remoteDomainGetSchedulerParameters,
    .domainSetSchedulerParameters = remoteDomainSetSchedulerParameters,
6729 6730 6731
    .domainMigratePrepare = remoteDomainMigratePrepare,
    .domainMigratePerform = remoteDomainMigratePerform,
    .domainMigrateFinish = remoteDomainMigrateFinish,
6732 6733
    .domainBlockStats = remoteDomainBlockStats,
    .domainInterfaceStats = remoteDomainInterfaceStats,
6734
    .domainBlockPeek = remoteDomainBlockPeek,
R
Richard W.M. Jones 已提交
6735
    .domainMemoryPeek = remoteDomainMemoryPeek,
6736 6737
    .nodeGetCellsFreeMemory = remoteNodeGetCellsFreeMemory,
    .getFreeMemory = remoteNodeGetFreeMemory,
6738 6739
    .domainEventRegister = remoteDomainEventRegister,
    .domainEventDeregister = remoteDomainEventDeregister,
D
Daniel Veillard 已提交
6740 6741
    .domainMigratePrepare2 = remoteDomainMigratePrepare2,
    .domainMigrateFinish2 = remoteDomainMigrateFinish2,
6742 6743 6744
};

static virNetworkDriver network_driver = {
6745
    .name = "remote",
6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764
    .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,
};

6765 6766 6767 6768 6769 6770 6771 6772
static virStorageDriver storage_driver = {
    .name = "remote",
    .open = remoteStorageOpen,
    .close = remoteStorageClose,
    .numOfPools = remoteNumOfStoragePools,
    .listPools = remoteListStoragePools,
    .numOfDefinedPools = remoteNumOfDefinedStoragePools,
    .listDefinedPools = remoteListDefinedStoragePools,
6773
    .findPoolSources = remoteFindStoragePoolSources,
6774
    .poolLookupByName = remoteStoragePoolLookupByName,
6775
    .poolLookupByUUID = remoteStoragePoolLookupByUUID,
6776 6777 6778
    .poolLookupByVolume = remoteStoragePoolLookupByVolume,
    .poolCreateXML = remoteStoragePoolCreateXML,
    .poolDefineXML = remoteStoragePoolDefineXML,
6779
    .poolBuild = remoteStoragePoolBuild,
6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801
    .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,
    .volDelete = remoteStorageVolDelete,
    .volGetInfo = remoteStorageVolGetInfo,
    .volGetXMLDesc = remoteStorageVolDumpXML,
    .volGetPath = remoteStorageVolGetPath,
};

6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815
static virDeviceMonitor dev_monitor = {
    .name = "remote",
    .open = remoteDevMonOpen,
    .close = remoteDevMonClose,
    .numOfDevices = remoteNodeNumOfDevices,
    .listDevices = remoteNodeListDevices,
    .deviceLookupByName = remoteNodeDeviceLookupByName,
    .deviceDumpXML = remoteNodeDeviceDumpXML,
    .deviceGetParent = remoteNodeDeviceGetParent,
    .deviceNumOfCaps = remoteNodeDeviceNumOfCaps,
    .deviceListCaps = remoteNodeDeviceListCaps,
};


A
Atsushi SAKAI 已提交
6816
#ifdef WITH_LIBVIRTD
6817
static virStateDriver state_driver = {
6818
    .initialize = remoteStartup,
6819
};
A
Atsushi SAKAI 已提交
6820
#endif
6821 6822


6823
/** remoteRegister:
6824 6825
 *
 * Register driver with libvirt driver system.
6826 6827
 *
 * Returns -1 on error.
6828 6829 6830 6831 6832 6833
 */
int
remoteRegister (void)
{
    if (virRegisterDriver (&driver) == -1) return -1;
    if (virRegisterNetworkDriver (&network_driver) == -1) return -1;
6834
    if (virRegisterStorageDriver (&storage_driver) == -1) return -1;
6835
    if (virRegisterDeviceMonitor (&dev_monitor) == -1) return -1;
A
Atsushi SAKAI 已提交
6836
#ifdef WITH_LIBVIRTD
6837
    if (virRegisterStateDriver (&state_driver) == -1) return -1;
A
Atsushi SAKAI 已提交
6838
#endif
6839 6840 6841

    return 0;
}
6842