remote_driver.c 220.3 KB
Newer Older
1 2 3 4
/*
 * remote_internal.c: driver to provide access to libvirtd running
 *   on a remote machine
 *
E
Eric Blake 已提交
5
 * Copyright (C) 2007-2011 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 27 28
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
29
#include <string.h>
30 31 32
#include <assert.h>
#include <signal.h>
#include <sys/types.h>
33 34
#include <sys/stat.h>
#include <fcntl.h>
35
#include <arpa/inet.h>
E
Eric Blake 已提交
36
#include <sys/wait.h>
37

38 39 40 41 42
/* Windows socket compatibility functions. */
#include <errno.h>
#include <sys/socket.h>

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

49
#ifdef HAVE_PWD_H
50
# include <pwd.h>
51 52 53
#endif

#ifdef HAVE_PATHS_H
54
# include <paths.h>
55 56
#endif

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

J
Jim Meyering 已提交
67
#include <netdb.h>
68

69 70
#include <poll.h>

71
#include "virterror_internal.h"
72
#include "logging.h"
73
#include "datatypes.h"
74
#include "domain_event.h"
75
#include "driver.h"
76 77
#include "buf.h"
#include "qparams.h"
78
#include "remote_driver.h"
79
#include "remote_protocol.h"
C
Chris Lalancette 已提交
80
#include "qemu_protocol.h"
81
#include "memory.h"
82
#include "util.h"
83
#include "event.h"
84
#include "ignore-value.h"
85
#include "files.h"
86
#include "command.h"
87

88 89
#define VIR_FROM_THIS VIR_FROM_REMOTE

90 91
static int inside_daemon = 0;

92 93 94 95 96 97 98 99 100 101 102 103 104
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;

105 106
    /* Buffer for outgoing data packet
     * 4 byte length, followed by RPC message header+body */
107 108 109 110 111 112 113 114 115
    char buffer[4 + REMOTE_MESSAGE_MAX];
    unsigned int bufferLength;
    unsigned int bufferOffset;

    unsigned int serial;
    unsigned int proc_nr;

    virCond cond;

116
    int want_reply;
117 118 119 120 121 122 123 124
    xdrproc_t ret_filter;
    char *ret;

    remote_error err;

    struct remote_thread_call *next;
};

125 126 127 128 129 130 131
struct private_stream_data {
    unsigned int has_error : 1;
    remote_error err;

    unsigned int serial;
    unsigned int proc_nr;

132 133 134 135 136 137 138
    virStreamEventCallback cb;
    void *cbOpaque;
    virFreeCallback cbFree;
    int cbEvents;
    int cbTimer;
    int cbDispatch;

139 140 141 142 143 144 145 146 147 148 149 150 151
    /* XXX this is potentially unbounded if the client
     * app has domain events registered, since packets
     * may be read off wire, while app isn't ready to
     * recv them. Figure out how to address this some
     * time....
     */
    char *incoming;
    unsigned int incomingOffset;
    unsigned int incomingLength;

    struct private_stream_data *next;
};

152
struct private_data {
153 154
    virMutex lock;

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

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

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

    const char *saslEncoded;
    unsigned int saslEncodedLength;
    unsigned int saslEncodedOffset;
178 179

    char saslTemporary[8192]; /* temorary holds data to be decoded */
180
#endif
181

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

188
    virDomainEventStatePtr domainEventState;
189 190 191 192 193 194 195

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

    /* List of threads currently waiting for dispatch */
    struct remote_thread_call *waitDispatch;
196 197

    struct private_stream_data *streams;
198 199
};

200
enum {
201
    REMOTE_CALL_IN_OPEN           = (1 << 0),
C
Chris Lalancette 已提交
202
    REMOTE_CALL_QUIET_MISSING_RPC = (1 << 1),
203 204
    REMOTE_CALL_QEMU              = (1 << 2),
    REMOTE_CALL_NONBLOCK          = (1 << 3),
205 206 207
};


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

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

218 219 220 221
static int remoteIO(virConnectPtr conn,
                    struct private_data *priv,
                    int flags,
                    struct remote_thread_call *thiscall);
222 223 224 225
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);
226 227
static int remoteAuthenticate (virConnectPtr conn, struct private_data *priv, int in_open,
                               virConnectAuthPtr auth, const char *authtype);
228
#if HAVE_SASL
229 230
static int remoteAuthSASL (virConnectPtr conn, struct private_data *priv, int in_open,
                           virConnectAuthPtr auth, const char *mech);
231
#endif
232
#if HAVE_POLKIT
233 234
static int remoteAuthPolkit (virConnectPtr conn, struct private_data *priv, int in_open,
                             virConnectAuthPtr auth);
235
#endif /* HAVE_POLKIT */
236 237

#define remoteError(code, ...)                                    \
238
    virReportErrorHelper(VIR_FROM_REMOTE, code, __FILE__,         \
239
                         __FUNCTION__, __LINE__, __VA_ARGS__)
240

241 242
static virDomainPtr get_nonnull_domain (virConnectPtr conn, remote_nonnull_domain domain);
static virNetworkPtr get_nonnull_network (virConnectPtr conn, remote_nonnull_network network);
243
static virNWFilterPtr get_nonnull_nwfilter (virConnectPtr conn, remote_nonnull_nwfilter nwfilter);
244
static virInterfacePtr get_nonnull_interface (virConnectPtr conn, remote_nonnull_interface iface);
245 246
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);
247
static virNodeDevicePtr get_nonnull_node_device (virConnectPtr conn, remote_nonnull_node_device dev);
248
static virSecretPtr get_nonnull_secret (virConnectPtr conn, remote_nonnull_secret secret);
C
Chris Lalancette 已提交
249
static virDomainSnapshotPtr get_nonnull_domain_snapshot (virDomainPtr domain, remote_nonnull_domain_snapshot snapshot);
250 251
static void make_nonnull_domain (remote_nonnull_domain *dom_dst, virDomainPtr dom_src);
static void make_nonnull_network (remote_nonnull_network *net_dst, virNetworkPtr net_src);
D
Daniel Veillard 已提交
252
static void make_nonnull_interface (remote_nonnull_interface *interface_dst, virInterfacePtr interface_src);
253 254
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);
255
static void make_nonnull_secret (remote_nonnull_secret *secret_dst, virSecretPtr secret_src);
256
static void make_nonnull_nwfilter (remote_nonnull_nwfilter *nwfilter_dst, virNWFilterPtr nwfilter_src);
C
Chris Lalancette 已提交
257
static void make_nonnull_domain_snapshot (remote_nonnull_domain_snapshot *snapshot_dst, virDomainSnapshotPtr snapshot_src);
258
void remoteDomainEventFired(int watch, int fd, int event, void *data);
259
void remoteDomainEventQueueFlush(int timer, void *opaque);
260
void remoteDomainEventQueue(struct private_data *priv, virDomainEventPtr event);
261 262 263 264 265 266
/*----------------------------------------------------------------------*/

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

/* GnuTLS functions used by remoteOpen. */
267
static int initialize_gnutls(char *pkipath, int flags);
268
static gnutls_session_t negotiate_gnutls_on_connection (virConnectPtr conn, struct private_data *priv, int no_verify);
269

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

282
#ifndef WIN32
283 284 285 286
/**
 * remoteFindServerPath:
 *
 * Tries to find the path to the libvirtd binary.
287
 *
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
 * 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++) {
E
Eric Blake 已提交
305
        if (virFileIsExecutable(serverPaths[i])) {
306 307 308 309 310 311 312 313 314 315 316 317 318
            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.
 */
319
static int
320
remoteForkDaemon(void)
321 322
{
    const char *daemonPath = remoteFindDaemonPath();
323 324
    virCommandPtr cmd = NULL;
    int ret;
325 326

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

332 333 334
    cmd = virCommandNewArgList(daemonPath, "--timeout", "30", NULL);
    virCommandClearCaps(cmd);
    virCommandDaemonize(cmd);
335

336 337 338 339
    ret = virCommandRun(cmd, NULL);
    virCommandFree(cmd);

    return ret;
340
}
341
#endif
342

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

349

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

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

387 388 389
    if (conn->uri) {
        if (!conn->uri->scheme) {
            /* This is the ///var/lib/xen/xend-socket local path style */
390
            transport = trans_unix;
391 392
        } else {
            transport_str = get_transport_from_scheme (conn->uri->scheme);
393

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
            if (!transport_str) {
                if (conn->uri->server)
                    transport = trans_tls;
                else
                    transport = trans_unix;
            } else {
                if (STRCASEEQ (transport_str, "tls"))
                    transport = trans_tls;
                else if (STRCASEEQ (transport_str, "unix"))
                    transport = trans_unix;
                else if (STRCASEEQ (transport_str, "ssh"))
                    transport = trans_ssh;
                else if (STRCASEEQ (transport_str, "ext"))
                    transport = trans_ext;
                else if (STRCASEEQ (transport_str, "tcp"))
                    transport = trans_tcp;
                else {
411 412 413
                    remoteError(VIR_ERR_INVALID_ARG, "%s",
                                _("remote_open: transport in URL not recognised "
                                  "(should be tls|unix|ssh|ext|tcp)"));
414 415 416 417 418 419 420
                    return VIR_DRV_OPEN_ERROR;
                }
            }
        }
    } else {
        /* No URI, then must be probing so use UNIX socket */
        transport = trans_unix;
421
    }
422

E
Eric Blake 已提交
423
    /* Local variables which we will initialize. These can
424 425
     * get freed in the failed: path.
     */
426 427
    char *name = NULL, *command = NULL, *sockname = NULL, *netcat = NULL;
    char *port = NULL, *authtype = NULL, *username = NULL;
428
    int no_verify = 0, no_tty = 0;
429
    char *pkipath = NULL;
430
    virCommandPtr cmd = NULL;
431

432 433 434
    /* Return code from this function, and the private data. */
    int retcode = VIR_DRV_OPEN_ERROR;

435
    /* Remote server defaults to "localhost" if not specified. */
436
    if (conn->uri && conn->uri->port != 0) {
437
        if (virAsprintf(&port, "%d", conn->uri->port) == -1) goto out_of_memory;
438 439 440 441 442 443 444
    } 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
445
        port = NULL; /* Port not used for unix, ext., default for ssh */
446

447

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

458 459 460 461 462
    /* 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).
     */
463 464
    struct qparam *var;
    int i;
465 466
    char *query;

467
    if (conn->uri) {
468
#ifdef HAVE_XMLURI_QUERY_RAW
469
        query = conn->uri->query_raw;
470
#else
471
        query = conn->uri->query;
472
#endif
473 474 475 476 477 478
        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")) {
P
Phil Petty 已提交
479
                VIR_FREE(name);
480 481 482 483
                name = strdup (var->value);
                if (!name) goto out_of_memory;
                var->ignore = 1;
            } else if (STRCASEEQ (var->name, "command")) {
P
Phil Petty 已提交
484
                VIR_FREE(command);
485 486 487 488
                command = strdup (var->value);
                if (!command) goto out_of_memory;
                var->ignore = 1;
            } else if (STRCASEEQ (var->name, "socket")) {
P
Phil Petty 已提交
489
                VIR_FREE(sockname);
490 491 492 493
                sockname = strdup (var->value);
                if (!sockname) goto out_of_memory;
                var->ignore = 1;
            } else if (STRCASEEQ (var->name, "auth")) {
P
Phil Petty 已提交
494
                VIR_FREE(authtype);
495 496 497 498
                authtype = strdup (var->value);
                if (!authtype) goto out_of_memory;
                var->ignore = 1;
            } else if (STRCASEEQ (var->name, "netcat")) {
P
Phil Petty 已提交
499
                VIR_FREE(netcat);
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
                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;
515
            } else if (STRCASEEQ(var->name, "pkipath")) {
P
Phil Petty 已提交
516
                VIR_FREE(pkipath);
517 518 519 520
                pkipath = strdup(var->value);
                if (!pkipath) goto out_of_memory;
                var->ignore = 1;
            } else {
521
                VIR_DEBUG("passing through variable '%s' ('%s') to remote end",
522
                      var->name, var->value);
523
            }
524
        }
525

526 527
        /* Construct the original name. */
        if (!name) {
528 529 530
            if (conn->uri->scheme &&
                (STREQ(conn->uri->scheme, "remote") ||
                 STRPREFIX(conn->uri->scheme, "remote+"))) {
531 532 533 534 535
                /* Allow remote serve to probe */
                name = strdup("");
            } else {
                xmlURI tmpuri = {
                    .scheme = conn->uri->scheme,
536
#ifdef HAVE_XMLURI_QUERY_RAW
537
                    .query_raw = qparam_get_query (vars),
538
#else
539
                    .query = qparam_get_query (vars),
540
#endif
541 542 543 544 545 546 547 548 549
                    .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';
                }
550

551
                name = (char *) xmlSaveUri (&tmpuri);
552

553 554 555 556 557 558 559 560 561 562
#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] = '+';
            }
563 564
        }

565
        free_qparam_set (vars);
566
        vars = NULL;
567 568 569 570
    } else {
        /* Probe URI server side */
        name = strdup("");
    }
571

572
    if (!name) {
573
        virReportOOMError();
574
        goto failed;
575 576
    }

577
    VIR_DEBUG("proceeding with name = %s", name);
578

579 580
    /* For ext transport, command is required. */
    if (transport == trans_ext && !command) {
581 582
        remoteError(VIR_ERR_INVALID_ARG, "%s",
                    _("remote_open: for 'ext' transport, command is required"));
583 584 585
        goto failed;
    }

586 587 588
    /* Connect to the remote service. */
    switch (transport) {
    case trans_tls:
589
        if (initialize_gnutls(pkipath, flags) == -1) goto failed;
590
        priv->uses_tls = 1;
591
        priv->is_secure = 1;
592 593 594

        /*FALLTHROUGH*/
    case trans_tcp: {
595
        /* http://people.redhat.com/drepper/userapi-ipv6.html */
596 597
        struct addrinfo *res, *r;
        struct addrinfo hints;
598
        int saved_errno = EINVAL;
599 600 601
        memset (&hints, 0, sizeof hints);
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_flags = AI_ADDRCONFIG;
602
        int e = getaddrinfo (priv->hostname, port, &hints, &res);
603
        if (e != 0) {
604 605 606
            remoteError(VIR_ERR_SYSTEM_ERROR,
                        _("unable to resolve hostname '%s': %s"),
                        priv->hostname, gai_strerror (e));
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
            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;

624 625
            priv->sock = socket (r->ai_family, SOCK_STREAM, 0);
            if (priv->sock == -1) {
J
Jim Meyering 已提交
626
                saved_errno = errno;
627 628 629 630
                continue;
            }

            /* Disable Nagle - Dan Berrange. */
631
            setsockopt (priv->sock,
632 633 634
                        IPPROTO_TCP, TCP_NODELAY, (void *)&no_slow_start,
                        sizeof no_slow_start);

635
            if (connect (priv->sock, r->ai_addr, r->ai_addrlen) == -1) {
J
Jim Meyering 已提交
636
                saved_errno = errno;
637
                VIR_FORCE_CLOSE(priv->sock);
638 639 640
                continue;
            }

641 642
            if (priv->uses_tls) {
                priv->session =
643
                    negotiate_gnutls_on_connection
644
                      (conn, priv, no_verify);
645
                if (!priv->session) {
646
                    VIR_FORCE_CLOSE(priv->sock);
647
                    goto failed;
648 649 650 651 652 653
                }
            }
            goto tcp_connected;
        }

        freeaddrinfo (res);
654
        virReportSystemError(saved_errno,
655
                             _("unable to connect to libvirtd at '%s'"),
656
                             priv->hostname);
657 658 659 660 661
        goto failed;

       tcp_connected:
        freeaddrinfo (res);

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

667
#ifndef WIN32
668 669
    case trans_unix: {
        if (!sockname) {
670
            if (flags & VIR_DRV_OPEN_REMOTE_USER) {
671
                char *userdir = virGetUserDirectory(getuid());
672

673
                if (!userdir)
674
                    goto failed;
675

676 677
                if (virAsprintf(&sockname, "@%s" LIBVIRTD_USER_UNIX_SOCKET, userdir) < 0) {
                    VIR_FREE(userdir);
678
                    goto out_of_memory;
679 680
                }
                VIR_FREE(userdir);
681
            } else {
682
                if (flags & VIR_DRV_OPEN_REMOTE_RO)
683 684 685
                    sockname = strdup (LIBVIRTD_PRIV_UNIX_SOCKET_RO);
                else
                    sockname = strdup (LIBVIRTD_PRIV_UNIX_SOCKET);
686 687
                if (sockname == NULL)
                    goto out_of_memory;
688
            }
689 690
        }

691 692 693
# ifndef UNIX_PATH_MAX
#  define UNIX_PATH_MAX(addr) (sizeof (addr).sun_path)
# endif
694
        struct sockaddr_un addr;
695 696
        int trials = 0;

697 698
        memset (&addr, 0, sizeof addr);
        addr.sun_family = AF_UNIX;
C
Chris Lalancette 已提交
699
        if (virStrcpyStatic(addr.sun_path, sockname) == NULL) {
700 701
            remoteError(VIR_ERR_INTERNAL_ERROR,
                        _("Socket %s too big for destination"), sockname);
C
Chris Lalancette 已提交
702 703
            goto failed;
        }
704 705
        if (addr.sun_path[0] == '@')
            addr.sun_path[0] = '\0';
706

707
      autostart_retry:
708
        priv->is_secure = 1;
709 710
        priv->sock = socket (AF_UNIX, SOCK_STREAM, 0);
        if (priv->sock == -1) {
711
            virReportSystemError(errno, "%s",
712
                                 _("unable to create socket"));
713 714
            goto failed;
        }
715 716 717 718 719 720 721 722 723 724
        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 &&
725
                trials < 20) {
726
                VIR_FORCE_CLOSE(priv->sock);
727
                if (trials > 0 ||
728
                    remoteForkDaemon() == 0) {
729
                    trials++;
730
                    usleep(1000 * 100 * trials);
731 732 733
                    goto autostart_retry;
                }
            }
734
            virReportSystemError(errno,
735 736
              _("unable to connect to '%s', libvirtd may need to be started"),
              sockname);
737 738 739 740 741 742 743
            goto failed;
        }

        break;
    }

    case trans_ssh: {
744
        cmd = virCommandNew(command ? command : "ssh");
745

746
        /* Generate the final command argv[] array.
747
         *   ssh [-p $port] [-l $username] $hostname $netcat -U $sockname */
J
Jim Meyering 已提交
748

749
        if (port) {
750
            virCommandAddArgList(cmd, "-p", port, NULL);
751
        }
752
        if (username) {
753
            virCommandAddArgList(cmd, "-l", username, NULL);
754
        }
755
        if (no_tty) {
756 757
            virCommandAddArgList(cmd, "-T", "-o", "BatchMode=yes", "-e",
                                 "none", NULL);
758
        }
759 760 761 762 763
        virCommandAddArgList(cmd, priv->hostname, netcat ? netcat : "nc",
                             "-U", (sockname ? sockname :
                                    (flags & VIR_CONNECT_RO
                                     ? LIBVIRTD_PRIV_UNIX_SOCKET_RO
                                     : LIBVIRTD_PRIV_UNIX_SOCKET)), NULL);
764 765

        priv->is_secure = 1;
766 767 768 769
    }

        /*FALLTHROUGH*/
    case trans_ext: {
770
        pid_t pid;
771
        int sv[2];
772
        int errfd[2];
773 774 775 776 777 778

        /* 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) {
779
            virReportSystemError(errno, "%s",
780
                                 _("unable to create socket pair"));
781 782 783
            goto failed;
        }

784 785 786 787 788 789
        if (pipe(errfd) == -1) {
            virReportSystemError(errno, "%s",
                                 _("unable to create socket pair"));
            goto failed;
        }

790 791 792 793 794
        virCommandSetInputFD(cmd, sv[1]);
        virCommandSetOutputFD(cmd, &(sv[1]));
        virCommandSetErrorFD(cmd, &(errfd[1]));
        virCommandClearCaps(cmd);
        if (virCommandRunAsync(cmd, &pid) < 0)
795 796 797
            goto failed;

        /* Parent continues here. */
798 799
        VIR_FORCE_CLOSE(sv[1]);
        VIR_FORCE_CLOSE(errfd[1]);
800
        priv->sock = sv[0];
801
        priv->errfd = errfd[0];
802
        priv->pid = pid;
803 804 805 806

        /* Do not set 'is_secure' flag since we can't guarentee
         * an external program is secure, and this flag must be
         * pessimistic */
807
    }
808 809 810 811 812
#else /* WIN32 */

    case trans_unix:
    case trans_ssh:
    case trans_ext:
813 814 815
        remoteError(VIR_ERR_INVALID_ARG, "%s",
                    _("transport methods unix, ssh and ext are not supported "
                      "under Windows"));
816
        goto failed;
817 818 819

#endif /* WIN32 */

820 821
    } /* switch (transport) */

822
    if (virSetNonBlock(priv->sock) < 0) {
823
        virReportSystemError(errno, "%s",
824
                             _("unable to make socket non-blocking"));
825 826 827
        goto failed;
    }

828 829 830 831 832 833
    if ((priv->errfd != -1) && virSetNonBlock(priv->errfd) < 0) {
        virReportSystemError(errno, "%s",
                             _("unable to make socket non-blocking"));
        goto failed;
    }

834
    if (pipe(wakeupFD) < 0) {
835
        virReportSystemError(errno, "%s",
836
                             _("unable to make pipe"));
837 838 839 840
        goto failed;
    }
    priv->wakeupReadFD = wakeupFD[0];
    priv->wakeupSendFD = wakeupFD[1];
841 842

    /* Try and authenticate with server */
843
    if (remoteAuthenticate(conn, priv, 1, auth, authtype) == -1)
844 845
        goto failed;

846
    /* Finally we can call the remote side's open function. */
847 848
    {
        remote_open_args args = { &name, flags };
849

850 851 852 853 854
        if (call (conn, priv, REMOTE_CALL_IN_OPEN, REMOTE_PROC_OPEN,
                  (xdrproc_t) xdr_remote_open_args, (char *) &args,
                  (xdrproc_t) xdr_void, (char *) NULL) == -1)
            goto failed;
    }
855

856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
    /* 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 */
872 873
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("unable to auto-detect URI"));
874 875 876 877 878 879
            goto failed;
        }
        if (urierr == -1) {
            goto failed;
        }

880
        VIR_DEBUG("Auto-probed URI is %s", uriret.uri);
881 882 883
        conn->uri = xmlParseURI(uriret.uri);
        VIR_FREE(uriret.uri);
        if (!conn->uri) {
884
            virReportOOMError();
885 886 887 888
            goto failed;
        }
    }

889
    /* Set up a callback to listen on the socket data */
890
    if ((priv->watch = virEventAddHandle(priv->sock,
891
                                         VIR_EVENT_HANDLE_READABLE,
892
                                         remoteDomainEventFired,
893
                                         conn, NULL)) < 0) {
894
        VIR_DEBUG("virEventAddHandle failed: No addHandleImpl defined."
895
               " continuing without events.");
896 897
        priv->watch = -1;
    }
898

899 900 901 902 903 904 905 906 907 908
    priv->domainEventState = virDomainEventStateNew(remoteDomainEventQueueFlush,
                                                    conn,
                                                    NULL,
                                                    false);
    if (!priv->domainEventState) {
        goto failed;
    }
    if (priv->domainEventState->timer < 0 && priv->watch != -1) {
        virEventRemoveHandle(priv->watch);
        priv->watch = -1;
909
    }
910

911 912 913
    /* Successful. */
    retcode = VIR_DRV_OPEN_SUCCESS;

914
 cleanup:
915
    /* Free up the URL and strings. */
916 917 918 919 920 921 922
    VIR_FREE(name);
    VIR_FREE(command);
    VIR_FREE(sockname);
    VIR_FREE(authtype);
    VIR_FREE(netcat);
    VIR_FREE(username);
    VIR_FREE(port);
923
    virCommandFree(cmd);
924
    VIR_FREE(pkipath);
925 926

    return retcode;
927 928

 out_of_memory:
929
    virReportOOMError();
930 931
    if (vars)
        free_qparam_set (vars);
932 933 934

 failed:
    /* Close the socket if we failed. */
935
    VIR_FORCE_CLOSE(priv->errfd);
936

937 938 939 940 941
    if (priv->sock >= 0) {
        if (priv->uses_tls && priv->session) {
            gnutls_bye (priv->session, GNUTLS_SHUT_RDWR);
            gnutls_deinit (priv->session);
        }
942
        VIR_FORCE_CLOSE(priv->sock);
943
#ifndef WIN32
944 945 946
        if (priv->pid > 0) {
            pid_t reap;
            do {
947
retry:
948 949
                reap = waitpid(priv->pid, NULL, 0);
                if (reap == -1 && errno == EINTR)
950
                    goto retry;
951 952
            } while (reap != -1 && reap != priv->pid);
        }
953
#endif
954 955
    }

956 957
    VIR_FORCE_CLOSE(wakeupFD[0]);
    VIR_FORCE_CLOSE(wakeupFD[1]);
958

959
    VIR_FREE(priv->hostname);
960
    goto cleanup;
961 962
}

963
static struct private_data *
964
remoteAllocPrivateData(void)
965
{
966
    struct private_data *priv;
967
    if (VIR_ALLOC(priv) < 0) {
968
        virReportOOMError();
969
        return NULL;
970 971
    }

972
    if (virMutexInit(&priv->lock) < 0) {
973 974
        remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("cannot initialize mutex"));
975
        VIR_FREE(priv);
976
        return NULL;
977 978 979
    }
    remoteDriverLock(priv);
    priv->localUses = 1;
980
    priv->watch = -1;
981
    priv->sock = -1;
982
    priv->errfd = -1;
983 984 985 986 987 988 989 990 991 992 993 994 995

    return priv;
}

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

996
    if (!((*priv) = remoteAllocPrivateData()))
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
        return VIR_DRV_OPEN_ERROR;

    if (flags & VIR_CONNECT_RO)
        rflags |= VIR_DRV_OPEN_REMOTE_RO;

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

    return ret;
}

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

1023
    if (inside_daemon && (!conn->uri || (conn->uri && !conn->uri->server)))
1024 1025
        return VIR_DRV_OPEN_DECLINED;

1026
    if (!(priv = remoteAllocPrivateData()))
1027
        return VIR_DRV_OPEN_ERROR;
1028

1029
    if (flags & VIR_CONNECT_RO)
1030 1031
        rflags |= VIR_DRV_OPEN_REMOTE_RO;

1032 1033 1034 1035 1036 1037 1038 1039 1040
    /*
     * 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 已提交
1041
        conn->uri->scheme &&
1042 1043
        ((strchr(conn->uri->scheme, '+') == 0)||
         (strstr(conn->uri->scheme, "+unix") != NULL)) &&
1044 1045
        (STREQ(conn->uri->path, "/session") ||
         STRPREFIX(conn->uri->scheme, "test+")) &&
1046
        getuid() > 0) {
1047
        VIR_DEBUG("Auto-spawn user daemon instance");
1048
        rflags |= VIR_DRV_OPEN_REMOTE_USER;
1049 1050 1051
        if (!autostart ||
            STRNEQ(autostart, "0"))
            rflags |= VIR_DRV_OPEN_REMOTE_AUTOSTART;
1052 1053 1054
    }

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

1073
    ret = doRemoteOpen(conn, priv, auth, rflags);
1074 1075
    if (ret != VIR_DRV_OPEN_SUCCESS) {
        conn->privateData = NULL;
1076
        remoteDriverUnlock(priv);
1077
        VIR_FREE(priv);
1078 1079
    } else {
        conn->privateData = priv;
1080
        remoteDriverUnlock(priv);
1081 1082 1083 1084 1085
    }
    return ret;
}


1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
/* 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;

1097 1098

static int
1099
check_cert_file(const char *type, const char *file)
1100
{
1101
    if (access(file, R_OK)) {
1102
        virReportSystemError(errno,
1103 1104
                             _("Cannot access %s '%s'"),
                             type, file);
1105 1106 1107 1108 1109 1110
        return -1;
    }
    return 0;
}


1111
static void remote_debug_gnutls_log(int level, const char* str) {
1112
    VIR_DEBUG("%d %s", level, str);
1113 1114
}

1115
static int
1116
initialize_gnutls(char *pkipath, int flags)
1117
{
E
Eric Blake 已提交
1118
    static int initialized = 0;
1119
    int err;
1120
    char *gnutlsdebug;
1121 1122 1123 1124 1125 1126
    char *libvirt_cacert = NULL;
    char *libvirt_clientkey = NULL;
    char *libvirt_clientcert = NULL;
    int ret = -1;
    char *userdir = NULL;
    char *user_pki_path = NULL;
1127

E
Eric Blake 已提交
1128
    if (initialized) return 0;
1129 1130 1131

    gnutls_global_init ();

1132 1133 1134 1135 1136 1137 1138 1139
    if ((gnutlsdebug = getenv("LIBVIRT_GNUTLS_DEBUG")) != NULL) {
        int val;
        if (virStrToLong_i(gnutlsdebug, NULL, 10, &val) < 0)
            val = 10;
        gnutls_global_set_log_level(val);
        gnutls_global_set_log_function(remote_debug_gnutls_log);
    }

1140 1141 1142
    /* X509 stuff */
    err = gnutls_certificate_allocate_credentials (&x509_cred);
    if (err) {
1143 1144 1145
        remoteError(VIR_ERR_GNUTLS_ERROR,
                    _("unable to allocate TLS credentials: %s"),
                    gnutls_strerror (err));
1146 1147 1148
        return -1;
    }

1149 1150 1151 1152
    if (pkipath) {
        if ((virAsprintf(&libvirt_cacert, "%s/%s", pkipath,
                        "cacert.pem")) < 0)
            goto out_of_memory;
1153

1154 1155 1156 1157 1158 1159 1160
        if ((virAsprintf(&libvirt_clientkey, "%s/%s", pkipath,
                        "clientkey.pem")) < 0)
            goto out_of_memory;

        if ((virAsprintf(&libvirt_clientcert, "%s/%s", pkipath,
                        "clientcert.pem")) < 0)
             goto out_of_memory;
1161
    } else if (flags & VIR_DRV_OPEN_REMOTE_USER || getuid() > 0) {
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
        userdir = virGetUserDirectory(getuid());

        if (!userdir)
            goto out_of_memory;

        if (virAsprintf(&user_pki_path, "%s/.pki/libvirt", userdir) < 0)
            goto out_of_memory;

        if ((virAsprintf(&libvirt_cacert, "%s/%s", user_pki_path,
                        "cacert.pem")) < 0)
            goto out_of_memory;

        if ((virAsprintf(&libvirt_clientkey, "%s/%s", user_pki_path,
                        "clientkey.pem")) < 0)
            goto out_of_memory;

        if ((virAsprintf(&libvirt_clientcert, "%s/%s", user_pki_path,
                        "clientcert.pem")) < 0)
            goto out_of_memory;

1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
        /* Use the default location of the CA certificate if it
         * cannot be found in $HOME/.pki/libvirt
         */
        if (!virFileExists(libvirt_cacert)) {
            VIR_FREE(libvirt_cacert);

            libvirt_cacert = strdup(LIBVIRT_CACERT);
            if (!libvirt_cacert) goto out_of_memory;
        }

        /* Use default location as long as one of
E
Eric Blake 已提交
1193
         * client key, and client certificate cannot be found in
1194 1195 1196
         * $HOME/.pki/libvirt, we don't want to make user confused
         * with one file is here, the other is there.
         */
1197
        if (!virFileExists(libvirt_clientkey) ||
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
            !virFileExists(libvirt_clientcert)) {
            VIR_FREE(libvirt_clientkey);
            VIR_FREE(libvirt_clientcert);

            libvirt_clientkey = strdup(LIBVIRT_CLIENTKEY);
            if (!libvirt_clientkey) goto out_of_memory;

            libvirt_clientcert = strdup(LIBVIRT_CLIENTCERT);
            if (!libvirt_clientcert) goto out_of_memory;
        }
    } else {
        libvirt_cacert = strdup(LIBVIRT_CACERT);
        if (!libvirt_cacert) goto out_of_memory;

        libvirt_clientkey = strdup(LIBVIRT_CLIENTKEY);
        if (!libvirt_clientkey) goto out_of_memory;

        libvirt_clientcert = strdup(LIBVIRT_CLIENTCERT);
        if (!libvirt_clientcert) goto out_of_memory;
    }

    if (check_cert_file("CA certificate", libvirt_cacert) < 0)
        goto error;
    if (check_cert_file("client key", libvirt_clientkey) < 0)
        goto error;
    if (check_cert_file("client certificate", libvirt_clientcert) < 0)
        goto error;
1225

1226
    /* Set the trusted CA cert. */
1227
    VIR_DEBUG("loading CA file %s", libvirt_cacert);
1228
    err =
1229
        gnutls_certificate_set_x509_trust_file (x509_cred, libvirt_cacert,
1230 1231
                                                GNUTLS_X509_FMT_PEM);
    if (err < 0) {
1232
        remoteError(VIR_ERR_GNUTLS_ERROR,
1233 1234
                    _("unable to load CA certificate '%s': %s"),
                    libvirt_cacert, gnutls_strerror (err));
1235
        goto error;
1236 1237 1238
    }

    /* Set the client certificate and private key. */
1239
    VIR_DEBUG("loading client cert and key from files %s and %s",
1240
          libvirt_clientcert, libvirt_clientkey);
1241 1242
    err =
        gnutls_certificate_set_x509_key_file (x509_cred,
1243 1244
                                              libvirt_clientcert,
                                              libvirt_clientkey,
1245 1246
                                              GNUTLS_X509_FMT_PEM);
    if (err < 0) {
1247
        remoteError(VIR_ERR_GNUTLS_ERROR,
1248 1249 1250
                    _("unable to load private key '%s' and/or "
                    "certificate '%s': %s"), libvirt_clientkey,
                    libvirt_clientcert, gnutls_strerror (err));
1251
        goto error;
1252 1253
    }

E
Eric Blake 已提交
1254
    initialized = 1;
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
    ret = 0;

cleanup:
    VIR_FREE(libvirt_cacert);
    VIR_FREE(libvirt_clientkey);
    VIR_FREE(libvirt_clientcert);
    VIR_FREE(userdir);
    VIR_FREE(user_pki_path);
    return ret;

error:
    ret = -1;
    goto cleanup;

out_of_memory:
    ret = -1;
    virReportOOMError();
    goto cleanup;
1273 1274
}

1275
static int verify_certificate (virConnectPtr conn, struct private_data *priv, gnutls_session_t session);
1276

1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
#if HAVE_WINSOCK2_H
static ssize_t
custom_gnutls_push(void *s, const void *buf, size_t len)
{
    return send((size_t)s, buf, len, 0);
}

static ssize_t
custom_gnutls_pull(void *s, void *buf, size_t len)
{
    return recv((size_t)s, buf, len, 0);
}
#endif

1291 1292
static gnutls_session_t
negotiate_gnutls_on_connection (virConnectPtr conn,
1293 1294
                                struct private_data *priv,
                                int no_verify)
1295 1296 1297 1298 1299 1300
{
    const int cert_type_priority[3] = {
        GNUTLS_CRT_X509,
        GNUTLS_CRT_OPENPGP,
        0
    };
1301
    bool success = false;
1302 1303 1304
    int err;
    gnutls_session_t session;

1305
    /* Initialize TLS session
1306 1307 1308
     */
    err = gnutls_init (&session, GNUTLS_CLIENT);
    if (err) {
1309 1310 1311
        remoteError(VIR_ERR_GNUTLS_ERROR,
                    _("unable to initialize TLS client: %s"),
                    gnutls_strerror (err));
1312 1313 1314 1315 1316 1317
        return NULL;
    }

    /* Use default priorities */
    err = gnutls_set_default_priority (session);
    if (err) {
1318 1319 1320
        remoteError(VIR_ERR_GNUTLS_ERROR,
                    _("unable to set TLS algorithm priority: %s"),
                    gnutls_strerror (err));
1321
        goto cleanup;
1322 1323 1324 1325 1326
    }
    err =
        gnutls_certificate_type_set_priority (session,
                                              cert_type_priority);
    if (err) {
1327 1328 1329
        remoteError(VIR_ERR_GNUTLS_ERROR,
                    _("unable to set certificate priority: %s"),
                    gnutls_strerror (err));
1330
        goto cleanup;
1331 1332 1333 1334 1335 1336
    }

    /* put the x509 credentials to the current session
     */
    err = gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, x509_cred);
    if (err) {
1337 1338 1339
        remoteError(VIR_ERR_GNUTLS_ERROR,
                    _("unable to set session credentials: %s"),
                    gnutls_strerror (err));
1340
        goto cleanup;
1341 1342 1343
    }

    gnutls_transport_set_ptr (session,
1344
                              (gnutls_transport_ptr_t) (long) priv->sock);
1345

1346 1347 1348 1349 1350 1351 1352
#if HAVE_WINSOCK2_H
    /* Make sure GnuTLS uses gnulib's replacment functions for send() and
     * recv() on Windows */
    gnutls_transport_set_push_function(session, custom_gnutls_push);
    gnutls_transport_set_pull_function(session, custom_gnutls_pull);
#endif

1353 1354 1355 1356 1357 1358
    /* Perform the TLS handshake. */
 again:
    err = gnutls_handshake (session);
    if (err < 0) {
        if (err == GNUTLS_E_AGAIN || err == GNUTLS_E_INTERRUPTED)
            goto again;
1359 1360 1361
        remoteError(VIR_ERR_GNUTLS_ERROR,
                    _("unable to complete TLS handshake: %s"),
                    gnutls_strerror (err));
1362
        goto cleanup;
1363 1364 1365
    }

    /* Verify certificate. */
1366
    if (verify_certificate (conn, priv, session) == -1) {
1367
        VIR_DEBUG("failed to verify peer's certificate");
1368 1369
        if (!no_verify)
            goto cleanup;
1370
    }
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381

    /* 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;
1382 1383 1384
        remoteError(VIR_ERR_GNUTLS_ERROR,
                    _("unable to complete TLS initialization: %s"),
                    gnutls_strerror (len));
1385
        goto cleanup;
1386 1387
    }
    if (len != 1 || buf[0] != '\1') {
1388 1389 1390
        remoteError(VIR_ERR_RPC, "%s",
                    _("server verification (of our certificate or IP "
                      "address) failed"));
1391
        goto cleanup;
1392 1393 1394 1395 1396 1397 1398
    }

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

1399 1400 1401 1402 1403 1404 1405 1406
    success = true;

cleanup:
    if (!success) {
        gnutls_deinit(session);
        session = NULL;
    }

1407 1408 1409 1410 1411
    return session;
}

static int
verify_certificate (virConnectPtr conn ATTRIBUTE_UNUSED,
1412 1413
                    struct private_data *priv,
                    gnutls_session_t session)
1414 1415 1416 1417 1418 1419 1420 1421
{
    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) {
1422 1423 1424
        remoteError(VIR_ERR_GNUTLS_ERROR,
                    _("unable to verify server certificate: %s"),
                    gnutls_strerror (ret));
1425 1426
        return -1;
    }
1427

1428
    if ((now = time(NULL)) == ((time_t)-1)) {
1429
        virReportSystemError(errno, "%s",
1430
                             _("cannot get current time"));
1431 1432 1433 1434
        return -1;
    }

    if (status != 0) {
1435
        const char *reason = _("Invalid certificate");
1436 1437

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

1440
        if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1441
            reason = _("The certificate hasn't got a known issuer.");
1442

1443
        if (status & GNUTLS_CERT_REVOKED)
1444
            reason = _("The certificate has been revoked.");
1445 1446

#ifndef GNUTLS_1_0_COMPAT
1447
        if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1448
            reason = _("The certificate uses an insecure algorithm");
1449
#endif
1450

1451 1452 1453
        remoteError(VIR_ERR_RPC,
                    _("server certificate failed validation: %s"),
                    reason);
1454 1455 1456 1457
        return -1;
    }

    if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509) {
1458
        remoteError(VIR_ERR_RPC,  "%s",_("Certificate type is not X.509"));
1459 1460
        return -1;
    }
1461

1462
    if (!(certs = gnutls_certificate_get_peers(session, &nCerts))) {
1463
        remoteError(VIR_ERR_RPC,  "%s",_("gnutls_certificate_get_peers failed"));
1464 1465
        return -1;
    }
1466

1467 1468 1469 1470 1471
    for (i = 0 ; i < nCerts ; i++) {
        gnutls_x509_crt_t cert;

        ret = gnutls_x509_crt_init (&cert);
        if (ret < 0) {
1472 1473 1474
            remoteError(VIR_ERR_GNUTLS_ERROR,
                        _("unable to initialize certificate: %s"),
                        gnutls_strerror (ret));
1475 1476
            return -1;
        }
1477

1478 1479
        ret = gnutls_x509_crt_import (cert, &certs[i], GNUTLS_X509_FMT_DER);
        if (ret < 0) {
1480 1481 1482
            remoteError(VIR_ERR_GNUTLS_ERROR,
                        _("unable to import certificate: %s"),
                        gnutls_strerror (ret));
1483 1484 1485
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1486

1487
        if (gnutls_x509_crt_get_expiration_time (cert) < now) {
1488
            remoteError(VIR_ERR_RPC, "%s", _("The certificate has expired"));
1489 1490 1491
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1492

1493
        if (gnutls_x509_crt_get_activation_time (cert) > now) {
1494 1495
            remoteError(VIR_ERR_RPC, "%s",
                        _("The certificate is not yet activated"));
1496 1497 1498
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1499

1500
        if (i == 0) {
1501
            if (!gnutls_x509_crt_check_hostname (cert, priv->hostname)) {
1502 1503 1504
                remoteError(VIR_ERR_RPC,
                            _("Certificate's owner does not match the hostname (%s)"),
                            priv->hostname);
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
                gnutls_x509_crt_deinit (cert);
                return -1;
            }
        }
    }

    return 0;
}

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

1516

1517
static int
1518
doRemoteClose (virConnectPtr conn, struct private_data *priv)
1519
{
1520 1521 1522 1523
    /* Remove timer before closing the connection, to avoid possible
     * remoteDomainEventFired with a free'd connection */
    if (priv->domainEventState->timer >= 0) {
        virEventRemoveTimeout(priv->domainEventState->timer);
1524
        virEventRemoveHandle(priv->watch);
1525
        priv->watch = -1;
1526
        priv->domainEventState->timer = -1;
1527
    }
1528

1529 1530 1531 1532 1533
    if (call (conn, priv, 0, REMOTE_PROC_CLOSE,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        return -1;

1534
    /* Close socket. */
1535
    if (priv->uses_tls && priv->session) {
1536
        gnutls_bye (priv->session, GNUTLS_SHUT_RDWR);
1537 1538 1539 1540 1541 1542
        gnutls_deinit (priv->session);
    }
#if HAVE_SASL
    if (priv->saslconn)
        sasl_dispose (&priv->saslconn);
#endif
1543 1544
    VIR_FORCE_CLOSE(priv->sock);
    VIR_FORCE_CLOSE(priv->errfd);
1545

1546
#ifndef WIN32
1547 1548 1549
    if (priv->pid > 0) {
        pid_t reap;
        do {
1550
retry:
1551 1552
            reap = waitpid(priv->pid, NULL, 0);
            if (reap == -1 && errno == EINTR)
1553
                goto retry;
1554 1555
        } while (reap != -1 && reap != priv->pid);
    }
1556
#endif
1557 1558
    VIR_FORCE_CLOSE(priv->wakeupReadFD);
    VIR_FORCE_CLOSE(priv->wakeupSendFD);
1559

1560

1561
    /* Free hostname copy */
1562
    VIR_FREE(priv->hostname);
1563

1564
    /* See comment for remoteType. */
1565
    VIR_FREE(priv->type);
1566

1567
    virDomainEventStateFree(priv->domainEventState);
1568

1569 1570 1571
    return 0;
}

1572 1573 1574
static int
remoteClose (virConnectPtr conn)
{
1575
    int ret = 0;
1576
    struct private_data *priv = conn->privateData;
1577

1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
    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);
1589 1590 1591 1592

    return ret;
}

1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
/* 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)
{
1604
    char *rv = NULL;
1605
    remote_get_type_ret ret;
1606
    struct private_data *priv = conn->privateData;
1607

1608 1609
    remoteDriverLock(priv);

1610
    /* Cached? */
1611 1612 1613 1614
    if (priv->type) {
        rv = priv->type;
        goto done;
    }
1615 1616 1617 1618 1619

    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)
1620
        goto done;
1621 1622

    /* Stash. */
1623 1624 1625
    rv = priv->type = ret.type;

done:
1626
    remoteDriverUnlock(priv);
1627
    return rv;
1628 1629
}

1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694
static int remoteIsSecure(virConnectPtr conn)
{
    int rv = -1;
    struct private_data *priv = conn->privateData;
    remote_is_secure_ret ret;
    remoteDriverLock(priv);

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

    /* We claim to be secure, if the remote driver
     * transport itself is secure, and the remote
     * HV connection is secure
     *
     * ie, we don't want to claim to be secure if the
     * remote driver is used to connect to a XenD
     * driver using unencrypted HTTP:/// access
     */
    rv = priv->is_secure && ret.secure ? 1 : 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static int remoteIsEncrypted(virConnectPtr conn)
{
    int rv = -1;
    int encrypted = 0;
    struct private_data *priv = conn->privateData;
    remote_is_secure_ret ret;
    remoteDriverLock(priv);

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

    if (priv->uses_tls)
        encrypted = 1;
#if HAVE_SASL
    else if (priv->saslconn)
        encrypted = 1;
#endif


    /* We claim to be encrypted, if the remote driver
     * transport itself is encrypted, and the remote
     * HV connection is secure.
     *
     * Yes, we really don't check the remote 'encrypted'
     * option, since it will almost always be false,
     * even if secure (eg UNIX sockets).
     */
    rv = encrypted && ret.secure ? 1 : 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

1695 1696 1697 1698 1699 1700
static int
remoteNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
1701
    int rv = -1;
1702 1703 1704
    remote_node_get_cells_free_memory_args args;
    remote_node_get_cells_free_memory_ret ret;
    int i;
1705
    struct private_data *priv = conn->privateData;
1706

1707 1708
    remoteDriverLock(priv);

1709
    if (maxCells > REMOTE_NODE_MAX_CELLS) {
1710 1711 1712
        remoteError(VIR_ERR_RPC,
                    _("too many NUMA cells: %d > %d"),
                    maxCells, REMOTE_NODE_MAX_CELLS);
1713
        goto done;
1714 1715 1716 1717 1718 1719 1720 1721 1722
    }

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

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

1730 1731 1732
    rv = ret.freeMems.freeMems_len;

done:
1733
    remoteDriverUnlock(priv);
1734
    return rv;
1735 1736
}

1737 1738 1739
static int
remoteListDomains (virConnectPtr conn, int *ids, int maxids)
{
1740
    int rv = -1;
1741 1742 1743
    int i;
    remote_list_domains_args args;
    remote_list_domains_ret ret;
1744
    struct private_data *priv = conn->privateData;
1745

1746 1747
    remoteDriverLock(priv);

1748
    if (maxids > REMOTE_DOMAIN_ID_LIST_MAX) {
1749 1750 1751
        remoteError(VIR_ERR_RPC,
                    _("too many remote domain IDs: %d > %d"),
                    maxids, REMOTE_DOMAIN_ID_LIST_MAX);
1752
        goto done;
1753 1754 1755 1756 1757 1758 1759
    }
    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)
1760
        goto done;
1761 1762

    if (ret.ids.ids_len > maxids) {
1763 1764 1765
        remoteError(VIR_ERR_RPC,
                    _("too many remote domain IDs: %d > %d"),
                    ret.ids.ids_len, maxids);
1766
        goto cleanup;
1767 1768 1769 1770 1771
    }

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

1772 1773 1774
    rv = ret.ids.ids_len;

cleanup:
1775 1776
    xdr_free ((xdrproc_t) xdr_remote_list_domains_ret, (char *) &ret);

1777
done:
1778
    remoteDriverUnlock(priv);
1779
    return rv;
1780 1781
}

1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
static int
remoteDomainSetMemoryParameters (virDomainPtr domain,
                                 virMemoryParameterPtr params,
                                 int nparams,
                                 unsigned int flags)
{
    int rv = -1;
    remote_domain_set_memory_parameters_args args;
    int i, do_error;
    struct private_data *priv = domain->conn->privateData;

    remoteDriverLock(priv);

    make_nonnull_domain (&args.dom, domain);

    /* Serialise the memory parameters. */
    args.params.params_len = nparams;
    args.flags = flags;
    if (VIR_ALLOC_N(args.params.params_val, nparams) < 0) {
        virReportOOMError();
        goto done;
    }

    do_error = 0;
    for (i = 0; i < nparams; ++i) {
1807
        /* call() will free this: */
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950
        args.params.params_val[i].field = strdup (params[i].field);
        if (args.params.params_val[i].field == NULL) {
            virReportOOMError();
            do_error = 1;
        }
        args.params.params_val[i].value.type = params[i].type;
        switch (params[i].type) {
        case VIR_DOMAIN_MEMORY_PARAM_INT:
            args.params.params_val[i].value.remote_memory_param_value_u.i =
                params[i].value.i; break;
        case VIR_DOMAIN_MEMORY_PARAM_UINT:
            args.params.params_val[i].value.remote_memory_param_value_u.ui =
                params[i].value.ui; break;
        case VIR_DOMAIN_MEMORY_PARAM_LLONG:
            args.params.params_val[i].value.remote_memory_param_value_u.l =
                params[i].value.l; break;
        case VIR_DOMAIN_MEMORY_PARAM_ULLONG:
            args.params.params_val[i].value.remote_memory_param_value_u.ul =
                params[i].value.ul; break;
        case VIR_DOMAIN_MEMORY_PARAM_DOUBLE:
            args.params.params_val[i].value.remote_memory_param_value_u.d =
                params[i].value.d; break;
        case VIR_DOMAIN_MEMORY_PARAM_BOOLEAN:
            args.params.params_val[i].value.remote_memory_param_value_u.b =
                params[i].value.b; break;
        default:
            remoteError(VIR_ERR_RPC, "%s", _("unknown parameter type"));
            do_error = 1;
        }
    }

    if (do_error) {
        xdr_free ((xdrproc_t) xdr_remote_domain_set_memory_parameters_args,
                  (char *) &args);
        goto done;
    }

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_SET_MEMORY_PARAMETERS,
              (xdrproc_t) xdr_remote_domain_set_memory_parameters_args,
              (char *) &args, (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static int
remoteDomainGetMemoryParameters (virDomainPtr domain,
                                 virMemoryParameterPtr params, int *nparams,
                                 unsigned int flags)
{
    int rv = -1;
    remote_domain_get_memory_parameters_args args;
    remote_domain_get_memory_parameters_ret ret;
    int i = -1;
    struct private_data *priv = domain->conn->privateData;

    remoteDriverLock(priv);

    make_nonnull_domain (&args.dom, domain);
    args.nparams = *nparams;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_MEMORY_PARAMETERS,
              (xdrproc_t) xdr_remote_domain_get_memory_parameters_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_memory_parameters_ret, (char *) &ret) == -1)
        goto done;

    /* Check the length of the returned list carefully. */
    if (ret.params.params_len > REMOTE_DOMAIN_MEMORY_PARAMETERS_MAX ||
        ret.params.params_len > *nparams) {
        remoteError(VIR_ERR_RPC, "%s",
                    _("remoteDomainGetMemoryParameters: "
                      "returned number of parameters exceeds limit"));
        goto cleanup;
    }
    /* Handle the case when the caller does not know the number of parameters
     * and is asking for the number of parameters supported
     */
    if (*nparams == 0) {
        *nparams = ret.nparams;
        rv = 0;
        goto cleanup;
    }

    *nparams = ret.params.params_len;

    /* Deserialise the result. */
    for (i = 0; i < *nparams; ++i) {
        if (virStrcpyStatic(params[i].field, ret.params.params_val[i].field) == NULL) {
            remoteError(VIR_ERR_INTERNAL_ERROR,
                        _("Parameter %s too big for destination"),
                        ret.params.params_val[i].field);
            goto cleanup;
        }
        params[i].type = ret.params.params_val[i].value.type;
        switch (params[i].type) {
        case VIR_DOMAIN_MEMORY_PARAM_INT:
            params[i].value.i =
                ret.params.params_val[i].value.remote_memory_param_value_u.i;
            break;
        case VIR_DOMAIN_MEMORY_PARAM_UINT:
            params[i].value.ui =
                ret.params.params_val[i].value.remote_memory_param_value_u.ui;
            break;
        case VIR_DOMAIN_MEMORY_PARAM_LLONG:
            params[i].value.l =
                ret.params.params_val[i].value.remote_memory_param_value_u.l;
            break;
        case VIR_DOMAIN_MEMORY_PARAM_ULLONG:
            params[i].value.ul =
                ret.params.params_val[i].value.remote_memory_param_value_u.ul;
            break;
        case VIR_DOMAIN_MEMORY_PARAM_DOUBLE:
            params[i].value.d =
                ret.params.params_val[i].value.remote_memory_param_value_u.d;
            break;
        case VIR_DOMAIN_MEMORY_PARAM_BOOLEAN:
            params[i].value.b =
                ret.params.params_val[i].value.remote_memory_param_value_u.b;
            break;
        default:
            remoteError(VIR_ERR_RPC, "%s",
                        _("remoteDomainGetMemoryParameters: "
                          "unknown parameter type"));
            goto cleanup;
        }
    }

    rv = 0;

cleanup:
    xdr_free ((xdrproc_t) xdr_remote_domain_get_memory_parameters_ret,
              (char *) &ret);
done:
    remoteDriverUnlock(priv);
    return rv;
}

1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119
static int
remoteDomainSetBlkioParameters (virDomainPtr domain,
                                virBlkioParameterPtr params,
                                 int nparams,
                                 unsigned int flags)
{
    int rv = -1;
    remote_domain_set_blkio_parameters_args args;
    int i, do_error;
    struct private_data *priv = domain->conn->privateData;

    remoteDriverLock(priv);

    make_nonnull_domain (&args.dom, domain);

    /* Serialise the blkio parameters. */
    args.params.params_len = nparams;
    args.flags = flags;
    if (VIR_ALLOC_N(args.params.params_val, nparams) < 0) {
        virReportOOMError();
        goto done;
    }

    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) {
            virReportOOMError();
            do_error = 1;
        }
        args.params.params_val[i].value.type = params[i].type;
        switch (params[i].type) {
        case VIR_DOMAIN_BLKIO_PARAM_INT:
            args.params.params_val[i].value.remote_blkio_param_value_u.i =
                params[i].value.i; break;
        case VIR_DOMAIN_BLKIO_PARAM_UINT:
            args.params.params_val[i].value.remote_blkio_param_value_u.ui =
                params[i].value.ui; break;
        case VIR_DOMAIN_BLKIO_PARAM_LLONG:
            args.params.params_val[i].value.remote_blkio_param_value_u.l =
                params[i].value.l; break;
        case VIR_DOMAIN_BLKIO_PARAM_ULLONG:
            args.params.params_val[i].value.remote_blkio_param_value_u.ul =
                params[i].value.ul; break;
        case VIR_DOMAIN_BLKIO_PARAM_DOUBLE:
            args.params.params_val[i].value.remote_blkio_param_value_u.d =
                params[i].value.d; break;
        case VIR_DOMAIN_BLKIO_PARAM_BOOLEAN:
            args.params.params_val[i].value.remote_blkio_param_value_u.b =
                params[i].value.b; break;
        default:
            remoteError(VIR_ERR_RPC, "%s", _("unknown parameter type"));
            do_error = 1;
        }
    }

    if (do_error) {
        xdr_free ((xdrproc_t) xdr_remote_domain_set_blkio_parameters_args,
                  (char *) &args);
        goto done;
    }

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_SET_BLKIO_PARAMETERS,
              (xdrproc_t) xdr_remote_domain_set_blkio_parameters_args,
              (char *) &args, (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static int
remoteDomainGetBlkioParameters (virDomainPtr domain,
                                 virBlkioParameterPtr params, int *nparams,
                                 unsigned int flags)
{
    int rv = -1;
    remote_domain_get_blkio_parameters_args args;
    remote_domain_get_blkio_parameters_ret ret;
    int i = -1;
    struct private_data *priv = domain->conn->privateData;

    remoteDriverLock(priv);

    make_nonnull_domain (&args.dom, domain);
    args.nparams = *nparams;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_BLKIO_PARAMETERS,
              (xdrproc_t) xdr_remote_domain_get_blkio_parameters_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_blkio_parameters_ret, (char *) &ret) == -1)
        goto done;

    /* Check the length of the returned list carefully. */
    if (ret.params.params_len > REMOTE_DOMAIN_BLKIO_PARAMETERS_MAX ||
        ret.params.params_len > *nparams) {
        remoteError(VIR_ERR_RPC, "%s",
                    _("remoteDomainGetBlkioParameters: "
                      "returned number of parameters exceeds limit"));
        goto cleanup;
    }
    /* Handle the case when the caller does not know the number of parameters
     * and is asking for the number of parameters supported
     */
    if (*nparams == 0) {
        *nparams = ret.nparams;
        rv = 0;
        goto cleanup;
    }

    *nparams = ret.params.params_len;

    /* Deserialise the result. */
    for (i = 0; i < *nparams; ++i) {
        if (virStrcpyStatic(params[i].field, ret.params.params_val[i].field) == NULL) {
            remoteError(VIR_ERR_INTERNAL_ERROR,
                        _("Parameter %s too big for destination"),
                        ret.params.params_val[i].field);
            goto cleanup;
        }
        params[i].type = ret.params.params_val[i].value.type;
        switch (params[i].type) {
        case VIR_DOMAIN_BLKIO_PARAM_INT:
            params[i].value.i =
                ret.params.params_val[i].value.remote_blkio_param_value_u.i;
            break;
        case VIR_DOMAIN_BLKIO_PARAM_UINT:
            params[i].value.ui =
                ret.params.params_val[i].value.remote_blkio_param_value_u.ui;
            break;
        case VIR_DOMAIN_BLKIO_PARAM_LLONG:
            params[i].value.l =
                ret.params.params_val[i].value.remote_blkio_param_value_u.l;
            break;
        case VIR_DOMAIN_BLKIO_PARAM_ULLONG:
            params[i].value.ul =
                ret.params.params_val[i].value.remote_blkio_param_value_u.ul;
            break;
        case VIR_DOMAIN_BLKIO_PARAM_DOUBLE:
            params[i].value.d =
                ret.params.params_val[i].value.remote_blkio_param_value_u.d;
            break;
        case VIR_DOMAIN_BLKIO_PARAM_BOOLEAN:
            params[i].value.b =
                ret.params.params_val[i].value.remote_blkio_param_value_u.b;
            break;
        default:
            remoteError(VIR_ERR_RPC, "%s",
                        _("remoteDomainGetBlkioParameters: "
                          "unknown parameter type"));
            goto cleanup;
        }
    }

    rv = 0;

cleanup:
    xdr_free ((xdrproc_t) xdr_remote_domain_get_blkio_parameters_ret,
              (char *) &ret);
done:
    remoteDriverUnlock(priv);
    return rv;
}

2120 2121 2122 2123 2124 2125 2126
static int
remoteDomainGetVcpus (virDomainPtr domain,
                      virVcpuInfoPtr info,
                      int maxinfo,
                      unsigned char *cpumaps,
                      int maplen)
{
2127
    int rv = -1;
2128 2129 2130
    int i;
    remote_domain_get_vcpus_args args;
    remote_domain_get_vcpus_ret ret;
2131
    struct private_data *priv = domain->conn->privateData;
2132

2133 2134
    remoteDriverLock(priv);

2135
    if (maxinfo > REMOTE_VCPUINFO_MAX) {
2136 2137 2138
        remoteError(VIR_ERR_RPC,
                    _("vCPU count exceeds maximum: %d > %d"),
                    maxinfo, REMOTE_VCPUINFO_MAX);
2139
        goto done;
2140
    }
2141
    if (maxinfo * maplen > REMOTE_CPUMAPS_MAX) {
2142 2143 2144
        remoteError(VIR_ERR_RPC,
                    _("vCPU map buffer length exceeds maximum: %d > %d"),
                    maxinfo * maplen, REMOTE_CPUMAPS_MAX);
2145
        goto done;
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
    }

    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)
2156
        goto done;
2157 2158

    if (ret.info.info_len > maxinfo) {
2159 2160 2161
        remoteError(VIR_ERR_RPC,
                    _("host reports too many vCPUs: %d > %d"),
                    ret.info.info_len, maxinfo);
2162
        goto cleanup;
2163
    }
2164
    if (ret.cpumaps.cpumaps_len > maxinfo * maplen) {
2165 2166 2167
        remoteError(VIR_ERR_RPC,
                    _("host reports map buffer length exceeds maximum: %d > %d"),
                    ret.cpumaps.cpumaps_len, maxinfo * maplen);
2168
        goto cleanup;
2169 2170
    }

2171 2172 2173
    memset (info, 0, sizeof (virVcpuInfo) * maxinfo);
    memset (cpumaps, 0, maxinfo * maplen);

2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
    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];

2184 2185 2186
    rv = ret.info.info_len;

cleanup:
2187
    xdr_free ((xdrproc_t) xdr_remote_domain_get_vcpus_ret, (char *) &ret);
2188 2189

done:
2190
    remoteDriverUnlock(priv);
2191
    return rv;
2192 2193
}

2194 2195 2196 2197 2198 2199
static int
remoteDomainGetSecurityLabel (virDomainPtr domain, virSecurityLabelPtr seclabel)
{
    remote_domain_get_security_label_args args;
    remote_domain_get_security_label_ret ret;
    struct private_data *priv = domain->conn->privateData;
2200 2201 2202
    int rv = -1;

    remoteDriverLock(priv);
2203 2204 2205

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

2208 2209 2210
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_SECURITY_LABEL,
              (xdrproc_t) xdr_remote_domain_get_security_label_args, (char *)&args,
              (xdrproc_t) xdr_remote_domain_get_security_label_ret, (char *)&ret) == -1) {
2211
        goto done;
2212 2213 2214 2215
    }

    if (ret.label.label_val != NULL) {
        if (strlen (ret.label.label_val) >= sizeof seclabel->label) {
2216 2217
            remoteError(VIR_ERR_RPC, _("security label exceeds maximum: %zd"),
                        sizeof seclabel->label - 1);
2218
            goto done;
2219 2220 2221 2222 2223
        }
        strcpy (seclabel->label, ret.label.label_val);
        seclabel->enforcing = ret.enforcing;
    }

2224 2225 2226 2227 2228
    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
2229 2230
}

2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
static int
remoteDomainGetState(virDomainPtr domain,
                     int *state,
                     int *reason,
                     unsigned int flags)
{
    int rv = -1;
    remote_domain_get_state_args args;
    remote_domain_get_state_ret ret;
    struct private_data *priv = domain->conn->privateData;

    remoteDriverLock(priv);

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

    memset(&ret, 0, sizeof ret);
    if (call(domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_STATE,
             (xdrproc_t) xdr_remote_domain_get_state_args, (char *) &args,
             (xdrproc_t) xdr_remote_domain_get_state_ret, (char *) &ret) == -1)
        goto done;

    *state = ret.state;
    if (reason)
        *reason = ret.reason;

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

2264 2265 2266 2267 2268
static int
remoteNodeGetSecurityModel (virConnectPtr conn, virSecurityModelPtr secmodel)
{
    remote_node_get_security_model_ret ret;
    struct private_data *priv = conn->privateData;
2269 2270 2271
    int rv = -1;

    remoteDriverLock(priv);
2272 2273

    memset (&ret, 0, sizeof ret);
2274 2275
    memset (secmodel, 0, sizeof (*secmodel));

2276 2277 2278
    if (call (conn, priv, 0, REMOTE_PROC_NODE_GET_SECURITY_MODEL,
              (xdrproc_t) xdr_void, NULL,
              (xdrproc_t) xdr_remote_node_get_security_model_ret, (char *)&ret) == -1) {
2279
        goto done;
2280 2281 2282 2283
    }

    if (ret.model.model_val != NULL) {
        if (strlen (ret.model.model_val) >= sizeof secmodel->model) {
2284 2285
            remoteError(VIR_ERR_RPC, _("security model exceeds maximum: %zd"),
                        sizeof secmodel->model - 1);
2286
            goto done;
2287 2288 2289 2290 2291 2292
        }
        strcpy (secmodel->model, ret.model.model_val);
    }

    if (ret.doi.doi_val != NULL) {
        if (strlen (ret.doi.doi_val) >= sizeof secmodel->doi) {
2293 2294
            remoteError(VIR_ERR_RPC, _("security doi exceeds maximum: %zd"),
                        sizeof secmodel->doi - 1);
2295
            goto done;
2296 2297 2298
        }
        strcpy (secmodel->doi, ret.doi.doi_val);
    }
2299 2300 2301 2302 2303 2304

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
2305 2306
}

2307 2308 2309 2310 2311 2312 2313
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)
{
2314
    int rv = -1;
2315 2316
    remote_domain_migrate_prepare_args args;
    remote_domain_migrate_prepare_ret ret;
2317
    struct private_data *priv = dconn->privateData;
2318

2319 2320
    remoteDriverLock(priv);

2321 2322 2323 2324 2325 2326 2327 2328 2329
    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)
2330
        goto done;
2331 2332 2333 2334 2335 2336 2337 2338

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

2339 2340 2341
    rv = 0;

done:
2342
    remoteDriverUnlock(priv);
2343
    return rv;
2344 2345
}

D
Daniel Veillard 已提交
2346 2347 2348 2349 2350 2351 2352 2353
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)
{
2354
    int rv = -1;
D
Daniel Veillard 已提交
2355 2356
    remote_domain_migrate_prepare2_args args;
    remote_domain_migrate_prepare2_ret ret;
2357
    struct private_data *priv = dconn->privateData;
D
Daniel Veillard 已提交
2358

2359 2360
    remoteDriverLock(priv);

D
Daniel Veillard 已提交
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
    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)
2371
        goto done;
D
Daniel Veillard 已提交
2372 2373

    if (ret.cookie.cookie_len > 0) {
2374 2375 2376 2377 2378
        if (!cookie || !cookielen) {
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("caller ignores cookie or cookielen"));
            goto error;
        }
D
Daniel Veillard 已提交
2379 2380 2381
        *cookie = ret.cookie.cookie_val; /* Caller frees. */
        *cookielen = ret.cookie.cookie_len;
    }
2382 2383 2384 2385 2386 2387
    if (ret.uri_out) {
        if (!uri_out) {
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("caller ignores uri_out"));
            goto error;
        }
D
Daniel Veillard 已提交
2388
        *uri_out = *ret.uri_out; /* Caller frees. */
2389
    }
D
Daniel Veillard 已提交
2390

2391 2392 2393
    rv = 0;

done:
2394
    remoteDriverUnlock(priv);
2395
    return rv;
2396 2397 2398 2399 2400 2401
error:
    if (ret.cookie.cookie_len)
        VIR_FREE(ret.cookie.cookie_val);
    if (ret.uri_out)
        VIR_FREE(*ret.uri_out);
    goto done;
D
Daniel Veillard 已提交
2402 2403
}

2404 2405 2406
static int
remoteDomainCreate (virDomainPtr domain)
{
2407
    int rv = -1;
2408
    remote_domain_create_args args;
2409 2410
    remote_domain_lookup_by_uuid_args args2;
    remote_domain_lookup_by_uuid_ret ret2;
2411
    struct private_data *priv = domain->conn->privateData;
2412

2413 2414
    remoteDriverLock(priv);

2415 2416 2417 2418 2419
    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)
2420
        goto done;
2421

2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435
    /* Need to do a lookup figure out ID of newly started guest, because
     * bug in design of REMOTE_PROC_DOMAIN_CREATE means we aren't getting
     * it returned.
     */
    memcpy (args2.uuid, domain->uuid, VIR_UUID_BUFLEN);
    memset (&ret2, 0, sizeof ret2);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_LOOKUP_BY_UUID,
              (xdrproc_t) xdr_remote_domain_lookup_by_uuid_args, (char *) &args2,
              (xdrproc_t) xdr_remote_domain_lookup_by_uuid_ret, (char *) &ret2) == -1)
        goto done;

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

2436 2437 2438
    rv = 0;

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

2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
static int
remoteDomainCreateWithFlags (virDomainPtr domain, unsigned int flags)
{
    int rv = -1;
    remote_domain_create_with_flags_args args;
    remote_domain_create_with_flags_ret ret;
    struct private_data *priv = domain->conn->privateData;

    remoteDriverLock(priv);

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

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_CREATE_WITH_FLAGS,
              (xdrproc_t) xdr_remote_domain_create_with_flags_args,
              (char *) &args,
              (xdrproc_t) xdr_remote_domain_create_with_flags_ret,
              (char *) &ret) == -1)
        goto done;

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

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

2475 2476
static char *
remoteDomainGetSchedulerType (virDomainPtr domain, int *nparams)
2477
{
2478 2479 2480
    char *rv = NULL;
    remote_domain_get_scheduler_type_args args;
    remote_domain_get_scheduler_type_ret ret;
2481
    struct private_data *priv = domain->conn->privateData;
2482

2483 2484
    remoteDriverLock(priv);

2485 2486
    make_nonnull_domain (&args.dom, domain);

2487 2488 2489 2490
    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)
2491
        goto done;
2492 2493 2494 2495

    if (nparams) *nparams = ret.nparams;

    /* Caller frees this. */
2496 2497 2498
    rv = ret.type;

done:
2499
    remoteDriverUnlock(priv);
2500
    return rv;
2501 2502 2503 2504 2505 2506
}

static int
remoteDomainGetSchedulerParameters (virDomainPtr domain,
                                    virSchedParameterPtr params, int *nparams)
{
2507
    int rv = -1;
2508 2509
    remote_domain_get_scheduler_parameters_args args;
    remote_domain_get_scheduler_parameters_ret ret;
2510
    int i = -1;
2511
    struct private_data *priv = domain->conn->privateData;
2512

2513 2514
    remoteDriverLock(priv);

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

    /* Check the length of the returned list carefully. */
    if (ret.params.params_len > REMOTE_DOMAIN_SCHEDULER_PARAMETERS_MAX ||
        ret.params.params_len > *nparams) {
2527 2528 2529
        remoteError(VIR_ERR_RPC, "%s",
                    _("remoteDomainGetSchedulerParameters: "
                      "returned number of parameters exceeds limit"));
2530
        goto cleanup;
2531 2532 2533 2534 2535
    }
    *nparams = ret.params.params_len;

    /* Deserialise the result. */
    for (i = 0; i < *nparams; ++i) {
C
Chris Lalancette 已提交
2536
        if (virStrcpyStatic(params[i].field, ret.params.params_val[i].field) == NULL) {
2537 2538 2539
            remoteError(VIR_ERR_INTERNAL_ERROR,
                        _("Parameter %s too big for destination"),
                        ret.params.params_val[i].field);
C
Chris Lalancette 已提交
2540 2541
            goto cleanup;
        }
2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
        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:
2557 2558 2559
            remoteError(VIR_ERR_RPC, "%s",
                        _("remoteDomainGetSchedulerParameters: "
                          "unknown parameter type"));
2560
            goto cleanup;
2561 2562 2563
        }
    }

2564 2565 2566
    rv = 0;

cleanup:
2567
    xdr_free ((xdrproc_t) xdr_remote_domain_get_scheduler_parameters_ret, (char *) &ret);
2568
done:
2569
    remoteDriverUnlock(priv);
2570
    return rv;
2571 2572 2573 2574 2575 2576
}

static int
remoteDomainSetSchedulerParameters (virDomainPtr domain,
                                    virSchedParameterPtr params, int nparams)
{
2577
    int rv = -1;
2578 2579
    remote_domain_set_scheduler_parameters_args args;
    int i, do_error;
2580
    struct private_data *priv = domain->conn->privateData;
2581

2582 2583
    remoteDriverLock(priv);

2584 2585 2586 2587
    make_nonnull_domain (&args.dom, domain);

    /* Serialise the scheduler parameters. */
    args.params.params_len = nparams;
2588
    if (VIR_ALLOC_N(args.params.params_val, nparams) < 0) {
2589
        virReportOOMError();
2590
        goto done;
2591 2592 2593 2594
    }

    do_error = 0;
    for (i = 0; i < nparams; ++i) {
2595
        /* call() will free this: */
2596 2597
        args.params.params_val[i].field = strdup (params[i].field);
        if (args.params.params_val[i].field == NULL) {
2598
            virReportOOMError();
2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
            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:
2616
            remoteError(VIR_ERR_RPC, "%s", _("unknown parameter type"));
2617 2618 2619 2620 2621 2622
            do_error = 1;
        }
    }

    if (do_error) {
        xdr_free ((xdrproc_t) xdr_remote_domain_set_scheduler_parameters_args, (char *) &args);
2623
        goto done;
2624 2625 2626 2627 2628
    }

    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)
2629
        goto done;
2630

2631 2632 2633
    rv = 0;

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

2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705
static int
remoteDomainSetSchedulerParametersFlags(virDomainPtr domain,
                                        virSchedParameterPtr params,
                                        int nparams,
                                        unsigned int flags)
{
    int rv = -1;
    remote_domain_set_scheduler_parameters_flags_args args;
    int i, do_error;
    struct private_data *priv = domain->conn->privateData;

    remoteDriverLock(priv);

    make_nonnull_domain (&args.dom, domain);

    /* Serialise the scheduler parameters. */
    args.params.params_len = nparams;
    args.flags = flags;
    if (VIR_ALLOC_N(args.params.params_val, nparams) < 0) {
        virReportOOMError();
        goto done;
    }

    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) {
            virReportOOMError();
            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:
            remoteError(VIR_ERR_RPC, "%s", _("unknown parameter type"));
            do_error = 1;
        }
    }

    if (do_error) {
        xdr_free ((xdrproc_t) xdr_remote_domain_set_scheduler_parameters_flags_args, (char *) &args);
        goto done;
    }

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_SET_SCHEDULER_PARAMETERS_FLAGS,
              (xdrproc_t) xdr_remote_domain_set_scheduler_parameters_flags_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720
static int
remoteDomainMemoryStats (virDomainPtr domain,
                         struct _virDomainMemoryStat *stats,
                         unsigned int nr_stats)
{
    int rv = -1;
    remote_domain_memory_stats_args args;
    remote_domain_memory_stats_ret ret;
    struct private_data *priv = domain->conn->privateData;
    unsigned int i;

    remoteDriverLock(priv);

    make_nonnull_domain (&args.dom, domain);
    if (nr_stats > REMOTE_DOMAIN_MEMORY_STATS_MAX) {
2721 2722 2723
        remoteError(VIR_ERR_RPC,
                    _("too many memory stats requested: %d > %d"), nr_stats,
                    REMOTE_DOMAIN_MEMORY_STATS_MAX);
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
        goto done;
    }
    args.maxStats = nr_stats;
    args.flags = 0;
    memset (&ret, 0, sizeof ret);

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_MEMORY_STATS,
              (xdrproc_t) xdr_remote_domain_memory_stats_args,
                (char *) &args,
              (xdrproc_t) xdr_remote_domain_memory_stats_ret,
                (char *) &ret) == -1)
        goto done;

    for (i = 0; i < ret.stats.stats_len; i++) {
        stats[i].tag = ret.stats.stats_val[i].tag;
        stats[i].val = ret.stats.stats_val[i].val;
    }
    rv = ret.stats.stats_len;
    xdr_free((xdrproc_t) xdr_remote_domain_memory_stats_ret, (char *) &ret);

done:
    remoteDriverUnlock(priv);
    return rv;
}

2749 2750 2751 2752 2753 2754 2755 2756
static int
remoteDomainBlockPeek (virDomainPtr domain,
                       const char *path,
                       unsigned long long offset,
                       size_t size,
                       void *buffer,
                       unsigned int flags)
{
2757
    int rv = -1;
2758 2759
    remote_domain_block_peek_args args;
    remote_domain_block_peek_ret ret;
2760
    struct private_data *priv = domain->conn->privateData;
2761

2762 2763
    remoteDriverLock(priv);

2764
    if (size > REMOTE_DOMAIN_BLOCK_PEEK_BUFFER_MAX) {
2765 2766 2767
        remoteError(VIR_ERR_RPC,
                    _("block peek request too large for remote protocol, %zi > %d"),
                    size, REMOTE_DOMAIN_BLOCK_PEEK_BUFFER_MAX);
2768
        goto done;
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
    }

    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)
2783
        goto done;
2784 2785

    if (ret.buffer.buffer_len != size) {
2786 2787
        remoteError(VIR_ERR_RPC, "%s",
                    _("returned buffer is not same size as requested"));
2788
        goto cleanup;
2789 2790 2791
    }

    memcpy (buffer, ret.buffer.buffer_val, size);
2792 2793 2794
    rv = 0;

cleanup:
2795
    VIR_FREE(ret.buffer.buffer_val);
2796

2797
done:
2798
    remoteDriverUnlock(priv);
2799
    return rv;
2800 2801
}

R
Richard W.M. Jones 已提交
2802 2803 2804 2805 2806 2807 2808
static int
remoteDomainMemoryPeek (virDomainPtr domain,
                        unsigned long long offset,
                        size_t size,
                        void *buffer,
                        unsigned int flags)
{
2809
    int rv = -1;
R
Richard W.M. Jones 已提交
2810 2811
    remote_domain_memory_peek_args args;
    remote_domain_memory_peek_ret ret;
2812
    struct private_data *priv = domain->conn->privateData;
R
Richard W.M. Jones 已提交
2813

2814 2815
    remoteDriverLock(priv);

R
Richard W.M. Jones 已提交
2816
    if (size > REMOTE_DOMAIN_MEMORY_PEEK_BUFFER_MAX) {
2817 2818 2819
        remoteError(VIR_ERR_RPC,
                    _("memory peek request too large for remote protocol, %zi > %d"),
                    size, REMOTE_DOMAIN_MEMORY_PEEK_BUFFER_MAX);
2820
        goto done;
R
Richard W.M. Jones 已提交
2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833
    }

    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)
2834
        goto done;
R
Richard W.M. Jones 已提交
2835 2836

    if (ret.buffer.buffer_len != size) {
2837 2838
        remoteError(VIR_ERR_RPC, "%s",
                    _("returned buffer is not same size as requested"));
2839
        goto cleanup;
R
Richard W.M. Jones 已提交
2840 2841 2842
    }

    memcpy (buffer, ret.buffer.buffer_val, size);
2843 2844 2845
    rv = 0;

cleanup:
2846
    VIR_FREE(ret.buffer.buffer_val);
R
Richard W.M. Jones 已提交
2847

2848
done:
2849
    remoteDriverUnlock(priv);
2850
    return rv;
R
Richard W.M. Jones 已提交
2851 2852
}

2853 2854
/*----------------------------------------------------------------------*/

J
Jim Meyering 已提交
2855
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
2856 2857
remoteGenericOpen(virConnectPtr conn, virConnectAuthPtr auth,
                  int flags, void **genericPrivateData)
2858
{
2859 2860 2861
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

J
Jim Meyering 已提交
2862
    if (conn->driver &&
2863
        STREQ (conn->driver->name, "remote")) {
2864 2865
        struct private_data *priv;

2866
        /* If we're here, the remote driver is already
2867
         * in use due to a) a QEMU uri, or b) a remote
2868
         * URI. So we can re-use existing connection */
2869 2870 2871
        priv = conn->privateData;
        remoteDriverLock(priv);
        priv->localUses++;
2872 2873 2874 2875 2876 2877 2878 2879 2880
        *genericPrivateData = priv;
        remoteDriverUnlock(priv);
        return VIR_DRV_OPEN_SUCCESS;
    } else if (conn->networkDriver &&
               STREQ (conn->networkDriver->name, "remote")) {
        struct private_data *priv = conn->networkPrivateData;
        remoteDriverLock(priv);
        *genericPrivateData = priv;
        priv->localUses++;
2881
        remoteDriverUnlock(priv);
2882
        return VIR_DRV_OPEN_SUCCESS;
2883 2884 2885
    } else {
        /* Using a non-remote driver, so we need to open a
         * new connection for network APIs, forcing it to
2886
         * use the UNIX transport. This handles Xen driver
2887
         * which doesn't have its own impl of the network APIs. */
2888
        struct private_data *priv;
2889
        int ret;
2890
        ret = remoteOpenSecondaryDriver(conn, auth, flags, &priv);
2891
        if (ret == VIR_DRV_OPEN_SUCCESS)
2892
            *genericPrivateData = priv;
2893 2894
        return ret;
    }
2895 2896 2897
}

static int
2898
remoteGenericClose(virConnectPtr conn, void **genericPrivateData)
2899
{
2900
    int rv = 0;
2901
    struct private_data *priv = *genericPrivateData;
2902

2903 2904 2905 2906
    remoteDriverLock(priv);
    priv->localUses--;
    if (!priv->localUses) {
        rv = doRemoteClose(conn, priv);
2907
        *genericPrivateData = NULL;
2908 2909 2910
        remoteDriverUnlock(priv);
        virMutexDestroy(&priv->lock);
        VIR_FREE(priv);
2911
    }
2912 2913
    if (priv)
        remoteDriverUnlock(priv);
2914
    return rv;
2915 2916
}

2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
remoteNetworkOpen(virConnectPtr conn, virConnectAuthPtr auth, int flags)
{
    return remoteGenericOpen(conn, auth, flags, &conn->networkPrivateData);
}

static int
remoteNetworkClose(virConnectPtr conn)
{
    return remoteGenericClose(conn, &conn->networkPrivateData);
}

D
Daniel Veillard 已提交
2929 2930
/*----------------------------------------------------------------------*/

J
Jim Meyering 已提交
2931
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
2932
remoteInterfaceOpen(virConnectPtr conn, virConnectAuthPtr auth, int flags)
D
Daniel Veillard 已提交
2933
{
2934
    return remoteGenericOpen(conn, auth, flags, &conn->interfacePrivateData);
D
Daniel Veillard 已提交
2935 2936 2937
}

static int
2938
remoteInterfaceClose(virConnectPtr conn)
D
Daniel Veillard 已提交
2939
{
2940
    return remoteGenericClose(conn, &conn->interfacePrivateData);
D
Daniel Veillard 已提交
2941 2942
}

2943 2944
/*----------------------------------------------------------------------*/

J
Jim Meyering 已提交
2945
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
2946
remoteStorageOpen(virConnectPtr conn, virConnectAuthPtr auth, int flags)
2947
{
2948
    return remoteGenericOpen(conn, auth, flags, &conn->storagePrivateData);
2949 2950 2951
}

static int
2952
remoteStorageClose(virConnectPtr conn)
2953
{
2954
    return remoteGenericClose(conn, &conn->storagePrivateData);
2955 2956
}

2957 2958 2959 2960 2961 2962
static char *
remoteFindStoragePoolSources (virConnectPtr conn,
                              const char *type,
                              const char *srcSpec,
                              unsigned int flags)
{
2963
    char *rv = NULL;
2964 2965
    remote_find_storage_pool_sources_args args;
    remote_find_storage_pool_sources_ret ret;
2966
    struct private_data *priv = conn->storagePrivateData;
2967 2968
    const char *emptyString = "";

2969 2970
    remoteDriverLock(priv);

2971 2972 2973 2974 2975 2976 2977
    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:
2978
     *    libvir: Remote error : marshaling args
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988
     *
     * 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,
2989
              (xdrproc_t) xdr_remote_find_storage_pool_sources_ret, (char *) &ret) == -1)
2990
        goto done;
2991

2992 2993 2994 2995
    rv = ret.xml;
    ret.xml = NULL; /* To stop xdr_free free'ing it */

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

done:
2998
    remoteDriverUnlock(priv);
2999
    return rv;
3000 3001
}

3002 3003
/*----------------------------------------------------------------------*/

J
Jim Meyering 已提交
3004
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
3005
remoteDevMonOpen(virConnectPtr conn, virConnectAuthPtr auth, int flags)
3006
{
3007
    return remoteGenericOpen(conn, auth, flags, &conn->devMonPrivateData);
3008 3009
}

3010 3011
static int
remoteDevMonClose(virConnectPtr conn)
3012
{
3013
    return remoteGenericClose(conn, &conn->devMonPrivateData);
3014 3015
}

3016 3017 3018 3019 3020
static int
remoteNodeDeviceDettach (virNodeDevicePtr dev)
{
    int rv = -1;
    remote_node_device_dettach_args args;
3021 3022
    /* This method is unusual in that it uses the HV driver, not the devMon driver
     * hence its use of privateData, instead of devMonPrivateData */
3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045
    struct private_data *priv = dev->conn->privateData;

    remoteDriverLock(priv);

    args.name = dev->name;

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

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static int
remoteNodeDeviceReAttach (virNodeDevicePtr dev)
{
    int rv = -1;
    remote_node_device_re_attach_args args;
3046 3047
    /* This method is unusual in that it uses the HV driver, not the devMon driver
     * hence its use of privateData, instead of devMonPrivateData */
3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
    struct private_data *priv = dev->conn->privateData;

    remoteDriverLock(priv);

    args.name = dev->name;

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

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

static int
remoteNodeDeviceReset (virNodeDevicePtr dev)
{
    int rv = -1;
    remote_node_device_reset_args args;
3071 3072
    /* This method is unusual in that it uses the HV driver, not the devMon driver
     * hence its use of privateData, instead of devMonPrivateData */
3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090
    struct private_data *priv = dev->conn->privateData;

    remoteDriverLock(priv);

    args.name = dev->name;

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

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

3091 3092 3093
/* ------------------------------------------------------------- */

static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
3094
remoteNWFilterOpen(virConnectPtr conn, virConnectAuthPtr auth, int flags)
3095
{
3096
    return remoteGenericOpen(conn, auth, flags, &conn->nwfilterPrivateData);
3097 3098 3099
}

static int
3100
remoteNWFilterClose(virConnectPtr conn)
3101
{
3102
    return remoteGenericClose(conn, &conn->nwfilterPrivateData);
3103 3104
}

3105 3106
/*----------------------------------------------------------------------*/

3107
static int
E
Eric Blake 已提交
3108 3109 3110
remoteAuthenticate (virConnectPtr conn, struct private_data *priv,
                    int in_open ATTRIBUTE_UNUSED,
                    virConnectAuthPtr auth ATTRIBUTE_UNUSED,
3111
                    const char *authtype)
3112 3113
{
    struct remote_auth_list_ret ret;
3114
    int err, type = REMOTE_AUTH_NONE;
3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130

    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;

3131 3132 3133 3134 3135 3136 3137 3138
    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 {
3139 3140
            remoteError(VIR_ERR_AUTH_FAILED,
                        _("unknown authentication type %s"), authtype);
3141 3142 3143 3144 3145 3146 3147
            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) {
3148 3149 3150
            remoteError(VIR_ERR_AUTH_FAILED,
                        _("requested authentication type %s rejected"),
                        authtype);
3151 3152 3153 3154 3155 3156 3157
            return -1;
        }
    } else {
        type = ret.types.types_val[0];
    }

    switch (type) {
3158
#if HAVE_SASL
3159 3160 3161 3162 3163 3164 3165
    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) {
3166
            VIR_FREE(ret.types.types_val);
3167 3168 3169
            return -1;
        }
        break;
3170
    }
3171 3172
#endif

3173 3174
#if HAVE_POLKIT
    case REMOTE_AUTH_POLKIT:
3175
        if (remoteAuthPolkit(conn, priv, in_open, auth) < 0) {
3176
            VIR_FREE(ret.types.types_val);
3177 3178 3179 3180 3181
            return -1;
        }
        break;
#endif

3182 3183 3184 3185 3186
    case REMOTE_AUTH_NONE:
        /* Nothing todo, hurrah ! */
        break;

    default:
3187 3188 3189
        remoteError(VIR_ERR_AUTH_FAILED,
                    _("unsupported authentication type %d"),
                    ret.types.types_val[0]);
3190
        VIR_FREE(ret.types.types_val);
3191 3192 3193
        return -1;
    }

3194
    VIR_FREE(ret.types.types_val);
3195 3196 3197 3198 3199 3200 3201

    return 0;
}



#if HAVE_SASL
3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279
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)
{
3280
    sasl_callback_t *cbs;
3281
    int i, n;
3282
    if (VIR_ALLOC_N(cbs, ncredtype+1) < 0) {
3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301
        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
3302
 *
3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316
 * 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 */

3317
    if (VIR_ALLOC_N(*cred, ninteract) < 0)
3318 3319 3320 3321 3322
        return -1;

    for (ninteract = 0 ; interact[ninteract].id != 0 ; ninteract++) {
        (*cred)[ninteract].type = remoteAuthCredSASL2Vir(interact[ninteract].id);
        if (!(*cred)[ninteract].type) {
3323
            VIR_FREE(*cred);
3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341
            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++)
3342 3343
        VIR_FREE(cred[i].result);
    VIR_FREE(cred);
3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364
}


/*
 * @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
3365 3366
 */
static int
3367 3368
remoteAuthSASL (virConnectPtr conn, struct private_data *priv, int in_open,
                virConnectAuthPtr auth, const char *wantmech)
3369 3370
{
    sasl_conn_t *saslconn = NULL;
3371
    sasl_security_properties_t secprops;
3372 3373 3374 3375 3376 3377
    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;
3378
    char *serverin = NULL;
3379 3380 3381
    unsigned int clientoutlen, serverinlen;
    const char *mech;
    int err, complete;
3382
    virSocketAddr sa;
3383
    char *localAddr = NULL, *remoteAddr = NULL;
3384 3385
    const void *val;
    sasl_ssf_t ssf;
3386 3387 3388 3389 3390 3391
    sasl_callback_t *saslcb = NULL;
    sasl_interact_t *interact = NULL;
    virConnectCredentialPtr cred = NULL;
    int ncred = 0;
    int ret = -1;
    const char *mechlist;
3392

3393
    VIR_DEBUG("Client initialize SASL authentication");
3394 3395 3396
    /* Sets up the SASL library as a whole */
    err = sasl_client_init(NULL);
    if (err != SASL_OK) {
3397 3398 3399
        remoteError(VIR_ERR_AUTH_FAILED,
                    _("failed to initialize SASL library: %d (%s)"),
                    err, sasl_errstring(err, NULL, NULL));
3400
        goto cleanup;
3401 3402 3403
    }

    /* Get local address in form  IPADDR:PORT */
3404 3405
    sa.len = sizeof(sa.data.stor);
    if (getsockname(priv->sock, &sa.data.sa, &sa.len) < 0) {
3406
        virReportSystemError(errno, "%s",
3407
                             _("failed to get sock address"));
3408
        goto cleanup;
3409
    }
3410
    if ((localAddr = virSocketFormatAddrFull(&sa, true, ";")) == NULL)
3411
        goto cleanup;
3412 3413

    /* Get remote address in form  IPADDR:PORT */
3414 3415
    sa.len = sizeof(sa.data.stor);
    if (getpeername(priv->sock, &sa.data.sa, &sa.len) < 0) {
3416
        virReportSystemError(errno, "%s",
3417
                             _("failed to get peer address"));
3418
        goto cleanup;
3419
    }
3420
    if ((remoteAddr = virSocketFormatAddrFull(&sa, true, ";")) == NULL)
3421 3422
        goto cleanup;

3423 3424 3425 3426 3427 3428
    if (auth) {
        if ((saslcb = remoteAuthMakeCallbacks(auth->credtype, auth->ncredtype)) == NULL)
            goto cleanup;
    } else {
        saslcb = NULL;
    }
3429 3430 3431 3432 3433 3434

    /* Setup a handle for being a client */
    err = sasl_client_new("libvirt",
                          priv->hostname,
                          localAddr,
                          remoteAddr,
3435
                          saslcb,
3436 3437
                          SASL_SUCCESS_DATA,
                          &saslconn);
3438

3439
    if (err != SASL_OK) {
3440 3441 3442
        remoteError(VIR_ERR_AUTH_FAILED,
                    _("Failed to create SASL client context: %d (%s)"),
                    err, sasl_errstring(err, NULL, NULL));
3443
        goto cleanup;
3444 3445
    }

3446 3447 3448 3449 3450 3451
    /* 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))) {
3452 3453
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("invalid cipher size for TLS session"));
3454
            goto cleanup;
3455 3456 3457
        }
        ssf *= 8; /* key size is bytes, sasl wants bits */

3458
        VIR_DEBUG("Setting external SSF %d", ssf);
3459 3460
        err = sasl_setprop(saslconn, SASL_SSF_EXTERNAL, &ssf);
        if (err != SASL_OK) {
3461 3462 3463
            remoteError(VIR_ERR_INTERNAL_ERROR,
                        _("cannot set external SSF %d (%s)"),
                        err, sasl_errstring(err, NULL, NULL));
3464
            goto cleanup;
3465 3466 3467 3468
        }
    }

    memset (&secprops, 0, sizeof secprops);
3469 3470 3471
    /* If we've got a secure channel (TLS or UNIX sock), we don't care about SSF */
    secprops.min_ssf = priv->is_secure ? 0 : 56; /* Equiv to DES supported by all Kerberos */
    secprops.max_ssf = priv->is_secure ? 0 : 100000; /* Very strong ! AES == 256 */
3472
    secprops.maxbufsize = 100000;
3473 3474
    /* If we're not secure, then forbid any anonymous or trivially crackable auth */
    secprops.security_flags = priv->is_secure ? 0 :
3475 3476 3477 3478
        SASL_SEC_NOANONYMOUS | SASL_SEC_NOPLAINTEXT;

    err = sasl_setprop(saslconn, SASL_SEC_PROPS, &secprops);
    if (err != SASL_OK) {
3479 3480 3481
        remoteError(VIR_ERR_INTERNAL_ERROR,
                    _("cannot set security props %d (%s)"),
                    err, sasl_errstring(err, NULL, NULL));
3482
        goto cleanup;
3483 3484
    }

3485 3486 3487 3488
    /* 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,
3489 3490
              (xdrproc_t) xdr_remote_auth_sasl_init_ret, (char *) &iret) != 0)
        goto cleanup;
3491 3492


3493 3494 3495
    mechlist = iret.mechlist;
    if (wantmech) {
        if (strstr(mechlist, wantmech) == NULL) {
3496 3497 3498
            remoteError(VIR_ERR_AUTH_FAILED,
                        _("SASL mechanism %s not supported by server"),
                        wantmech);
3499
            VIR_FREE(iret.mechlist);
3500 3501 3502 3503 3504
            goto cleanup;
        }
        mechlist = wantmech;
    }
 restart:
3505
    /* Start the auth negotiation on the client end first */
3506
    VIR_DEBUG("Client start negotiation mechlist '%s'", mechlist);
3507
    err = sasl_client_start(saslconn,
3508 3509
                            mechlist,
                            &interact,
3510 3511 3512
                            &clientout,
                            &clientoutlen,
                            &mech);
3513
    if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
3514 3515 3516
        remoteError(VIR_ERR_AUTH_FAILED,
                    _("Failed to start SASL negotiation: %d (%s)"),
                    err, sasl_errdetail(saslconn));
3517
        VIR_FREE(iret.mechlist);
3518 3519 3520 3521 3522
        goto cleanup;
    }

    /* Need to gather some credentials from the client */
    if (err == SASL_INTERACT) {
3523
        const char *msg;
3524 3525 3526 3527
        if (cred) {
            remoteAuthFreeCredentials(cred, ncred);
            cred = NULL;
        }
3528 3529 3530
        if ((ncred = remoteAuthMakeCredentials(interact, &cred)) < 0) {
            remoteError(VIR_ERR_AUTH_FAILED, "%s",
                        _("Failed to make auth credentials"));
3531
            VIR_FREE(iret.mechlist);
3532 3533 3534
            goto cleanup;
        }
        /* Run the authentication callback */
3535
        if (auth && auth->cb) {
3536 3537 3538
            if ((*(auth->cb))(cred, ncred, auth->cbdata) >= 0) {
                remoteAuthFillInteract(cred, interact);
                goto restart;
3539
            }
3540
            msg = "Failed to collect auth credentials";
3541
        } else {
3542
            msg = "No authentication callback available";
3543
        }
3544
        remoteError(VIR_ERR_AUTH_FAILED, "%s", msg);
3545
        goto cleanup;
3546
    }
3547
    VIR_FREE(iret.mechlist);
3548 3549

    if (clientoutlen > REMOTE_AUTH_SASL_DATA_MAX) {
3550 3551 3552
        remoteError(VIR_ERR_AUTH_FAILED,
                    _("SASL negotiation data too long: %d bytes"),
                    clientoutlen);
3553
        goto cleanup;
3554 3555 3556 3557 3558 3559 3560
    }
    /* 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;
3561
    VIR_DEBUG("Server start negotiation with mech %s. Data %d bytes %p", mech, clientoutlen, clientout);
3562 3563 3564 3565 3566

    /* 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,
3567 3568
              (xdrproc_t) xdr_remote_auth_sasl_start_ret, (char *) &sret) != 0)
        goto cleanup;
3569 3570 3571 3572 3573

    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;
3574
    VIR_DEBUG("Client step result complete: %d. Data %d bytes %p",
3575
          complete, serverinlen, serverin);
3576 3577 3578

    /* Loop-the-loop...
     * Even if the server has completed, the client must *always* do at least one step
D
Daniel Veillard 已提交
3579
     * in this loop to verify the server isn't lying about something. Mutual auth */
3580
    for (;;) {
3581
    restep:
3582 3583 3584
        err = sasl_client_step(saslconn,
                               serverin,
                               serverinlen,
3585
                               &interact,
3586 3587
                               &clientout,
                               &clientoutlen);
3588
        if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
3589 3590 3591
            remoteError(VIR_ERR_AUTH_FAILED,
                        _("Failed SASL step: %d (%s)"),
                        err, sasl_errdetail(saslconn));
3592 3593 3594 3595
            goto cleanup;
        }
        /* Need to gather some credentials from the client */
        if (err == SASL_INTERACT) {
3596
            const char *msg;
3597 3598 3599 3600 3601
            if (cred) {
                remoteAuthFreeCredentials(cred, ncred);
                cred = NULL;
            }
            if ((ncred = remoteAuthMakeCredentials(interact, &cred)) < 0) {
3602 3603
                remoteError(VIR_ERR_AUTH_FAILED, "%s",
                            _("Failed to make auth credentials"));
3604 3605 3606
                goto cleanup;
            }
            /* Run the authentication callback */
3607
            if (auth && auth->cb) {
3608 3609 3610
                if ((*(auth->cb))(cred, ncred, auth->cbdata) >= 0) {
                    remoteAuthFillInteract(cred, interact);
                    goto restep;
3611
                }
3612
                msg = _("Failed to collect auth credentials");
3613
            } else {
3614
                msg = _("No authentication callback available");
3615
            }
3616
            remoteError(VIR_ERR_AUTH_FAILED, "%s", msg);
3617
            goto cleanup;
3618 3619
        }

3620
        VIR_FREE(serverin);
3621
        VIR_DEBUG("Client step result %d. Data %d bytes %p", err, clientoutlen, clientout);
3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632

        /* 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;
3633
        VIR_DEBUG("Server step with %d bytes %p", clientoutlen, clientout);
3634 3635 3636 3637

        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,
3638 3639
                  (xdrproc_t) xdr_remote_auth_sasl_step_ret, (char *) &pret) != 0)
            goto cleanup;
3640 3641 3642 3643 3644 3645

        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;

3646
        VIR_DEBUG("Client step result complete: %d. Data %d bytes %p",
3647
              complete, serverinlen, serverin);
3648 3649 3650

        /* This server call shows complete, and earlier client step was OK */
        if (complete && err == SASL_OK) {
3651
            VIR_FREE(serverin);
3652 3653 3654 3655
            break;
        }
    }

3656 3657
    /* Check for suitable SSF if not already secure (TLS or UNIX sock) */
    if (!priv->is_secure) {
3658 3659
        err = sasl_getprop(saslconn, SASL_SSF, &val);
        if (err != SASL_OK) {
3660 3661 3662
            remoteError(VIR_ERR_AUTH_FAILED,
                        _("cannot query SASL ssf on connection %d (%s)"),
                        err, sasl_errstring(err, NULL, NULL));
3663
            goto cleanup;
3664 3665
        }
        ssf = *(const int *)val;
3666
        VIR_DEBUG("SASL SSF value %d", ssf);
3667
        if (ssf < 56) { /* 56 == DES level, good for Kerberos */
3668 3669
            remoteError(VIR_ERR_AUTH_FAILED,
                        _("negotiation SSF %d was not strong enough"), ssf);
3670
            goto cleanup;
3671
        }
3672
        priv->is_secure = 1;
3673 3674
    }

3675
    VIR_DEBUG("SASL authentication complete");
3676
    priv->saslconn = saslconn;
3677 3678 3679
    ret = 0;

 cleanup:
3680 3681 3682
    VIR_FREE(localAddr);
    VIR_FREE(remoteAddr);
    VIR_FREE(serverin);
3683

3684
    VIR_FREE(saslcb);
3685 3686 3687
    remoteAuthFreeCredentials(cred, ncred);
    if (ret != 0 && saslconn)
        sasl_dispose(&saslconn);
3688

3689
    return ret;
3690 3691 3692
}
#endif /* HAVE_SASL */

3693 3694

#if HAVE_POLKIT
3695
# if HAVE_POLKIT1
3696 3697 3698 3699 3700
static int
remoteAuthPolkit (virConnectPtr conn, struct private_data *priv, int in_open,
                  virConnectAuthPtr auth ATTRIBUTE_UNUSED)
{
    remote_auth_polkit_ret ret;
3701
    VIR_DEBUG("Client initialize PolicyKit-1 authentication");
3702 3703 3704 3705 3706 3707 3708 3709

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

3710
    VIR_DEBUG("PolicyKit-1 authentication complete");
3711 3712
    return 0;
}
3713
# elif HAVE_POLKIT0
3714 3715 3716 3717 3718 3719 3720
/* Perform the PolicyKit authentication process
 */
static int
remoteAuthPolkit (virConnectPtr conn, struct private_data *priv, int in_open,
                  virConnectAuthPtr auth)
{
    remote_auth_polkit_ret ret;
3721
    int i, allowcb = 0;
3722 3723 3724 3725 3726 3727 3728 3729
    virConnectCredential cred = {
        VIR_CRED_EXTERNAL,
        conn->flags & VIR_CONNECT_RO ? "org.libvirt.unix.monitor" : "org.libvirt.unix.manage",
        "PolicyKit",
        NULL,
        NULL,
        0,
    };
3730
    VIR_DEBUG("Client initialize PolicyKit-0 authentication");
3731

3732
    if (auth && auth->cb) {
3733
        /* Check if the necessary credential type for PolicyKit is supported */
3734 3735 3736 3737
        for (i = 0 ; i < auth->ncredtype ; i++) {
            if (auth->credtype[i] == VIR_CRED_EXTERNAL)
                allowcb = 1;
        }
3738

3739
        if (allowcb) {
3740
            VIR_DEBUG("Client run callback for PolicyKit authentication");
3741 3742
            /* Run the authentication callback */
            if ((*(auth->cb))(&cred, 1, auth->cbdata) < 0) {
3743 3744
                remoteError(VIR_ERR_AUTH_FAILED, "%s",
                            _("Failed to collect auth credentials"));
3745 3746
                return -1;
            }
3747
        } else {
3748
            VIR_DEBUG("Client auth callback does not support PolicyKit");
3749 3750
        }
    } else {
3751
        VIR_DEBUG("No auth callback provided");
3752 3753 3754 3755 3756 3757 3758 3759 3760
    }

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

3761
    VIR_DEBUG("PolicyKit-0 authentication complete");
3762 3763
    return 0;
}
3764
# endif /* HAVE_POLKIT0 */
3765
#endif /* HAVE_POLKIT */
3766 3767
/*----------------------------------------------------------------------*/

3768 3769 3770 3771
static int remoteDomainEventRegister(virConnectPtr conn,
                                     virConnectDomainEventCallback callback,
                                     void *opaque,
                                     virFreeCallback freecb)
3772
{
3773
    int rv = -1;
3774 3775
    struct private_data *priv = conn->privateData;

3776 3777
    remoteDriverLock(priv);

3778
    if (priv->domainEventState->timer < 0) {
3779
         remoteError(VIR_ERR_NO_SUPPORT, "%s", _("no event support"));
3780
         goto done;
3781
    }
3782 3783

    if (virDomainEventCallbackListAdd(conn, priv->domainEventState->callbacks,
3784
                                      callback, opaque, freecb) < 0) {
3785
         remoteError(VIR_ERR_RPC, "%s", _("adding cb to list"));
3786
         goto done;
3787 3788
    }

3789 3790 3791
    if (virDomainEventCallbackListCountID(conn,
                                          priv->domainEventState->callbacks,
                                          VIR_DOMAIN_EVENT_ID_LIFECYCLE) == 1) {
3792 3793 3794 3795
        /* 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)
3796
            goto done;
3797 3798
    }

3799 3800 3801
    rv = 0;

done:
3802
    remoteDriverUnlock(priv);
3803
    return rv;
3804 3805
}

3806 3807
static int remoteDomainEventDeregister(virConnectPtr conn,
                                       virConnectDomainEventCallback callback)
3808 3809
{
    struct private_data *priv = conn->privateData;
3810
    int rv = -1;
3811

3812 3813
    remoteDriverLock(priv);

3814 3815 3816 3817
    if (virDomainEventStateDeregister(conn,
                                      priv->domainEventState,
                                      callback) < 0)
        goto done;
3818

3819 3820 3821
    if (virDomainEventCallbackListCountID(conn,
                                          priv->domainEventState->callbacks,
                                          VIR_DOMAIN_EVENT_ID_LIFECYCLE) == 0) {
3822 3823 3824 3825 3826
        /* Tell the server when we are the last callback deregistering */
        if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_EVENTS_DEREGISTER,
                  (xdrproc_t) xdr_void, (char *) NULL,
                  (xdrproc_t) xdr_void, (char *) NULL) == -1)
            goto done;
3827 3828
    }

3829 3830 3831
    rv = 0;

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

3836 3837 3838 3839 3840 3841 3842 3843
/**
 * remoteDomainReadEventLifecycle
 *
 * Read the domain lifecycle event data off the wire
 */
static virDomainEventPtr
remoteDomainReadEventLifecycle(virConnectPtr conn, XDR *xdr)
{
3844
    remote_domain_event_lifecycle_msg msg;
3845 3846 3847 3848
    virDomainPtr dom;
    virDomainEventPtr event = NULL;
    memset (&msg, 0, sizeof msg);

3849
    /* unmarshal parameters, and process it*/
3850
    if (! xdr_remote_domain_event_lifecycle_msg(xdr, &msg) ) {
3851
        remoteError(VIR_ERR_RPC, "%s",
3852
                    _("Unable to demarshal lifecycle event"));
3853 3854 3855 3856 3857 3858 3859 3860
        return NULL;
    }

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

    event = virDomainEventNewFromDom(dom, msg.event, msg.detail);
3861
    xdr_free ((xdrproc_t) &xdr_remote_domain_event_lifecycle_msg, (char *) &msg);
3862 3863 3864 3865 3866 3867

    virDomainFree(dom);
    return event;
}


3868 3869 3870 3871 3872 3873 3874 3875
static virDomainEventPtr
remoteDomainReadEventReboot(virConnectPtr conn, XDR *xdr)
{
    remote_domain_event_reboot_msg msg;
    virDomainPtr dom;
    virDomainEventPtr event = NULL;
    memset (&msg, 0, sizeof msg);

3876
    /* unmarshal parameters, and process it*/
3877
    if (! xdr_remote_domain_event_reboot_msg(xdr, &msg) ) {
3878
        remoteError(VIR_ERR_RPC, "%s",
3879
                    _("Unable to demarshal reboot event"));
3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894
        return NULL;
    }

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

    event = virDomainEventRebootNewFromDom(dom);
    xdr_free ((xdrproc_t) &xdr_remote_domain_event_reboot_msg, (char *) &msg);

    virDomainFree(dom);
    return event;
}


3895 3896 3897 3898 3899 3900 3901 3902
static virDomainEventPtr
remoteDomainReadEventRTCChange(virConnectPtr conn, XDR *xdr)
{
    remote_domain_event_rtc_change_msg msg;
    virDomainPtr dom;
    virDomainEventPtr event = NULL;
    memset (&msg, 0, sizeof msg);

3903
    /* unmarshal parameters, and process it*/
3904
    if (! xdr_remote_domain_event_rtc_change_msg(xdr, &msg) ) {
3905
        remoteError(VIR_ERR_RPC, "%s",
3906
                    _("Unable to demarshal RTC change event"));
3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921
        return NULL;
    }

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

    event = virDomainEventRTCChangeNewFromDom(dom, msg.offset);
    xdr_free ((xdrproc_t) &xdr_remote_domain_event_rtc_change_msg, (char *) &msg);

    virDomainFree(dom);
    return event;
}


3922 3923 3924 3925 3926 3927 3928 3929
static virDomainEventPtr
remoteDomainReadEventWatchdog(virConnectPtr conn, XDR *xdr)
{
    remote_domain_event_watchdog_msg msg;
    virDomainPtr dom;
    virDomainEventPtr event = NULL;
    memset (&msg, 0, sizeof msg);

3930
    /* unmarshal parameters, and process it*/
3931
    if (! xdr_remote_domain_event_watchdog_msg(xdr, &msg) ) {
3932
        remoteError(VIR_ERR_RPC, "%s",
3933
                    _("Unable to demarshal watchdog event"));
3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948
        return NULL;
    }

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

    event = virDomainEventWatchdogNewFromDom(dom, msg.action);
    xdr_free ((xdrproc_t) &xdr_remote_domain_event_watchdog_msg, (char *) &msg);

    virDomainFree(dom);
    return event;
}


3949 3950 3951 3952 3953 3954 3955 3956
static virDomainEventPtr
remoteDomainReadEventIOError(virConnectPtr conn, XDR *xdr)
{
    remote_domain_event_io_error_msg msg;
    virDomainPtr dom;
    virDomainEventPtr event = NULL;
    memset (&msg, 0, sizeof msg);

3957
    /* unmarshal parameters, and process it*/
3958
    if (! xdr_remote_domain_event_io_error_msg(xdr, &msg) ) {
3959
        remoteError(VIR_ERR_RPC, "%s",
3960
                    _("Unable to demarshal IO error event"));
3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978
        return NULL;
    }

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

    event = virDomainEventIOErrorNewFromDom(dom,
                                            msg.srcPath,
                                            msg.devAlias,
                                            msg.action);
    xdr_free ((xdrproc_t) &xdr_remote_domain_event_io_error_msg, (char *) &msg);

    virDomainFree(dom);
    return event;
}


3979 3980 3981 3982 3983 3984 3985 3986
static virDomainEventPtr
remoteDomainReadEventIOErrorReason(virConnectPtr conn, XDR *xdr)
{
    remote_domain_event_io_error_reason_msg msg;
    virDomainPtr dom;
    virDomainEventPtr event = NULL;
    memset (&msg, 0, sizeof msg);

3987
    /* unmarshal parameters, and process it*/
3988 3989
    if (! xdr_remote_domain_event_io_error_reason_msg(xdr, &msg) ) {
        remoteError(VIR_ERR_RPC, "%s",
3990
                    _("Unable to demarshal IO error reason event"));
3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009
        return NULL;
    }

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

    event = virDomainEventIOErrorReasonNewFromDom(dom,
                                                  msg.srcPath,
                                                  msg.devAlias,
                                                  msg.action,
                                                  msg.reason);
    xdr_free ((xdrproc_t) &xdr_remote_domain_event_io_error_reason_msg, (char *) &msg);

    virDomainFree(dom);
    return event;
}


4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022
static virDomainEventPtr
remoteDomainReadEventGraphics(virConnectPtr conn, XDR *xdr)
{
    remote_domain_event_graphics_msg msg;
    virDomainPtr dom;
    virDomainEventPtr event = NULL;
    virDomainEventGraphicsAddressPtr localAddr = NULL;
    virDomainEventGraphicsAddressPtr remoteAddr = NULL;
    virDomainEventGraphicsSubjectPtr subject = NULL;
    int i;

    memset (&msg, 0, sizeof msg);

4023
    /* unmarshal parameters, and process it*/
4024
    if (! xdr_remote_domain_event_graphics_msg(xdr, &msg) ) {
4025
        remoteError(VIR_ERR_RPC, "%s",
4026
                    _("Unable to demarshal graphics event"));
4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094
        return NULL;
    }

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

    if (VIR_ALLOC(localAddr) < 0)
        goto no_memory;
    localAddr->family = msg.local.family;
    if (!(localAddr->service = strdup(msg.local.service)) ||
        !(localAddr->node = strdup(msg.local.node)))
        goto no_memory;

    if (VIR_ALLOC(remoteAddr) < 0)
        goto no_memory;
    remoteAddr->family = msg.remote.family;
    if (!(remoteAddr->service = strdup(msg.remote.service)) ||
        !(remoteAddr->node = strdup(msg.remote.node)))
        goto no_memory;

    if (VIR_ALLOC(subject) < 0)
        goto no_memory;
    if (VIR_ALLOC_N(subject->identities, msg.subject.subject_len) < 0)
        goto no_memory;
    subject->nidentity = msg.subject.subject_len;
    for (i = 0 ; i < subject->nidentity ; i++) {
        if (!(subject->identities[i].type = strdup(msg.subject.subject_val[i].type)) ||
            !(subject->identities[i].name = strdup(msg.subject.subject_val[i].name)))
            goto no_memory;
    }

    event = virDomainEventGraphicsNewFromDom(dom,
                                             msg.phase,
                                             localAddr,
                                             remoteAddr,
                                             msg.authScheme,
                                             subject);
    xdr_free ((xdrproc_t) &xdr_remote_domain_event_graphics_msg, (char *) &msg);

    virDomainFree(dom);
    return event;

no_memory:
    xdr_free ((xdrproc_t) &xdr_remote_domain_event_graphics_msg, (char *) &msg);

    if (localAddr) {
        VIR_FREE(localAddr->service);
        VIR_FREE(localAddr->node);
        VIR_FREE(localAddr);
    }
    if (remoteAddr) {
        VIR_FREE(remoteAddr->service);
        VIR_FREE(remoteAddr->node);
        VIR_FREE(remoteAddr);
    }
    if (subject) {
        for (i = 0 ; i < subject->nidentity ; i++) {
            VIR_FREE(subject->identities[i].type);
            VIR_FREE(subject->identities[i].name);
        }
        VIR_FREE(subject->identities);
        VIR_FREE(subject);
    }
    return NULL;
}


J
Jim Meyering 已提交
4095
static virDrvOpenStatus ATTRIBUTE_NONNULL (1)
4096
remoteSecretOpen(virConnectPtr conn, virConnectAuthPtr auth, int flags)
4097
{
4098
    return remoteGenericOpen(conn, auth, flags, &conn->secretPrivateData);
4099 4100 4101 4102 4103
}

static int
remoteSecretClose (virConnectPtr conn)
{
4104
    return remoteGenericClose(conn, &conn->secretPrivateData);
4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134
}

static unsigned char *
remoteSecretGetValue (virSecretPtr secret, size_t *value_size,
                      unsigned int flags)
{
    unsigned char *rv = NULL;
    remote_secret_get_value_args args;
    remote_secret_get_value_ret ret;
    struct private_data *priv = secret->conn->secretPrivateData;

    remoteDriverLock (priv);

    make_nonnull_secret (&args.secret, secret);
    args.flags = flags;

    memset (&ret, 0, sizeof (ret));
    if (call (secret->conn, priv, 0, REMOTE_PROC_SECRET_GET_VALUE,
              (xdrproc_t) xdr_remote_secret_get_value_args, (char *) &args,
              (xdrproc_t) xdr_remote_secret_get_value_ret, (char *) &ret) == -1)
        goto done;

    *value_size = ret.value.value_len;
    rv = (unsigned char *) ret.value.value_val; /* Caller frees. */

done:
    remoteDriverUnlock (priv);
    return rv;
}

4135 4136 4137 4138 4139 4140 4141 4142
static struct private_stream_data *
remoteStreamOpen(virStreamPtr st,
                 unsigned int proc_nr,
                 unsigned int serial)
{
    struct private_data *priv = st->conn->privateData;
    struct private_stream_data *stpriv;

4143
    if (VIR_ALLOC(stpriv) < 0) {
4144
        virReportOOMError();
4145
        return NULL;
4146
    }
4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158

    /* Initialize call object used to receive replies */
    stpriv->proc_nr = proc_nr;
    stpriv->serial = serial;

    stpriv->next = priv->streams;
    priv->streams = stpriv;

    return stpriv;
}


4159 4160 4161 4162 4163 4164
static void
remoteStreamEventTimerUpdate(struct private_stream_data *privst)
{
    if (!privst->cb)
        return;

4165 4166 4167 4168
    VIR_DEBUG("Check timer offset=%d %d", privst->incomingOffset, privst->cbEvents);
    if ((privst->incomingOffset &&
         (privst->cbEvents & VIR_STREAM_EVENT_READABLE)) ||
        (privst->cbEvents & VIR_STREAM_EVENT_WRITABLE)) {
4169
        VIR_DEBUG("Enabling event timer");
4170
        virEventUpdateTimeout(privst->cbTimer, 0);
4171
    } else {
4172
        VIR_DEBUG("Disabling event timer");
4173 4174
        virEventUpdateTimeout(privst->cbTimer, -1);
    }
4175 4176 4177
}


4178 4179 4180 4181 4182 4183
static int
remoteStreamPacket(virStreamPtr st,
                   int status,
                   const char *data,
                   size_t nbytes)
{
4184
    VIR_DEBUG("st=%p status=%d data=%p nbytes=%zu", st, status, data, nbytes);
4185 4186 4187 4188 4189
    struct private_data *priv = st->conn->privateData;
    struct private_stream_data *privst = st->privateData;
    XDR xdr;
    struct remote_thread_call *thiscall;
    remote_message_header hdr;
4190
    int ret;
4191 4192 4193 4194

    memset(&hdr, 0, sizeof hdr);

    if (VIR_ALLOC(thiscall) < 0) {
4195
        virReportOOMError();
4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207
        return -1;
    }

    thiscall->mode = REMOTE_MODE_WAIT_TX;
    thiscall->serial = privst->serial;
    thiscall->proc_nr = privst->proc_nr;
    if (status == REMOTE_OK ||
        status == REMOTE_ERROR)
        thiscall->want_reply = 1;

    if (virCondInit(&thiscall->cond) < 0) {
        VIR_FREE(thiscall);
4208 4209
        remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("cannot initialize mutex"));
4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233
        return -1;
    }

    /* Don't fill in any other fields in 'thiscall' since
     * we're not expecting a reply for this */

    hdr.prog = REMOTE_PROGRAM;
    hdr.vers = REMOTE_PROTOCOL_VERSION;
    hdr.proc = privst->proc_nr;
    hdr.type = REMOTE_STREAM;
    hdr.serial = privst->serial;
    hdr.status = status;


    /* Length must include the length word itself (always encoded in
     * 4 bytes as per RFC 4506), so offset start length. We write this
     * later.
     */
    thiscall->bufferLength = REMOTE_MESSAGE_HEADER_XDR_LEN;

    /* Serialise header followed by args. */
    xdrmem_create (&xdr, thiscall->buffer + thiscall->bufferLength,
                   REMOTE_MESSAGE_MAX, XDR_ENCODE);
    if (!xdr_remote_message_header (&xdr, &hdr)) {
4234
        remoteError(VIR_ERR_RPC, "%s", _("xdr_remote_message_header failed"));
4235 4236 4237 4238 4239 4240 4241 4242
        goto error;
    }

    thiscall->bufferLength += xdr_getpos (&xdr);
    xdr_destroy (&xdr);

    if (status == REMOTE_CONTINUE) {
        if (((4 + REMOTE_MESSAGE_MAX) - thiscall->bufferLength) < nbytes) {
4243 4244
            remoteError(VIR_ERR_RPC, _("data size %zu too large for payload %d"),
                        nbytes, ((4 + REMOTE_MESSAGE_MAX) - thiscall->bufferLength));
4245 4246 4247 4248 4249 4250 4251 4252 4253 4254
            goto error;
        }

        memcpy(thiscall->buffer + thiscall->bufferLength, data, nbytes);
        thiscall->bufferLength += nbytes;
    }

    /* Go back to packet start and encode the length word. */
    xdrmem_create (&xdr, thiscall->buffer, REMOTE_MESSAGE_HEADER_XDR_LEN, XDR_ENCODE);
    if (!xdr_u_int (&xdr, &thiscall->bufferLength)) {
4255
        remoteError(VIR_ERR_RPC, "%s", _("xdr_u_int (length word)"));
4256 4257 4258 4259
        goto error;
    }
    xdr_destroy (&xdr);

4260
    ret = remoteIO(st->conn, priv, 0, thiscall);
4261
    ignore_value(virCondDestroy(&thiscall->cond));
4262 4263
    VIR_FREE(thiscall);
    if (ret < 0)
4264 4265 4266 4267 4268 4269
        return -1;

    return nbytes;

error:
    xdr_destroy (&xdr);
4270
    ignore_value(virCondDestroy(&thiscall->cond));
4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281
    VIR_FREE(thiscall);
    return -1;
}

static int
remoteStreamHasError(virStreamPtr st) {
    struct private_stream_data *privst = st->privateData;
    if (!privst->has_error) {
        return 0;
    }

4282
    VIR_DEBUG("Raising async error");
4283
    virRaiseErrorFull(__FILE__, __FUNCTION__, __LINE__,
4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329
                      privst->err.domain,
                      privst->err.code,
                      privst->err.level,
                      privst->err.str1 ? *privst->err.str1 : NULL,
                      privst->err.str2 ? *privst->err.str2 : NULL,
                      privst->err.str3 ? *privst->err.str3 : NULL,
                      privst->err.int1,
                      privst->err.int2,
                      "%s", privst->err.message ? *privst->err.message : NULL);

    return 1;
}

static void
remoteStreamRelease(virStreamPtr st)
{
    struct private_data *priv = st->conn->privateData;
    struct private_stream_data *privst = st->privateData;

    if (priv->streams == privst)
        priv->streams = privst->next;
    else {
        struct private_stream_data *tmp = priv->streams;
        while (tmp && tmp->next) {
            if (tmp->next == privst) {
                tmp->next = privst->next;
                break;
            }
        }
    }

    if (privst->has_error)
        xdr_free((xdrproc_t)xdr_remote_error,  (char *)&privst->err);

    VIR_FREE(privst);

    st->driver = NULL;
    st->privateData = NULL;
}


static int
remoteStreamSend(virStreamPtr st,
                 const char *data,
                 size_t nbytes)
{
4330
    VIR_DEBUG("st=%p data=%p nbytes=%zu", st, data, nbytes);
4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358
    struct private_data *priv = st->conn->privateData;
    int rv = -1;

    remoteDriverLock(priv);

    if (remoteStreamHasError(st))
        goto cleanup;

    rv = remoteStreamPacket(st,
                            REMOTE_CONTINUE,
                            data,
                            nbytes);

cleanup:
    if (rv == -1)
        remoteStreamRelease(st);

    remoteDriverUnlock(priv);

    return rv;
}


static int
remoteStreamRecv(virStreamPtr st,
                 char *data,
                 size_t nbytes)
{
4359
    VIR_DEBUG("st=%p data=%p nbytes=%zu", st, data, nbytes);
4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370
    struct private_data *priv = st->conn->privateData;
    struct private_stream_data *privst = st->privateData;
    int rv = -1;

    remoteDriverLock(priv);

    if (remoteStreamHasError(st))
        goto cleanup;

    if (!privst->incomingOffset) {
        struct remote_thread_call *thiscall;
4371
        int ret;
4372

4373
        if (st->flags & VIR_STREAM_NONBLOCK) {
4374
            VIR_DEBUG("Non-blocking mode and no data available");
4375 4376 4377 4378
            rv = -2;
            goto cleanup;
        }

4379
        if (VIR_ALLOC(thiscall) < 0) {
4380
            virReportOOMError();
4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392
            goto cleanup;
        }

        /* We're not really doing an RPC calls, so we're
         * skipping straight to RX part */
        thiscall->mode = REMOTE_MODE_WAIT_RX;
        thiscall->serial = privst->serial;
        thiscall->proc_nr = privst->proc_nr;
        thiscall->want_reply = 1;

        if (virCondInit(&thiscall->cond) < 0) {
            VIR_FREE(thiscall);
4393 4394
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("cannot initialize mutex"));
4395 4396 4397
            goto cleanup;
        }

4398
        ret = remoteIO(st->conn, priv, 0, thiscall);
4399
        ignore_value(virCondDestroy(&thiscall->cond));
4400 4401
        VIR_FREE(thiscall);
        if (ret < 0)
4402 4403 4404
            goto cleanup;
    }

4405
    VIR_DEBUG("After IO %d", privst->incomingOffset);
4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422
    if (privst->incomingOffset) {
        int want = privst->incomingOffset;
        if (want > nbytes)
            want = nbytes;
        memcpy(data, privst->incoming, want);
        if (want < privst->incomingOffset) {
            memmove(privst->incoming, privst->incoming + want, privst->incomingOffset - want);
            privst->incomingOffset -= want;
        } else {
            VIR_FREE(privst->incoming);
            privst->incomingOffset = privst->incomingLength = 0;
        }
        rv = want;
    } else {
        rv = 0;
    }

4423 4424
    remoteStreamEventTimerUpdate(privst);

4425
    VIR_DEBUG("Done %d", rv);
4426 4427 4428 4429 4430 4431 4432 4433 4434

cleanup:
    if (rv == -1)
        remoteStreamRelease(st);
    remoteDriverUnlock(priv);

    return rv;
}

4435 4436 4437 4438 4439 4440 4441

static void
remoteStreamEventTimer(int timer ATTRIBUTE_UNUSED, void *opaque)
{
    virStreamPtr st = opaque;
    struct private_data *priv = st->conn->privateData;
    struct private_stream_data *privst = st->privateData;
4442
    int events = 0;
4443 4444

    remoteDriverLock(priv);
4445

4446 4447
    if (privst->cb &&
        (privst->cbEvents & VIR_STREAM_EVENT_READABLE) &&
4448 4449 4450 4451 4452 4453 4454
        privst->incomingOffset)
        events |= VIR_STREAM_EVENT_READABLE;
    if (privst->cb &&
        (privst->cbEvents & VIR_STREAM_EVENT_WRITABLE))
        events |= VIR_STREAM_EVENT_WRITABLE;
    VIR_DEBUG("Got Timer dispatch %d %d offset=%d", events, privst->cbEvents, privst->incomingOffset);
    if (events) {
4455 4456 4457 4458 4459 4460
        virStreamEventCallback cb = privst->cb;
        void *cbOpaque = privst->cbOpaque;
        virFreeCallback cbFree = privst->cbFree;

        privst->cbDispatch = 1;
        remoteDriverUnlock(priv);
4461
        (cb)(st, events, cbOpaque);
4462 4463 4464 4465 4466 4467
        remoteDriverLock(priv);
        privst->cbDispatch = 0;

        if (!privst->cb && cbFree)
            (cbFree)(cbOpaque);
    }
4468

4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480
    remoteDriverUnlock(priv);
}


static void
remoteStreamEventTimerFree(void *opaque)
{
    virStreamPtr st = opaque;
    virUnrefStream(st);
}


4481
static int
4482 4483 4484 4485 4486
remoteStreamEventAddCallback(virStreamPtr st,
                             int events,
                             virStreamEventCallback cb,
                             void *opaque,
                             virFreeCallback ff)
4487
{
4488 4489 4490 4491 4492 4493 4494 4495
    struct private_data *priv = st->conn->privateData;
    struct private_stream_data *privst = st->privateData;
    int ret = -1;

    remoteDriverLock(priv);

    if (privst->cb) {
        remoteError(VIR_ERR_INTERNAL_ERROR,
4496
                    "%s", _("multiple stream callbacks not supported"));
4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514
        goto cleanup;
    }

    virStreamRef(st);
    if ((privst->cbTimer =
         virEventAddTimeout(-1,
                            remoteStreamEventTimer,
                            st,
                            remoteStreamEventTimerFree)) < 0) {
        virUnrefStream(st);
        goto cleanup;
    }

    privst->cb = cb;
    privst->cbOpaque = opaque;
    privst->cbFree = ff;
    privst->cbEvents = events;

4515 4516
    remoteStreamEventTimerUpdate(privst);

4517 4518 4519 4520 4521
    ret = 0;

cleanup:
    remoteDriverUnlock(priv);
    return ret;
4522 4523 4524
}

static int
4525 4526
remoteStreamEventUpdateCallback(virStreamPtr st,
                                int events)
4527
{
4528 4529 4530 4531 4532 4533 4534 4535
    struct private_data *priv = st->conn->privateData;
    struct private_stream_data *privst = st->privateData;
    int ret = -1;

    remoteDriverLock(priv);

    if (!privst->cb) {
        remoteError(VIR_ERR_INTERNAL_ERROR,
4536
                    "%s", _("no stream callback registered"));
4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548
        goto cleanup;
    }

    privst->cbEvents = events;

    remoteStreamEventTimerUpdate(privst);

    ret = 0;

cleanup:
    remoteDriverUnlock(priv);
    return ret;
4549 4550 4551 4552
}


static int
4553
remoteStreamEventRemoveCallback(virStreamPtr st)
4554
{
4555 4556 4557 4558 4559 4560 4561 4562
    struct private_data *priv = st->conn->privateData;
    struct private_stream_data *privst = st->privateData;
    int ret = -1;

    remoteDriverLock(priv);

    if (!privst->cb) {
        remoteError(VIR_ERR_INTERNAL_ERROR,
4563
                    "%s", _("no stream callback registered"));
4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580
        goto cleanup;
    }

    if (!privst->cbDispatch &&
        privst->cbFree)
        (privst->cbFree)(privst->cbOpaque);
    privst->cb = NULL;
    privst->cbOpaque = NULL;
    privst->cbFree = NULL;
    privst->cbEvents = 0;
    virEventRemoveTimeout(privst->cbTimer);

    ret = 0;

cleanup:
    remoteDriverUnlock(priv);
    return ret;
4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641
}

static int
remoteStreamFinish(virStreamPtr st)
{
    struct private_data *priv = st->conn->privateData;
    int ret = -1;

    remoteDriverLock(priv);

    if (remoteStreamHasError(st))
        goto cleanup;

    ret = remoteStreamPacket(st,
                             REMOTE_OK,
                             NULL,
                             0);

cleanup:
    remoteStreamRelease(st);

    remoteDriverUnlock(priv);
    return ret;
}

static int
remoteStreamAbort(virStreamPtr st)
{
    struct private_data *priv = st->conn->privateData;
    int ret = -1;

    remoteDriverLock(priv);

    if (remoteStreamHasError(st))
        goto cleanup;

    ret = remoteStreamPacket(st,
                             REMOTE_ERROR,
                             NULL,
                             0);

cleanup:
    remoteStreamRelease(st);

    remoteDriverUnlock(priv);
    return ret;
}



static virStreamDriver remoteStreamDrv = {
    .streamRecv = remoteStreamRecv,
    .streamSend = remoteStreamSend,
    .streamFinish = remoteStreamFinish,
    .streamAbort = remoteStreamAbort,
    .streamAddCallback = remoteStreamEventAddCallback,
    .streamUpdateCallback = remoteStreamEventUpdateCallback,
    .streamRemoveCallback = remoteStreamEventRemoveCallback,
};


C
Chris Lalancette 已提交
4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656
static int
remoteDomainMigratePrepareTunnel(virConnectPtr conn,
                                 virStreamPtr st,
                                 unsigned long flags,
                                 const char *dname,
                                 unsigned long resource,
                                 const char *dom_xml)
{
    struct private_data *priv = conn->privateData;
    struct private_stream_data *privst = NULL;
    int rv = -1;
    remote_domain_migrate_prepare_tunnel_args args;

    remoteDriverLock(priv);

4657
    if (!(privst = remoteStreamOpen(st, REMOTE_PROC_DOMAIN_MIGRATE_PREPARE_TUNNEL, priv->counter)))
C
Chris Lalancette 已提交
4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682
        goto done;

    st->driver = &remoteStreamDrv;
    st->privateData = privst;

    args.flags = flags;
    args.dname = dname == NULL ? NULL : (char **) &dname;
    args.resource = resource;
    args.dom_xml = (char *) dom_xml;

    if (call(conn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_PREPARE_TUNNEL,
             (xdrproc_t) xdr_remote_domain_migrate_prepare_tunnel_args, (char *) &args,
             (xdrproc_t) xdr_void, NULL) == -1) {
        remoteStreamRelease(st);
        goto done;
    }

    rv = 0;

done:
    remoteDriverUnlock(priv);

    return rv;
}

4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696
static int remoteDomainEventRegisterAny(virConnectPtr conn,
                                        virDomainPtr dom,
                                        int eventID,
                                        virConnectDomainEventGenericCallback callback,
                                        void *opaque,
                                        virFreeCallback freecb)
{
    int rv = -1;
    struct private_data *priv = conn->privateData;
    remote_domain_events_register_any_args args;
    int callbackID;

    remoteDriverLock(priv);

4697
    if (priv->domainEventState->timer < 0) {
4698
         remoteError(VIR_ERR_NO_SUPPORT, "%s", _("no event support"));
4699 4700 4701
         goto done;
    }

4702 4703
    if ((callbackID = virDomainEventCallbackListAddID(conn,
                                                      priv->domainEventState->callbacks,
4704 4705
                                                      dom, eventID,
                                                      callback, opaque, freecb)) < 0) {
4706
         remoteError(VIR_ERR_RPC, "%s", _("adding cb to list"));
4707 4708 4709 4710 4711
         goto done;
    }

    /* If this is the first callback for this eventID, we need to enable
     * events on the server */
4712 4713 4714
    if (virDomainEventCallbackListCountID(conn,
                                          priv->domainEventState->callbacks,
                                          eventID) == 1) {
4715 4716 4717 4718 4719
        args.eventID = eventID;

        if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_EVENTS_REGISTER_ANY,
                  (xdrproc_t) xdr_remote_domain_events_register_any_args, (char *) &args,
                  (xdrproc_t) xdr_void, (char *)NULL) == -1) {
4720 4721 4722
            virDomainEventCallbackListRemoveID(conn,
                                               priv->domainEventState->callbacks,
                                               callbackID);
4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744
            goto done;
        }
    }

    rv = callbackID;

done:
    remoteDriverUnlock(priv);
    return rv;
}


static int remoteDomainEventDeregisterAny(virConnectPtr conn,
                                          int callbackID)
{
    struct private_data *priv = conn->privateData;
    int rv = -1;
    remote_domain_events_deregister_any_args args;
    int eventID;

    remoteDriverLock(priv);

4745 4746 4747
    if ((eventID = virDomainEventCallbackListEventID(conn,
                                                     priv->domainEventState->callbacks,
                                                     callbackID)) < 0) {
4748
        remoteError(VIR_ERR_RPC, _("unable to find callback ID %d"), callbackID);
4749 4750 4751
        goto done;
    }

4752 4753 4754 4755
    if (virDomainEventStateDeregisterAny(conn,
                                         priv->domainEventState,
                                         callbackID) < 0)
        goto done;
4756 4757 4758

    /* If that was the last callback for this eventID, we need to disable
     * events on the server */
4759 4760 4761
    if (virDomainEventCallbackListCountID(conn,
                                          priv->domainEventState->callbacks,
                                          eventID) == 0) {
4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776
        args.eventID = eventID;

        if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_EVENTS_DEREGISTER_ANY,
                  (xdrproc_t) xdr_remote_domain_events_deregister_any_args, (char *) &args,
                  (xdrproc_t) xdr_void, (char *) NULL) == -1)
            goto done;
    }

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}

4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816
static char *
remoteDomainScreenshot (virDomainPtr domain,
                        virStreamPtr st,
                        unsigned int screen,
                        unsigned int flags)
{
    struct private_data *priv = domain->conn->privateData;
    struct private_stream_data *privst = NULL;
    remote_domain_screenshot_args args;
    remote_domain_screenshot_ret ret;
    char *rv = NULL;

    remoteDriverLock(priv);

    if (!(privst = remoteStreamOpen(st,
                                    REMOTE_PROC_DOMAIN_SCREENSHOT,
                                    priv->counter)))
        goto done;

    st->driver = &remoteStreamDrv;
    st->privateData = privst;

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

    memset(&ret, 0, sizeof(ret));
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_SCREENSHOT,
              (xdrproc_t) xdr_remote_domain_screenshot_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_screenshot_ret, (char *) &ret) == -1)
        goto done;

    rv = ret.mime ? *ret.mime : NULL;
    VIR_FREE(ret.mime);

done:
    remoteDriverUnlock(priv);
    return rv;
}

4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901
static int
remoteStorageVolUpload(virStorageVolPtr vol,
                       virStreamPtr st,
                       unsigned long long offset,
                       unsigned long long length,
                       unsigned int flags)
{
    struct private_data *priv = vol->conn->privateData;
    struct private_stream_data *privst = NULL;
    int rv = -1;
    remote_storage_vol_upload_args args;

    remoteDriverLock(priv);

    if (!(privst = remoteStreamOpen(st,
                                    REMOTE_PROC_STORAGE_VOL_UPLOAD,
                                    priv->counter)))
        goto done;

    st->driver = &remoteStreamDrv;
    st->privateData = privst;

    make_nonnull_storage_vol(&args.vol, vol);
    args.offset = offset;
    args.length = length;
    args.flags = flags;

    if (call (vol->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_UPLOAD,
              (xdrproc_t) xdr_remote_storage_vol_upload_args, (char *) &args,
              (xdrproc_t) xdr_void, NULL) == -1) {
        remoteStreamRelease(st);
        goto done;
    }

    rv = 0;

done:
    remoteDriverUnlock(priv);

    return rv;
}


static int
remoteStorageVolDownload(virStorageVolPtr vol,
                         virStreamPtr st,
                         unsigned long long offset,
                         unsigned long long length,
                         unsigned int flags)
{
    struct private_data *priv = vol->conn->privateData;
    struct private_stream_data *privst = NULL;
    int rv = -1;
    remote_storage_vol_download_args args;

    remoteDriverLock(priv);

    if (!(privst = remoteStreamOpen(st,
                                    REMOTE_PROC_STORAGE_VOL_DOWNLOAD,
                                    priv->counter)))
        goto done;

    st->driver = &remoteStreamDrv;
    st->privateData = privst;

    make_nonnull_storage_vol(&args.vol, vol);
    args.offset = offset;
    args.length = length;
    args.flags = flags;

    if (call (vol->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_DOWNLOAD,
              (xdrproc_t) xdr_remote_storage_vol_download_args, (char *) &args,
              (xdrproc_t) xdr_void, NULL) == -1) {
        remoteStreamRelease(st);
        goto done;
    }

    rv = 0;

done:
    remoteDriverUnlock(priv);

    return rv;
}

4902

4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915
static int
remoteDomainOpenConsole(virDomainPtr dom,
                        const char *devname,
                        virStreamPtr st,
                        unsigned int flags)
{
    struct private_data *priv = dom->conn->privateData;
    struct private_stream_data *privst = NULL;
    int rv = -1;
    remote_domain_open_console_args args;

    remoteDriverLock(priv);

4916
    if (!(privst = remoteStreamOpen(st, REMOTE_PROC_DOMAIN_OPEN_CONSOLE, priv->counter)))
4917 4918 4919 4920 4921
        goto done;

    st->driver = &remoteStreamDrv;
    st->privateData = privst;

4922
    make_nonnull_domain (&args.dom, dom);
4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941
    args.devname = devname ? (char **)&devname : NULL;
    args.flags = flags;

    if (call(dom->conn, priv, 0, REMOTE_PROC_DOMAIN_OPEN_CONSOLE,
             (xdrproc_t) xdr_remote_domain_open_console_args, (char *) &args,
             (xdrproc_t) xdr_void, NULL) == -1) {
        remoteStreamRelease(st);
        goto done;
    }

    rv = 0;

done:
    remoteDriverUnlock(priv);

    return rv;
}


4942 4943
/*----------------------------------------------------------------------*/

C
Chris Lalancette 已提交
4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954
static int
remoteQemuDomainMonitorCommand (virDomainPtr domain, const char *cmd,
                                char **result, unsigned int flags)
{
    int rv = -1;
    qemu_monitor_command_args args;
    qemu_monitor_command_ret ret;
    struct private_data *priv = domain->conn->privateData;

    remoteDriverLock(priv);

4955
    make_nonnull_domain(&args.dom, domain);
C
Chris Lalancette 已提交
4956 4957 4958 4959
    args.cmd = (char *)cmd;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
4960
    if (call (domain->conn, priv, REMOTE_CALL_QEMU, QEMU_PROC_MONITOR_COMMAND,
C
Chris Lalancette 已提交
4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980
              (xdrproc_t) xdr_qemu_monitor_command_args, (char *) &args,
              (xdrproc_t) xdr_qemu_monitor_command_ret, (char *) &ret) == -1)
        goto done;

    *result = strdup(ret.result);
    if (*result == NULL) {
        virReportOOMError();
        goto cleanup;
    }

    rv = 0;

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

done:
    remoteDriverUnlock(priv);
    return rv;
}

4981 4982 4983

static char *
remoteDomainMigrateBegin3(virDomainPtr domain,
4984
                          const char *xmlin,
4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001
                          char **cookieout,
                          int *cookieoutlen,
                          unsigned long flags,
                          const char *dname,
                          unsigned long resource)
{
    char *rv = NULL;
    remote_domain_migrate_begin3_args args;
    remote_domain_migrate_begin3_ret ret;
    struct private_data *priv = domain->conn->privateData;

    remoteDriverLock(priv);

    memset(&args, 0, sizeof(args));
    memset(&ret, 0, sizeof(ret));

    make_nonnull_domain (&args.dom, domain);
5002
    args.xmlin = xmlin == NULL ? NULL : (char **) &xmlin;
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 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170
    args.flags = flags;
    args.dname = dname == NULL ? NULL : (char **) &dname;
    args.resource = resource;

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_BEGIN3,
              (xdrproc_t) xdr_remote_domain_migrate_begin3_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_migrate_begin3_ret, (char *) &ret) == -1)
        goto done;

    if (ret.cookie_out.cookie_out_len > 0) {
        if (!cookieout || !cookieoutlen) {
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("caller ignores cookieout or cookieoutlen"));
            goto error;
        }
        *cookieout = ret.cookie_out.cookie_out_val; /* Caller frees. */
        *cookieoutlen = ret.cookie_out.cookie_out_len;
    }

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

done:
    remoteDriverUnlock(priv);
    return rv;

error:
    VIR_FREE(ret.cookie_out.cookie_out_val);
    goto done;
}


static int
remoteDomainMigratePrepare3(virConnectPtr dconn,
                            const char *cookiein,
                            int cookieinlen,
                            char **cookieout,
                            int *cookieoutlen,
                            const char *uri_in,
                            char **uri_out,
                            unsigned long flags,
                            const char *dname,
                            unsigned long resource,
                            const char *dom_xml)
{
    int rv = -1;
    remote_domain_migrate_prepare3_args args;
    remote_domain_migrate_prepare3_ret ret;
    struct private_data *priv = dconn->privateData;

    remoteDriverLock(priv);

    memset(&args, 0, sizeof(args));
    memset(&ret, 0, sizeof(ret));

    args.cookie_in.cookie_in_val = (char *)cookiein;
    args.cookie_in.cookie_in_len = cookieinlen;
    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_PREPARE3,
              (xdrproc_t) xdr_remote_domain_migrate_prepare3_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_migrate_prepare3_ret, (char *) &ret) == -1)
        goto done;

    if (ret.cookie_out.cookie_out_len > 0) {
        if (!cookieout || !cookieoutlen) {
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("caller ignores cookieout or cookieoutlen"));
            goto error;
        }
        *cookieout = ret.cookie_out.cookie_out_val; /* Caller frees. */
        *cookieoutlen = ret.cookie_out.cookie_out_len;
    }
    if (ret.uri_out) {
        if (!uri_out) {
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("caller ignores uri_out"));
            goto error;
        }
        *uri_out = *ret.uri_out; /* Caller frees. */
    }

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
error:
    VIR_FREE(ret.cookie_out.cookie_out_val);
    if (ret.uri_out)
        VIR_FREE(*ret.uri_out);
    goto done;
}


static int
remoteDomainMigratePrepareTunnel3(virConnectPtr dconn,
                                  virStreamPtr st,
                                  const char *cookiein,
                                  int cookieinlen,
                                  char **cookieout,
                                  int *cookieoutlen,
                                  unsigned long flags,
                                  const char *dname,
                                  unsigned long resource,
                                  const char *dom_xml)
{
    struct private_data *priv = dconn->privateData;
    struct private_stream_data *privst = NULL;
    int rv = -1;
    remote_domain_migrate_prepare_tunnel3_args args;
    remote_domain_migrate_prepare_tunnel3_ret ret;

    remoteDriverLock(priv);

    memset(&args, 0, sizeof(args));
    memset(&ret, 0, sizeof(ret));

    if (!(privst = remoteStreamOpen(st,
                                    REMOTE_PROC_DOMAIN_MIGRATE_PREPARE_TUNNEL3,
                                    priv->counter)))
        goto done;

    st->driver = &remoteStreamDrv;
    st->privateData = privst;

    args.cookie_in.cookie_in_val = (char *)cookiein;
    args.cookie_in.cookie_in_len = cookieinlen;
    args.flags = flags;
    args.dname = dname == NULL ? NULL : (char **) &dname;
    args.resource = resource;
    args.dom_xml = (char *) dom_xml;

    if (call(dconn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_PREPARE_TUNNEL3,
             (xdrproc_t) xdr_remote_domain_migrate_prepare_tunnel3_args, (char *) &args,
             (xdrproc_t) xdr_remote_domain_migrate_prepare_tunnel3_ret, (char *) &ret) == -1) {
        remoteStreamRelease(st);
        goto done;
    }

    if (ret.cookie_out.cookie_out_len > 0) {
        if (!cookieout || !cookieoutlen) {
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("caller ignores cookieout or cookieoutlen"));
            goto error;
        }
        *cookieout = ret.cookie_out.cookie_out_val; /* Caller frees. */
        *cookieoutlen = ret.cookie_out.cookie_out_len;
    }

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;

error:
    VIR_FREE(ret.cookie_out.cookie_out_val);
    goto done;
}


static int
remoteDomainMigratePerform3(virDomainPtr dom,
5171
                            const char *xmlin,
5172 5173 5174 5175
                            const char *cookiein,
                            int cookieinlen,
                            char **cookieout,
                            int *cookieoutlen,
5176
                            const char *dconnuri,
5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193
                            const char *uri,
                            unsigned long flags,
                            const char *dname,
                            unsigned long resource)
{
    int rv = -1;
    remote_domain_migrate_perform3_args args;
    remote_domain_migrate_perform3_ret ret;
    struct private_data *priv = dom->conn->privateData;

    remoteDriverLock(priv);

    memset(&args, 0, sizeof(args));
    memset(&ret, 0, sizeof(ret));

    make_nonnull_domain(&args.dom, dom);

5194
    args.xmlin = xmlin == NULL ? NULL : (char **) &xmlin;
5195 5196 5197 5198
    args.cookie_in.cookie_in_val = (char *)cookiein;
    args.cookie_in.cookie_in_len = cookieinlen;
    args.flags = flags;
    args.dname = dname == NULL ? NULL : (char **) &dname;
5199 5200
    args.uri = uri == NULL ? NULL : (char **) &uri;
    args.dconnuri = dconnuri == NULL ? NULL : (char **) &dconnuri;
5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229
    args.resource = resource;

    if (call (dom->conn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_PERFORM3,
              (xdrproc_t) xdr_remote_domain_migrate_perform3_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_migrate_perform3_ret, (char *) &ret) == -1)
        goto done;

    if (ret.cookie_out.cookie_out_len > 0) {
        if (!cookieout || !cookieoutlen) {
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("caller ignores cookieout or cookieoutlen"));
            goto error;
        }
        *cookieout = ret.cookie_out.cookie_out_val; /* Caller frees. */
        *cookieoutlen = ret.cookie_out.cookie_out_len;
    }

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;

error:
    VIR_FREE(ret.cookie_out.cookie_out_val);
    goto done;
}


5230
static virDomainPtr
5231 5232 5233 5234 5235 5236
remoteDomainMigrateFinish3(virConnectPtr dconn,
                           const char *dname,
                           const char *cookiein,
                           int cookieinlen,
                           char **cookieout,
                           int *cookieoutlen,
5237
                           const char *dconnuri,
5238 5239
                           const char *uri,
                           unsigned long flags,
5240
                           int cancelled)
5241 5242 5243 5244
{
    remote_domain_migrate_finish3_args args;
    remote_domain_migrate_finish3_ret ret;
    struct private_data *priv = dconn->privateData;
5245
    virDomainPtr rv = NULL;
5246 5247 5248 5249 5250 5251 5252 5253 5254

    remoteDriverLock(priv);

    memset(&args, 0, sizeof(args));
    memset(&ret, 0, sizeof(ret));

    args.cookie_in.cookie_in_val = (char *)cookiein;
    args.cookie_in.cookie_in_len = cookieinlen;
    args.dname = (char *) dname;
5255 5256
    args.uri = uri == NULL ? NULL : (char **) &uri;
    args.dconnuri = dconnuri == NULL ? NULL : (char **) &dconnuri;
5257 5258 5259 5260 5261 5262 5263 5264
    args.flags = flags;
    args.cancelled = cancelled;

    if (call (dconn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_FINISH3,
              (xdrproc_t) xdr_remote_domain_migrate_finish3_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_migrate_finish3_ret, (char *) &ret) == -1)
        goto done;

5265
    rv = get_nonnull_domain(dconn, ret.dom);
5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324

    if (ret.cookie_out.cookie_out_len > 0) {
        if (!cookieout || !cookieoutlen) {
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("caller ignores cookieout or cookieoutlen"));
            goto error;
        }
        *cookieout = ret.cookie_out.cookie_out_val; /* Caller frees. */
        *cookieoutlen = ret.cookie_out.cookie_out_len;
        ret.cookie_out.cookie_out_val = NULL;
        ret.cookie_out.cookie_out_len = 0;
    }

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

done:
    remoteDriverUnlock(priv);
    return rv;

error:
    VIR_FREE(ret.cookie_out.cookie_out_val);
    goto done;
}


static int
remoteDomainMigrateConfirm3(virDomainPtr domain,
                            const char *cookiein,
                            int cookieinlen,
                            unsigned long flags,
                            int cancelled)
{
    int rv = -1;
    remote_domain_migrate_confirm3_args args;
    struct private_data *priv = domain->conn->privateData;

    remoteDriverLock(priv);

    memset(&args, 0, sizeof(args));

    make_nonnull_domain (&args.dom, domain);
    args.cookie_in.cookie_in_len = cookieinlen;
    args.cookie_in.cookie_in_val = (char *) cookiein;
    args.flags = flags;
    args.cancelled = cancelled;

    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_CONFIRM3,
              (xdrproc_t) xdr_remote_domain_migrate_confirm3_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto done;

    rv = 0;

done:
    remoteDriverUnlock(priv);
    return rv;
}


5325 5326
#include "remote_client_bodies.h"
#include "qemu_client_bodies.h"
5327

5328

C
Chris Lalancette 已提交
5329
/*----------------------------------------------------------------------*/
5330

5331
static struct remote_thread_call *
5332
prepareCall(struct private_data *priv,
C
Chris Lalancette 已提交
5333
            int flags,
5334 5335 5336 5337
            int proc_nr,
            xdrproc_t args_filter, char *args,
            xdrproc_t ret_filter, char *ret)
{
5338
    XDR xdr;
5339 5340 5341
    struct remote_message_header hdr;
    struct remote_thread_call *rv;

5342
    if (VIR_ALLOC(rv) < 0) {
5343
        virReportOOMError();
5344
        return NULL;
5345
    }
5346 5347 5348

    if (virCondInit(&rv->cond) < 0) {
        VIR_FREE(rv);
5349 5350
        remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                    _("cannot initialize mutex"));
5351 5352
        return NULL;
    }
5353 5354

    /* Get a unique serial number for this message. */
5355 5356 5357 5358
    rv->serial = priv->counter++;
    rv->proc_nr = proc_nr;
    rv->ret_filter = ret_filter;
    rv->ret = ret;
5359
    rv->want_reply = 1;
5360

5361
    if (flags & REMOTE_CALL_QEMU) {
C
Chris Lalancette 已提交
5362 5363 5364 5365 5366 5367 5368
        hdr.prog = QEMU_PROGRAM;
        hdr.vers = QEMU_PROTOCOL_VERSION;
    }
    else {
        hdr.prog = REMOTE_PROGRAM;
        hdr.vers = REMOTE_PROTOCOL_VERSION;
    }
5369
    hdr.proc = proc_nr;
5370
    hdr.type = REMOTE_CALL;
5371
    hdr.serial = rv->serial;
5372 5373 5374
    hdr.status = REMOTE_OK;

    /* Serialise header followed by args. */
5375
    xdrmem_create (&xdr, rv->buffer+4, REMOTE_MESSAGE_MAX, XDR_ENCODE);
5376
    if (!xdr_remote_message_header (&xdr, &hdr)) {
5377
        remoteError(VIR_ERR_RPC, "%s", _("xdr_remote_message_header failed"));
5378
        goto error;
5379 5380 5381
    }

    if (!(*args_filter) (&xdr, args)) {
5382 5383 5384
        remoteError(VIR_ERR_RPC,
                    _("Unable to marshal arguments for program %d version %d procedure %d type %d status %d"),
                    hdr.prog, hdr.vers, hdr.proc, hdr.type, hdr.status);
5385
        goto error;
5386 5387 5388
    }

    /* Get the length stored in buffer. */
5389
    rv->bufferLength = xdr_getpos (&xdr);
5390 5391 5392 5393 5394
    xdr_destroy (&xdr);

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

    /* Encode the length word. */
5398 5399
    xdrmem_create (&xdr, rv->buffer, REMOTE_MESSAGE_HEADER_XDR_LEN, XDR_ENCODE);
    if (!xdr_u_int (&xdr, &rv->bufferLength)) {
5400
        remoteError(VIR_ERR_RPC, "%s", _("xdr_u_int (length word)"));
5401
        goto error;
5402 5403 5404
    }
    xdr_destroy (&xdr);

5405 5406 5407 5408
    return rv;

error:
    xdr_destroy (&xdr);
5409
    ignore_value(virCondDestroy(&rv->cond));
5410 5411 5412 5413 5414 5415 5416
    VIR_FREE(rv);
    return NULL;
}



static int
5417
remoteIOWriteBuffer(struct private_data *priv,
5418
                    const char *bytes, int len)
5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430
{
    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;

5431
            remoteError(VIR_ERR_GNUTLS_ERROR, "%s", gnutls_strerror (ret));
5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442
            return -1;
        }
    } else {
    resend:
        ret = send (priv->sock, bytes, len, 0);
        if (ret == -1) {
            if (errno == EINTR)
                goto resend;
            if (errno == EWOULDBLOCK)
                return 0;

5443
            virReportSystemError(errno, "%s", _("cannot send data"));
5444 5445 5446 5447 5448 5449 5450 5451 5452 5453
            return -1;

        }
    }

    return ret;
}


static int
5454
remoteIOReadBuffer(struct private_data *priv,
5455
                   char *bytes, int len)
5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469
{
    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)
5470 5471 5472
                remoteError(VIR_ERR_GNUTLS_ERROR,
                            _("failed to read from TLS socket %s"),
                            gnutls_strerror (ret));
5473
            else
5474 5475
                remoteError(VIR_ERR_SYSTEM_ERROR, "%s",
                            _("server closed connection"));
5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487
            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;

5488 5489
                char errout[1024] = "\0";
                if (priv->errfd != -1) {
5490 5491 5492 5493 5494
                    if (saferead(priv->errfd, errout, sizeof(errout)) < 0) {
                        virReportSystemError(errno, "%s",
                                             _("cannot recv data"));
                        return -1;
                    }
5495 5496
                }

5497
                virReportSystemError(errno,
5498 5499
                                     _("cannot recv data: %s"), errout);

5500
            } else {
5501 5502
                char errout[1024] = "\0";
                if (priv->errfd != -1) {
5503 5504 5505 5506 5507 5508
                    if (saferead(priv->errfd, errout, sizeof(errout)) < 0) {
                        remoteError(VIR_ERR_SYSTEM_ERROR,
                                    _("server closed connection: %s"),
                                    virStrerror(errno, errout, sizeof errout));
                        return -1;
                    }
5509 5510
                }

5511 5512
                remoteError(VIR_ERR_SYSTEM_ERROR,
                            _("server closed connection: %s"), errout);
5513 5514 5515 5516 5517 5518 5519 5520 5521 5522
            }
            return -1;
        }
    }

    return ret;
}


static int
5523
remoteIOWriteMessage(struct private_data *priv,
5524
                     struct remote_thread_call *thecall)
5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537
{
#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) {
5538 5539 5540
                remoteError(VIR_ERR_INTERNAL_ERROR,
                            _("failed to encode SASL data: %s"),
                            sasl_errstring(err, NULL, NULL));
5541 5542 5543 5544 5545 5546 5547 5548 5549
                return -1;
            }
            priv->saslEncoded = output;
            priv->saslEncodedLength = outputlen;
            priv->saslEncodedOffset = 0;

            thecall->bufferOffset = thecall->bufferLength;
        }

5550
        ret = remoteIOWriteBuffer(priv,
5551 5552
                                  priv->saslEncoded + priv->saslEncodedOffset,
                                  priv->saslEncodedLength - priv->saslEncodedOffset);
5553 5554 5555 5556 5557 5558 5559
        if (ret < 0)
            return ret;
        priv->saslEncodedOffset += ret;

        if (priv->saslEncodedOffset == priv->saslEncodedLength) {
            priv->saslEncoded = NULL;
            priv->saslEncodedOffset = priv->saslEncodedLength = 0;
5560 5561 5562 5563
            if (thecall->want_reply)
                thecall->mode = REMOTE_MODE_WAIT_RX;
            else
                thecall->mode = REMOTE_MODE_COMPLETE;
5564 5565 5566 5567
        }
    } else {
#endif
        int ret;
5568
        ret = remoteIOWriteBuffer(priv,
5569 5570
                                  thecall->buffer + thecall->bufferOffset,
                                  thecall->bufferLength - thecall->bufferOffset);
5571 5572 5573 5574 5575 5576
        if (ret < 0)
            return ret;
        thecall->bufferOffset += ret;

        if (thecall->bufferOffset == thecall->bufferLength) {
            thecall->bufferOffset = thecall->bufferLength = 0;
5577 5578 5579 5580
            if (thecall->want_reply)
                thecall->mode = REMOTE_MODE_WAIT_RX;
            else
                thecall->mode = REMOTE_MODE_COMPLETE;
5581 5582 5583 5584 5585 5586 5587 5588 5589
        }
#if HAVE_SASL
    }
#endif
    return 0;
}


static int
5590
remoteIOHandleOutput(struct private_data *priv) {
5591 5592 5593 5594 5595 5596 5597 5598 5599 5600
    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) {
5601
        int ret = remoteIOWriteMessage(priv, thecall);
5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614
        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
5615
remoteIOReadMessage(struct private_data *priv) {
5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627
    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) {
            int ret, err;
5628 5629
            ret = remoteIOReadBuffer(priv, priv->saslTemporary,
                                     sizeof(priv->saslTemporary));
5630 5631 5632 5633 5634
            if (ret < 0)
                return -1;
            if (ret == 0)
                return 0;

5635
            err = sasl_decode(priv->saslconn, priv->saslTemporary, ret,
5636 5637
                              &priv->saslDecoded, &priv->saslDecodedLength);
            if (err != SASL_OK) {
5638 5639 5640
                remoteError(VIR_ERR_INTERNAL_ERROR,
                            _("failed to decode SASL data: %s"),
                            sasl_errstring(err, NULL, NULL));
5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654
                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) {
5655
            priv->saslDecodedOffset = priv->saslDecodedLength = 0;
5656 5657 5658 5659 5660 5661 5662 5663
            priv->saslDecoded = NULL;
        }

        return wantData;
    } else {
#endif
        int ret;

5664
        ret = remoteIOReadBuffer(priv,
5665 5666
                                 priv->buffer + priv->bufferOffset,
                                 wantData);
5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678
        if (ret < 0)
            return -1;
        if (ret == 0)
            return 0;

        priv->bufferOffset += ret;

        return ret;
#if HAVE_SASL
    }
#endif
}
5679 5680


5681
static int
5682
remoteIODecodeMessageLength(struct private_data *priv) {
5683
    XDR xdr;
5684
    unsigned int len;
5685 5686

    xdrmem_create (&xdr, priv->buffer, priv->bufferLength, XDR_DECODE);
5687
    if (!xdr_u_int (&xdr, &len)) {
5688
        remoteError(VIR_ERR_RPC, "%s", _("xdr_u_int (length word, reply)"));
5689 5690 5691 5692
        return -1;
    }
    xdr_destroy (&xdr);

5693
    if (len < REMOTE_MESSAGE_HEADER_XDR_LEN) {
5694 5695
        remoteError(VIR_ERR_RPC, "%s",
                    _("packet received from server too small"));
5696 5697 5698
        return -1;
    }

5699
    /* Length includes length word - adjust to real length to read. */
5700
    len -= REMOTE_MESSAGE_HEADER_XDR_LEN;
5701

5702
    if (len > REMOTE_MESSAGE_MAX) {
5703 5704
        remoteError(VIR_ERR_RPC, "%s",
                    _("packet received from server too large"));
5705 5706 5707
        return -1;
    }

5708 5709 5710
    /* Extend our declared buffer length and carry
       on reading the header + payload */
    priv->bufferLength += len;
5711
    VIR_DEBUG("Got length, now need %d total (%d more)", priv->bufferLength, len);
5712 5713 5714 5715 5716
    return 0;
}


static int
5717 5718 5719 5720 5721 5722 5723 5724 5725 5726
processCallDispatchReply(virConnectPtr conn, struct private_data *priv,
                         remote_message_header *hdr,
                         XDR *xdr);

static int
processCallDispatchMessage(virConnectPtr conn, struct private_data *priv,
                           int in_open,
                           remote_message_header *hdr,
                           XDR *xdr);

5727 5728 5729 5730 5731
static int
processCallDispatchStream(virConnectPtr conn, struct private_data *priv,
                          remote_message_header *hdr,
                          XDR *xdr);

5732 5733 5734

static int
processCallDispatch(virConnectPtr conn, struct private_data *priv,
C
Chris Lalancette 已提交
5735
                    int flags) {
5736 5737 5738
    XDR xdr;
    struct remote_message_header hdr;
    int len = priv->bufferLength - 4;
5739
    int rv = -1;
C
Chris Lalancette 已提交
5740 5741
    int expectedprog;
    int expectedvers;
5742

5743 5744 5745
    /* Length word has already been read */
    priv->bufferOffset = 4;

5746
    /* Deserialise reply header. */
5747
    xdrmem_create (&xdr, priv->buffer + priv->bufferOffset, len, XDR_DECODE);
5748
    if (!xdr_remote_message_header (&xdr, &hdr)) {
5749
        remoteError(VIR_ERR_RPC, "%s", _("invalid header in reply"));
5750 5751 5752
        return -1;
    }

5753 5754
    priv->bufferOffset += xdr_getpos(&xdr);

C
Chris Lalancette 已提交
5755 5756
    expectedprog = REMOTE_PROGRAM;
    expectedvers = REMOTE_PROTOCOL_VERSION;
5757
    if (flags & REMOTE_CALL_QEMU) {
C
Chris Lalancette 已提交
5758 5759 5760 5761
        expectedprog = QEMU_PROGRAM;
        expectedvers = QEMU_PROTOCOL_VERSION;
    }

5762
    /* Check program, version, etc. are what we expect. */
C
Chris Lalancette 已提交
5763
    if (hdr.prog != expectedprog) {
5764 5765
        remoteError(VIR_ERR_RPC,
                    _("unknown program (received %x, expected %x)"),
C
Chris Lalancette 已提交
5766
                    hdr.prog, expectedprog);
5767 5768
        return -1;
    }
C
Chris Lalancette 已提交
5769
    if (hdr.vers != expectedvers) {
5770 5771
        remoteError(VIR_ERR_RPC,
                    _("unknown protocol version (received %x, expected %x)"),
C
Chris Lalancette 已提交
5772
                    hdr.vers, expectedvers);
5773 5774 5775
        return -1;
    }

5776

5777 5778
    switch (hdr.type) {
    case REMOTE_REPLY: /* Normal RPC replies */
C
Chris Lalancette 已提交
5779
        rv = processCallDispatchReply(conn, priv, &hdr, &xdr);
5780
        break;
5781

5782
    case REMOTE_MESSAGE: /* Async notifications */
5783
        VIR_DEBUG("Dispatch event %d %d", hdr.proc, priv->bufferLength);
C
Chris Lalancette 已提交
5784
        rv = processCallDispatchMessage(conn, priv, flags & REMOTE_CALL_IN_OPEN,
5785 5786 5787
                                        &hdr, &xdr);
        break;

5788
    case REMOTE_STREAM: /* Stream protocol */
C
Chris Lalancette 已提交
5789
        rv = processCallDispatchStream(conn, priv, &hdr, &xdr);
5790 5791
        break;

5792
    default:
5793 5794 5795
        remoteError(VIR_ERR_RPC,
                    _("got unexpected RPC call %d from server"),
                    hdr.proc);
5796 5797
        rv = -1;
        break;
5798
    }
5799

5800 5801 5802 5803 5804 5805
    xdr_destroy(&xdr);
    return rv;
}


static int
5806 5807
processCallDispatchReply(virConnectPtr conn ATTRIBUTE_UNUSED,
                         struct private_data *priv,
5808 5809 5810 5811
                         remote_message_header *hdr,
                         XDR *xdr) {
    struct remote_thread_call *thecall;

5812 5813 5814 5815
    /* Ok, definitely got an RPC reply now find
       out who's been waiting for it */
    thecall = priv->waitDispatch;
    while (thecall &&
5816
           thecall->serial != hdr->serial)
5817 5818 5819
        thecall = thecall->next;

    if (!thecall) {
5820 5821 5822
        remoteError(VIR_ERR_RPC,
                    _("no call waiting for reply with serial %d"),
                    hdr->serial);
5823 5824
        return -1;
    }
5825

5826
    if (hdr->proc != thecall->proc_nr) {
5827 5828 5829
        remoteError(VIR_ERR_RPC,
                    _("unknown procedure (received %x, expected %x)"),
                    hdr->proc, thecall->proc_nr);
5830 5831 5832 5833 5834 5835 5836
        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).
     */
5837
    switch (hdr->status) {
5838
    case REMOTE_OK:
5839
        if (!(*thecall->ret_filter) (xdr, thecall->ret)) {
5840 5841 5842
            remoteError(VIR_ERR_RPC,
                        _("Unable to marshal reply for program %d version %d procedure %d type %d status %d"),
                        hdr->prog, hdr->vers, hdr->proc, hdr->type, hdr->status);
5843 5844
            return -1;
        }
5845
        thecall->mode = REMOTE_MODE_COMPLETE;
5846 5847 5848
        return 0;

    case REMOTE_ERROR:
5849
        memset (&thecall->err, 0, sizeof thecall->err);
5850
        if (!xdr_remote_error (xdr, &thecall->err)) {
5851 5852 5853
            remoteError(VIR_ERR_RPC,
                        _("Unable to marshal error for program %d version %d procedure %d type %d status %d"),
                        hdr->prog, hdr->vers, hdr->proc, hdr->type, hdr->status);
5854 5855
            return -1;
        }
5856 5857
        thecall->mode = REMOTE_MODE_ERROR;
        return 0;
5858 5859

    default:
5860
        remoteError(VIR_ERR_RPC, _("unknown status (received %x)"), hdr->status);
5861 5862 5863 5864
        return -1;
    }
}

5865 5866 5867 5868 5869
static int
processCallDispatchMessage(virConnectPtr conn, struct private_data *priv,
                           int in_open,
                           remote_message_header *hdr,
                           XDR *xdr) {
5870
    virDomainEventPtr event = NULL;
5871 5872 5873 5874 5875
    /* An async message has come in while we were waiting for the
     * response. Process it to pull it off the wire, and try again
     */

    if (in_open) {
5876
        VIR_DEBUG("Ignoring bogus event %d received while in open", hdr->proc);
5877 5878 5879
        return -1;
    }

5880
    switch (hdr->proc) {
5881
    case REMOTE_PROC_DOMAIN_EVENT_LIFECYCLE:
5882 5883 5884
        event = remoteDomainReadEventLifecycle(conn, xdr);
        break;

5885 5886 5887 5888
    case REMOTE_PROC_DOMAIN_EVENT_REBOOT:
        event = remoteDomainReadEventReboot(conn, xdr);
        break;

5889 5890 5891 5892
    case REMOTE_PROC_DOMAIN_EVENT_RTC_CHANGE:
        event = remoteDomainReadEventRTCChange(conn, xdr);
        break;

5893 5894 5895 5896
    case REMOTE_PROC_DOMAIN_EVENT_WATCHDOG:
        event = remoteDomainReadEventWatchdog(conn, xdr);
        break;

5897 5898 5899 5900
    case REMOTE_PROC_DOMAIN_EVENT_IO_ERROR:
        event = remoteDomainReadEventIOError(conn, xdr);
        break;

5901 5902 5903 5904
    case REMOTE_PROC_DOMAIN_EVENT_IO_ERROR_REASON:
        event = remoteDomainReadEventIOErrorReason(conn, xdr);
        break;

5905 5906 5907 5908
    case REMOTE_PROC_DOMAIN_EVENT_GRAPHICS:
        event = remoteDomainReadEventGraphics(conn, xdr);
        break;

5909
    default:
5910
        VIR_DEBUG("Unexpected event proc %d", hdr->proc);
5911
        break;
5912
    }
5913
    VIR_DEBUG("Event ready for queue %p %p", event, conn);
5914 5915 5916 5917

    if (!event)
        return -1;

5918
    remoteDomainEventQueue(priv, event);
5919 5920 5921
    return 0;
}

5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937
static int
processCallDispatchStream(virConnectPtr conn ATTRIBUTE_UNUSED,
                          struct private_data *priv,
                          remote_message_header *hdr,
                          XDR *xdr) {
    struct private_stream_data *privst;
    struct remote_thread_call *thecall;

    /* Try and find a matching stream */
    privst = priv->streams;
    while (privst &&
           privst->serial != hdr->serial &&
           privst->proc_nr != hdr->proc)
        privst = privst->next;

    if (!privst) {
5938 5939
        VIR_DEBUG("No registered stream matching serial=%d, proc=%d",
                  hdr->serial, hdr->proc);
5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957
        return -1;
    }

    /* See if there's also a (optional) call waiting for this reply */
    thecall = priv->waitDispatch;
    while (thecall &&
           thecall->serial != hdr->serial)
        thecall = thecall->next;


    /* Status is either REMOTE_OK (meaning that what follows is a ret
     * structure), or REMOTE_ERROR (and what follows is a remote_error
     * structure).
     */
    switch (hdr->status) {
    case REMOTE_CONTINUE: {
        int avail = privst->incomingLength - privst->incomingOffset;
        int need = priv->bufferLength - priv->bufferOffset;
5958
        VIR_DEBUG("Got a stream data packet");
5959 5960 5961 5962 5963 5964 5965

        /* XXX flag stream as complete somwhere if need==0 */

        if (need > avail) {
            int extra = need - avail;
            if (VIR_REALLOC_N(privst->incoming,
                              privst->incomingLength + extra) < 0) {
5966
                VIR_DEBUG("Out of memory handling stream data");
5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977
                return -1;
            }
            privst->incomingLength += extra;
        }

        memcpy(privst->incoming + privst->incomingOffset,
               priv->buffer + priv->bufferOffset,
               priv->bufferLength - priv->bufferOffset);
        privst->incomingOffset += (priv->bufferLength - priv->bufferOffset);

        if (thecall && thecall->want_reply) {
5978
            VIR_DEBUG("Got sync data packet offset=%d", privst->incomingOffset);
5979 5980
            thecall->mode = REMOTE_MODE_COMPLETE;
        } else {
5981
            VIR_DEBUG("Got aysnc data packet offset=%d", privst->incomingOffset);
5982
            remoteStreamEventTimerUpdate(privst);
5983 5984 5985 5986 5987
        }
        return 0;
    }

    case REMOTE_OK:
5988
        VIR_DEBUG("Got a synchronous confirm");
5989
        if (!thecall) {
5990
            VIR_DEBUG("Got unexpected stream finish confirmation");
5991 5992 5993 5994 5995 5996 5997
            return -1;
        }
        thecall->mode = REMOTE_MODE_COMPLETE;
        return 0;

    case REMOTE_ERROR:
        if (thecall && thecall->want_reply) {
5998
            VIR_DEBUG("Got a synchronous error");
5999 6000 6001
            /* Give the error straight to this call */
            memset (&thecall->err, 0, sizeof thecall->err);
            if (!xdr_remote_error (xdr, &thecall->err)) {
6002
                remoteError(VIR_ERR_RPC, "%s", _("unmarshaling remote_error"));
6003 6004 6005 6006
                return -1;
            }
            thecall->mode = REMOTE_MODE_ERROR;
        } else {
6007
            VIR_DEBUG("Got a asynchronous error");
6008 6009
            /* No call, so queue the error against the stream */
            if (privst->has_error) {
6010
                VIR_DEBUG("Got unexpected duplicate stream error");
6011 6012 6013 6014 6015
                return -1;
            }
            privst->has_error = 1;
            memset (&privst->err, 0, sizeof privst->err);
            if (!xdr_remote_error (xdr, &privst->err)) {
6016
                VIR_DEBUG("Failed to unmarshal error");
6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027
                return -1;
            }
        }
        return 0;

    default:
        VIR_WARN("Stream with unexpected serial=%d, proc=%d, status=%d",
                 hdr->serial, hdr->proc, hdr->status);
        return -1;
    }
}
6028 6029

static int
6030
remoteIOHandleInput(virConnectPtr conn, struct private_data *priv,
C
Chris Lalancette 已提交
6031
                    int flags)
6032
{
6033
    /* Read as much data as is available, until we get
6034
     * EAGAIN
6035
     */
6036
    for (;;) {
6037
        int ret = remoteIOReadMessage(priv);
6038

6039 6040 6041 6042
        if (ret < 0)
            return -1;
        if (ret == 0)
            return 0;  /* Blocking on read */
6043

6044 6045 6046
        /* Check for completion of our goal */
        if (priv->bufferOffset == priv->bufferLength) {
            if (priv->bufferOffset == 4) {
6047
                ret = remoteIODecodeMessageLength(priv);
6048 6049 6050 6051 6052 6053 6054 6055 6056
                if (ret < 0)
                    return -1;

                /*
                 * We'll carry on around the loop to immediately
                 * process the message body, because it has probably
                 * already arrived. Worst case, we'll get EAGAIN on
                 * next iteration.
                 */
6057
            } else {
C
Chris Lalancette 已提交
6058
                ret = processCallDispatch(conn, priv, flags);
6059
                priv->bufferOffset = priv->bufferLength = 0;
6060
                /*
6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074
                 * We've completed one call, but we don't want to
                 * spin around the loop forever if there are many
                 * incoming async events, or replies for other
                 * thread's RPC calls. We want to get out & let
                 * any other thread take over as soon as we've
                 * got our reply. When SASL is active though, we
                 * may have read more data off the wire than we
                 * initially wanted & cached it in memory. In this
                 * case, poll() would not detect that there is more
                 * ready todo.
                 *
                 * So if SASL is active *and* some SASL data is
                 * already cached, then we'll process that now,
                 * before returning.
6075
                 */
6076 6077 6078 6079 6080 6081
#if HAVE_SASL
                if (ret == 0 &&
                    priv->saslconn &&
                    priv->saslDecoded)
                    continue;
#endif
6082
                return ret;
6083 6084 6085
            }
        }
    }
6086 6087
}

6088 6089 6090 6091 6092
/*
 * Process all calls pending dispatch/receive until we
 * get a reply to our own call. Then quit and pass the buck
 * to someone else.
 */
6093
static int
6094 6095
remoteIOEventLoop(virConnectPtr conn,
                  struct private_data *priv,
C
Chris Lalancette 已提交
6096
                  int flags,
6097
                  struct remote_thread_call *thiscall)
6098
{
6099 6100
    struct pollfd fds[2];
    int ret;
6101

6102 6103 6104 6105 6106 6107 6108
    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;
6109
#ifdef HAVE_PTHREAD_SIGMASK
6110
        sigset_t oldmask, blockedsigs;
6111
#endif
6112 6113 6114 6115 6116 6117
        int timeout = -1;

        /* If we have existing SASL decoded data we
         * don't want to sleep in the poll(), just
         * check if any other FDs are also ready
         */
6118
#if HAVE_SASL
6119 6120
        if (priv->saslDecoded)
            timeout = 0;
6121
#endif
6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135

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

6136 6137 6138
        if (priv->streams)
            fds[0].events |= POLLIN;

6139 6140 6141 6142
        /* Release lock while poll'ing so other threads
         * can stuff themselves on the queue */
        remoteDriverUnlock(priv);

6143 6144 6145 6146 6147
        /* Block SIGWINCH from interrupting poll in curses programs,
         * then restore the original signal mask again immediately
         * after the call (RHBZ#567931).  Same for SIGCHLD and SIGPIPE
         * at the suggestion of Paolo Bonzini and Daniel Berrange.
         */
6148
#ifdef HAVE_PTHREAD_SIGMASK
6149 6150 6151 6152
        sigemptyset (&blockedsigs);
        sigaddset (&blockedsigs, SIGWINCH);
        sigaddset (&blockedsigs, SIGCHLD);
        sigaddset (&blockedsigs, SIGPIPE);
6153
        ignore_value(pthread_sigmask(SIG_BLOCK, &blockedsigs, &oldmask));
6154
#endif
6155

6156
    repoll:
6157
        ret = poll(fds, ARRAY_CARDINALITY(fds), timeout);
6158
        if (ret < 0 && errno == EAGAIN)
6159
            goto repoll;
6160

6161
#ifdef HAVE_PTHREAD_SIGMASK
6162
        ignore_value(pthread_sigmask(SIG_SETMASK, &oldmask, NULL));
6163
#endif
6164

6165 6166
        remoteDriverLock(priv);

6167 6168 6169
        /* If we have existing SASL decoded data, pretend
         * the socket became readable so we consume it
         */
6170
#if HAVE_SASL
6171 6172
        if (priv->saslDecoded)
            fds[0].revents |= POLLIN;
6173
#endif
6174

6175
        if (fds[1].revents) {
6176
            ssize_t s;
6177
            VIR_DEBUG("Woken up from poll by other thread");
6178 6179 6180 6181 6182 6183 6184 6185 6186 6187
            s = saferead(priv->wakeupReadFD, &ignore, sizeof(ignore));
            if (s < 0) {
                virReportSystemError(errno, "%s",
                                     _("read on wakeup fd failed"));
                goto error;
            } else if (s != sizeof(ignore)) {
                remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                            _("read on wakeup fd failed"));
                goto error;
            }
6188 6189 6190 6191 6192
        }

        if (ret < 0) {
            if (errno == EWOULDBLOCK)
                continue;
6193
            virReportSystemError(errno,
6194
                                 "%s", _("poll on socket failed"));
6195
            goto error;
6196 6197 6198
        }

        if (fds[0].revents & POLLOUT) {
6199
            if (remoteIOHandleOutput(priv) < 0)
6200
                goto error;
6201
        }
6202 6203

        if (fds[0].revents & POLLIN) {
C
Chris Lalancette 已提交
6204
            if (remoteIOHandleInput(conn, priv, flags) < 0)
6205
                goto error;
6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227
        }

        /* 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...
                 */
6228
                VIR_DEBUG("Waking up sleep %d %p %p", tmp->proc_nr, tmp, priv->waitDispatch);
6229
                virCondSignal(&tmp->cond);
6230 6231
            } else {
                prev = tmp;
6232
            }
6233
            tmp = tmp->next;
6234 6235
        }

6236 6237 6238 6239 6240 6241 6242
        /* 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;
6243
            VIR_DEBUG("Giving up the buck %d %p %p", thiscall->proc_nr, thiscall, priv->waitDispatch);
6244 6245 6246
            /* See if someone else is still waiting
             * and if so, then pass the buck ! */
            if (priv->waitDispatch) {
6247
                VIR_DEBUG("Passing the buck to %d %p", priv->waitDispatch->proc_nr, priv->waitDispatch);
6248 6249 6250 6251
                virCondSignal(&priv->waitDispatch->cond);
            }
            return 0;
        }
6252

6253 6254

        if (fds[0].revents & (POLLHUP | POLLERR)) {
6255 6256
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("received hangup / error event on socket"));
6257
            goto error;
6258 6259
        }
    }
6260 6261 6262 6263


error:
    priv->waitDispatch = thiscall->next;
6264
    VIR_DEBUG("Giving up the buck due to I/O error %d %p %p", thiscall->proc_nr, thiscall, priv->waitDispatch);
6265 6266 6267
    /* See if someone else is still waiting
     * and if so, then pass the buck ! */
    if (priv->waitDispatch) {
6268
        VIR_DEBUG("Passing the buck to %d %p", priv->waitDispatch->proc_nr, priv->waitDispatch);
6269 6270 6271
        virCondSignal(&priv->waitDispatch->cond);
    }
    return -1;
6272 6273
}

6274
/*
6275
 * This function sends a message to remote server and awaits a reply
6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289
 *
 * 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
6290
 * to sleep on condition variables. The existing thread may completely
6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306
 * 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!
 */
6307
static int
6308 6309 6310 6311
remoteIO(virConnectPtr conn,
         struct private_data *priv,
         int flags,
         struct remote_thread_call *thiscall)
6312
{
6313 6314
    int rv;

6315
    VIR_DEBUG("Do proc=%d serial=%d length=%d wait=%p",
6316 6317
          thiscall->proc_nr, thiscall->serial,
          thiscall->bufferLength, priv->waitDispatch);
6318

6319 6320 6321 6322 6323
    /* 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;
6324
        ssize_t s;
6325 6326 6327 6328 6329 6330
        while (tmp && tmp->next)
            tmp = tmp->next;
        if (tmp)
            tmp->next = thiscall;
        else
            priv->waitDispatch = thiscall;
6331

6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344
        /* Force other thread to wakeup from poll */
        s = safewrite(priv->wakeupSendFD, &ignore, sizeof(ignore));
        if (s < 0) {
            char errout[1024];
            remoteError(VIR_ERR_INTERNAL_ERROR,
                        _("failed to wake up polling thread: %s"),
                        virStrerror(errno, errout, sizeof errout));
            return -1;
        } else if (s != sizeof(ignore)) {
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("failed to wake up polling thread"));
            return -1;
        }
6345

6346
        VIR_DEBUG("Going to sleep %d %p %p", thiscall->proc_nr, priv->waitDispatch, thiscall);
6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359
        /* 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;
            }
6360 6361
            remoteError(VIR_ERR_INTERNAL_ERROR, "%s",
                        _("failed to wait on condition"));
6362
            return -1;
6363
        }
6364

6365
        VIR_DEBUG("Wokeup from sleep %d %p %p", thiscall->proc_nr, priv->waitDispatch, thiscall);
6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379
        /* 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;
6380
        }
6381 6382 6383

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

6384
    } else {
6385 6386 6387 6388
        /* We're first to catch the buck */
        priv->waitDispatch = thiscall;
    }

6389
    VIR_DEBUG("We have the buck %d %p %p", thiscall->proc_nr, priv->waitDispatch, thiscall);
6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406
    /*
     * 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);

C
Chris Lalancette 已提交
6407
    rv = remoteIOEventLoop(conn, priv, flags, thiscall);
6408 6409 6410 6411

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

6412
    if (rv < 0)
6413 6414 6415
        return -1;

cleanup:
6416
    VIR_DEBUG("All done with our call %d %p %p", thiscall->proc_nr,
6417
          priv->waitDispatch, thiscall);
6418
    if (thiscall->mode == REMOTE_MODE_ERROR) {
6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447
        /* Interop for virErrorNumber glitch in 0.8.0, if server is
         * 0.7.1 through 0.7.7; see comments in virterror.h. */
        switch (thiscall->err.code) {
        case VIR_WAR_NO_NWFILTER:
            /* no way to tell old VIR_WAR_NO_SECRET apart from
             * VIR_WAR_NO_NWFILTER, but both are very similar
             * warnings, so ignore the difference */
            break;
        case VIR_ERR_INVALID_NWFILTER:
        case VIR_ERR_NO_NWFILTER:
        case VIR_ERR_BUILD_FIREWALL:
            /* server was trying to pass VIR_ERR_INVALID_SECRET,
             * VIR_ERR_NO_SECRET, or VIR_ERR_CONFIG_UNSUPPORTED */
            if (thiscall->err.domain != VIR_FROM_NWFILTER)
                thiscall->err.code += 4;
            break;
        case VIR_WAR_NO_SECRET:
            if (thiscall->err.domain == VIR_FROM_QEMU)
                thiscall->err.code = VIR_ERR_OPERATION_TIMEOUT;
            break;
        case VIR_ERR_INVALID_SECRET:
            if (thiscall->err.domain == VIR_FROM_XEN)
                thiscall->err.code = VIR_ERR_MIGRATE_PERSIST_FAILED;
            break;
        default:
            /* Nothing to alter. */
            break;
        }

6448 6449 6450 6451 6452 6453
        /* 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 &&
6454
            thiscall->err.message &&
6455 6456
            STRPREFIX(*thiscall->err.message, "unknown procedure")) {
            rv = -2;
6457 6458 6459 6460 6461 6462 6463 6464 6465
        } else if (thiscall->err.domain == VIR_FROM_REMOTE &&
                   thiscall->err.code == VIR_ERR_RPC &&
                   thiscall->err.level == VIR_ERR_ERROR &&
                   thiscall->err.message &&
                   STRPREFIX(*thiscall->err.message, "unknown procedure")) {
            /*
             * convert missing remote entry points into the unsupported
             * feature error
             */
6466
            virRaiseErrorFull(__FILE__, __FUNCTION__, __LINE__,
6467 6468 6469 6470 6471 6472 6473 6474 6475 6476
                              thiscall->err.domain,
                              VIR_ERR_NO_SUPPORT,
                              thiscall->err.level,
                              thiscall->err.str1 ? *thiscall->err.str1 : NULL,
                              thiscall->err.str2 ? *thiscall->err.str2 : NULL,
                              thiscall->err.str3 ? *thiscall->err.str3 : NULL,
                              thiscall->err.int1,
                              thiscall->err.int2,
                              "%s", *thiscall->err.message);
            rv = -1;
6477
        } else {
6478
            virRaiseErrorFull(__FILE__, __FUNCTION__, __LINE__,
6479 6480 6481 6482 6483 6484 6485 6486
                              thiscall->err.domain,
                              thiscall->err.code,
                              thiscall->err.level,
                              thiscall->err.str1 ? *thiscall->err.str1 : NULL,
                              thiscall->err.str2 ? *thiscall->err.str2 : NULL,
                              thiscall->err.str3 ? *thiscall->err.str3 : NULL,
                              thiscall->err.int1,
                              thiscall->err.int2,
6487
                              "%s", thiscall->err.message ? *thiscall->err.message : "unknown");
6488
            rv = -1;
6489
        }
6490
        xdr_free((xdrproc_t)xdr_remote_error,  (char *)&thiscall->err);
6491 6492
    } else {
        rv = 0;
6493
    }
6494 6495
    return rv;
}
6496

6497 6498 6499 6500 6501 6502 6503

/*
 * Serial a set of arguments into a method call message,
 * send that to the server and wait for reply
 */
static int
call (virConnectPtr conn, struct private_data *priv,
C
Chris Lalancette 已提交
6504
      int flags,
6505 6506 6507 6508 6509
      int proc_nr,
      xdrproc_t args_filter, char *args,
      xdrproc_t ret_filter, char *ret)
{
    struct remote_thread_call *thiscall;
6510
    int rv;
6511

C
Chris Lalancette 已提交
6512
    thiscall = prepareCall(priv, flags, proc_nr, args_filter, args,
6513 6514 6515 6516 6517 6518
                           ret_filter, ret);

    if (!thiscall) {
        return -1;
    }

6519
    rv = remoteIO(conn, priv, flags, thiscall);
6520
    ignore_value(virCondDestroy(&thiscall->cond));
6521 6522
    VIR_FREE(thiscall);
    return rv;
6523 6524 6525
}


6526 6527 6528 6529 6530 6531 6532 6533 6534 6535
/** remoteDomainEventFired:
 *
 * The callback for monitoring the remote socket
 * for event data
 */
void
remoteDomainEventFired(int watch,
                       int fd,
                       int event,
                       void *opaque)
6536
{
6537 6538
    virConnectPtr        conn = opaque;
    struct private_data *priv = conn->privateData;
6539

6540
    remoteDriverLock(priv);
6541

6542 6543 6544
    /* This should be impossible, but it doesn't hurt to check */
    if (priv->waitDispatch)
        goto done;
6545

6546
    VIR_DEBUG("Event fired %d %d %d %X", watch, fd, event, event);
6547

6548
    if (event & (VIR_EVENT_HANDLE_HANGUP | VIR_EVENT_HANDLE_ERROR)) {
6549
         VIR_DEBUG("%s : VIR_EVENT_HANDLE_HANGUP or "
6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561
               "VIR_EVENT_HANDLE_ERROR encountered", __FUNCTION__);
         virEventRemoveHandle(watch);
         priv->watch = -1;
         goto done;
    }

    if (fd != priv->sock) {
        virEventRemoveHandle(watch);
        priv->watch = -1;
        goto done;
    }

6562
    if (remoteIOHandleInput(conn, priv, 0) < 0)
6563
        VIR_DEBUG("Something went wrong during async message processing");
6564 6565 6566

done:
    remoteDriverUnlock(priv);
6567 6568
}

6569 6570
static void remoteDomainEventDispatchFunc(virConnectPtr conn,
                                          virDomainEventPtr event,
6571
                                          virConnectDomainEventGenericCallback cb,
6572 6573 6574 6575 6576 6577 6578
                                          void *cbopaque,
                                          void *opaque)
{
    struct private_data *priv = opaque;

    /* Drop the lock whle dispatching, for sake of re-entrancy */
    remoteDriverUnlock(priv);
6579
    VIR_DEBUG("Dispatch event %p %p", event, conn);
6580 6581 6582 6583
    virDomainEventDispatchDefaultFunc(conn, event, cb, cbopaque, NULL);
    remoteDriverLock(priv);
}

6584 6585
void
remoteDomainEventQueueFlush(int timer ATTRIBUTE_UNUSED, void *opaque)
6586
{
6587 6588 6589 6590
    virConnectPtr conn = opaque;
    struct private_data *priv = conn->privateData;


6591
    remoteDriverLock(priv);
6592
    VIR_DEBUG("Event queue flush %p", conn);
6593

6594 6595 6596
    virDomainEventStateFlush(priv->domainEventState,
                             remoteDomainEventDispatchFunc,
                             priv);
6597
    remoteDriverUnlock(priv);
6598 6599
}

6600 6601 6602 6603 6604
void
remoteDomainEventQueue(struct private_data *priv, virDomainEventPtr event)
{
    virDomainEventStateQueue(priv->domainEventState, event);
}
6605

6606 6607 6608 6609 6610 6611
/* get_nonnull_domain and get_nonnull_network turn an on-wire
 * (name, uuid) pair into virDomainPtr or virNetworkPtr object.
 * These can return NULL if underlying memory allocations fail,
 * but if they do then virterror_internal.has been set.
 */
static virDomainPtr
6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625
get_nonnull_domain (virConnectPtr conn, remote_nonnull_domain domain)
{
    virDomainPtr dom;
    dom = virGetDomain (conn, domain.name, BAD_CAST domain.uuid);
    if (dom) dom->id = domain.id;
    return dom;
}

static virNetworkPtr
get_nonnull_network (virConnectPtr conn, remote_nonnull_network network)
{
    return virGetNetwork (conn, network.name, BAD_CAST network.uuid);
}

D
Daniel Veillard 已提交
6626
static virInterfacePtr
6627
get_nonnull_interface (virConnectPtr conn, remote_nonnull_interface iface)
D
Daniel Veillard 已提交
6628
{
6629
    return virGetInterface (conn, iface.name, iface.mac);
D
Daniel Veillard 已提交
6630 6631
}

6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643
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);
}

6644 6645 6646 6647 6648 6649
static virNodeDevicePtr
get_nonnull_node_device (virConnectPtr conn, remote_nonnull_node_device dev)
{
    return virGetNodeDevice(conn, dev.name);
}

6650 6651 6652
static virSecretPtr
get_nonnull_secret (virConnectPtr conn, remote_nonnull_secret secret)
{
6653
    return virGetSecret(conn, BAD_CAST secret.uuid, secret.usageType, secret.usageID);
6654 6655
}

6656 6657 6658 6659 6660 6661
static virNWFilterPtr
get_nonnull_nwfilter (virConnectPtr conn, remote_nonnull_nwfilter nwfilter)
{
    return virGetNWFilter (conn, nwfilter.name, BAD_CAST nwfilter.uuid);
}

C
Chris Lalancette 已提交
6662 6663 6664 6665 6666 6667
static virDomainSnapshotPtr
get_nonnull_domain_snapshot (virDomainPtr domain, remote_nonnull_domain_snapshot snapshot)
{
    return virGetDomainSnapshot(domain, snapshot.name);
}

6668

6669 6670 6671 6672
/* Make remote_nonnull_domain and remote_nonnull_network. */
static void
make_nonnull_domain (remote_nonnull_domain *dom_dst, virDomainPtr dom_src)
{
6673
    dom_dst->id = dom_src->id;
6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684
    dom_dst->name = dom_src->name;
    memcpy (dom_dst->uuid, dom_src->uuid, VIR_UUID_BUFLEN);
}

static void
make_nonnull_network (remote_nonnull_network *net_dst, virNetworkPtr net_src)
{
    net_dst->name = net_src->name;
    memcpy (net_dst->uuid, net_src->uuid, VIR_UUID_BUFLEN);
}

D
Daniel Veillard 已提交
6685 6686 6687 6688 6689 6690 6691 6692
static void
make_nonnull_interface (remote_nonnull_interface *interface_dst,
                        virInterfacePtr interface_src)
{
    interface_dst->name = interface_src->name;
    interface_dst->mac = interface_src->mac;
}

6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707
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;
}

6708 6709 6710
static void
make_nonnull_secret (remote_nonnull_secret *secret_dst, virSecretPtr secret_src)
{
6711
    memcpy (secret_dst->uuid, secret_src->uuid, VIR_UUID_BUFLEN);
6712 6713
    secret_dst->usageType = secret_src->usageType;
    secret_dst->usageID = secret_src->usageID;
6714 6715
}

6716 6717 6718 6719 6720 6721 6722
static void
make_nonnull_nwfilter (remote_nonnull_nwfilter *nwfilter_dst, virNWFilterPtr nwfilter_src)
{
    nwfilter_dst->name = nwfilter_src->name;
    memcpy (nwfilter_dst->uuid, nwfilter_src->uuid, VIR_UUID_BUFLEN);
}

C
Chris Lalancette 已提交
6723 6724 6725 6726
static void
make_nonnull_domain_snapshot (remote_nonnull_domain_snapshot *snapshot_dst, virDomainSnapshotPtr snapshot_src)
{
    snapshot_dst->name = snapshot_src->name;
6727
    make_nonnull_domain(&snapshot_dst->dom, snapshot_src->domain);
C
Chris Lalancette 已提交
6728 6729
}

6730 6731
/*----------------------------------------------------------------------*/

6732 6733 6734 6735 6736
unsigned long remoteVersion(void)
{
    return REMOTE_PROTOCOL_VERSION;
}

6737
static virDriver remote_driver = {
6738 6739
    .no = VIR_DRV_REMOTE,
    .name = "remote",
6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850
    .open = remoteOpen, /* 0.3.0 */
    .close = remoteClose, /* 0.3.0 */
    .supports_feature = remoteSupportsFeature, /* 0.3.0 */
    .type = remoteType, /* 0.3.0 */
    .version = remoteGetVersion, /* 0.3.0 */
    .libvirtVersion = remoteGetLibVersion, /* 0.7.3 */
    .getHostname = remoteGetHostname, /* 0.3.0 */
    .getSysinfo = remoteGetSysinfo, /* 0.8.8 */
    .getMaxVcpus = remoteGetMaxVcpus, /* 0.3.0 */
    .nodeGetInfo = remoteNodeGetInfo, /* 0.3.0 */
    .getCapabilities = remoteGetCapabilities, /* 0.3.0 */
    .listDomains = remoteListDomains, /* 0.3.0 */
    .numOfDomains = remoteNumOfDomains, /* 0.3.0 */
    .domainCreateXML = remoteDomainCreateXML, /* 0.3.0 */
    .domainLookupByID = remoteDomainLookupByID, /* 0.3.0 */
    .domainLookupByUUID = remoteDomainLookupByUUID, /* 0.3.0 */
    .domainLookupByName = remoteDomainLookupByName, /* 0.3.0 */
    .domainSuspend = remoteDomainSuspend, /* 0.3.0 */
    .domainResume = remoteDomainResume, /* 0.3.0 */
    .domainShutdown = remoteDomainShutdown, /* 0.3.0 */
    .domainReboot = remoteDomainReboot, /* 0.3.0 */
    .domainDestroy = remoteDomainDestroy, /* 0.3.0 */
    .domainGetOSType = remoteDomainGetOSType, /* 0.3.0 */
    .domainGetMaxMemory = remoteDomainGetMaxMemory, /* 0.3.0 */
    .domainSetMaxMemory = remoteDomainSetMaxMemory, /* 0.3.0 */
    .domainSetMemory = remoteDomainSetMemory, /* 0.3.0 */
    .domainSetMemoryFlags = remoteDomainSetMemoryFlags, /* 0.9.0 */
    .domainSetMemoryParameters = remoteDomainSetMemoryParameters, /* 0.8.5 */
    .domainGetMemoryParameters = remoteDomainGetMemoryParameters, /* 0.8.5 */
    .domainSetBlkioParameters = remoteDomainSetBlkioParameters, /* 0.9.0 */
    .domainGetBlkioParameters = remoteDomainGetBlkioParameters, /* 0.9.0 */
    .domainGetInfo = remoteDomainGetInfo, /* 0.3.0 */
    .domainGetState = remoteDomainGetState, /* 0.9.2 */
    .domainSave = remoteDomainSave, /* 0.3.0 */
    .domainRestore = remoteDomainRestore, /* 0.3.0 */
    .domainCoreDump = remoteDomainCoreDump, /* 0.3.0 */
    .domainScreenshot = remoteDomainScreenshot, /* 0.9.2 */
    .domainSetVcpus = remoteDomainSetVcpus, /* 0.3.0 */
    .domainSetVcpusFlags = remoteDomainSetVcpusFlags, /* 0.8.5 */
    .domainGetVcpusFlags = remoteDomainGetVcpusFlags, /* 0.8.5 */
    .domainPinVcpu = remoteDomainPinVcpu, /* 0.3.0 */
    .domainGetVcpus = remoteDomainGetVcpus, /* 0.3.0 */
    .domainGetMaxVcpus = remoteDomainGetMaxVcpus, /* 0.3.0 */
    .domainGetSecurityLabel = remoteDomainGetSecurityLabel, /* 0.6.1 */
    .nodeGetSecurityModel = remoteNodeGetSecurityModel, /* 0.6.1 */
    .domainGetXMLDesc = remoteDomainGetXMLDesc, /* 0.3.0 */
    .domainXMLFromNative = remoteDomainXMLFromNative, /* 0.6.4 */
    .domainXMLToNative = remoteDomainXMLToNative, /* 0.6.4 */
    .listDefinedDomains = remoteListDefinedDomains, /* 0.3.0 */
    .numOfDefinedDomains = remoteNumOfDefinedDomains, /* 0.3.0 */
    .domainCreate = remoteDomainCreate, /* 0.3.0 */
    .domainCreateWithFlags = remoteDomainCreateWithFlags, /* 0.8.2 */
    .domainDefineXML = remoteDomainDefineXML, /* 0.3.0 */
    .domainUndefine = remoteDomainUndefine, /* 0.3.0 */
    .domainAttachDevice = remoteDomainAttachDevice, /* 0.3.0 */
    .domainAttachDeviceFlags = remoteDomainAttachDeviceFlags, /* 0.7.7 */
    .domainDetachDevice = remoteDomainDetachDevice, /* 0.3.0 */
    .domainDetachDeviceFlags = remoteDomainDetachDeviceFlags, /* 0.7.7 */
    .domainUpdateDeviceFlags = remoteDomainUpdateDeviceFlags, /* 0.8.0 */
    .domainGetAutostart = remoteDomainGetAutostart, /* 0.3.0 */
    .domainSetAutostart = remoteDomainSetAutostart, /* 0.3.0 */
    .domainGetSchedulerType = remoteDomainGetSchedulerType, /* 0.3.0 */
    .domainGetSchedulerParameters = remoteDomainGetSchedulerParameters, /* 0.3.0 */
    .domainSetSchedulerParameters = remoteDomainSetSchedulerParameters, /* 0.3.0 */
    .domainMigratePrepare = remoteDomainMigratePrepare, /* 0.3.2 */
    .domainMigratePerform = remoteDomainMigratePerform, /* 0.3.2 */
    .domainMigrateFinish = remoteDomainMigrateFinish, /* 0.3.2 */
    .domainBlockStats = remoteDomainBlockStats, /* 0.3.2 */
    .domainInterfaceStats = remoteDomainInterfaceStats, /* 0.3.2 */
    .domainMemoryStats = remoteDomainMemoryStats, /* 0.7.5 */
    .domainBlockPeek = remoteDomainBlockPeek, /* 0.4.2 */
    .domainMemoryPeek = remoteDomainMemoryPeek, /* 0.4.2 */
    .domainGetBlockInfo = remoteDomainGetBlockInfo, /* 0.8.1 */
    .nodeGetCellsFreeMemory = remoteNodeGetCellsFreeMemory, /* 0.3.3 */
    .nodeGetFreeMemory = remoteNodeGetFreeMemory, /* 0.3.3 */
    .domainEventRegister = remoteDomainEventRegister, /* 0.5.0 */
    .domainEventDeregister = remoteDomainEventDeregister, /* 0.5.0 */
    .domainMigratePrepare2 = remoteDomainMigratePrepare2, /* 0.5.0 */
    .domainMigrateFinish2 = remoteDomainMigrateFinish2, /* 0.5.0 */
    .nodeDeviceDettach = remoteNodeDeviceDettach, /* 0.6.1 */
    .nodeDeviceReAttach = remoteNodeDeviceReAttach, /* 0.6.1 */
    .nodeDeviceReset = remoteNodeDeviceReset, /* 0.6.1 */
    .domainMigratePrepareTunnel = remoteDomainMigratePrepareTunnel, /* 0.7.2 */
    .isEncrypted = remoteIsEncrypted, /* 0.7.3 */
    .isSecure = remoteIsSecure, /* 0.7.3 */
    .domainIsActive = remoteDomainIsActive, /* 0.7.3 */
    .domainIsPersistent = remoteDomainIsPersistent, /* 0.7.3 */
    .domainIsUpdated = remoteDomainIsUpdated, /* 0.8.6 */
    .cpuCompare = remoteCPUCompare, /* 0.7.5 */
    .cpuBaseline = remoteCPUBaseline, /* 0.7.7 */
    .domainGetJobInfo = remoteDomainGetJobInfo, /* 0.7.7 */
    .domainAbortJob = remoteDomainAbortJob, /* 0.7.7 */
    .domainMigrateSetMaxDowntime = remoteDomainMigrateSetMaxDowntime, /* 0.8.0 */
    .domainMigrateSetMaxSpeed = remoteDomainMigrateSetMaxSpeed, /* 0.9.0 */
    .domainEventRegisterAny = remoteDomainEventRegisterAny, /* 0.8.0 */
    .domainEventDeregisterAny = remoteDomainEventDeregisterAny, /* 0.8.0 */
    .domainManagedSave = remoteDomainManagedSave, /* 0.8.0 */
    .domainHasManagedSaveImage = remoteDomainHasManagedSaveImage, /* 0.8.0 */
    .domainManagedSaveRemove = remoteDomainManagedSaveRemove, /* 0.8.0 */
    .domainSnapshotCreateXML = remoteDomainSnapshotCreateXML, /* 0.8.0 */
    .domainSnapshotGetXMLDesc = remoteDomainSnapshotGetXMLDesc, /* 0.8.0 */
    .domainSnapshotNum = remoteDomainSnapshotNum, /* 0.8.0 */
    .domainSnapshotListNames = remoteDomainSnapshotListNames, /* 0.8.0 */
    .domainSnapshotLookupByName = remoteDomainSnapshotLookupByName, /* 0.8.0 */
    .domainHasCurrentSnapshot = remoteDomainHasCurrentSnapshot, /* 0.8.0 */
    .domainSnapshotCurrent = remoteDomainSnapshotCurrent, /* 0.8.0 */
    .domainRevertToSnapshot = remoteDomainRevertToSnapshot, /* 0.8.0 */
    .domainSnapshotDelete = remoteDomainSnapshotDelete, /* 0.8.0 */
    .qemuDomainMonitorCommand = remoteQemuDomainMonitorCommand, /* 0.8.3 */
    .domainOpenConsole = remoteDomainOpenConsole, /* 0.8.6 */
    .domainInjectNMI = remoteDomainInjectNMI, /* 0.9.2 */
6851 6852 6853 6854 6855 6856
    .domainMigrateBegin3 = remoteDomainMigrateBegin3, /* 0.9.2 */
    .domainMigratePrepare3 = remoteDomainMigratePrepare3, /* 0.9.2 */
    .domainMigratePrepareTunnel3 = remoteDomainMigratePrepareTunnel3, /* 0.9.2 */
    .domainMigratePerform3 = remoteDomainMigratePerform3, /* 0.9.2 */
    .domainMigrateFinish3 = remoteDomainMigrateFinish3, /* 0.9.2 */
    .domainMigrateConfirm3 = remoteDomainMigrateConfirm3, /* 0.9.2 */
6857
    .domainSetSchedulerParametersFlags = remoteDomainSetSchedulerParametersFlags, /* 0.9.2 */
6858 6859 6860
};

static virNetworkDriver network_driver = {
6861
    .name = "remote",
6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880
    .open = remoteNetworkOpen, /* 0.3.0 */
    .close = remoteNetworkClose, /* 0.3.0 */
    .numOfNetworks = remoteNumOfNetworks, /* 0.3.0 */
    .listNetworks = remoteListNetworks, /* 0.3.0 */
    .numOfDefinedNetworks = remoteNumOfDefinedNetworks, /* 0.3.0 */
    .listDefinedNetworks = remoteListDefinedNetworks, /* 0.3.0 */
    .networkLookupByUUID = remoteNetworkLookupByUUID, /* 0.3.0 */
    .networkLookupByName = remoteNetworkLookupByName, /* 0.3.0 */
    .networkCreateXML = remoteNetworkCreateXML, /* 0.3.0 */
    .networkDefineXML = remoteNetworkDefineXML, /* 0.3.0 */
    .networkUndefine = remoteNetworkUndefine, /* 0.3.0 */
    .networkCreate = remoteNetworkCreate, /* 0.3.0 */
    .networkDestroy = remoteNetworkDestroy, /* 0.3.0 */
    .networkGetXMLDesc = remoteNetworkGetXMLDesc, /* 0.3.0 */
    .networkGetBridgeName = remoteNetworkGetBridgeName, /* 0.3.0 */
    .networkGetAutostart = remoteNetworkGetAutostart, /* 0.3.0 */
    .networkSetAutostart = remoteNetworkSetAutostart, /* 0.3.0 */
    .networkIsActive = remoteNetworkIsActive, /* 0.7.3 */
    .networkIsPersistent = remoteNetworkIsPersistent, /* 0.7.3 */
6881 6882
};

D
Daniel Veillard 已提交
6883 6884
static virInterfaceDriver interface_driver = {
    .name = "remote",
6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898
    .open = remoteInterfaceOpen, /* 0.7.2 */
    .close = remoteInterfaceClose, /* 0.7.2 */
    .numOfInterfaces = remoteNumOfInterfaces, /* 0.7.2 */
    .listInterfaces = remoteListInterfaces, /* 0.7.2 */
    .numOfDefinedInterfaces = remoteNumOfDefinedInterfaces, /* 0.7.2 */
    .listDefinedInterfaces = remoteListDefinedInterfaces, /* 0.7.2 */
    .interfaceLookupByName = remoteInterfaceLookupByName, /* 0.7.2 */
    .interfaceLookupByMACString = remoteInterfaceLookupByMACString, /* 0.7.2 */
    .interfaceGetXMLDesc = remoteInterfaceGetXMLDesc, /* 0.7.2 */
    .interfaceDefineXML = remoteInterfaceDefineXML, /* 0.7.2 */
    .interfaceUndefine = remoteInterfaceUndefine, /* 0.7.2 */
    .interfaceCreate = remoteInterfaceCreate, /* 0.7.2 */
    .interfaceDestroy = remoteInterfaceDestroy, /* 0.7.2 */
    .interfaceIsActive = remoteInterfaceIsActive, /* 0.7.3 */
D
Daniel Veillard 已提交
6899 6900
};

6901 6902
static virStorageDriver storage_driver = {
    .name = "remote",
6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941
    .open = remoteStorageOpen, /* 0.4.1 */
    .close = remoteStorageClose, /* 0.4.1 */
    .numOfPools = remoteNumOfStoragePools, /* 0.4.1 */
    .listPools = remoteListStoragePools, /* 0.4.1 */
    .numOfDefinedPools = remoteNumOfDefinedStoragePools, /* 0.4.1 */
    .listDefinedPools = remoteListDefinedStoragePools, /* 0.4.1 */
    .findPoolSources = remoteFindStoragePoolSources, /* 0.4.5 */
    .poolLookupByName = remoteStoragePoolLookupByName, /* 0.4.1 */
    .poolLookupByUUID = remoteStoragePoolLookupByUUID, /* 0.4.1 */
    .poolLookupByVolume = remoteStoragePoolLookupByVolume, /* 0.4.1 */
    .poolCreateXML = remoteStoragePoolCreateXML, /* 0.4.1 */
    .poolDefineXML = remoteStoragePoolDefineXML, /* 0.4.1 */
    .poolBuild = remoteStoragePoolBuild, /* 0.4.1 */
    .poolUndefine = remoteStoragePoolUndefine, /* 0.4.1 */
    .poolCreate = remoteStoragePoolCreate, /* 0.4.1 */
    .poolDestroy = remoteStoragePoolDestroy, /* 0.4.1 */
    .poolDelete = remoteStoragePoolDelete, /* 0.4.1 */
    .poolRefresh = remoteStoragePoolRefresh, /* 0.4.1 */
    .poolGetInfo = remoteStoragePoolGetInfo, /* 0.4.1 */
    .poolGetXMLDesc = remoteStoragePoolGetXMLDesc, /* 0.4.1 */
    .poolGetAutostart = remoteStoragePoolGetAutostart, /* 0.4.1 */
    .poolSetAutostart = remoteStoragePoolSetAutostart, /* 0.4.1 */
    .poolNumOfVolumes = remoteStoragePoolNumOfVolumes, /* 0.4.1 */
    .poolListVolumes = remoteStoragePoolListVolumes, /* 0.4.1 */

    .volLookupByName = remoteStorageVolLookupByName, /* 0.4.1 */
    .volLookupByKey = remoteStorageVolLookupByKey, /* 0.4.1 */
    .volLookupByPath = remoteStorageVolLookupByPath, /* 0.4.1 */
    .volCreateXML = remoteStorageVolCreateXML, /* 0.4.1 */
    .volCreateXMLFrom = remoteStorageVolCreateXMLFrom, /* 0.6.4 */
    .volDownload = remoteStorageVolDownload, /* 0.9.0 */
    .volUpload = remoteStorageVolUpload, /* 0.9.0 */
    .volDelete = remoteStorageVolDelete, /* 0.4.1 */
    .volWipe = remoteStorageVolWipe, /* 0.8.0 */
    .volGetInfo = remoteStorageVolGetInfo, /* 0.4.1 */
    .volGetXMLDesc = remoteStorageVolGetXMLDesc, /* 0.4.1 */
    .volGetPath = remoteStorageVolGetPath, /* 0.4.1 */
    .poolIsActive = remoteStoragePoolIsActive, /* 0.7.3 */
    .poolIsPersistent = remoteStoragePoolIsPersistent, /* 0.7.3 */
6942 6943
};

6944 6945
static virSecretDriver secret_driver = {
    .name = "remote",
6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956
    .open = remoteSecretOpen, /* 0.7.1 */
    .close = remoteSecretClose, /* 0.7.1 */
    .numOfSecrets = remoteNumOfSecrets, /* 0.7.1 */
    .listSecrets = remoteListSecrets, /* 0.7.1 */
    .lookupByUUID = remoteSecretLookupByUUID, /* 0.7.1 */
    .lookupByUsage = remoteSecretLookupByUsage, /* 0.7.1 */
    .defineXML = remoteSecretDefineXML, /* 0.7.1 */
    .getXMLDesc = remoteSecretGetXMLDesc, /* 0.7.1 */
    .setValue = remoteSecretSetValue, /* 0.7.1 */
    .getValue = remoteSecretGetValue, /* 0.7.1 */
    .undefine = remoteSecretUndefine /* 0.7.1 */
6957 6958
};

6959 6960
static virDeviceMonitor dev_monitor = {
    .name = "remote",
6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971
    .open = remoteDevMonOpen, /* 0.5.0 */
    .close = remoteDevMonClose, /* 0.5.0 */
    .numOfDevices = remoteNodeNumOfDevices, /* 0.5.0 */
    .listDevices = remoteNodeListDevices, /* 0.5.0 */
    .deviceLookupByName = remoteNodeDeviceLookupByName, /* 0.5.0 */
    .deviceGetXMLDesc = remoteNodeDeviceGetXMLDesc, /* 0.5.0 */
    .deviceGetParent = remoteNodeDeviceGetParent, /* 0.5.0 */
    .deviceNumOfCaps = remoteNodeDeviceNumOfCaps, /* 0.5.0 */
    .deviceListCaps = remoteNodeDeviceListCaps, /* 0.5.0 */
    .deviceCreateXML = remoteNodeDeviceCreateXML, /* 0.6.3 */
    .deviceDestroy = remoteNodeDeviceDestroy /* 0.6.3 */
6972 6973
};

6974 6975
static virNWFilterDriver nwfilter_driver = {
    .name = "remote",
6976 6977 6978 6979 6980 6981 6982 6983 6984
    .open = remoteNWFilterOpen, /* 0.8.0 */
    .close = remoteNWFilterClose, /* 0.8.0 */
    .nwfilterLookupByUUID = remoteNWFilterLookupByUUID, /* 0.8.0 */
    .nwfilterLookupByName = remoteNWFilterLookupByName, /* 0.8.0 */
    .getXMLDesc           = remoteNWFilterGetXMLDesc, /* 0.8.0 */
    .defineXML            = remoteNWFilterDefineXML, /* 0.8.0 */
    .undefine             = remoteNWFilterUndefine, /* 0.8.0 */
    .numOfNWFilters       = remoteNumOfNWFilters, /* 0.8.0 */
    .listNWFilters        = remoteListNWFilters, /* 0.8.0 */
6985 6986
};

6987

A
Atsushi SAKAI 已提交
6988
#ifdef WITH_LIBVIRTD
6989
static virStateDriver state_driver = {
6990
    .name = "Remote",
6991
    .initialize = remoteStartup,
6992
};
A
Atsushi SAKAI 已提交
6993
#endif
6994 6995


6996
/** remoteRegister:
6997 6998
 *
 * Register driver with libvirt driver system.
6999 7000
 *
 * Returns -1 on error.
7001 7002 7003 7004
 */
int
remoteRegister (void)
{
7005
    if (virRegisterDriver (&remote_driver) == -1) return -1;
7006
    if (virRegisterNetworkDriver (&network_driver) == -1) return -1;
D
Daniel Veillard 已提交
7007
    if (virRegisterInterfaceDriver (&interface_driver) == -1) return -1;
7008
    if (virRegisterStorageDriver (&storage_driver) == -1) return -1;
7009
    if (virRegisterDeviceMonitor (&dev_monitor) == -1) return -1;
7010
    if (virRegisterSecretDriver (&secret_driver) == -1) return -1;
7011
    if (virRegisterNWFilterDriver(&nwfilter_driver) == -1) return -1;
A
Atsushi SAKAI 已提交
7012
#ifdef WITH_LIBVIRTD
7013
    if (virRegisterStateDriver (&state_driver) == -1) return -1;
A
Atsushi SAKAI 已提交
7014
#endif
7015 7016 7017

    return 0;
}