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

24
#include <config.h>
25

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

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

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

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

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

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

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

J
Jim Meyering 已提交
69
#include <netdb.h>
70 71 72 73 74 75

/* AI_ADDRCONFIG is missing on some systems. */
#ifndef AI_ADDRCONFIG
# define AI_ADDRCONFIG 0
#endif

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

/* Per-connection private data. */
#define MAGIC 999               /* private_data->magic if OK */
#define DEAD 998                /* private_data->magic if dead/closed */

93 94
static int inside_daemon = 0;

95 96 97
struct private_data {
    int magic;                  /* Should be MAGIC or DEAD. */
    int sock;                   /* Socket. */
98
    int watch;                  /* File handle watch */
99
    pid_t pid;                  /* PID of tunnel process */
100 101 102 103
    int uses_tls;               /* TLS enabled on socket? */
    gnutls_session_t session;   /* GnuTLS session (if uses_tls != 0). */
    char *type;                 /* Cached return from remoteType. */
    int counter;                /* Generates serial numbers for RPC. */
104
    int localUses;              /* Ref count for private data */
105 106 107 108
    char *hostname;             /* Original hostname */
    FILE *debugLog;             /* Debug remote protocol */
#if HAVE_SASL
    sasl_conn_t *saslconn;      /* SASL context */
109 110 111
    const char *saslDecoded;
    unsigned int saslDecodedLength;
    unsigned int saslDecodedOffset;
112
#endif
113 114 115 116 117 118 119
    /* The list of domain event callbacks */
    virDomainEventCallbackListPtr callbackList;
    /* The queue of domain events generated
       during a call / response rpc          */
    virDomainEventQueuePtr domainEvents;
    /* Timer for flushing domainEvents queue */
    int eventFlushTimer;
120 121 122 123
};

#define GET_PRIVATE(conn,retcode)                                       \
    struct private_data *priv = (struct private_data *) (conn)->privateData; \
124
    if (!priv || priv->magic != MAGIC) {                                \
125
        error (conn, VIR_ERR_INVALID_ARG,                               \
126
               _("tried to use a closed or uninitialised handle"));     \
127
        return (retcode);                                               \
128 129 130 131 132 133
    }

#define GET_NETWORK_PRIVATE(conn,retcode)                               \
    struct private_data *priv = (struct private_data *) (conn)->networkPrivateData; \
    if (!priv || priv->magic != MAGIC) {                                \
        error (conn, VIR_ERR_INVALID_ARG,                               \
134
               _("tried to use a closed or uninitialised handle"));     \
135 136
        return (retcode);                                               \
    }
137

138 139 140 141 142 143 144 145
#define GET_STORAGE_PRIVATE(conn,retcode)                               \
    struct private_data *priv = (struct private_data *) (conn)->storagePrivateData; \
    if (!priv || priv->magic != MAGIC) {                                \
        error (conn, VIR_ERR_INVALID_ARG,                               \
               "tried to use a closed or uninitialised handle");        \
        return (retcode);                                               \
    }

146 147 148 149 150 151 152 153
#define GET_DEVMON_PRIVATE(conn,retcode)                               \
    struct private_data *priv = (struct private_data *) (conn)->devMonPrivateData; \
    if (!priv || priv->magic != MAGIC) {                                \
        error (conn, VIR_ERR_INVALID_ARG,                               \
               _("tried to use a closed or uninitialised handle"));     \
        return (retcode);                                               \
    }

154

155 156 157 158 159 160 161 162 163 164
enum {
    REMOTE_CALL_IN_OPEN = 1,
    REMOTE_CALL_QUIET_MISSING_RPC = 2,
};


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);
165 166
static int remoteAuthenticate (virConnectPtr conn, struct private_data *priv, int in_open,
                               virConnectAuthPtr auth, const char *authtype);
167
#if HAVE_SASL
168 169
static int remoteAuthSASL (virConnectPtr conn, struct private_data *priv, int in_open,
                           virConnectAuthPtr auth, const char *mech);
170
#endif
171
#if HAVE_POLKIT
172 173
static int remoteAuthPolkit (virConnectPtr conn, struct private_data *priv, int in_open,
                             virConnectAuthPtr auth);
174
#endif /* HAVE_POLKIT */
175
static void error (virConnectPtr conn, virErrorNumber code, const char *info);
176 177
static void errorf (virConnectPtr conn, virErrorNumber code,
                     const char *fmt, ...) ATTRIBUTE_FORMAT(printf, 3, 4);
178 179 180
static void server_error (virConnectPtr conn, remote_error *err);
static virDomainPtr get_nonnull_domain (virConnectPtr conn, remote_nonnull_domain domain);
static virNetworkPtr get_nonnull_network (virConnectPtr conn, remote_nonnull_network network);
181 182
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);
183
static virNodeDevicePtr get_nonnull_node_device (virConnectPtr conn, remote_nonnull_node_device dev);
184 185
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);
186 187
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);
188
void remoteDomainEventFired(int watch, int fd, int event, void *data);
189 190 191
static void remoteDomainProcessEvent(virConnectPtr conn, XDR *xdr);
static void remoteDomainQueueEvent(virConnectPtr conn, XDR *xdr);
void remoteDomainEventQueueFlush(int timer, void *opaque);
192 193 194 195 196 197 198
/*----------------------------------------------------------------------*/

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

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

A
Atsushi SAKAI 已提交
201
#ifdef WITH_LIBVIRTD
202 203 204 205 206 207 208 209 210
static int
remoteStartup(void)
{
    /* Mark that we're inside the daemon so we can avoid
     * re-entering ourselves
     */
    inside_daemon = 1;
    return 0;
}
A
Atsushi SAKAI 已提交
211
#endif
212

213
#ifndef WIN32
214 215 216 217
/**
 * remoteFindServerPath:
 *
 * Tries to find the path to the libvirtd binary.
218
 *
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
 * Returns path on success or NULL in case of error.
 */
static const char *
remoteFindDaemonPath(void)
{
    static const char *serverPaths[] = {
        SBINDIR "/libvirtd",
        SBINDIR "/libvirtd_dbg",
        NULL
    };
    int i;
    const char *customDaemon = getenv("LIBVIRTD_PATH");

    if (customDaemon)
        return(customDaemon);

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

/**
 * qemuForkDaemon:
 *
 * Forks and try to launch the libvirtd daemon
 *
 * Returns 0 in case of success or -1 in case of detected error.
 */
250
static int
251 252 253
remoteForkDaemon(virConnectPtr conn)
{
    const char *daemonPath = remoteFindDaemonPath();
254
    const char *const daemonargs[] = { daemonPath, "--timeout=30", NULL };
255 256 257
    int ret, pid, status;

    if (!daemonPath) {
258
        error(conn, VIR_ERR_INTERNAL_ERROR, _("failed to find libvirtd binary"));
259
        return -1;
260 261
    }

262 263 264
    if (virExec(NULL, daemonargs, NULL, NULL,
                &pid, -1, NULL, NULL, VIR_EXEC_DAEMON) < 0)
        return -1;
265 266 267 268 269 270 271 272 273 274
    /*
     * do a waitpid on the intermediate process to avoid zombies.
     */
 retry_wait:
    ret = waitpid(pid, &status, 0);
    if (ret < 0) {
        if (errno == EINTR)
            goto retry_wait;
    }

275
    return 0;
276
}
277
#endif
278

279
enum virDrvOpenRemoteFlags {
280 281 282 283
    VIR_DRV_OPEN_REMOTE_RO = (1 << 0),
    VIR_DRV_OPEN_REMOTE_UNIX = (1 << 1),
    VIR_DRV_OPEN_REMOTE_USER = (1 << 2),
    VIR_DRV_OPEN_REMOTE_AUTOSTART = (1 << 3),
284
};
285

286 287 288 289 290 291 292 293 294 295
/* What transport? */
enum {
    trans_tls,
    trans_unix,
    trans_ssh,
    trans_ext,
    trans_tcp,
} transport;


296
static int
297 298 299 300
doRemoteOpen (virConnectPtr conn,
              struct private_data *priv,
              virConnectAuthPtr auth ATTRIBUTE_UNUSED,
              int flags)
301
{
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
    char *transport_str = NULL;

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

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

        if (!transport_str || STRCASEEQ (transport_str, "tls"))
            transport = trans_tls;
        else if (STRCASEEQ (transport_str, "unix"))
            transport = trans_unix;
        else if (STRCASEEQ (transport_str, "ssh"))
            transport = trans_ssh;
        else if (STRCASEEQ (transport_str, "ext"))
            transport = trans_ext;
        else if (STRCASEEQ (transport_str, "tcp"))
            transport = trans_tcp;
        else {
            error (conn, VIR_ERR_INVALID_ARG,
                   _("remote_open: transport in URL not recognised "
                     "(should be tls|unix|ssh|ext|tcp)"));
            return VIR_DRV_OPEN_ERROR;
        }
326 327
    }

328 329 330
    if (!transport_str) {
        if ((!conn->uri || !conn->uri->server) &&
            (flags & VIR_DRV_OPEN_REMOTE_UNIX))
331 332 333 334
            transport = trans_unix;
        else
            return VIR_DRV_OPEN_DECLINED; /* Decline - not a remote URL. */
    }
335

336 337 338
    /* Local variables which we will initialise. These can
     * get freed in the failed: path.
     */
339
    char *name = 0, *command = 0, *sockname = 0, *netcat = 0, *username = 0;
340
    char *port = 0, *authtype = 0;
341
    int no_verify = 0, no_tty = 0;
342
    char **cmd_argv = NULL;
343

344 345 346
    /* Return code from this function, and the private data. */
    int retcode = VIR_DRV_OPEN_ERROR;

347
    /* Remote server defaults to "localhost" if not specified. */
348 349
    if (conn->uri && conn->uri->port != 0) {
        if (asprintf (&port, "%d", conn->uri->port) == -1) goto out_of_memory;
350 351 352 353 354 355 356 357 358 359 360 361
    } else if (transport == trans_tls) {
        port = strdup (LIBVIRTD_TLS_PORT);
        if (!port) goto out_of_memory;
    } else if (transport == trans_tcp) {
        port = strdup (LIBVIRTD_TCP_PORT);
        if (!port) goto out_of_memory;
    } else if (transport == trans_ssh) {
        port = strdup ("22");
        if (!port) goto out_of_memory;
    } else
        port = NULL;           /* Port not used for unix, ext. */

362

363 364
    priv->hostname = strdup (conn->uri && conn->uri->server ?
                             conn->uri->server : "localhost");
365 366
    if (!priv->hostname)
        goto out_of_memory;
367 368
    if (conn->uri && conn->uri->user) {
        username = strdup (conn->uri->user);
369 370
        if (!username)
            goto out_of_memory;
371 372
    }

373 374 375 376 377
    /* 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).
     */
378 379 380
    struct qparam_set *vars;
    struct qparam *var;
    int i;
381 382
    char *query;

383
    if (conn->uri) {
384
#ifdef HAVE_XMLURI_QUERY_RAW
385
        query = conn->uri->query_raw;
386
#else
387
        query = conn->uri->query;
388
#endif
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
        vars = qparam_query_parse (query);
        if (vars == NULL) goto failed;

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

431 432 433 434
        /* Construct the original name. */
        if (!name) {
            xmlURI tmpuri = {
                .scheme = conn->uri->scheme,
435
#ifdef HAVE_XMLURI_QUERY_RAW
436
                .query_raw = qparam_get_query (vars),
437
#else
438
                .query = qparam_get_query (vars),
439
#endif
440 441 442 443 444 445 446 447 448
                .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';
            }
449

450
            name = (char *) xmlSaveUri (&tmpuri);
451

452 453 454
            /* Restore transport scheme */
            if (transport_str)
                transport_str[-1] = '+';
455 456
        }

457 458 459 460 461
        free_qparam_set (vars);
    } else {
        /* Probe URI server side */
        name = strdup("");
    }
462

463 464 465
    if (!name) {
        error(conn, VIR_ERR_NO_MEMORY, NULL);
        goto failed;
466 467
    }

468
    DEBUG("proceeding with name = %s", name);
469

470 471 472 473 474 475 476
    /* For ext transport, command is required. */
    if (transport == trans_ext && !command) {
        error (conn, VIR_ERR_INVALID_ARG,
               _("remote_open: for 'ext' transport, command is required"));
        goto failed;
    }

477 478 479 480
    /* Connect to the remote service. */
    switch (transport) {
    case trans_tls:
        if (initialise_gnutls (conn) == -1) goto failed;
481
        priv->uses_tls = 1;
482 483 484 485 486 487

        /*FALLTHROUGH*/
    case trans_tcp: {
        // http://people.redhat.com/drepper/userapi-ipv6.html
        struct addrinfo *res, *r;
        struct addrinfo hints;
488
        int saved_errno = EINVAL;
489 490 491
        memset (&hints, 0, sizeof hints);
        hints.ai_socktype = SOCK_STREAM;
        hints.ai_flags = AI_ADDRCONFIG;
492
        int e = getaddrinfo (priv->hostname, port, &hints, &res);
493
        if (e != 0) {
494 495 496
            errorf (conn, VIR_ERR_SYSTEM_ERROR,
                    _("unable to resolve hostname '%s': %s"),
                    priv->hostname, gai_strerror (e));
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
            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;

514 515
            priv->sock = socket (r->ai_family, SOCK_STREAM, 0);
            if (priv->sock == -1) {
J
Jim Meyering 已提交
516
                saved_errno = errno;
517 518 519 520
                continue;
            }

            /* Disable Nagle - Dan Berrange. */
521
            setsockopt (priv->sock,
522 523 524
                        IPPROTO_TCP, TCP_NODELAY, (void *)&no_slow_start,
                        sizeof no_slow_start);

525
            if (connect (priv->sock, r->ai_addr, r->ai_addrlen) == -1) {
J
Jim Meyering 已提交
526
                saved_errno = errno;
527
                close (priv->sock);
528 529 530
                continue;
            }

531 532
            if (priv->uses_tls) {
                priv->session =
533
                    negotiate_gnutls_on_connection
534
                      (conn, priv, no_verify);
535 536 537
                if (!priv->session) {
                    close (priv->sock);
                    priv->sock = -1;
538 539 540 541 542 543 544
                    continue;
                }
            }
            goto tcp_connected;
        }

        freeaddrinfo (res);
545 546 547
        errorf (conn, VIR_ERR_SYSTEM_ERROR,
                _("unable to connect to '%s': %s"),
                priv->hostname, strerror (saved_errno));
548 549 550 551 552 553 554 555 556 557
        goto failed;

       tcp_connected:
        freeaddrinfo (res);

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

558
#ifndef WIN32
559 560
    case trans_unix: {
        if (!sockname) {
561
            if (flags & VIR_DRV_OPEN_REMOTE_USER) {
562 563
                struct passwd *pw;
                uid_t uid = getuid();
564

565
                if (!(pw = getpwuid(uid))) {
566 567 568
                    errorf (conn, VIR_ERR_SYSTEM_ERROR,
                            _("unable to lookup user '%d': %s"),
                            uid, strerror (errno));
569 570
                    goto failed;
                }
571

572
                if (asprintf (&sockname, "@%s" LIBVIRTD_USER_UNIX_SOCKET, pw->pw_dir) < 0) {
573 574
                    sockname = NULL;
                    goto out_of_memory;
575 576
                }
            } else {
577
                if (flags & VIR_DRV_OPEN_REMOTE_RO)
578 579 580
                    sockname = strdup (LIBVIRTD_PRIV_UNIX_SOCKET_RO);
                else
                    sockname = strdup (LIBVIRTD_PRIV_UNIX_SOCKET);
581 582
                if (sockname == NULL)
                    goto out_of_memory;
583
            }
584 585 586 587 588 589
        }

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

592 593 594
        memset (&addr, 0, sizeof addr);
        addr.sun_family = AF_UNIX;
        strncpy (addr.sun_path, sockname, UNIX_PATH_MAX (addr));
595 596
        if (addr.sun_path[0] == '@')
            addr.sun_path[0] = '\0';
597

598 599 600
      autostart_retry:
        priv->sock = socket (AF_UNIX, SOCK_STREAM, 0);
        if (priv->sock == -1) {
601 602 603
            errorf (conn, VIR_ERR_SYSTEM_ERROR,
                    _("unable to create socket %s"),
                    strerror (errno));
604 605
            goto failed;
        }
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
        if (connect (priv->sock, (struct sockaddr *) &addr, sizeof addr) == -1) {
            /* We might have to autostart the daemon in some cases....
             * It takes a short while for the daemon to startup, hence we
             * have a number of retries, with a small sleep. This will
             * sometimes cause multiple daemons to be started - this is
             * ok because the duplicates will fail to bind to the socket
             * and immediately exit, leaving just one daemon.
             */
            if (errno == ECONNREFUSED &&
                flags & VIR_DRV_OPEN_REMOTE_AUTOSTART &&
                trials < 5) {
                close(priv->sock);
                priv->sock = -1;
                if (remoteForkDaemon(conn) == 0) {
                    trials++;
                    usleep(5000 * trials * trials);
                    goto autostart_retry;
                }
            }
625 626 627
            errorf (conn, VIR_ERR_SYSTEM_ERROR,
                    _("unable to connect to '%s': %s"),
                    sockname, strerror (errno));
628 629 630 631 632 633 634
            goto failed;
        }

        break;
    }

    case trans_ssh: {
635 636 637 638
        int j, nr_args = 8;

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

        command = command ? : strdup ("ssh");
641 642
        if (command == NULL)
            goto out_of_memory;
643 644 645

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

649 650 651 652 653 654 655 656
        j = 0;
        cmd_argv[j++] = strdup (command);
        cmd_argv[j++] = strdup ("-p");
        cmd_argv[j++] = strdup (port);
        if (username) {
            cmd_argv[j++] = strdup ("-l");
            cmd_argv[j++] = strdup (username);
        }
657 658 659 660 661 662 663
        if (no_tty) {
            cmd_argv[j++] = strdup ("-T");
            cmd_argv[j++] = strdup ("-o");
            cmd_argv[j++] = strdup ("BatchMode=yes");
            cmd_argv[j++] = strdup ("-e");
            cmd_argv[j++] = strdup ("none");
        }
664
        cmd_argv[j++] = strdup (priv->hostname);
665 666
        cmd_argv[j++] = strdup (netcat ? netcat : "nc");
        cmd_argv[j++] = strdup ("-U");
667
        cmd_argv[j++] = strdup (sockname ? sockname : LIBVIRTD_PRIV_UNIX_SOCKET);
668 669
        cmd_argv[j++] = 0;
        assert (j == nr_args);
670 671 672
        for (j = 0; j < (nr_args-1); j++)
            if (cmd_argv[j] == NULL)
                goto out_of_memory;
673 674 675 676
    }

        /*FALLTHROUGH*/
    case trans_ext: {
677
        pid_t pid;
678 679 680 681 682 683 684
        int sv[2];

        /* Fork off the external process.  Use socketpair to create a private
         * (unnamed) Unix domain socket to the child process so we don't have
         * to faff around with two file descriptors (a la 'pipe(2)').
         */
        if (socketpair (PF_UNIX, SOCK_STREAM, 0, sv) == -1) {
685 686 687
            errorf (conn, VIR_ERR_SYSTEM_ERROR,
                    _("unable to create socket pair %s"),
                    strerror (errno));
688 689 690
            goto failed;
        }

691 692
        if (virExec(conn, (const char**)cmd_argv, NULL, NULL,
                    &pid, sv[1], &(sv[1]), NULL, VIR_EXEC_NONE) < 0)
693 694 695 696
            goto failed;

        /* Parent continues here. */
        close (sv[1]);
697
        priv->sock = sv[0];
698
        priv->pid = pid;
699
    }
700 701 702 703 704 705 706 707 708 709
#else /* WIN32 */

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

#endif /* WIN32 */

710 711
    } /* switch (transport) */

712 713

    /* Try and authenticate with server */
714
    if (remoteAuthenticate(conn, priv, 1, auth, authtype) == -1)
715 716
        goto failed;

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

720
    if (call (conn, priv, REMOTE_CALL_IN_OPEN, REMOTE_PROC_OPEN,
721 722 723 724
              (xdrproc_t) xdr_remote_open_args, (char *) &args,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        goto failed;

725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
    /* Now try and find out what URI the daemon used */
    if (conn->uri == NULL) {
        remote_get_uri_ret uriret;
        int urierr;

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

        DEBUG("Auto-probed URI is %s", uriret.uri);
        conn->uri = xmlParseURI(uriret.uri);
        VIR_FREE(uriret.uri);
        if (!conn->uri) {
            error (conn, VIR_ERR_NO_MEMORY, NULL);
            goto failed;
        }
    }

757 758 759 760 761 762 763 764 765 766 767 768
    if(VIR_ALLOC(priv->callbackList)<0) {
        error(conn, VIR_ERR_INVALID_ARG, _("Error allocating callbacks list"));
        goto failed;
    }

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

    DEBUG0("Adding Handler for remote events");
    /* Set up a callback to listen on the socket data */
769 770 771 772 773
    if ((priv->watch = virEventAddHandle(priv->sock,
                                         VIR_EVENT_HANDLE_READABLE |
                                         VIR_EVENT_HANDLE_ERROR |
                                         VIR_EVENT_HANDLE_HANGUP,
                                         remoteDomainEventFired,
774
                                         conn, NULL)) < 0) {
775 776 777 778 779 780
        DEBUG0("virEventAddHandle failed: No addHandleImpl defined."
               " continuing without events.");
    } else {

        DEBUG0("Adding Timeout for remote event queue flushing");
        if ( (priv->eventFlushTimer = virEventAddTimeout(-1,
781 782
                                                         remoteDomainEventQueueFlush,
                                                         conn, NULL)) < 0) {
783 784
            DEBUG0("virEventAddTimeout failed: No addTimeoutImpl defined. "
                    "continuing without events.");
785
            virEventRemoveHandle(priv->watch);
786 787
        }
    }
788 789 790
    /* Successful. */
    retcode = VIR_DRV_OPEN_SUCCESS;

791
 cleanup:
792
    /* Free up the URL and strings. */
793 794 795 796 797 798 799
    free (name);
    free (command);
    free (sockname);
    free (authtype);
    free (netcat);
    free (username);
    free (port);
800 801 802 803 804 805 806 807 808 809
    if (cmd_argv) {
        char **cmd_argv_ptr = cmd_argv;
        while (*cmd_argv_ptr) {
            free (*cmd_argv_ptr);
            cmd_argv_ptr++;
        }
        free (cmd_argv);
    }

    return retcode;
810 811

 out_of_memory:
812
    error (conn, VIR_ERR_NO_MEMORY, NULL);
813 814 815 816 817 818 819 820 821

 failed:
    /* Close the socket if we failed. */
    if (priv->sock >= 0) {
        if (priv->uses_tls && priv->session) {
            gnutls_bye (priv->session, GNUTLS_SHUT_RDWR);
            gnutls_deinit (priv->session);
        }
        close (priv->sock);
822
#ifndef WIN32
823 824 825 826 827 828 829 830
        if (priv->pid > 0) {
            pid_t reap;
            do {
                reap = waitpid(priv->pid, NULL, 0);
                if (reap == -1 && errno == EINTR)
                    continue;
            } while (reap != -1 && reap != priv->pid);
        }
831
#endif
832 833 834 835 836 837 838 839
    }

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

    goto cleanup;
840 841
}

842
static int
843 844 845
remoteOpen (virConnectPtr conn,
            virConnectAuthPtr auth,
            int flags)
846
{
847
    struct private_data *priv;
848 849
    int ret, rflags = 0;

850 851 852
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

853
    if (VIR_ALLOC(priv) < 0) {
854
        error (conn, VIR_ERR_NO_MEMORY, _("struct private_data"));
855 856 857
        return VIR_DRV_OPEN_ERROR;
    }

858
    if (flags & VIR_CONNECT_RO)
859 860
        rflags |= VIR_DRV_OPEN_REMOTE_RO;

861 862 863 864 865 866 867
    /*
     * If no servername is given, and no +XXX
     * transport is listed, then force to a
     * local UNIX socket connection
     */
    if (conn->uri &&
        !conn->uri->server &&
D
Daniel P. Berrange 已提交
868
        conn->uri->scheme &&
869 870
        !strchr(conn->uri->scheme, '+')) {
        DEBUG0("Auto-remote UNIX socket");
871 872
        rflags |= VIR_DRV_OPEN_REMOTE_UNIX;
    }
873 874 875 876 877 878 879 880 881 882

    /*
     * 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 已提交
883
        conn->uri->scheme &&
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
        ((strchr(conn->uri->scheme, '+') == 0)||
         (strstr(conn->uri->scheme, "+unix") != NULL)) &&
        STREQ(conn->uri->path, "/session") &&
        getuid() > 0) {
        DEBUG0("Auto-spawn user daemon instance");
        rflags |= VIR_DRV_OPEN_REMOTE_USER;
        rflags |= VIR_DRV_OPEN_REMOTE_AUTOSTART;
    }

    /*
     * If URI is NULL, then do a UNIX connection
     * possibly auto-spawning unprivileged server
     * and probe remote server for URI
     */
    if (!conn->uri) {
        DEBUG0("Auto-probe remote URI");
900
        rflags |= VIR_DRV_OPEN_REMOTE_UNIX;
901 902 903 904 905
        if (getuid() > 0) {
            DEBUG0("Auto-spawn user daemon instance");
            rflags |= VIR_DRV_OPEN_REMOTE_USER;
            rflags |= VIR_DRV_OPEN_REMOTE_AUTOSTART;
        }
906
    }
907 908 909

    priv->magic = DEAD;
    priv->sock = -1;
910
    ret = doRemoteOpen(conn, priv, auth, rflags);
911 912
    if (ret != VIR_DRV_OPEN_SUCCESS) {
        conn->privateData = NULL;
913
        VIR_FREE(priv);
914 915 916 917 918 919 920 921
    } else {
        priv->magic = MAGIC;
        conn->privateData = priv;
    }
    return ret;
}


922 923 924 925 926 927 928 929 930 931 932
/* 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;

933 934

static int
935
check_cert_file (virConnectPtr conn, const char *type, const char *file)
936 937 938
{
    struct stat sb;
    if (stat(file, &sb) < 0) {
939 940 941
        errorf(conn, VIR_ERR_RPC,
               _("Cannot access %s '%s': %s (%d)"),
               type, file, strerror(errno), errno);
942 943 944 945 946 947
        return -1;
    }
    return 0;
}


948
static int
949
initialise_gnutls (virConnectPtr conn)
950 951 952 953 954 955 956 957 958 959 960
{
    static int initialised = 0;
    int err;

    if (initialised) return 0;

    gnutls_global_init ();

    /* X509 stuff */
    err = gnutls_certificate_allocate_credentials (&x509_cred);
    if (err) {
961 962 963
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to allocate TLS credentials: %s"),
                gnutls_strerror (err));
964 965 966
        return -1;
    }

967

968
    if (check_cert_file(conn, "CA certificate", LIBVIRT_CACERT) < 0)
969
        return -1;
970
    if (check_cert_file(conn, "client key", LIBVIRT_CLIENTKEY) < 0)
971
        return -1;
972
    if (check_cert_file(conn, "client certificate", LIBVIRT_CLIENTCERT) < 0)
973 974
        return -1;

975
    /* Set the trusted CA cert. */
976
    DEBUG("loading CA file %s", LIBVIRT_CACERT);
977 978 979 980
    err =
        gnutls_certificate_set_x509_trust_file (x509_cred, LIBVIRT_CACERT,
                                                GNUTLS_X509_FMT_PEM);
    if (err < 0) {
981 982 983
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to load CA certificate: %s"),
                gnutls_strerror (err));
984 985 986 987
        return -1;
    }

    /* Set the client certificate and private key. */
988 989
    DEBUG("loading client cert and key from files %s and %s",
          LIBVIRT_CLIENTCERT, LIBVIRT_CLIENTKEY);
990 991 992 993 994 995
    err =
        gnutls_certificate_set_x509_key_file (x509_cred,
                                              LIBVIRT_CLIENTCERT,
                                              LIBVIRT_CLIENTKEY,
                                              GNUTLS_X509_FMT_PEM);
    if (err < 0) {
996 997 998
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to load private key/certificate: %s"),
                gnutls_strerror (err));
999 1000 1001 1002 1003 1004 1005
        return -1;
    }

    initialised = 1;
    return 0;
}

1006
static int verify_certificate (virConnectPtr conn, struct private_data *priv, gnutls_session_t session);
1007 1008 1009

static gnutls_session_t
negotiate_gnutls_on_connection (virConnectPtr conn,
1010 1011
                                struct private_data *priv,
                                int no_verify)
1012 1013 1014 1015 1016 1017 1018 1019 1020
{
    const int cert_type_priority[3] = {
        GNUTLS_CRT_X509,
        GNUTLS_CRT_OPENPGP,
        0
    };
    int err;
    gnutls_session_t session;

1021
    /* Initialize TLS session
1022 1023 1024
     */
    err = gnutls_init (&session, GNUTLS_CLIENT);
    if (err) {
1025 1026 1027
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to initialize TLS client: %s"),
                gnutls_strerror (err));
1028 1029 1030 1031 1032 1033
        return NULL;
    }

    /* Use default priorities */
    err = gnutls_set_default_priority (session);
    if (err) {
1034 1035 1036
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to set TLS algorithm priority: %s"),
                gnutls_strerror (err));
1037 1038 1039 1040 1041 1042
        return NULL;
    }
    err =
        gnutls_certificate_type_set_priority (session,
                                              cert_type_priority);
    if (err) {
1043 1044 1045
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to set certificate priority: %s"),
                gnutls_strerror (err));
1046 1047 1048 1049 1050 1051 1052
        return NULL;
    }

    /* put the x509 credentials to the current session
     */
    err = gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, x509_cred);
    if (err) {
1053 1054 1055
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to set session credentials: %s"),
                gnutls_strerror (err));
1056 1057 1058 1059
        return NULL;
    }

    gnutls_transport_set_ptr (session,
1060
                              (gnutls_transport_ptr_t) (long) priv->sock);
1061 1062 1063 1064 1065 1066 1067

    /* Perform the TLS handshake. */
 again:
    err = gnutls_handshake (session);
    if (err < 0) {
        if (err == GNUTLS_E_AGAIN || err == GNUTLS_E_INTERRUPTED)
            goto again;
1068 1069 1070
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to complete TLS handshake: %s"),
                gnutls_strerror (err));
1071 1072 1073 1074
        return NULL;
    }

    /* Verify certificate. */
1075
    if (verify_certificate (conn, priv, session) == -1) {
1076 1077 1078
        DEBUG0("failed to verify peer's certificate");
        if (!no_verify) return NULL;
    }
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089

    /* 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;
1090 1091 1092
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to complete TLS initialization: %s"),
                gnutls_strerror (len));
1093 1094 1095
        return NULL;
    }
    if (len != 1 || buf[0] != '\1') {
1096
        error (conn, VIR_ERR_RPC,
1097
               _("server verification (of our certificate or IP address) failed\n"));
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
        return NULL;
    }

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

    return session;
}

static int
verify_certificate (virConnectPtr conn ATTRIBUTE_UNUSED,
1111 1112
                    struct private_data *priv,
                    gnutls_session_t session)
1113 1114 1115 1116 1117 1118 1119 1120
{
    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) {
1121 1122 1123
        errorf (conn, VIR_ERR_GNUTLS_ERROR,
                _("unable to verify server certificate: %s"),
                gnutls_strerror (ret));
1124 1125
        return -1;
    }
1126

1127
    if ((now = time(NULL)) == ((time_t)-1)) {
1128 1129 1130
        errorf (conn, VIR_ERR_SYSTEM_ERROR,
                _("cannot get current time: %s"),
                strerror (errno));
1131 1132 1133 1134
        return -1;
    }

    if (status != 0) {
1135
        const char *reason = _("Invalid certificate");
1136 1137

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

1140
        if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1141
            reason = _("The certificate hasn't got a known issuer.");
1142

1143
        if (status & GNUTLS_CERT_REVOKED)
1144
            reason = _("The certificate has been revoked.");
1145 1146

#ifndef GNUTLS_1_0_COMPAT
1147
        if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1148
            reason = _("The certificate uses an insecure algorithm");
1149
#endif
1150

1151 1152 1153
        errorf (conn, VIR_ERR_RPC,
                _("server certificate failed validation: %s"),
                reason);
1154 1155 1156 1157
        return -1;
    }

    if (gnutls_certificate_type_get(session) != GNUTLS_CRT_X509) {
1158
        error (conn, VIR_ERR_RPC, _("Certificate type is not X.509"));
1159 1160
        return -1;
    }
1161

1162
    if (!(certs = gnutls_certificate_get_peers(session, &nCerts))) {
1163
        error (conn, VIR_ERR_RPC, _("gnutls_certificate_get_peers failed"));
1164 1165
        return -1;
    }
1166

1167 1168 1169 1170 1171
    for (i = 0 ; i < nCerts ; i++) {
        gnutls_x509_crt_t cert;

        ret = gnutls_x509_crt_init (&cert);
        if (ret < 0) {
1172 1173 1174
            errorf (conn, VIR_ERR_GNUTLS_ERROR,
                    _("unable to initialize certificate: %s"),
                    gnutls_strerror (ret));
1175 1176
            return -1;
        }
1177

1178 1179
        ret = gnutls_x509_crt_import (cert, &certs[i], GNUTLS_X509_FMT_DER);
        if (ret < 0) {
1180 1181 1182
            errorf (conn, VIR_ERR_GNUTLS_ERROR,
                    _("unable to import certificate: %s"),
                    gnutls_strerror (ret));
1183 1184 1185
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1186

1187
        if (gnutls_x509_crt_get_expiration_time (cert) < now) {
1188
            error (conn, VIR_ERR_RPC, _("The certificate has expired"));
1189 1190 1191
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1192

1193
        if (gnutls_x509_crt_get_activation_time (cert) > now) {
1194
            error (conn, VIR_ERR_RPC, _("The certificate is not yet activated"));
1195 1196 1197
            gnutls_x509_crt_deinit (cert);
            return -1;
        }
1198

1199
        if (i == 0) {
1200
            if (!gnutls_x509_crt_check_hostname (cert, priv->hostname)) {
1201 1202 1203
                errorf(conn, VIR_ERR_RPC,
                       _("Certificate's owner does not match the hostname (%s)"),
                       priv->hostname);
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
                gnutls_x509_crt_deinit (cert);
                return -1;
            }
        }
    }

    return 0;
}

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

1215

1216
static int
1217
doRemoteClose (virConnectPtr conn, struct private_data *priv)
1218 1219 1220 1221 1222 1223
{
    if (call (conn, priv, 0, REMOTE_PROC_CLOSE,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_void, (char *) NULL) == -1)
        return -1;

1224 1225 1226 1227 1228 1229
    if (priv->eventFlushTimer >= 0) {
        /* Remove timeout */
        virEventRemoveTimeout(priv->eventFlushTimer);
        /* Remove handle for remote events */
        virEventRemoveHandle(priv->watch);
    }
1230

1231
    /* Close socket. */
1232
    if (priv->uses_tls && priv->session) {
1233
        gnutls_bye (priv->session, GNUTLS_SHUT_RDWR);
1234 1235 1236 1237 1238 1239
        gnutls_deinit (priv->session);
    }
#if HAVE_SASL
    if (priv->saslconn)
        sasl_dispose (&priv->saslconn);
#endif
1240 1241
    close (priv->sock);

1242
#ifndef WIN32
1243 1244 1245 1246 1247 1248 1249 1250
    if (priv->pid > 0) {
        pid_t reap;
        do {
            reap = waitpid(priv->pid, NULL, 0);
            if (reap == -1 && errno == EINTR)
                continue;
        } while (reap != -1 && reap != priv->pid);
    }
1251
#endif
1252

1253
    /* Free hostname copy */
1254
    free (priv->hostname);
1255

1256
    /* See comment for remoteType. */
1257
    free (priv->type);
1258

1259 1260 1261
    /* Free private data. */
    priv->magic = DEAD;

1262 1263 1264 1265 1266 1267
    /* Free callback list */
    virDomainEventCallbackListFree(priv->callbackList);

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

1268 1269 1270
    return 0;
}

1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
static int
remoteClose (virConnectPtr conn)
{
    int ret;
    GET_PRIVATE (conn, -1);

    ret = doRemoteClose(conn, priv);
    free (priv);
    conn->privateData = NULL;

    return ret;
}

1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
static int
remoteSupportsFeature (virConnectPtr conn, int feature)
{
    remote_supports_feature_args args;
    remote_supports_feature_ret ret;
    GET_PRIVATE (conn, -1);

    /* VIR_DRV_FEATURE_REMOTE* features are handled directly. */
    if (feature == VIR_DRV_FEATURE_REMOTE) return 1;

    args.feature = feature;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_SUPPORTS_FEATURE,
              (xdrproc_t) xdr_remote_supports_feature_args, (char *) &args,
              (xdrproc_t) xdr_remote_supports_feature_ret, (char *) &ret) == -1)
        return -1;

    return ret.supported;
}

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347
/* 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)
{
    remote_get_type_ret ret;
    GET_PRIVATE (conn, NULL);

    /* Cached? */
    if (priv->type) return priv->type;

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

    /* Stash. */
    return priv->type = ret.type;
}

static int
remoteVersion (virConnectPtr conn, unsigned long *hvVer)
{
    remote_get_version_ret ret;
    GET_PRIVATE (conn, -1);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_GET_VERSION,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_get_version_ret, (char *) &ret) == -1)
        return -1;

    if (hvVer) *hvVer = ret.hv_ver;
    return 0;
}

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363
static char *
remoteGetHostname (virConnectPtr conn)
{
    remote_get_hostname_ret ret;
    GET_PRIVATE (conn, NULL);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_GET_HOSTNAME,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_get_hostname_ret, (char *) &ret) == -1)
        return NULL;

    /* Caller frees this. */
    return ret.hostname;
}

1364 1365 1366 1367 1368 1369 1370 1371
static int
remoteGetMaxVcpus (virConnectPtr conn, const char *type)
{
    remote_get_max_vcpus_args args;
    remote_get_max_vcpus_ret ret;
    GET_PRIVATE (conn, -1);

    memset (&ret, 0, sizeof ret);
1372
    args.type = type == NULL ? NULL : (char **) &type;
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
    if (call (conn, priv, 0, REMOTE_PROC_GET_MAX_VCPUS,
              (xdrproc_t) xdr_remote_get_max_vcpus_args, (char *) &args,
              (xdrproc_t) xdr_remote_get_max_vcpus_ret, (char *) &ret) == -1)
        return -1;

    return ret.max_vcpus;
}

static int
remoteNodeGetInfo (virConnectPtr conn, virNodeInfoPtr info)
{
    remote_node_get_info_ret ret;
    GET_PRIVATE (conn, -1);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NODE_GET_INFO,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_node_get_info_ret, (char *) &ret) == -1)
        return -1;

    strncpy (info->model, ret.model, 32);
    info->model[31] = '\0';
    info->memory = ret.memory;
    info->cpus = ret.cpus;
    info->mhz = ret.mhz;
    info->nodes = ret.nodes;
    info->sockets = ret.sockets;
    info->cores = ret.cores;
    info->threads = ret.threads;
    return 0;
}

static char *
remoteGetCapabilities (virConnectPtr conn)
{
    remote_get_capabilities_ret ret;
    GET_PRIVATE (conn, NULL);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_GET_CAPABILITIES,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_get_capabilities_ret, (char *)&ret) == -1)
        return NULL;

    /* Caller frees this. */
    return ret.capabilities;
}

1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
static int
remoteNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
    remote_node_get_cells_free_memory_args args;
    remote_node_get_cells_free_memory_ret ret;
    int i;
    GET_PRIVATE (conn, -1);

    if (maxCells > REMOTE_NODE_MAX_CELLS) {
        errorf (conn, VIR_ERR_RPC,
                _("too many NUMA cells: %d > %d"),
                maxCells,
                REMOTE_NODE_MAX_CELLS);
        return -1;
    }

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

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

    return ret.freeMems.freeMems_len;
}

static unsigned long long
remoteNodeGetFreeMemory (virConnectPtr conn)
{
    remote_node_get_free_memory_ret ret;
    GET_PRIVATE (conn, -1);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NODE_GET_FREE_MEMORY,
              (xdrproc_t) xdr_void, NULL,
              (xdrproc_t) xdr_remote_node_get_free_memory_ret, (char *)&ret) == -1)
        return 0;

    return ret.freeMem;
}


1473 1474 1475 1476 1477 1478 1479 1480 1481
static int
remoteListDomains (virConnectPtr conn, int *ids, int maxids)
{
    int i;
    remote_list_domains_args args;
    remote_list_domains_ret ret;
    GET_PRIVATE (conn, -1);

    if (maxids > REMOTE_DOMAIN_ID_LIST_MAX) {
1482 1483 1484
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain IDs: %d > %d"),
                maxids, REMOTE_DOMAIN_ID_LIST_MAX);
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
        return -1;
    }
    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)
        return -1;

    if (ret.ids.ids_len > maxids) {
1496 1497 1498
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain IDs: %d > %d"),
                ret.ids.ids_len, maxids);
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
        xdr_free ((xdrproc_t) xdr_remote_list_domains_ret, (char *) &ret);
        return -1;
    }

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

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

    return ret.ids.ids_len;
}

static int
remoteNumOfDomains (virConnectPtr conn)
{
    remote_num_of_domains_ret ret;
    GET_PRIVATE (conn, -1);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_DOMAINS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_domains_ret, (char *) &ret) == -1)
        return -1;

    return ret.num;
}

static virDomainPtr
1527
remoteDomainCreateXML (virConnectPtr conn,
1528 1529 1530 1531
                         const char *xmlDesc,
                         unsigned int flags)
{
    virDomainPtr dom;
1532 1533
    remote_domain_create_xml_args args;
    remote_domain_create_xml_ret ret;
1534 1535 1536 1537 1538 1539
    GET_PRIVATE (conn, NULL);

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

    memset (&ret, 0, sizeof ret);
1540 1541 1542
    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_CREATE_XML,
              (xdrproc_t) xdr_remote_domain_create_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_create_xml_ret, (char *) &ret) == -1)
1543 1544 1545
        return NULL;

    dom = get_nonnull_domain (conn, ret.dom);
1546
    xdr_free ((xdrproc_t) &xdr_remote_domain_create_xml_ret, (char *) &ret);
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 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 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787

    return dom;
}

static virDomainPtr
remoteDomainLookupByID (virConnectPtr conn, int id)
{
    virDomainPtr dom;
    remote_domain_lookup_by_id_args args;
    remote_domain_lookup_by_id_ret ret;
    GET_PRIVATE (conn, NULL);

    args.id = id;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_LOOKUP_BY_ID,
              (xdrproc_t) xdr_remote_domain_lookup_by_id_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_lookup_by_id_ret, (char *) &ret) == -1)
        return NULL;

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

    return dom;
}

static virDomainPtr
remoteDomainLookupByUUID (virConnectPtr conn, const unsigned char *uuid)
{
    virDomainPtr dom;
    remote_domain_lookup_by_uuid_args args;
    remote_domain_lookup_by_uuid_ret ret;
    GET_PRIVATE (conn, NULL);

    memcpy (args.uuid, uuid, VIR_UUID_BUFLEN);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_LOOKUP_BY_UUID,
              (xdrproc_t) xdr_remote_domain_lookup_by_uuid_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_lookup_by_uuid_ret, (char *) &ret) == -1)
        return NULL;

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

static virDomainPtr
remoteDomainLookupByName (virConnectPtr conn, const char *name)
{
    virDomainPtr dom;
    remote_domain_lookup_by_name_args args;
    remote_domain_lookup_by_name_ret ret;
    GET_PRIVATE (conn, NULL);

    args.name = (char *) name;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_LOOKUP_BY_NAME,
              (xdrproc_t) xdr_remote_domain_lookup_by_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_lookup_by_name_ret, (char *) &ret) == -1)
        return NULL;

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

    return dom;
}

static int
remoteDomainSuspend (virDomainPtr domain)
{
    remote_domain_suspend_args args;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);

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

    return 0;
}

static int
remoteDomainResume (virDomainPtr domain)
{
    remote_domain_resume_args args;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);

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

    return 0;
}

static int
remoteDomainShutdown (virDomainPtr domain)
{
    remote_domain_shutdown_args args;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);

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

    return 0;
}

static int
remoteDomainReboot (virDomainPtr domain, unsigned int flags)
{
    remote_domain_reboot_args args;
    GET_PRIVATE (domain->conn, -1);

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

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

    return 0;
}

static int
remoteDomainDestroy (virDomainPtr domain)
{
    remote_domain_destroy_args args;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);

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

    return 0;
}

static char *
remoteDomainGetOSType (virDomainPtr domain)
{
    remote_domain_get_os_type_args args;
    remote_domain_get_os_type_ret ret;
    GET_PRIVATE (domain->conn, NULL);

    make_nonnull_domain (&args.dom, domain);

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_OS_TYPE,
              (xdrproc_t) xdr_remote_domain_get_os_type_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_os_type_ret, (char *) &ret) == -1)
        return NULL;

    /* Caller frees. */
    return ret.type;
}

static unsigned long
remoteDomainGetMaxMemory (virDomainPtr domain)
{
    remote_domain_get_max_memory_args args;
    remote_domain_get_max_memory_ret ret;
    GET_PRIVATE (domain->conn, 0);

    make_nonnull_domain (&args.dom, domain);

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

    return ret.memory;
}

static int
remoteDomainSetMaxMemory (virDomainPtr domain, unsigned long memory)
{
    remote_domain_set_max_memory_args args;
    GET_PRIVATE (domain->conn, -1);

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

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

    return 0;
}

static int
remoteDomainSetMemory (virDomainPtr domain, unsigned long memory)
{
    remote_domain_set_memory_args args;
    GET_PRIVATE (domain->conn, -1);

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

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

    return 0;
}

static int
remoteDomainGetInfo (virDomainPtr domain, virDomainInfoPtr info)
{
    remote_domain_get_info_args args;
    remote_domain_get_info_ret ret;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_INFO,
              (xdrproc_t) xdr_remote_domain_get_info_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_info_ret, (char *) &ret) == -1)
        return -1;

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

1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 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
    return 0;
}

static int
remoteDomainSave (virDomainPtr domain, const char *to)
{
    remote_domain_save_args args;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);
    args.to = (char *) to;

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

    return 0;
}

static int
remoteDomainRestore (virConnectPtr conn, const char *from)
{
    remote_domain_restore_args args;
    GET_PRIVATE (conn, -1);

    args.from = (char *) from;

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

    return 0;
}

static int
remoteDomainCoreDump (virDomainPtr domain, const char *to, int flags)
{
    remote_domain_core_dump_args args;
    GET_PRIVATE (domain->conn, -1);

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

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

    return 0;
}

static int
remoteDomainSetVcpus (virDomainPtr domain, unsigned int nvcpus)
{
    remote_domain_set_vcpus_args args;
    GET_PRIVATE (domain->conn, -1);

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

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

    return 0;
}

static int
remoteDomainPinVcpu (virDomainPtr domain,
                     unsigned int vcpu,
                     unsigned char *cpumap,
                     int maplen)
{
    remote_domain_pin_vcpu_args args;
    GET_PRIVATE (domain->conn, -1);

    if (maplen > REMOTE_CPUMAP_MAX) {
1870 1871 1872
        errorf (domain->conn, VIR_ERR_RPC,
                _("map length greater than maximum: %d > %d"),
                maplen, REMOTE_CPUMAP_MAX);
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
        return -1;
    }

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

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

    return 0;
}

static int
remoteDomainGetVcpus (virDomainPtr domain,
                      virVcpuInfoPtr info,
                      int maxinfo,
                      unsigned char *cpumaps,
                      int maplen)
{
    int i;
    remote_domain_get_vcpus_args args;
    remote_domain_get_vcpus_ret ret;
    GET_PRIVATE (domain->conn, -1);

    if (maxinfo > REMOTE_VCPUINFO_MAX) {
1902 1903 1904
        errorf (domain->conn, VIR_ERR_RPC,
                _("vCPU count exceeds maximum: %d > %d"),
                maxinfo, REMOTE_VCPUINFO_MAX);
1905 1906
        return -1;
    }
1907
    if (maxinfo * maplen > REMOTE_CPUMAPS_MAX) {
1908 1909 1910
        errorf (domain->conn, VIR_ERR_RPC,
                _("vCPU map buffer length exceeds maximum: %d > %d"),
                maxinfo * maplen, REMOTE_CPUMAPS_MAX);
1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
        return -1;
    }

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

    if (ret.info.info_len > maxinfo) {
1925 1926 1927
        errorf (domain->conn, VIR_ERR_RPC,
                _("host reports too many vCPUs: %d > %d"),
                ret.info.info_len, maxinfo);
1928 1929 1930
        xdr_free ((xdrproc_t) xdr_remote_domain_get_vcpus_ret, (char *) &ret);
        return -1;
    }
1931
    if (ret.cpumaps.cpumaps_len > maxinfo * maplen) {
1932 1933 1934
        errorf (domain->conn, VIR_ERR_RPC,
                _("host reports map buffer length exceeds maximum: %d > %d"),
                ret.cpumaps.cpumaps_len, maxinfo * maplen);
1935 1936 1937 1938
        xdr_free ((xdrproc_t) xdr_remote_domain_get_vcpus_ret, (char *) &ret);
        return -1;
    }

1939 1940 1941
    memset (info, 0, sizeof (virVcpuInfo) * maxinfo);
    memset (cpumaps, 0, maxinfo * maplen);

1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
    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];

    xdr_free ((xdrproc_t) xdr_remote_domain_get_vcpus_ret, (char *) &ret);
    return ret.info.info_len;
}

static int
remoteDomainGetMaxVcpus (virDomainPtr domain)
{
    remote_domain_get_max_vcpus_args args;
    remote_domain_get_max_vcpus_ret ret;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);

    memset (&ret, 0, sizeof ret);
1966
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_MAX_VCPUS,
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
              (xdrproc_t) xdr_remote_domain_get_max_vcpus_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_max_vcpus_ret, (char *) &ret) == -1)
        return -1;

    return ret.num;
}

static char *
remoteDomainDumpXML (virDomainPtr domain, int flags)
{
    remote_domain_dump_xml_args args;
    remote_domain_dump_xml_ret ret;
    GET_PRIVATE (domain->conn, NULL);

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

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_DUMP_XML,
              (xdrproc_t) xdr_remote_domain_dump_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_dump_xml_ret, (char *) &ret) == -1)
        return NULL;

    /* Caller frees. */
    return ret.xml;
}

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
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)
{
    remote_domain_migrate_prepare_args args;
    remote_domain_migrate_prepare_ret ret;
    GET_PRIVATE (dconn, -1);

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

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

    return 0;
}

static int
remoteDomainMigratePerform (virDomainPtr domain,
                            const char *cookie,
                            int cookielen,
                            const char *uri,
                            unsigned long flags,
                            const char *dname,
                            unsigned long resource)
{
    remote_domain_migrate_perform_args args;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);
    args.cookie.cookie_len = cookielen;
    args.cookie.cookie_val = (char *) cookie;
    args.uri = (char *) uri;
    args.flags = flags;
    args.dname = dname == NULL ? NULL : (char **) &dname;
    args.resource = resource;

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

    return 0;
}

static virDomainPtr
remoteDomainMigrateFinish (virConnectPtr dconn,
                           const char *dname,
                           const char *cookie,
                           int cookielen,
                           const char *uri,
                           unsigned long flags)
{
    virDomainPtr ddom;
    remote_domain_migrate_finish_args args;
    remote_domain_migrate_finish_ret ret;
    GET_PRIVATE (dconn, NULL);

    args.dname = (char *) dname;
    args.cookie.cookie_len = cookielen;
    args.cookie.cookie_val = (char *) cookie;
    args.uri = (char *) uri;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (dconn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_FINISH,
              (xdrproc_t) xdr_remote_domain_migrate_finish_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_migrate_finish_ret, (char *) &ret) == -1)
        return NULL;

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

    return ddom;
}

D
Daniel Veillard 已提交
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 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
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)
{
    remote_domain_migrate_prepare2_args args;
    remote_domain_migrate_prepare2_ret ret;
    GET_PRIVATE (dconn, -1);

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

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

    return 0;
}

static virDomainPtr
remoteDomainMigrateFinish2 (virConnectPtr dconn,
                            const char *dname,
                            const char *cookie,
                            int cookielen,
                            const char *uri,
                            unsigned long flags,
                            int retcode)
{
    virDomainPtr ddom;
    remote_domain_migrate_finish2_args args;
    remote_domain_migrate_finish2_ret ret;
    GET_PRIVATE (dconn, NULL);

    args.dname = (char *) dname;
    args.cookie.cookie_len = cookielen;
    args.cookie.cookie_val = (char *) cookie;
    args.uri = (char *) uri;
    args.flags = flags;
    args.retcode = retcode;

    memset (&ret, 0, sizeof ret);
    if (call (dconn, priv, 0, REMOTE_PROC_DOMAIN_MIGRATE_FINISH2,
              (xdrproc_t) xdr_remote_domain_migrate_finish2_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_migrate_finish2_ret, (char *) &ret) == -1)
        return NULL;

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

    return ddom;
}

2152 2153 2154 2155 2156 2157 2158 2159 2160
static int
remoteListDefinedDomains (virConnectPtr conn, char **const names, int maxnames)
{
    int i;
    remote_list_defined_domains_args args;
    remote_list_defined_domains_ret ret;
    GET_PRIVATE (conn, -1);

    if (maxnames > REMOTE_DOMAIN_NAME_LIST_MAX) {
2161 2162 2163
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain names: %d > %d"),
                maxnames, REMOTE_DOMAIN_NAME_LIST_MAX);
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
        return -1;
    }
    args.maxnames = maxnames;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_DEFINED_DOMAINS,
              (xdrproc_t) xdr_remote_list_defined_domains_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_defined_domains_ret, (char *) &ret) == -1)
        return -1;

    if (ret.names.names_len > maxnames) {
2175 2176 2177
        errorf (conn, VIR_ERR_RPC,
                _("too many remote domain names: %d > %d"),
                ret.names.names_len, maxnames);
2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 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 2264
        xdr_free ((xdrproc_t) xdr_remote_list_defined_domains_ret, (char *) &ret);
        return -1;
    }

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

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

    return ret.names.names_len;
}

static int
remoteNumOfDefinedDomains (virConnectPtr conn)
{
    remote_num_of_defined_domains_ret ret;
    GET_PRIVATE (conn, -1);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_DEFINED_DOMAINS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_defined_domains_ret, (char *) &ret) == -1)
        return -1;

    return ret.num;
}

static int
remoteDomainCreate (virDomainPtr domain)
{
    remote_domain_create_args args;
    GET_PRIVATE (domain->conn, -1);

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

    return 0;
}

static virDomainPtr
remoteDomainDefineXML (virConnectPtr conn, const char *xml)
{
    virDomainPtr dom;
    remote_domain_define_xml_args args;
    remote_domain_define_xml_ret ret;
    GET_PRIVATE (conn, NULL);

    args.xml = (char *) xml;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_DEFINE_XML,
              (xdrproc_t) xdr_remote_domain_define_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_define_xml_ret, (char *) &ret) == -1)
        return NULL;

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

    return dom;
}

static int
remoteDomainUndefine (virDomainPtr domain)
{
    remote_domain_undefine_args args;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);

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

    return 0;
}

static int
2265
remoteDomainAttachDevice (virDomainPtr domain, const char *xml)
2266 2267 2268 2269 2270
{
    remote_domain_attach_device_args args;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);
2271
    args.xml = (char *) xml;
2272 2273 2274 2275 2276 2277 2278 2279 2280 2281

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

    return 0;
}

static int
2282
remoteDomainDetachDevice (virDomainPtr domain, const char *xml)
2283 2284 2285 2286 2287
{
    remote_domain_detach_device_args args;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);
2288
    args.xml = (char *) xml;
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333

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

    return 0;
}

static int
remoteDomainGetAutostart (virDomainPtr domain, int *autostart)
{
    remote_domain_get_autostart_args args;
    remote_domain_get_autostart_ret ret;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);

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

    if (autostart) *autostart = ret.autostart;
    return 0;
}

static int
remoteDomainSetAutostart (virDomainPtr domain, int autostart)
{
    remote_domain_set_autostart_args args;
    GET_PRIVATE (domain->conn, -1);

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

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

    return 0;
}

2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376
static char *
remoteDomainGetSchedulerType (virDomainPtr domain, int *nparams)
{
    remote_domain_get_scheduler_type_args args;
    remote_domain_get_scheduler_type_ret ret;
    GET_PRIVATE (domain->conn, NULL);

    make_nonnull_domain (&args.dom, domain);

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_GET_SCHEDULER_TYPE,
              (xdrproc_t) xdr_remote_domain_get_scheduler_type_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_get_scheduler_type_ret, (char *) &ret) == -1)
        return NULL;

    if (nparams) *nparams = ret.nparams;

    /* Caller frees this. */
    return ret.type;
}

static int
remoteDomainGetSchedulerParameters (virDomainPtr domain,
                                    virSchedParameterPtr params, int *nparams)
{
    remote_domain_get_scheduler_parameters_args args;
    remote_domain_get_scheduler_parameters_ret ret;
    int i;
    GET_PRIVATE (domain->conn, -1);

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

    /* Check the length of the returned list carefully. */
    if (ret.params.params_len > REMOTE_DOMAIN_SCHEDULER_PARAMETERS_MAX ||
        ret.params.params_len > *nparams) {
        xdr_free ((xdrproc_t) xdr_remote_domain_get_scheduler_parameters_ret, (char *) &ret);
2377 2378 2379
        error (domain->conn, VIR_ERR_RPC,
               _("remoteDomainGetSchedulerParameters: "
                 "returned number of parameters exceeds limit"));
2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
        return -1;
    }
    *nparams = ret.params.params_len;

    /* Deserialise the result. */
    for (i = 0; i < *nparams; ++i) {
        strncpy (params[i].field, ret.params.params_val[i].field,
                 VIR_DOMAIN_SCHED_FIELD_LENGTH);
        params[i].field[VIR_DOMAIN_SCHED_FIELD_LENGTH-1] = '\0';
        params[i].type = ret.params.params_val[i].value.type;
        switch (params[i].type) {
        case VIR_DOMAIN_SCHED_FIELD_INT:
            params[i].value.i = ret.params.params_val[i].value.remote_sched_param_value_u.i; break;
        case VIR_DOMAIN_SCHED_FIELD_UINT:
            params[i].value.ui = ret.params.params_val[i].value.remote_sched_param_value_u.ui; break;
        case VIR_DOMAIN_SCHED_FIELD_LLONG:
            params[i].value.l = ret.params.params_val[i].value.remote_sched_param_value_u.l; break;
        case VIR_DOMAIN_SCHED_FIELD_ULLONG:
            params[i].value.ul = ret.params.params_val[i].value.remote_sched_param_value_u.ul; break;
        case VIR_DOMAIN_SCHED_FIELD_DOUBLE:
            params[i].value.d = ret.params.params_val[i].value.remote_sched_param_value_u.d; break;
        case VIR_DOMAIN_SCHED_FIELD_BOOLEAN:
            params[i].value.b = ret.params.params_val[i].value.remote_sched_param_value_u.b; break;
        default:
            xdr_free ((xdrproc_t) xdr_remote_domain_get_scheduler_parameters_ret, (char *) &ret);
2405 2406 2407
            error (domain->conn, VIR_ERR_RPC,
                   _("remoteDomainGetSchedulerParameters: "
                     "unknown parameter type"));
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427
            return -1;
        }
    }

    xdr_free ((xdrproc_t) xdr_remote_domain_get_scheduler_parameters_ret, (char *) &ret);
    return 0;
}

static int
remoteDomainSetSchedulerParameters (virDomainPtr domain,
                                    virSchedParameterPtr params, int nparams)
{
    remote_domain_set_scheduler_parameters_args args;
    int i, do_error;
    GET_PRIVATE (domain->conn, -1);

    make_nonnull_domain (&args.dom, domain);

    /* Serialise the scheduler parameters. */
    args.params.params_len = nparams;
2428
    if (VIR_ALLOC_N(args.params.params_val, nparams) < 0) {
2429
        error (domain->conn, VIR_ERR_RPC, _("out of memory allocating array"));
2430 2431 2432 2433 2434 2435 2436 2437
        return -1;
    }

    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) {
2438
            error (domain->conn, VIR_ERR_NO_MEMORY, _("out of memory"));
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
            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:
2456
            error (domain->conn, VIR_ERR_RPC, _("unknown parameter type"));
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
            do_error = 1;
        }
    }

    if (do_error) {
        xdr_free ((xdrproc_t) xdr_remote_domain_set_scheduler_parameters_args, (char *) &args);
        return -1;
    }

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

    return 0;
}

2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531
static int
remoteDomainBlockStats (virDomainPtr domain, const char *path,
                        struct _virDomainBlockStats *stats)
{
    remote_domain_block_stats_args args;
    remote_domain_block_stats_ret ret;
    GET_PRIVATE (domain->conn, -1);

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

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_BLOCK_STATS,
              (xdrproc_t) xdr_remote_domain_block_stats_args, (char *) &args,
              (xdrproc_t) xdr_remote_domain_block_stats_ret, (char *) &ret)
        == -1)
        return -1;

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

    return 0;
}

static int
remoteDomainInterfaceStats (virDomainPtr domain, const char *path,
                            struct _virDomainInterfaceStats *stats)
{
    remote_domain_interface_stats_args args;
    remote_domain_interface_stats_ret ret;
    GET_PRIVATE (domain->conn, -1);

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

    memset (&ret, 0, sizeof ret);
    if (call (domain->conn, priv, 0, REMOTE_PROC_DOMAIN_INTERFACE_STATS,
              (xdrproc_t) xdr_remote_domain_interface_stats_args,
                (char *) &args,
              (xdrproc_t) xdr_remote_domain_interface_stats_ret,
                (char *) &ret) == -1)
        return -1;

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

    return 0;
}

2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
static int
remoteDomainBlockPeek (virDomainPtr domain,
                       const char *path,
                       unsigned long long offset,
                       size_t size,
                       void *buffer,
                       unsigned int flags)
{
    remote_domain_block_peek_args args;
    remote_domain_block_peek_ret ret;
    GET_PRIVATE (domain->conn, -1);

    if (size > REMOTE_DOMAIN_BLOCK_PEEK_BUFFER_MAX) {
        errorf (domain->conn, VIR_ERR_RPC,
                _("block peek request too large for remote protocol, %zi > %d"),
                size, REMOTE_DOMAIN_BLOCK_PEEK_BUFFER_MAX);
        return -1;
    }

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

    if (ret.buffer.buffer_len != size) {
            errorf (domain->conn, VIR_ERR_RPC,
J
Jim Meyering 已提交
2567
                    "%s", _("returned buffer is not same size as requested"));
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
            free (ret.buffer.buffer_val);
            return -1;
    }

    memcpy (buffer, ret.buffer.buffer_val, size);
    free (ret.buffer.buffer_val);

    return 0;
}

R
Richard W.M. Jones 已提交
2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
static int
remoteDomainMemoryPeek (virDomainPtr domain,
                        unsigned long long offset,
                        size_t size,
                        void *buffer,
                        unsigned int flags)
{
    remote_domain_memory_peek_args args;
    remote_domain_memory_peek_ret ret;
    GET_PRIVATE (domain->conn, -1);

    if (size > REMOTE_DOMAIN_MEMORY_PEEK_BUFFER_MAX) {
        errorf (domain->conn, VIR_ERR_RPC,
                _("memory peek request too large for remote protocol, %zi > %d"),
                size, REMOTE_DOMAIN_MEMORY_PEEK_BUFFER_MAX);
        return -1;
    }

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

    if (ret.buffer.buffer_len != size) {
            errorf (domain->conn, VIR_ERR_RPC,
J
Jim Meyering 已提交
2611
                    "%s", _("returned buffer is not same size as requested"));
R
Richard W.M. Jones 已提交
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
            free (ret.buffer.buffer_val);
            return -1;
    }

    memcpy (buffer, ret.buffer.buffer_val, size);
    free (ret.buffer.buffer_val);

    return 0;
}

2622 2623 2624 2625
/*----------------------------------------------------------------------*/

static int
remoteNetworkOpen (virConnectPtr conn,
2626
                   virConnectAuthPtr auth,
2627
                   int flags)
2628
{
2629 2630 2631
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

2632 2633
    if (conn &&
        conn->driver &&
2634
        STREQ (conn->driver->name, "remote")) {
2635 2636 2637 2638 2639
        /* If we're here, the remote driver is already
         * in use due to a) a QEMU uri, or b) a remote
         * URI. So we can re-use existing connection
         */
        conn->networkPrivateData = conn->privateData;
2640
        return VIR_DRV_OPEN_SUCCESS;
2641 2642 2643
    } else {
        /* Using a non-remote driver, so we need to open a
         * new connection for network APIs, forcing it to
2644 2645
         * use the UNIX transport. This handles Xen driver
         * which doesn't have its own impl of the network APIs.
2646
         */
2647
        struct private_data *priv;
2648
        int ret, rflags = 0;
2649
        if (VIR_ALLOC(priv) < 0) {
2650
            error (conn, VIR_ERR_NO_MEMORY, _("struct private_data"));
2651 2652
            return VIR_DRV_OPEN_ERROR;
        }
2653
        if (flags & VIR_CONNECT_RO)
2654
            rflags |= VIR_DRV_OPEN_REMOTE_RO;
D
Daniel P. Berrange 已提交
2655
        rflags |= VIR_DRV_OPEN_REMOTE_UNIX;
2656 2657 2658

        priv->magic = DEAD;
        priv->sock = -1;
2659
        ret = doRemoteOpen(conn, priv, auth, rflags);
2660 2661
        if (ret != VIR_DRV_OPEN_SUCCESS) {
            conn->networkPrivateData = NULL;
2662
            VIR_FREE(priv);
2663 2664
        } else {
            priv->magic = MAGIC;
2665
            priv->localUses = 1;
2666 2667 2668 2669
            conn->networkPrivateData = priv;
        }
        return ret;
    }
2670 2671 2672
}

static int
2673 2674 2675 2676
remoteNetworkClose (virConnectPtr conn)
{
    int ret = 0;
    GET_NETWORK_PRIVATE (conn, -1);
2677 2678 2679 2680
    if (priv->localUses) {
        priv->localUses--;
        if (!priv->localUses) {
            ret = doRemoteClose(conn, priv);
2681
            VIR_FREE(priv);
2682 2683
            conn->networkPrivateData = NULL;
        }
2684 2685
    }
    return ret;
2686 2687 2688 2689 2690 2691
}

static int
remoteNumOfNetworks (virConnectPtr conn)
{
    remote_num_of_networks_ret ret;
2692
    GET_NETWORK_PRIVATE (conn, -1);
2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_NETWORKS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_networks_ret, (char *) &ret) == -1)
        return -1;

    return ret.num;
}

static int
remoteListNetworks (virConnectPtr conn, char **const names, int maxnames)
{
    int i;
    remote_list_networks_args args;
    remote_list_networks_ret ret;
2709
    GET_NETWORK_PRIVATE (conn, -1);
2710 2711

    if (maxnames > REMOTE_NETWORK_NAME_LIST_MAX) {
2712 2713 2714
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                maxnames, REMOTE_NETWORK_NAME_LIST_MAX);
2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725
        return -1;
    }
    args.maxnames = maxnames;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_NETWORKS,
              (xdrproc_t) xdr_remote_list_networks_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_networks_ret, (char *) &ret) == -1)
        return -1;

    if (ret.names.names_len > maxnames) {
2726 2727 2728
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                ret.names.names_len, maxnames);
2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749
        xdr_free ((xdrproc_t) xdr_remote_list_networks_ret, (char *) &ret);
        return -1;
    }

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

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

    return ret.names.names_len;
}

static int
remoteNumOfDefinedNetworks (virConnectPtr conn)
{
    remote_num_of_defined_networks_ret ret;
2750
    GET_NETWORK_PRIVATE (conn, -1);
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_DEFINED_NETWORKS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_defined_networks_ret, (char *) &ret) == -1)
        return -1;

    return ret.num;
}

static int
remoteListDefinedNetworks (virConnectPtr conn,
                           char **const names, int maxnames)
{
    int i;
    remote_list_defined_networks_args args;
    remote_list_defined_networks_ret ret;
2768
    GET_NETWORK_PRIVATE (conn, -1);
2769 2770

    if (maxnames > REMOTE_NETWORK_NAME_LIST_MAX) {
2771 2772 2773
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                maxnames, REMOTE_NETWORK_NAME_LIST_MAX);
2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784
        return -1;
    }
    args.maxnames = maxnames;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_DEFINED_NETWORKS,
              (xdrproc_t) xdr_remote_list_defined_networks_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_defined_networks_ret, (char *) &ret) == -1)
        return -1;

    if (ret.names.names_len > maxnames) {
2785 2786 2787
        errorf (conn, VIR_ERR_RPC,
                _("too many remote networks: %d > %d"),
                ret.names.names_len, maxnames);
2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811
        xdr_free ((xdrproc_t) xdr_remote_list_defined_networks_ret, (char *) &ret);
        return -1;
    }

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

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

    return ret.names.names_len;
}

static virNetworkPtr
remoteNetworkLookupByUUID (virConnectPtr conn,
                           const unsigned char *uuid)
{
    virNetworkPtr net;
    remote_network_lookup_by_uuid_args args;
    remote_network_lookup_by_uuid_ret ret;
2812
    GET_NETWORK_PRIVATE (conn, NULL);
2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834

    memcpy (args.uuid, uuid, VIR_UUID_BUFLEN);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NETWORK_LOOKUP_BY_UUID,
              (xdrproc_t) xdr_remote_network_lookup_by_uuid_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_lookup_by_uuid_ret, (char *) &ret) == -1)
        return NULL;

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

    return net;
}

static virNetworkPtr
remoteNetworkLookupByName (virConnectPtr conn,
                           const char *name)
{
    virNetworkPtr net;
    remote_network_lookup_by_name_args args;
    remote_network_lookup_by_name_ret ret;
2835
    GET_NETWORK_PRIVATE (conn, NULL);
2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856

    args.name = (char *) name;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NETWORK_LOOKUP_BY_NAME,
              (xdrproc_t) xdr_remote_network_lookup_by_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_lookup_by_name_ret, (char *) &ret) == -1)
        return NULL;

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

    return net;
}

static virNetworkPtr
remoteNetworkCreateXML (virConnectPtr conn, const char *xmlDesc)
{
    virNetworkPtr net;
    remote_network_create_xml_args args;
    remote_network_create_xml_ret ret;
2857
    GET_NETWORK_PRIVATE (conn, NULL);
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878

    args.xml = (char *) xmlDesc;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NETWORK_CREATE_XML,
              (xdrproc_t) xdr_remote_network_create_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_create_xml_ret, (char *) &ret) == -1)
        return NULL;

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

    return net;
}

static virNetworkPtr
remoteNetworkDefineXML (virConnectPtr conn, const char *xml)
{
    virNetworkPtr net;
    remote_network_define_xml_args args;
    remote_network_define_xml_ret ret;
2879
    GET_NETWORK_PRIVATE (conn, NULL);
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898

    args.xml = (char *) xml;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NETWORK_DEFINE_XML,
              (xdrproc_t) xdr_remote_network_define_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_define_xml_ret, (char *) &ret) == -1)
        return NULL;

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

    return net;
}

static int
remoteNetworkUndefine (virNetworkPtr network)
{
    remote_network_undefine_args args;
2899
    GET_NETWORK_PRIVATE (network->conn, -1);
2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914

    make_nonnull_network (&args.net, network);

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

    return 0;
}

static int
remoteNetworkCreate (virNetworkPtr network)
{
    remote_network_create_args args;
2915
    GET_NETWORK_PRIVATE (network->conn, -1);
2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930

    make_nonnull_network (&args.net, network);

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

    return 0;
}

static int
remoteNetworkDestroy (virNetworkPtr network)
{
    remote_network_destroy_args args;
2931
    GET_NETWORK_PRIVATE (network->conn, -1);
2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947

    make_nonnull_network (&args.net, network);

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

    return 0;
}

static char *
remoteNetworkDumpXML (virNetworkPtr network, int flags)
{
    remote_network_dump_xml_args args;
    remote_network_dump_xml_ret ret;
2948
    GET_NETWORK_PRIVATE (network->conn, NULL);
2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967

    make_nonnull_network (&args.net, network);
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (network->conn, priv, 0, REMOTE_PROC_NETWORK_DUMP_XML,
              (xdrproc_t) xdr_remote_network_dump_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_dump_xml_ret, (char *) &ret) == -1)
        return NULL;

    /* Caller frees. */
    return ret.xml;
}

static char *
remoteNetworkGetBridgeName (virNetworkPtr network)
{
    remote_network_get_bridge_name_args args;
    remote_network_get_bridge_name_ret ret;
2968
    GET_NETWORK_PRIVATE (network->conn, NULL);
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986

    make_nonnull_network (&args.net, network);

    memset (&ret, 0, sizeof ret);
    if (call (network->conn, priv, 0, REMOTE_PROC_NETWORK_GET_BRIDGE_NAME,
              (xdrproc_t) xdr_remote_network_get_bridge_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_get_bridge_name_ret, (char *) &ret) == -1)
        return NULL;

    /* Caller frees. */
    return ret.name;
}

static int
remoteNetworkGetAutostart (virNetworkPtr network, int *autostart)
{
    remote_network_get_autostart_args args;
    remote_network_get_autostart_ret ret;
2987
    GET_NETWORK_PRIVATE (network->conn, -1);
2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005

    make_nonnull_network (&args.net, network);

    memset (&ret, 0, sizeof ret);
    if (call (network->conn, priv, 0, REMOTE_PROC_NETWORK_GET_AUTOSTART,
              (xdrproc_t) xdr_remote_network_get_autostart_args, (char *) &args,
              (xdrproc_t) xdr_remote_network_get_autostart_ret, (char *) &ret) == -1)
        return -1;

    if (autostart) *autostart = ret.autostart;

    return 0;
}

static int
remoteNetworkSetAutostart (virNetworkPtr network, int autostart)
{
    remote_network_set_autostart_args args;
3006
    GET_NETWORK_PRIVATE (network->conn, -1);
3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018

    make_nonnull_network (&args.net, network);
    args.autostart = autostart;

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

    return 0;
}

3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051



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

static int
remoteStorageOpen (virConnectPtr conn,
                   virConnectAuthPtr auth,
                   int flags)
{
    if (inside_daemon)
        return VIR_DRV_OPEN_DECLINED;

    if (conn &&
        conn->driver &&
        STREQ (conn->driver->name, "remote")) {
        /* If we're here, the remote driver is already
         * in use due to a) a QEMU uri, or b) a remote
         * URI. So we can re-use existing connection
         */
        conn->storagePrivateData = conn->privateData;
        return VIR_DRV_OPEN_SUCCESS;
    } else if (conn->networkDriver &&
               STREQ (conn->networkDriver->name, "remote")) {
        conn->storagePrivateData = conn->networkPrivateData;
        ((struct private_data *)conn->storagePrivateData)->localUses++;
        return VIR_DRV_OPEN_SUCCESS;
    } else {
        /* Using a non-remote driver, so we need to open a
         * new connection for network APIs, forcing it to
         * use the UNIX transport. This handles Xen driver
         * which doesn't have its own impl of the network APIs.
         */
3052
        struct private_data *priv;
3053
        int ret, rflags = 0;
3054
        if (VIR_ALLOC(priv) < 0) {
3055 3056 3057 3058 3059 3060 3061 3062 3063
            error (NULL, VIR_ERR_NO_MEMORY, _("struct private_data"));
            return VIR_DRV_OPEN_ERROR;
        }
        if (flags & VIR_CONNECT_RO)
            rflags |= VIR_DRV_OPEN_REMOTE_RO;
        rflags |= VIR_DRV_OPEN_REMOTE_UNIX;

        priv->magic = DEAD;
        priv->sock = -1;
3064
        ret = doRemoteOpen(conn, priv, auth, rflags);
3065 3066
        if (ret != VIR_DRV_OPEN_SUCCESS) {
            conn->storagePrivateData = NULL;
3067
            VIR_FREE(priv);
3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
        } else {
            priv->magic = MAGIC;
            priv->localUses = 1;
            conn->storagePrivateData = priv;
        }
        return ret;
    }
}

static int
remoteStorageClose (virConnectPtr conn)
{
    int ret = 0;
    GET_STORAGE_PRIVATE (conn, -1);
    if (priv->localUses) {
        priv->localUses--;
        if (!priv->localUses) {
            ret = doRemoteClose(conn, priv);
3086
            VIR_FREE(priv);
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
            conn->storagePrivateData = NULL;
        }
    }
    return ret;
}

static int
remoteNumOfStoragePools (virConnectPtr conn)
{
    remote_num_of_storage_pools_ret ret;
    GET_STORAGE_PRIVATE (conn, -1);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_STORAGE_POOLS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_storage_pools_ret, (char *) &ret) == -1)
        return -1;

    return ret.num;
}

static int
remoteListStoragePools (virConnectPtr conn, char **const names, int maxnames)
{
    int i;
    remote_list_storage_pools_args args;
    remote_list_storage_pools_ret ret;
    GET_STORAGE_PRIVATE (conn, -1);

    if (maxnames > REMOTE_STORAGE_POOL_NAME_LIST_MAX) {
        error (conn, VIR_ERR_RPC, _("too many storage pools requested"));
        return -1;
    }
    args.maxnames = maxnames;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_STORAGE_POOLS,
              (xdrproc_t) xdr_remote_list_storage_pools_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_storage_pools_ret, (char *) &ret) == -1)
        return -1;

    if (ret.names.names_len > maxnames) {
        error (conn, VIR_ERR_RPC, _("too many storage pools received"));
        xdr_free ((xdrproc_t) xdr_remote_list_storage_pools_ret, (char *) &ret);
        return -1;
    }

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

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

    return ret.names.names_len;
}

static int
remoteNumOfDefinedStoragePools (virConnectPtr conn)
{
    remote_num_of_defined_storage_pools_ret ret;
    GET_STORAGE_PRIVATE (conn, -1);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NUM_OF_DEFINED_STORAGE_POOLS,
              (xdrproc_t) xdr_void, (char *) NULL,
              (xdrproc_t) xdr_remote_num_of_defined_storage_pools_ret, (char *) &ret) == -1)
        return -1;

    return ret.num;
}

static int
remoteListDefinedStoragePools (virConnectPtr conn,
                               char **const names, int maxnames)
{
    int i;
    remote_list_defined_storage_pools_args args;
    remote_list_defined_storage_pools_ret ret;
    GET_STORAGE_PRIVATE (conn, -1);

    if (maxnames > REMOTE_STORAGE_POOL_NAME_LIST_MAX) {
        error (conn, VIR_ERR_RPC, _("too many storage pools requested"));
        return -1;
    }
    args.maxnames = maxnames;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_LIST_DEFINED_STORAGE_POOLS,
              (xdrproc_t) xdr_remote_list_defined_storage_pools_args, (char *) &args,
              (xdrproc_t) xdr_remote_list_defined_storage_pools_ret, (char *) &ret) == -1)
        return -1;

    if (ret.names.names_len > maxnames) {
        error (conn, VIR_ERR_RPC, _("too many storage pools received"));
        xdr_free ((xdrproc_t) xdr_remote_list_defined_storage_pools_ret, (char *) &ret);
        return -1;
    }

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

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

    return ret.names.names_len;
}

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
static char *
remoteFindStoragePoolSources (virConnectPtr conn,
                              const char *type,
                              const char *srcSpec,
                              unsigned int flags)
{
    remote_find_storage_pool_sources_args args;
    remote_find_storage_pool_sources_ret ret;
    GET_STORAGE_PRIVATE (conn, NULL);
    const char *emptyString = "";
    char *retval;

    args.type = (char*)type;
    /*
     * I'd think the following would work here:
     *    args.srcSpec = (char**)&srcSpec;
     * since srcSpec is a remote_string (not a remote_nonnull_string).
     *
     * But when srcSpec is NULL, this yields:
     *    libvir: Remote error : marshalling args
     *
     * So for now I'm working around this by turning NULL srcSpecs
     * into empty strings.
     */
    args.srcSpec = srcSpec ? (char **)&srcSpec : (char **)&emptyString;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_FIND_STORAGE_POOL_SOURCES,
              (xdrproc_t) xdr_remote_find_storage_pool_sources_args, (char *) &args,
              (xdrproc_t) xdr_remote_find_storage_pool_sources_ret, (char *) &ret) == -1)
        return NULL;

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

    return retval;
}

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 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778
static virStoragePoolPtr
remoteStoragePoolLookupByUUID (virConnectPtr conn,
                               const unsigned char *uuid)
{
    virStoragePoolPtr pool;
    remote_storage_pool_lookup_by_uuid_args args;
    remote_storage_pool_lookup_by_uuid_ret ret;
    GET_STORAGE_PRIVATE (conn, NULL);

    memcpy (args.uuid, uuid, VIR_UUID_BUFLEN);

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_STORAGE_POOL_LOOKUP_BY_UUID,
              (xdrproc_t) xdr_remote_storage_pool_lookup_by_uuid_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_lookup_by_uuid_ret, (char *) &ret) == -1)
        return NULL;

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

    return pool;
}

static virStoragePoolPtr
remoteStoragePoolLookupByName (virConnectPtr conn,
                               const char *name)
{
    virStoragePoolPtr pool;
    remote_storage_pool_lookup_by_name_args args;
    remote_storage_pool_lookup_by_name_ret ret;
    GET_STORAGE_PRIVATE (conn, NULL);

    args.name = (char *) name;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_STORAGE_POOL_LOOKUP_BY_NAME,
              (xdrproc_t) xdr_remote_storage_pool_lookup_by_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_lookup_by_name_ret, (char *) &ret) == -1)
        return NULL;

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

    return pool;
}

static virStoragePoolPtr
remoteStoragePoolLookupByVolume (virStorageVolPtr vol)
{
    virStoragePoolPtr pool;
    remote_storage_pool_lookup_by_volume_args args;
    remote_storage_pool_lookup_by_volume_ret ret;
    GET_STORAGE_PRIVATE (vol->conn, NULL);

    make_nonnull_storage_vol (&args.vol, vol);

    memset (&ret, 0, sizeof ret);
    if (call (vol->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_LOOKUP_BY_VOLUME,
              (xdrproc_t) xdr_remote_storage_pool_lookup_by_volume_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_lookup_by_volume_ret, (char *) &ret) == -1)
        return NULL;

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

    return pool;
}


static virStoragePoolPtr
remoteStoragePoolCreateXML (virConnectPtr conn, const char *xmlDesc, unsigned int flags)
{
    virStoragePoolPtr pool;
    remote_storage_pool_create_xml_args args;
    remote_storage_pool_create_xml_ret ret;
    GET_STORAGE_PRIVATE (conn, NULL);

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

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_STORAGE_POOL_CREATE_XML,
              (xdrproc_t) xdr_remote_storage_pool_create_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_create_xml_ret, (char *) &ret) == -1)
        return NULL;

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

    return pool;
}

static virStoragePoolPtr
remoteStoragePoolDefineXML (virConnectPtr conn, const char *xml, unsigned int flags)
{
    virStoragePoolPtr pool;
    remote_storage_pool_define_xml_args args;
    remote_storage_pool_define_xml_ret ret;
    GET_STORAGE_PRIVATE (conn, NULL);

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

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_STORAGE_POOL_DEFINE_XML,
              (xdrproc_t) xdr_remote_storage_pool_define_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_define_xml_ret, (char *) &ret) == -1)
        return NULL;

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

    return pool;
}

static int
remoteStoragePoolUndefine (virStoragePoolPtr pool)
{
    remote_storage_pool_undefine_args args;
    GET_STORAGE_PRIVATE (pool->conn, -1);

    make_nonnull_storage_pool (&args.pool, pool);

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

    return 0;
}

static int
remoteStoragePoolCreate (virStoragePoolPtr pool, unsigned int flags)
{
    remote_storage_pool_create_args args;
    GET_STORAGE_PRIVATE (pool->conn, -1);

    make_nonnull_storage_pool (&args.pool, pool);
    args.flags = flags;

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

    return 0;
}

static int
remoteStoragePoolBuild (virStoragePoolPtr pool,
                        unsigned int flags)
{
    remote_storage_pool_build_args args;
    GET_STORAGE_PRIVATE (pool->conn, -1);

    make_nonnull_storage_pool (&args.pool, pool);
    args.flags = flags;

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

    return 0;
}

static int
remoteStoragePoolDestroy (virStoragePoolPtr pool)
{
    remote_storage_pool_destroy_args args;
    GET_STORAGE_PRIVATE (pool->conn, -1);

    make_nonnull_storage_pool (&args.pool, pool);

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

    return 0;
}

static int
remoteStoragePoolDelete (virStoragePoolPtr pool,
                         unsigned int flags)
{
    remote_storage_pool_delete_args args;
    GET_STORAGE_PRIVATE (pool->conn, -1);

    make_nonnull_storage_pool (&args.pool, pool);
    args.flags = flags;

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

    return 0;
}

static int
remoteStoragePoolRefresh (virStoragePoolPtr pool,
                          unsigned int flags)
{
    remote_storage_pool_refresh_args args;
    GET_STORAGE_PRIVATE (pool->conn, -1);

    make_nonnull_storage_pool (&args.pool, pool);
    args.flags = flags;

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

    return 0;
}

static int
remoteStoragePoolGetInfo (virStoragePoolPtr pool, virStoragePoolInfoPtr info)
{
    remote_storage_pool_get_info_args args;
    remote_storage_pool_get_info_ret ret;
    GET_STORAGE_PRIVATE (pool->conn, -1);

    make_nonnull_storage_pool (&args.pool, pool);

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_GET_INFO,
              (xdrproc_t) xdr_remote_storage_pool_get_info_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_get_info_ret, (char *) &ret) == -1)
        return -1;

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

    return 0;
}

static char *
remoteStoragePoolDumpXML (virStoragePoolPtr pool,
                          unsigned int flags)
{
    remote_storage_pool_dump_xml_args args;
    remote_storage_pool_dump_xml_ret ret;
    GET_STORAGE_PRIVATE (pool->conn, NULL);

    make_nonnull_storage_pool (&args.pool, pool);
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_DUMP_XML,
              (xdrproc_t) xdr_remote_storage_pool_dump_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_dump_xml_ret, (char *) &ret) == -1)
        return NULL;

    /* Caller frees. */
    return ret.xml;
}

static int
remoteStoragePoolGetAutostart (virStoragePoolPtr pool, int *autostart)
{
    remote_storage_pool_get_autostart_args args;
    remote_storage_pool_get_autostart_ret ret;
    GET_STORAGE_PRIVATE (pool->conn, -1);

    make_nonnull_storage_pool (&args.pool, pool);

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_GET_AUTOSTART,
              (xdrproc_t) xdr_remote_storage_pool_get_autostart_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_get_autostart_ret, (char *) &ret) == -1)
        return -1;

    if (autostart) *autostart = ret.autostart;

    return 0;
}

static int
remoteStoragePoolSetAutostart (virStoragePoolPtr pool, int autostart)
{
    remote_storage_pool_set_autostart_args args;
    GET_STORAGE_PRIVATE (pool->conn, -1);

    make_nonnull_storage_pool (&args.pool, pool);
    args.autostart = autostart;

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

    return 0;
}


static int
remoteStoragePoolNumOfVolumes (virStoragePoolPtr pool)
{
    remote_storage_pool_num_of_volumes_args args;
    remote_storage_pool_num_of_volumes_ret ret;
    GET_STORAGE_PRIVATE (pool->conn, -1);

    make_nonnull_storage_pool(&args.pool, pool);

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

    return ret.num;
}

static int
remoteStoragePoolListVolumes (virStoragePoolPtr pool, char **const names, int maxnames)
{
    int i;
    remote_storage_pool_list_volumes_args args;
    remote_storage_pool_list_volumes_ret ret;
    GET_STORAGE_PRIVATE (pool->conn, -1);

    if (maxnames > REMOTE_STORAGE_VOL_NAME_LIST_MAX) {
        error (pool->conn, VIR_ERR_RPC, _("too many storage volumes requested"));
        return -1;
    }
    args.maxnames = maxnames;
    make_nonnull_storage_pool(&args.pool, pool);

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_POOL_LIST_VOLUMES,
              (xdrproc_t) xdr_remote_storage_pool_list_volumes_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_pool_list_volumes_ret, (char *) &ret) == -1)
        return -1;

    if (ret.names.names_len > maxnames) {
        error (pool->conn, VIR_ERR_RPC, _("too many storage volumes received"));
        xdr_free ((xdrproc_t) xdr_remote_storage_pool_list_volumes_ret, (char *) &ret);
        return -1;
    }

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

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

    return ret.names.names_len;
}



static virStorageVolPtr
remoteStorageVolLookupByName (virStoragePoolPtr pool,
                              const char *name)
{
    virStorageVolPtr vol;
    remote_storage_vol_lookup_by_name_args args;
    remote_storage_vol_lookup_by_name_ret ret;
    GET_STORAGE_PRIVATE (pool->conn, NULL);

    make_nonnull_storage_pool(&args.pool, pool);
    args.name = (char *) name;

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_LOOKUP_BY_NAME,
              (xdrproc_t) xdr_remote_storage_vol_lookup_by_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_lookup_by_name_ret, (char *) &ret) == -1)
        return NULL;

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

    return vol;
}

static virStorageVolPtr
remoteStorageVolLookupByKey (virConnectPtr conn,
                             const char *key)
{
    virStorageVolPtr vol;
    remote_storage_vol_lookup_by_key_args args;
    remote_storage_vol_lookup_by_key_ret ret;
    GET_STORAGE_PRIVATE (conn, NULL);

    args.key = (char *) key;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_STORAGE_VOL_LOOKUP_BY_KEY,
              (xdrproc_t) xdr_remote_storage_vol_lookup_by_key_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_lookup_by_key_ret, (char *) &ret) == -1)
        return NULL;

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

    return vol;
}

static virStorageVolPtr
remoteStorageVolLookupByPath (virConnectPtr conn,
                              const char *path)
{
    virStorageVolPtr vol;
    remote_storage_vol_lookup_by_path_args args;
    remote_storage_vol_lookup_by_path_ret ret;
    GET_STORAGE_PRIVATE (conn, NULL);

    args.path = (char *) path;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_STORAGE_VOL_LOOKUP_BY_PATH,
              (xdrproc_t) xdr_remote_storage_vol_lookup_by_path_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_lookup_by_path_ret, (char *) &ret) == -1)
        return NULL;

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

    return vol;
}

static virStorageVolPtr
remoteStorageVolCreateXML (virStoragePoolPtr pool, const char *xmlDesc,
                           unsigned int flags)
{
    virStorageVolPtr vol;
    remote_storage_vol_create_xml_args args;
    remote_storage_vol_create_xml_ret ret;
    GET_STORAGE_PRIVATE (pool->conn, NULL);

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

    memset (&ret, 0, sizeof ret);
    if (call (pool->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_CREATE_XML,
              (xdrproc_t) xdr_remote_storage_vol_create_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_create_xml_ret, (char *) &ret) == -1)
        return NULL;

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

    return vol;
}

static int
remoteStorageVolDelete (virStorageVolPtr vol,
                        unsigned int flags)
{
    remote_storage_vol_delete_args args;
    GET_STORAGE_PRIVATE (vol->conn, -1);

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

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

    return 0;
}

static int
remoteStorageVolGetInfo (virStorageVolPtr vol, virStorageVolInfoPtr info)
{
    remote_storage_vol_get_info_args args;
    remote_storage_vol_get_info_ret ret;
    GET_STORAGE_PRIVATE (vol->conn, -1);

    make_nonnull_storage_vol (&args.vol, vol);

    memset (&ret, 0, sizeof ret);
    if (call (vol->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_GET_INFO,
              (xdrproc_t) xdr_remote_storage_vol_get_info_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_get_info_ret, (char *) &ret) == -1)
        return -1;

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

    return 0;
}

static char *
remoteStorageVolDumpXML (virStorageVolPtr vol,
                         unsigned int flags)
{
    remote_storage_vol_dump_xml_args args;
    remote_storage_vol_dump_xml_ret ret;
    GET_STORAGE_PRIVATE (vol->conn, NULL);

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

    memset (&ret, 0, sizeof ret);
    if (call (vol->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_DUMP_XML,
              (xdrproc_t) xdr_remote_storage_vol_dump_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_dump_xml_ret, (char *) &ret) == -1)
        return NULL;

    /* Caller frees. */
    return ret.xml;
}

static char *
remoteStorageVolGetPath (virStorageVolPtr vol)
{
    remote_storage_vol_get_path_args args;
    remote_storage_vol_get_path_ret ret;
    GET_NETWORK_PRIVATE (vol->conn, NULL);

    make_nonnull_storage_vol (&args.vol, vol);

    memset (&ret, 0, sizeof ret);
    if (call (vol->conn, priv, 0, REMOTE_PROC_STORAGE_VOL_GET_PATH,
              (xdrproc_t) xdr_remote_storage_vol_get_path_args, (char *) &args,
              (xdrproc_t) xdr_remote_storage_vol_get_path_ret, (char *) &ret) == -1)
        return NULL;

    /* Caller frees. */
    return ret.name;
}


3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001
/*----------------------------------------------------------------------*/

static virDrvOpenStatus
remoteDevMonOpen(virConnectPtr conn,
                 virConnectAuthPtr auth ATTRIBUTE_UNUSED,
                 int flags ATTRIBUTE_UNUSED)
{
    if (conn &&
        conn->driver &&
        STREQ (conn->driver->name, "remote")) {
        /* If we're here, the remote driver is already
         * in use due to a) a QEMU uri, or b) a remote
         * URI. So we can re-use existing connection
         */
        conn->devMonPrivateData = conn->privateData;
        return VIR_DRV_OPEN_SUCCESS;
    }

    /* Decline open.  Will fallback to appropriate local node driver. */
    return VIR_DRV_OPEN_DECLINED;
}

static int remoteDevMonClose(virConnectPtr conn)
{
    int ret = 0;
    GET_DEVMON_PRIVATE (conn, -1);
    if (priv->localUses) {
        priv->localUses--;
        if (!priv->localUses) {
            ret = doRemoteClose(conn, priv);
            VIR_FREE(priv);
            conn->devMonPrivateData = NULL;
        }
    }
    return ret;
}

static int remoteNodeNumOfDevices(virConnectPtr conn,
                                  const char *cap,
                                  unsigned int flags)
{
    remote_node_num_of_devices_args args;
    remote_node_num_of_devices_ret ret;
    GET_STORAGE_PRIVATE (conn, -1);

    args.cap = cap ? (char **)&cap : NULL;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NODE_NUM_OF_DEVICES,
              (xdrproc_t) xdr_remote_node_num_of_devices_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_num_of_devices_ret, (char *) &ret) == -1)
        return -1;

    return ret.num;
}


static int remoteNodeListDevices(virConnectPtr conn,
                                 const char *cap,
                                 char **const names,
                                 int maxnames,
                                 unsigned int flags)
{
    int i;
    remote_node_list_devices_args args;
    remote_node_list_devices_ret ret;
    GET_STORAGE_PRIVATE (conn, -1);

    if (maxnames > REMOTE_NODE_DEVICE_NAME_LIST_MAX) {
        error (conn, VIR_ERR_RPC, _("too many device names requested"));
        return -1;
    }
    args.cap = cap ? (char **)&cap : NULL;
    args.maxnames = maxnames;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NODE_LIST_DEVICES,
              (xdrproc_t) xdr_remote_node_list_devices_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_list_devices_ret, (char *) &ret) == -1)
        return -1;

    if (ret.names.names_len > maxnames) {
        error (conn, VIR_ERR_RPC, _("too many device names received"));
        xdr_free ((xdrproc_t) xdr_remote_node_list_devices_ret, (char *) &ret);
        return -1;
    }

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

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

    return ret.names.names_len;
}


static virNodeDevicePtr remoteNodeDeviceLookupByName(virConnectPtr conn,
                                                     const char *name)
{
    remote_node_device_lookup_by_name_args args;
    remote_node_device_lookup_by_name_ret ret;
    virNodeDevicePtr dev;
    GET_STORAGE_PRIVATE (conn, NULL);

    args.name = (char *)name;

    memset (&ret, 0, sizeof ret);
    if (call (conn, priv, 0, REMOTE_PROC_NODE_DEVICE_LOOKUP_BY_NAME,
              (xdrproc_t) xdr_remote_node_device_lookup_by_name_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_device_lookup_by_name_ret, (char *) &ret) == -1)
        return NULL;

    dev = get_nonnull_node_device(conn, ret.dev);

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

    return dev;
}

static char *remoteNodeDeviceDumpXML(virNodeDevicePtr dev,
                                     unsigned int flags)
{
    remote_node_device_dump_xml_args args;
    remote_node_device_dump_xml_ret ret;
    GET_STORAGE_PRIVATE (dev->conn, NULL);

    args.name = dev->name;
    args.flags = flags;

    memset (&ret, 0, sizeof ret);
    if (call (dev->conn, priv, 0, REMOTE_PROC_NODE_DEVICE_DUMP_XML,
              (xdrproc_t) xdr_remote_node_device_dump_xml_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_device_dump_xml_ret, (char *) &ret) == -1)
        return NULL;

    /* Caller frees. */
    return ret.xml;
}

static char *remoteNodeDeviceGetParent(virNodeDevicePtr dev)
{
    remote_node_device_get_parent_args args;
    remote_node_device_get_parent_ret ret;
    GET_STORAGE_PRIVATE (dev->conn, NULL);

    args.name = dev->name;

    memset (&ret, 0, sizeof ret);
    if (call (dev->conn, priv, 0, REMOTE_PROC_NODE_DEVICE_GET_PARENT,
              (xdrproc_t) xdr_remote_node_device_get_parent_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_device_get_parent_ret, (char *) &ret) == -1)
        return NULL;

    /* Caller frees. */
    return ret.parent ? *ret.parent : NULL;
}

static int remoteNodeDeviceNumOfCaps(virNodeDevicePtr dev)
{
    remote_node_device_num_of_caps_args args;
    remote_node_device_num_of_caps_ret ret;
    GET_STORAGE_PRIVATE (dev->conn, -1);

    args.name = dev->name;

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

    return ret.num;
}

static int remoteNodeDeviceListCaps(virNodeDevicePtr dev,
                                    char **const names,
                                    int maxnames)
{
    int i;
    remote_node_device_list_caps_args args;
    remote_node_device_list_caps_ret ret;
    GET_STORAGE_PRIVATE (dev->conn, -1);

    if (maxnames > REMOTE_NODE_DEVICE_CAPS_LIST_MAX) {
        error (dev->conn, VIR_ERR_RPC, _("too many capability names requested"));
        return -1;
    }
    args.maxnames = maxnames;
    args.name = dev->name;

    memset (&ret, 0, sizeof ret);
    if (call (dev->conn, priv, 0, REMOTE_PROC_NODE_DEVICE_LIST_CAPS,
              (xdrproc_t) xdr_remote_node_device_list_caps_args, (char *) &args,
              (xdrproc_t) xdr_remote_node_device_list_caps_ret, (char *) &ret) == -1)
        return -1;

    if (ret.names.names_len > maxnames) {
        error (dev->conn, VIR_ERR_RPC, _("too many capability names received"));
        xdr_free ((xdrproc_t) xdr_remote_node_device_list_caps_ret, (char *) &ret);
        return -1;
    }

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

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

    return ret.names.names_len;
}


4002 4003
/*----------------------------------------------------------------------*/

4004
static int
4005
remoteAuthenticate (virConnectPtr conn, struct private_data *priv, int in_open,
4006 4007 4008 4009 4010 4011
                    virConnectAuthPtr auth
#if !HAVE_SASL && !HAVE_POLKIT
                    ATTRIBUTE_UNUSED
#endif
                    ,
                    const char *authtype)
4012 4013
{
    struct remote_auth_list_ret ret;
4014
    int err, type = REMOTE_AUTH_NONE;
4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030

    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;

4031 4032 4033 4034 4035 4036 4037 4038
    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 {
4039
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4040 4041 4042
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                             NULL, NULL, NULL, 0, 0,
                             _("unknown authentication type %s"), authtype);
4043 4044 4045 4046 4047 4048 4049
            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) {
4050
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4051
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4052 4053
                             _("requested authentication type %s rejected"),
                             authtype);
4054 4055 4056 4057 4058 4059 4060
            return -1;
        }
    } else {
        type = ret.types.types_val[0];
    }

    switch (type) {
4061
#if HAVE_SASL
4062 4063 4064 4065 4066 4067 4068
    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) {
4069
            VIR_FREE(ret.types.types_val);
4070 4071 4072
            return -1;
        }
        break;
4073
    }
4074 4075
#endif

4076 4077
#if HAVE_POLKIT
    case REMOTE_AUTH_POLKIT:
4078
        if (remoteAuthPolkit(conn, priv, in_open, auth) < 0) {
4079
            VIR_FREE(ret.types.types_val);
4080 4081 4082 4083 4084
            return -1;
        }
        break;
#endif

4085 4086 4087 4088 4089
    case REMOTE_AUTH_NONE:
        /* Nothing todo, hurrah ! */
        break;

    default:
4090
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4091 4092 4093 4094
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                         NULL, NULL, NULL, 0, 0,
                         _("unsupported authentication type %d"),
                         ret.types.types_val[0]);
4095
        VIR_FREE(ret.types.types_val);
4096 4097 4098
        return -1;
    }

4099
    VIR_FREE(ret.types.types_val);
4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119

    return 0;
}



#if HAVE_SASL
/*
 * NB, keep in sync with similar method in qemud/remote.c
 */
static char *addrToString(struct sockaddr_storage *sa, socklen_t salen)
{
    char host[NI_MAXHOST], port[NI_MAXSERV];
    char *addr;
    int err;

    if ((err = getnameinfo((struct sockaddr *)sa, salen,
                           host, sizeof(host),
                           port, sizeof(port),
                           NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
4120
        virRaiseError (NULL, NULL, NULL, VIR_FROM_REMOTE,
4121 4122 4123 4124
                         VIR_ERR_NO_MEMORY, VIR_ERR_ERROR,
                         NULL, NULL, NULL, 0, 0,
                         _("Cannot resolve address %d: %s"),
                         err, gai_strerror(err));
4125 4126 4127
        return NULL;
    }

4128
    if (VIR_ALLOC_N(addr, strlen(host) + 1 + strlen(port) + 1) < 0) {
4129
        virRaiseError (NULL, NULL, NULL, VIR_FROM_REMOTE,
4130 4131
                         VIR_ERR_NO_MEMORY, VIR_ERR_ERROR,
                         NULL, NULL, NULL, 0, 0,
4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142
                         "address");
        return NULL;
    }

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


4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220
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)
{
4221
    sasl_callback_t *cbs;
4222
    int i, n;
4223
    if (VIR_ALLOC_N(cbs, ncredtype+1) < 0) {
4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242
        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
4243
 *
4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257
 * 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 */

4258
    if (VIR_ALLOC_N(*cred, ninteract) < 0)
4259 4260 4261 4262 4263
        return -1;

    for (ninteract = 0 ; interact[ninteract].id != 0 ; ninteract++) {
        (*cred)[ninteract].type = remoteAuthCredSASL2Vir(interact[ninteract].id);
        if (!(*cred)[ninteract].type) {
4264
            VIR_FREE(*cred);
4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282
            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++)
4283 4284
        VIR_FREE(cred[i].result);
    VIR_FREE(cred);
4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305
}


/*
 * @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
4306 4307
 */
static int
4308 4309
remoteAuthSASL (virConnectPtr conn, struct private_data *priv, int in_open,
                virConnectAuthPtr auth, const char *wantmech)
4310 4311
{
    sasl_conn_t *saslconn = NULL;
4312
    sasl_security_properties_t secprops;
4313 4314 4315 4316 4317 4318
    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;
4319
    char *serverin = NULL;
4320 4321 4322 4323 4324
    unsigned int clientoutlen, serverinlen;
    const char *mech;
    int err, complete;
    struct sockaddr_storage sa;
    socklen_t salen;
4325
    char *localAddr = NULL, *remoteAddr = NULL;
4326 4327
    const void *val;
    sasl_ssf_t ssf;
4328 4329 4330 4331 4332 4333
    sasl_callback_t *saslcb = NULL;
    sasl_interact_t *interact = NULL;
    virConnectCredentialPtr cred = NULL;
    int ncred = 0;
    int ret = -1;
    const char *mechlist;
4334

4335
    DEBUG0("Client initialize SASL authentication");
4336 4337 4338
    /* Sets up the SASL library as a whole */
    err = sasl_client_init(NULL);
    if (err != SASL_OK) {
4339
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4340
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4341
                         _("failed to initialize SASL library: %d (%s)"),
4342
                         err, sasl_errstring(err, NULL, NULL));
4343
        goto cleanup;
4344 4345 4346 4347 4348
    }

    /* Get local address in form  IPADDR:PORT */
    salen = sizeof(sa);
    if (getsockname(priv->sock, (struct sockaddr*)&sa, &salen) < 0) {
4349
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4350
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4351
                         _("failed to get sock address %d (%s)"),
J
Jim Meyering 已提交
4352
                         errno, strerror(errno));
4353
        goto cleanup;
4354
    }
4355 4356
    if ((localAddr = addrToString(&sa, salen)) == NULL)
        goto cleanup;
4357 4358 4359 4360

    /* Get remote address in form  IPADDR:PORT */
    salen = sizeof(sa);
    if (getpeername(priv->sock, (struct sockaddr*)&sa, &salen) < 0) {
4361
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4362
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4363
                         _("failed to get peer address %d (%s)"),
J
Jim Meyering 已提交
4364
                         errno, strerror(errno));
4365
        goto cleanup;
4366
    }
4367 4368 4369
    if ((remoteAddr = addrToString(&sa, salen)) == NULL)
        goto cleanup;

4370 4371 4372 4373 4374 4375
    if (auth) {
        if ((saslcb = remoteAuthMakeCallbacks(auth->credtype, auth->ncredtype)) == NULL)
            goto cleanup;
    } else {
        saslcb = NULL;
    }
4376 4377 4378 4379 4380 4381

    /* Setup a handle for being a client */
    err = sasl_client_new("libvirt",
                          priv->hostname,
                          localAddr,
                          remoteAddr,
4382
                          saslcb,
4383 4384
                          SASL_SUCCESS_DATA,
                          &saslconn);
4385

4386
    if (err != SASL_OK) {
4387
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4388
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4389
                         _("Failed to create SASL client context: %d (%s)"),
4390
                         err, sasl_errstring(err, NULL, NULL));
4391
        goto cleanup;
4392 4393
    }

4394 4395 4396 4397 4398 4399
    /* 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))) {
4400
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4401
                             VIR_ERR_INTERNAL_ERROR, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4402
                             "%s", _("invalid cipher size for TLS session"));
4403
            goto cleanup;
4404 4405 4406
        }
        ssf *= 8; /* key size is bytes, sasl wants bits */

4407
        DEBUG("Setting external SSF %d", ssf);
4408 4409
        err = sasl_setprop(saslconn, SASL_SSF_EXTERNAL, &ssf);
        if (err != SASL_OK) {
4410
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4411
                             VIR_ERR_INTERNAL_ERROR, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4412
                             _("cannot set external SSF %d (%s)"),
4413
                             err, sasl_errstring(err, NULL, NULL));
4414
            goto cleanup;
4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428
        }
    }

    memset (&secprops, 0, sizeof secprops);
    /* If we've got TLS, we don't care about SSF */
    secprops.min_ssf = priv->uses_tls ? 0 : 56; /* Equiv to DES supported by all Kerberos */
    secprops.max_ssf = priv->uses_tls ? 0 : 100000; /* Very strong ! AES == 256 */
    secprops.maxbufsize = 100000;
    /* If we're not TLS, then forbid any anonymous or trivially crackable auth */
    secprops.security_flags = priv->uses_tls ? 0 :
        SASL_SEC_NOANONYMOUS | SASL_SEC_NOPLAINTEXT;

    err = sasl_setprop(saslconn, SASL_SEC_PROPS, &secprops);
    if (err != SASL_OK) {
4429
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4430
                         VIR_ERR_INTERNAL_ERROR, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4431
                         _("cannot set security props %d (%s)"),
4432
                         err, sasl_errstring(err, NULL, NULL));
4433
        goto cleanup;
4434 4435
    }

4436 4437 4438 4439
    /* 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,
4440 4441
              (xdrproc_t) xdr_remote_auth_sasl_init_ret, (char *) &iret) != 0)
        goto cleanup;
4442 4443


4444 4445 4446
    mechlist = iret.mechlist;
    if (wantmech) {
        if (strstr(mechlist, wantmech) == NULL) {
4447
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4448 4449 4450 4451
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                             NULL, NULL, NULL, 0, 0,
                             _("SASL mechanism %s not supported by server"),
                             wantmech);
4452
            VIR_FREE(iret.mechlist);
4453 4454 4455 4456 4457
            goto cleanup;
        }
        mechlist = wantmech;
    }
 restart:
4458
    /* Start the auth negotiation on the client end first */
4459
    DEBUG("Client start negotiation mechlist '%s'", mechlist);
4460
    err = sasl_client_start(saslconn,
4461 4462
                            mechlist,
                            &interact,
4463 4464 4465
                            &clientout,
                            &clientoutlen,
                            &mech);
4466
    if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
4467
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4468
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4469
                         _("Failed to start SASL negotiation: %d (%s)"),
4470
                         err, sasl_errdetail(saslconn));
4471
        VIR_FREE(iret.mechlist);
4472 4473 4474 4475 4476
        goto cleanup;
    }

    /* Need to gather some credentials from the client */
    if (err == SASL_INTERACT) {
4477
        const char *msg;
4478 4479 4480 4481 4482 4483
        if (cred) {
            remoteAuthFreeCredentials(cred, ncred);
            cred = NULL;
        }
        if ((ncred =
             remoteAuthMakeCredentials(interact, &cred)) < 0) {
4484
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4485 4486 4487
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR,
                             NULL, NULL, NULL, 0, 0,
                             "%s", _("Failed to make auth credentials"));
4488
            VIR_FREE(iret.mechlist);
4489 4490 4491
            goto cleanup;
        }
        /* Run the authentication callback */
4492
        if (auth && auth->cb) {
4493 4494 4495
            if ((*(auth->cb))(cred, ncred, auth->cbdata) >= 0) {
                remoteAuthFillInteract(cred, interact);
                goto restart;
4496
            }
4497
            msg = "Failed to collect auth credentials";
4498
        } else {
4499
            msg = "No authentication callback available";
4500
        }
4501
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4502
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL,
4503
                         0, 0, "%s", msg);
4504
        goto cleanup;
4505
    }
4506
    VIR_FREE(iret.mechlist);
4507 4508

    if (clientoutlen > REMOTE_AUTH_SASL_DATA_MAX) {
4509
        virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4510
                         VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4511 4512
                         _("SASL negotiation data too long: %d bytes"),
                         clientoutlen);
4513
        goto cleanup;
4514 4515 4516 4517 4518 4519 4520
    }
    /* 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;
4521
    DEBUG("Server start negotiation with mech %s. Data %d bytes %p", mech, clientoutlen, clientout);
4522 4523 4524 4525 4526

    /* 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,
4527 4528
              (xdrproc_t) xdr_remote_auth_sasl_start_ret, (char *) &sret) != 0)
        goto cleanup;
4529 4530 4531 4532 4533

    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;
4534 4535
    DEBUG("Client step result complete: %d. Data %d bytes %p",
          complete, serverinlen, serverin);
4536 4537 4538

    /* Loop-the-loop...
     * Even if the server has completed, the client must *always* do at least one step
D
Daniel Veillard 已提交
4539
     * in this loop to verify the server isn't lying about something. Mutual auth */
4540
    for (;;) {
4541
    restep:
4542 4543 4544
        err = sasl_client_step(saslconn,
                               serverin,
                               serverinlen,
4545
                               &interact,
4546 4547
                               &clientout,
                               &clientoutlen);
4548
        if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
4549
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4550
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4551
                             _("Failed SASL step: %d (%s)"),
4552
                             err, sasl_errdetail(saslconn));
4553 4554 4555 4556
            goto cleanup;
        }
        /* Need to gather some credentials from the client */
        if (err == SASL_INTERACT) {
4557
            const char *msg;
4558 4559 4560 4561 4562
            if (cred) {
                remoteAuthFreeCredentials(cred, ncred);
                cred = NULL;
            }
            if ((ncred = remoteAuthMakeCredentials(interact, &cred)) < 0) {
4563
                virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4564
                                 VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4565
                                 "%s", _("Failed to make auth credentials"));
4566 4567 4568
                goto cleanup;
            }
            /* Run the authentication callback */
4569
            if (auth && auth->cb) {
4570 4571 4572
                if ((*(auth->cb))(cred, ncred, auth->cbdata) >= 0) {
                    remoteAuthFillInteract(cred, interact);
                    goto restep;
4573
                }
4574
                msg = "Failed to collect auth credentials";
4575
            } else {
4576
                msg = "No authentication callback available";
4577
            }
4578
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4579
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL,
4580
                             0, 0, "%s", msg);
4581
            goto cleanup;
4582 4583 4584
        }

        if (serverin) {
4585
            VIR_FREE(serverin);
4586
        }
4587
        DEBUG("Client step result %d. Data %d bytes %p", err, clientoutlen, clientout);
4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598

        /* 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;
4599
        DEBUG("Server step with %d bytes %p", clientoutlen, clientout);
4600 4601 4602 4603

        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,
4604 4605
                  (xdrproc_t) xdr_remote_auth_sasl_step_ret, (char *) &pret) != 0)
            goto cleanup;
4606 4607 4608 4609 4610 4611

        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;

4612 4613
        DEBUG("Client step result complete: %d. Data %d bytes %p",
              complete, serverinlen, serverin);
4614 4615 4616

        /* This server call shows complete, and earlier client step was OK */
        if (complete && err == SASL_OK) {
4617
            VIR_FREE(serverin);
4618 4619 4620 4621
            break;
        }
    }

4622 4623 4624 4625
    /* Check for suitable SSF if non-TLS */
    if (!priv->uses_tls) {
        err = sasl_getprop(saslconn, SASL_SSF, &val);
        if (err != SASL_OK) {
4626
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4627
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4628
                             _("cannot query SASL ssf on connection %d (%s)"),
4629
                             err, sasl_errstring(err, NULL, NULL));
4630
            goto cleanup;
4631 4632
        }
        ssf = *(const int *)val;
4633
        DEBUG("SASL SSF value %d", ssf);
4634
        if (ssf < 56) { /* 56 == DES level, good for Kerberos */
4635
            virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4636
                             VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4637
                             _("negotiation SSF %d was not strong enough"), ssf);
4638
            goto cleanup;
4639 4640 4641
        }
    }

4642
    DEBUG0("SASL authentication complete");
4643
    priv->saslconn = saslconn;
4644 4645 4646
    ret = 0;

 cleanup:
4647 4648 4649
    VIR_FREE(localAddr);
    VIR_FREE(remoteAddr);
    VIR_FREE(serverin);
4650

4651
    VIR_FREE(saslcb);
4652 4653 4654 4655
    remoteAuthFreeCredentials(cred, ncred);
    if (ret != 0 && saslconn)
        sasl_dispose(&saslconn);
    return ret;
4656 4657 4658
}
#endif /* HAVE_SASL */

4659 4660 4661 4662 4663 4664 4665 4666 4667

#if HAVE_POLKIT
/* Perform the PolicyKit authentication process
 */
static int
remoteAuthPolkit (virConnectPtr conn, struct private_data *priv, int in_open,
                  virConnectAuthPtr auth)
{
    remote_auth_polkit_ret ret;
4668
    int i, allowcb = 0;
4669 4670 4671 4672 4673 4674 4675 4676
    virConnectCredential cred = {
        VIR_CRED_EXTERNAL,
        conn->flags & VIR_CONNECT_RO ? "org.libvirt.unix.monitor" : "org.libvirt.unix.manage",
        "PolicyKit",
        NULL,
        NULL,
        0,
    };
4677
    DEBUG0("Client initialize PolicyKit authentication");
4678

4679
    if (auth && auth->cb) {
4680
        /* Check if the necessary credential type for PolicyKit is supported */
4681 4682 4683 4684
        for (i = 0 ; i < auth->ncredtype ; i++) {
            if (auth->credtype[i] == VIR_CRED_EXTERNAL)
                allowcb = 1;
        }
4685

4686 4687 4688
        if (allowcb) {
            /* Run the authentication callback */
            if ((*(auth->cb))(&cred, 1, auth->cbdata) < 0) {
4689
                virRaiseError (in_open ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4690
                                 VIR_ERR_AUTH_FAILED, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
J
Jim Meyering 已提交
4691
                                 "%s", _("Failed to collect auth credentials"));
4692 4693
                return -1;
            }
4694
        } else {
4695
            DEBUG0("Client auth callback does not support PolicyKit");
4696 4697
        }
    } else {
4698
        DEBUG0("No auth callback provided");
4699 4700 4701 4702 4703 4704 4705 4706 4707
    }

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

4708
    DEBUG0("PolicyKit authentication complete");
4709 4710 4711
    return 0;
}
#endif /* HAVE_POLKIT */
4712 4713 4714
/*----------------------------------------------------------------------*/

static int remoteDomainEventRegister (virConnectPtr conn,
4715 4716 4717
                                      void *callback ATTRIBUTE_UNUSED,
                                      void *opaque ATTRIBUTE_UNUSED,
                                      virFreeCallback freecb)
4718 4719 4720
{
    struct private_data *priv = conn->privateData;

4721 4722 4723 4724
    if (priv->eventFlushTimer < 0) {
         error (conn, VIR_ERR_NO_SUPPORT, _("no event support"));
         return -1;
    }
4725
    if (virDomainEventCallbackListAdd(conn, priv->callbackList,
4726
                                      callback, opaque, freecb) < 0) {
4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762
         error (conn, VIR_ERR_RPC, _("adding cb to list"));
         return -1;
    }

    if ( priv->callbackList->count == 1 ) {
        /* Tell the server when we are the first callback deregistering */
        if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_EVENTS_REGISTER,
                (xdrproc_t) xdr_void, (char *) NULL,
                (xdrproc_t) xdr_void, (char *) NULL) == -1)
            return -1;
    }

    return 0;
}

static int remoteDomainEventDeregister (virConnectPtr conn,
                                 void *callback ATTRIBUTE_UNUSED)
{
    struct private_data *priv = conn->privateData;

    if (virDomainEventCallbackListRemove(conn, priv->callbackList,
                                  callback) < 0) {
         error (conn, VIR_ERR_RPC, _("removing cb fron list"));
         return -1;
    }

    if ( priv->callbackList->count == 0 ) {
        /* Tell the server when we are the last callback deregistering */
        if (call (conn, priv, 0, REMOTE_PROC_DOMAIN_EVENTS_DEREGISTER,
                (xdrproc_t) xdr_void, (char *) NULL,
                (xdrproc_t) xdr_void, (char *) NULL) == -1)
            return -1;
    }

    return 0;
}
4763

4764 4765
/*----------------------------------------------------------------------*/

4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782
static int really_write (virConnectPtr conn, struct private_data *priv,
                         int in_open, char *bytes, int len);
static int really_read (virConnectPtr conn, struct private_data *priv,
                        int in_open, char *bytes, int len);

/* This function performs a remote procedure call to procedure PROC_NR.
 *
 * NB. This does not free the args structure (not desirable, since you
 * often want this allocated on the stack or else it contains strings
 * which come from the user).  It does however free any intermediate
 * results, eg. the error structure if there is one.
 *
 * NB(2). Make sure to memset (&ret, 0, sizeof ret) before calling,
 * else Bad Things will happen in the XDR code.
 */
static int
call (virConnectPtr conn, struct private_data *priv,
4783
      int flags /* if we are in virConnectOpen */,
4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807
      int proc_nr,
      xdrproc_t args_filter, char *args,
      xdrproc_t ret_filter, char *ret)
{
    char buffer[REMOTE_MESSAGE_MAX];
    char buffer2[4];
    struct remote_message_header hdr;
    XDR xdr;
    int len;
    struct remote_error rerror;

    /* Get a unique serial number for this message. */
    int serial = priv->counter++;

    hdr.prog = REMOTE_PROGRAM;
    hdr.vers = REMOTE_PROTOCOL_VERSION;
    hdr.proc = proc_nr;
    hdr.direction = REMOTE_CALL;
    hdr.serial = serial;
    hdr.status = REMOTE_OK;

    /* Serialise header followed by args. */
    xdrmem_create (&xdr, buffer, sizeof buffer, XDR_ENCODE);
    if (!xdr_remote_message_header (&xdr, &hdr)) {
4808
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
4809
               VIR_ERR_RPC, _("xdr_remote_message_header failed"));
4810 4811 4812 4813
        return -1;
    }

    if (!(*args_filter) (&xdr, args)) {
4814 4815
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn, VIR_ERR_RPC,
               _("marshalling args"));
4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830
        return -1;
    }

    /* Get the length stored in buffer. */
    len = xdr_getpos (&xdr);
    xdr_destroy (&xdr);

    /* Length must include the length word itself (always encoded in
     * 4 bytes as per RFC 4506).
     */
    len += 4;

    /* Encode the length word. */
    xdrmem_create (&xdr, buffer2, sizeof buffer2, XDR_ENCODE);
    if (!xdr_int (&xdr, &len)) {
4831 4832
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn, VIR_ERR_RPC,
               _("xdr_int (length word)"));
4833 4834 4835 4836 4837
        return -1;
    }
    xdr_destroy (&xdr);

    /* Send length word followed by header+args. */
4838 4839
    if (really_write (conn, priv, flags & REMOTE_CALL_IN_OPEN, buffer2, sizeof buffer2) == -1 ||
        really_write (conn, priv, flags & REMOTE_CALL_IN_OPEN, buffer, len-4) == -1)
4840 4841
        return -1;

4842
retry_read:
4843
    /* Read and deserialise length word. */
4844
    if (really_read (conn, priv, flags & REMOTE_CALL_IN_OPEN, buffer2, sizeof buffer2) == -1)
4845 4846 4847 4848
        return -1;

    xdrmem_create (&xdr, buffer2, sizeof buffer2, XDR_DECODE);
    if (!xdr_int (&xdr, &len)) {
4849
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
4850
               VIR_ERR_RPC, _("xdr_int (length word, reply)"));
4851 4852 4853 4854 4855 4856 4857 4858
        return -1;
    }
    xdr_destroy (&xdr);

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

    if (len < 0 || len > REMOTE_MESSAGE_MAX) {
4859
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
4860
               VIR_ERR_RPC, _("packet received from server too large"));
4861 4862 4863 4864
        return -1;
    }

    /* Read reply header and what follows (either a ret or an error). */
4865
    if (really_read (conn, priv, flags & REMOTE_CALL_IN_OPEN, buffer, len) == -1)
4866 4867 4868 4869 4870
        return -1;

    /* Deserialise reply header. */
    xdrmem_create (&xdr, buffer, len, XDR_DECODE);
    if (!xdr_remote_message_header (&xdr, &hdr)) {
4871
        error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
4872
               VIR_ERR_RPC, _("invalid header in reply"));
4873 4874 4875 4876 4877
        return -1;
    }

    /* Check program, version, etc. are what we expect. */
    if (hdr.prog != REMOTE_PROGRAM) {
4878
        virRaiseError (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
4879
                         NULL, NULL, VIR_FROM_REMOTE,
4880
                         VIR_ERR_RPC, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4881
                         _("unknown program (received %x, expected %x)"),
4882 4883 4884 4885
                         hdr.prog, REMOTE_PROGRAM);
        return -1;
    }
    if (hdr.vers != REMOTE_PROTOCOL_VERSION) {
4886
        virRaiseError (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
4887
                         NULL, NULL, VIR_FROM_REMOTE,
4888
                         VIR_ERR_RPC, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4889
                         _("unknown protocol version (received %x, expected %x)"),
4890 4891 4892 4893
                         hdr.vers, REMOTE_PROTOCOL_VERSION);
        return -1;
    }

4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907
    if (hdr.proc == REMOTE_PROC_DOMAIN_EVENT &&
        hdr.direction == REMOTE_MESSAGE) {
        /* An async message has come in while we were waiting for the
         * response. Process it to pull it off the wire, and try again
         */
        DEBUG0("Encountered an event while waiting for a response");

        remoteDomainQueueEvent(conn, &xdr);
        virEventUpdateTimeout(priv->eventFlushTimer, 0);

        DEBUG0("Retrying read");
        xdr_destroy (&xdr);
        goto retry_read;
    }
4908
    if (hdr.proc != proc_nr) {
4909
        virRaiseError (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
4910
                         NULL, NULL, VIR_FROM_REMOTE,
4911
                         VIR_ERR_RPC, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4912
                         _("unknown procedure (received %x, expected %x)"),
4913 4914 4915 4916
                         hdr.proc, proc_nr);
        return -1;
    }
    if (hdr.direction != REMOTE_REPLY) {
4917
        virRaiseError (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
4918
                         NULL, NULL, VIR_FROM_REMOTE,
4919
                         VIR_ERR_RPC, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4920
                         _("unknown direction (received %x, expected %x)"),
4921 4922 4923 4924
                         hdr.direction, REMOTE_REPLY);
        return -1;
    }
    if (hdr.serial != serial) {
4925
        virRaiseError (flags & REMOTE_CALL_IN_OPEN ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4926
                         VIR_ERR_RPC, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4927
                         _("unknown serial (received %x, expected %x)"),
4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938
                         hdr.serial, serial);
        return -1;
    }

    /* Status is either REMOTE_OK (meaning that what follows is a ret
     * structure), or REMOTE_ERROR (and what follows is a remote_error
     * structure).
     */
    switch (hdr.status) {
    case REMOTE_OK:
        if (!(*ret_filter) (&xdr, ret)) {
4939 4940
            error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn, VIR_ERR_RPC,
                   _("unmarshalling ret"));
4941 4942 4943 4944 4945 4946 4947 4948
            return -1;
        }
        xdr_destroy (&xdr);
        return 0;

    case REMOTE_ERROR:
        memset (&rerror, 0, sizeof rerror);
        if (!xdr_remote_error (&xdr, &rerror)) {
4949
            error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn,
4950
                   VIR_ERR_RPC, _("unmarshalling remote_error"));
4951 4952 4953
            return -1;
        }
        xdr_destroy (&xdr);
4954 4955 4956 4957 4958 4959
        /* See if caller asked us to keep quiet about missing RPCs
         * eg for interop with older servers */
        if (flags & REMOTE_CALL_QUIET_MISSING_RPC &&
            rerror.domain == VIR_FROM_REMOTE &&
            rerror.code == VIR_ERR_RPC &&
            rerror.level == VIR_ERR_ERROR &&
4960
            STRPREFIX(*rerror.message, "unknown procedure")) {
4961 4962 4963
            return -2;
        }
        server_error (flags & REMOTE_CALL_IN_OPEN ? NULL : conn, &rerror);
4964 4965 4966 4967
        xdr_free ((xdrproc_t) xdr_remote_error, (char *) &rerror);
        return -1;

    default:
4968
        virRaiseError (flags & REMOTE_CALL_IN_OPEN ? NULL : conn, NULL, NULL, VIR_FROM_REMOTE,
4969
                         VIR_ERR_RPC, VIR_ERR_ERROR, NULL, NULL, NULL, 0, 0,
4970
                         _("unknown status (received %x)"),
4971 4972 4973 4974 4975 4976 4977
                         hdr.status);
        xdr_destroy (&xdr);
        return -1;
    }
}

static int
4978 4979 4980
really_write_buf (virConnectPtr conn, struct private_data *priv,
                  int in_open /* if we are in virConnectOpen */,
                  const char *bytes, int len)
4981
{
4982
    const char *p;
4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001
    int err;

    p = bytes;
    if (priv->uses_tls) {
        do {
            err = gnutls_record_send (priv->session, p, len);
            if (err < 0) {
                if (err == GNUTLS_E_INTERRUPTED || err == GNUTLS_E_AGAIN)
                    continue;
                error (in_open ? NULL : conn,
                       VIR_ERR_GNUTLS_ERROR, gnutls_strerror (err));
                return -1;
            }
            len -= err;
            p += err;
        }
        while (len > 0);
    } else {
        do {
5002
            err = send (priv->sock, p, len, 0);
5003
            if (err == -1) {
J
Jim Meyering 已提交
5004
                if (errno == EINTR || errno == EAGAIN)
5005 5006
                    continue;
                error (in_open ? NULL : conn,
J
Jim Meyering 已提交
5007
                       VIR_ERR_SYSTEM_ERROR, strerror (errno));
5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019
                return -1;
            }
            len -= err;
            p += err;
        }
        while (len > 0);
    }

    return 0;
}

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

#if HAVE_SASL
static int
really_write_sasl (virConnectPtr conn, struct private_data *priv,
              int in_open /* if we are in virConnectOpen */,
              char *bytes, int len)
{
    const char *output;
    unsigned int outputlen;
    int err;

    err = sasl_encode(priv->saslconn, bytes, len, &output, &outputlen);
    if (err != SASL_OK) {
        return -1;
    }

    return really_write_buf(conn, priv, in_open, output, outputlen);
}
#endif

static int
really_write (virConnectPtr conn, struct private_data *priv,
              int in_open /* if we are in virConnectOpen */,
              char *bytes, int len)
{
#if HAVE_SASL
    if (priv->saslconn)
        return really_write_sasl(conn, priv, in_open, bytes, len);
    else
#endif
        return really_write_plain(conn, priv, in_open, bytes, len);
}

static int
really_read_buf (virConnectPtr conn, struct private_data *priv,
                 int in_open /* if we are in virConnectOpen */,
                 char *bytes, int len)
5063 5064 5065 5066
{
    int err;

    if (priv->uses_tls) {
5067 5068 5069 5070 5071 5072 5073 5074
    tlsreread:
        err = gnutls_record_recv (priv->session, bytes, len);
        if (err < 0) {
            if (err == GNUTLS_E_INTERRUPTED)
                goto tlsreread;
            error (in_open ? NULL : conn,
                   VIR_ERR_GNUTLS_ERROR, gnutls_strerror (err));
            return -1;
5075
        }
5076 5077
        if (err == 0) {
            error (in_open ? NULL : conn,
5078
                   VIR_ERR_RPC, _("socket closed unexpectedly"));
5079 5080 5081
            return -1;
        }
        return err;
5082
    } else {
5083
    reread:
5084
        err = recv (priv->sock, bytes, len, 0);
5085
        if (err == -1) {
J
Jim Meyering 已提交
5086
            if (errno == EINTR)
5087 5088
                goto reread;
            error (in_open ? NULL : conn,
J
Jim Meyering 已提交
5089
                   VIR_ERR_SYSTEM_ERROR, strerror (errno));
5090
            return -1;
5091
        }
5092 5093
        if (err == 0) {
            error (in_open ? NULL : conn,
5094
                   VIR_ERR_RPC, _("socket closed unexpectedly"));
5095 5096 5097
            return -1;
        }
        return err;
5098 5099 5100 5101 5102
    }

    return 0;
}

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 5171
static int
really_read_plain (virConnectPtr conn, struct private_data *priv,
                   int in_open /* if we are in virConnectOpen */,
                   char *bytes, int len)
{
    do {
        int ret = really_read_buf (conn, priv, in_open, bytes, len);
        if (ret < 0)
            return -1;

        len -= ret;
        bytes += ret;
    } while (len > 0);

    return 0;
}

#if HAVE_SASL
static int
really_read_sasl (virConnectPtr conn, struct private_data *priv,
                  int in_open /* if we are in virConnectOpen */,
                  char *bytes, int len)
{
    do {
        int want, got;
        if (priv->saslDecoded == NULL) {
            char encoded[8192];
            int encodedLen = sizeof(encoded);
            int err, ret;
            ret = really_read_buf (conn, priv, in_open, encoded, encodedLen);
            if (ret < 0)
                return -1;

            err = sasl_decode(priv->saslconn, encoded, ret,
                              &priv->saslDecoded, &priv->saslDecodedLength);
        }

        got = priv->saslDecodedLength - priv->saslDecodedOffset;
        want = len;
        if (want > got)
            want = got;

        memcpy(bytes, priv->saslDecoded + priv->saslDecodedOffset, want);
        priv->saslDecodedOffset += want;
        if (priv->saslDecodedOffset == priv->saslDecodedLength) {
            priv->saslDecoded = NULL;
            priv->saslDecodedOffset = priv->saslDecodedLength = 0;
        }
        bytes += want;
        len -= want;
    } while (len > 0);

    return 0;
}
#endif

static int
really_read (virConnectPtr conn, struct private_data *priv,
             int in_open /* if we are in virConnectOpen */,
             char *bytes, int len)
{
#if HAVE_SASL
    if (priv->saslconn)
        return really_read_sasl (conn, priv, in_open, bytes, len);
    else
#endif
        return really_read_plain (conn, priv, in_open, bytes, len);
}

5172 5173 5174 5175 5176 5177
/* For errors internal to this library. */
static void
error (virConnectPtr conn, virErrorNumber code, const char *info)
{
    const char *errmsg;

5178 5179
    errmsg = virErrorMsg (code, info);
    virRaiseError (conn, NULL, NULL, VIR_FROM_REMOTE,
5180 5181 5182 5183
                     code, VIR_ERR_ERROR, errmsg, info, NULL, 0, 0,
                     errmsg, info);
}

5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200
/* For errors internal to this library.
   Identical to the above, but with a format string and optional params.  */
static void
errorf (virConnectPtr conn, virErrorNumber code, const char *fmt, ...)
{
    const char *errmsg;
    va_list args;
    char errorMessage[256];

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

5201 5202
    errmsg = virErrorMsg (code, errorMessage);
    virRaiseError (conn, NULL, NULL, VIR_FROM_REMOTE,
5203 5204 5205
                     code, VIR_ERR_ERROR,
                     errmsg, errorMessage, NULL, -1, -1,
                     errmsg, errorMessage);
5206 5207
}

5208 5209 5210 5211 5212 5213 5214
/* For errors generated on the server side and sent back to us. */
static void
server_error (virConnectPtr conn, remote_error *err)
{
    virDomainPtr dom;
    virNetworkPtr net;

5215
    /* Get the domain and network, if set. */
5216 5217 5218
    dom = err->dom ? get_nonnull_domain (conn, *err->dom) : NULL;
    net = err->net ? get_nonnull_network (conn, *err->net) : NULL;

5219
    virRaiseError (conn, dom, net,
5220
                     err->domain, err->code, err->level,
D
Daniel P. Berrange 已提交
5221 5222 5223
                     err->str1 ? *err->str1 : NULL,
                     err->str2 ? *err->str2 : NULL,
                     err->str3 ? *err->str3 : NULL,
5224
                     err->int1, err->int2,
D
Daniel P. Berrange 已提交
5225
                     "%s", err->message ? *err->message : NULL);
5226 5227 5228 5229
    if (dom)
        virDomainFree(dom);
    if (net)
        virNetworkFree(net);
5230 5231 5232 5233
}

/* get_nonnull_domain and get_nonnull_network turn an on-wire
 * (name, uuid) pair into virDomainPtr or virNetworkPtr object.
5234
 * These can return NULL if underlying memory allocations fail,
5235
 * but if they do then virterror_internal.has been set.
5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251
 */
static virDomainPtr
get_nonnull_domain (virConnectPtr conn, remote_nonnull_domain domain)
{
    virDomainPtr dom;
    dom = virGetDomain (conn, domain.name, BAD_CAST domain.uuid);
    if (dom) dom->id = domain.id;
    return dom;
}

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

5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263
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);
}

5264 5265 5266 5267 5268 5269
static virNodeDevicePtr
get_nonnull_node_device (virConnectPtr conn, remote_nonnull_node_device dev)
{
    return virGetNodeDevice(conn, dev.name);
}

5270 5271 5272 5273
/* Make remote_nonnull_domain and remote_nonnull_network. */
static void
make_nonnull_domain (remote_nonnull_domain *dom_dst, virDomainPtr dom_src)
{
5274
    dom_dst->id = dom_src->id;
5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285
    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);
}

5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300
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;
}

5301 5302 5303 5304 5305 5306 5307 5308
/*----------------------------------------------------------------------*/

static virDriver driver = {
    .no = VIR_DRV_REMOTE,
    .name = "remote",
    .ver = REMOTE_PROTOCOL_VERSION,
    .open = remoteOpen,
    .close = remoteClose,
5309
    .supports_feature = remoteSupportsFeature,
5310 5311
        .type = remoteType,
        .version = remoteVersion,
5312
    .getHostname = remoteGetHostname,
5313 5314
        .getMaxVcpus = remoteGetMaxVcpus,
        .nodeGetInfo = remoteNodeGetInfo,
5315 5316 5317
    .getCapabilities = remoteGetCapabilities,
    .listDomains = remoteListDomains,
    .numOfDomains = remoteNumOfDomains,
5318
    .domainCreateXML = remoteDomainCreateXML,
5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348
    .domainLookupByID = remoteDomainLookupByID,
    .domainLookupByUUID = remoteDomainLookupByUUID,
    .domainLookupByName = remoteDomainLookupByName,
    .domainSuspend = remoteDomainSuspend,
    .domainResume = remoteDomainResume,
    .domainShutdown = remoteDomainShutdown,
    .domainReboot = remoteDomainReboot,
    .domainDestroy = remoteDomainDestroy,
    .domainGetOSType = remoteDomainGetOSType,
    .domainGetMaxMemory = remoteDomainGetMaxMemory,
    .domainSetMaxMemory = remoteDomainSetMaxMemory,
    .domainSetMemory = remoteDomainSetMemory,
    .domainGetInfo = remoteDomainGetInfo,
    .domainSave = remoteDomainSave,
    .domainRestore = remoteDomainRestore,
    .domainCoreDump = remoteDomainCoreDump,
    .domainSetVcpus = remoteDomainSetVcpus,
    .domainPinVcpu = remoteDomainPinVcpu,
    .domainGetVcpus = remoteDomainGetVcpus,
    .domainGetMaxVcpus = remoteDomainGetMaxVcpus,
    .domainDumpXML = remoteDomainDumpXML,
    .listDefinedDomains = remoteListDefinedDomains,
    .numOfDefinedDomains = remoteNumOfDefinedDomains,
    .domainCreate = remoteDomainCreate,
    .domainDefineXML = remoteDomainDefineXML,
    .domainUndefine = remoteDomainUndefine,
    .domainAttachDevice = remoteDomainAttachDevice,
    .domainDetachDevice = remoteDomainDetachDevice,
    .domainGetAutostart = remoteDomainGetAutostart,
    .domainSetAutostart = remoteDomainSetAutostart,
5349 5350 5351
    .domainGetSchedulerType = remoteDomainGetSchedulerType,
    .domainGetSchedulerParameters = remoteDomainGetSchedulerParameters,
    .domainSetSchedulerParameters = remoteDomainSetSchedulerParameters,
5352 5353 5354
    .domainMigratePrepare = remoteDomainMigratePrepare,
    .domainMigratePerform = remoteDomainMigratePerform,
    .domainMigrateFinish = remoteDomainMigrateFinish,
5355 5356
    .domainBlockStats = remoteDomainBlockStats,
    .domainInterfaceStats = remoteDomainInterfaceStats,
5357
    .domainBlockPeek = remoteDomainBlockPeek,
R
Richard W.M. Jones 已提交
5358
    .domainMemoryPeek = remoteDomainMemoryPeek,
5359 5360
    .nodeGetCellsFreeMemory = remoteNodeGetCellsFreeMemory,
    .getFreeMemory = remoteNodeGetFreeMemory,
5361 5362
    .domainEventRegister = remoteDomainEventRegister,
    .domainEventDeregister = remoteDomainEventDeregister,
D
Daniel Veillard 已提交
5363 5364
    .domainMigratePrepare2 = remoteDomainMigratePrepare2,
    .domainMigrateFinish2 = remoteDomainMigrateFinish2,
5365 5366 5367
};

static virNetworkDriver network_driver = {
5368
    .name = "remote",
5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387
    .open = remoteNetworkOpen,
    .close = remoteNetworkClose,
    .numOfNetworks = remoteNumOfNetworks,
    .listNetworks = remoteListNetworks,
    .numOfDefinedNetworks = remoteNumOfDefinedNetworks,
    .listDefinedNetworks = remoteListDefinedNetworks,
    .networkLookupByUUID = remoteNetworkLookupByUUID,
    .networkLookupByName = remoteNetworkLookupByName,
    .networkCreateXML = remoteNetworkCreateXML,
    .networkDefineXML = remoteNetworkDefineXML,
    .networkUndefine = remoteNetworkUndefine,
    .networkCreate = remoteNetworkCreate,
    .networkDestroy = remoteNetworkDestroy,
    .networkDumpXML = remoteNetworkDumpXML,
    .networkGetBridgeName = remoteNetworkGetBridgeName,
    .networkGetAutostart = remoteNetworkGetAutostart,
    .networkSetAutostart = remoteNetworkSetAutostart,
};

5388 5389 5390 5391 5392 5393 5394 5395
static virStorageDriver storage_driver = {
    .name = "remote",
    .open = remoteStorageOpen,
    .close = remoteStorageClose,
    .numOfPools = remoteNumOfStoragePools,
    .listPools = remoteListStoragePools,
    .numOfDefinedPools = remoteNumOfDefinedStoragePools,
    .listDefinedPools = remoteListDefinedStoragePools,
5396
    .findPoolSources = remoteFindStoragePoolSources,
5397
    .poolLookupByName = remoteStoragePoolLookupByName,
5398
    .poolLookupByUUID = remoteStoragePoolLookupByUUID,
5399 5400 5401
    .poolLookupByVolume = remoteStoragePoolLookupByVolume,
    .poolCreateXML = remoteStoragePoolCreateXML,
    .poolDefineXML = remoteStoragePoolDefineXML,
5402
    .poolBuild = remoteStoragePoolBuild,
5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424
    .poolUndefine = remoteStoragePoolUndefine,
    .poolCreate = remoteStoragePoolCreate,
    .poolDestroy = remoteStoragePoolDestroy,
    .poolDelete = remoteStoragePoolDelete,
    .poolRefresh = remoteStoragePoolRefresh,
    .poolGetInfo = remoteStoragePoolGetInfo,
    .poolGetXMLDesc = remoteStoragePoolDumpXML,
    .poolGetAutostart = remoteStoragePoolGetAutostart,
    .poolSetAutostart = remoteStoragePoolSetAutostart,
    .poolNumOfVolumes = remoteStoragePoolNumOfVolumes,
    .poolListVolumes = remoteStoragePoolListVolumes,

    .volLookupByName = remoteStorageVolLookupByName,
    .volLookupByKey = remoteStorageVolLookupByKey,
    .volLookupByPath = remoteStorageVolLookupByPath,
    .volCreateXML = remoteStorageVolCreateXML,
    .volDelete = remoteStorageVolDelete,
    .volGetInfo = remoteStorageVolGetInfo,
    .volGetXMLDesc = remoteStorageVolDumpXML,
    .volGetPath = remoteStorageVolGetPath,
};

5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438
static virDeviceMonitor dev_monitor = {
    .name = "remote",
    .open = remoteDevMonOpen,
    .close = remoteDevMonClose,
    .numOfDevices = remoteNodeNumOfDevices,
    .listDevices = remoteNodeListDevices,
    .deviceLookupByName = remoteNodeDeviceLookupByName,
    .deviceDumpXML = remoteNodeDeviceDumpXML,
    .deviceGetParent = remoteNodeDeviceGetParent,
    .deviceNumOfCaps = remoteNodeDeviceNumOfCaps,
    .deviceListCaps = remoteNodeDeviceListCaps,
};


A
Atsushi SAKAI 已提交
5439
#ifdef WITH_LIBVIRTD
5440
static virStateDriver state_driver = {
5441
    .initialize = remoteStartup,
5442
};
A
Atsushi SAKAI 已提交
5443
#endif
5444 5445


5446
/** remoteRegister:
5447 5448
 *
 * Register driver with libvirt driver system.
5449 5450
 *
 * Returns -1 on error.
5451 5452 5453 5454 5455 5456
 */
int
remoteRegister (void)
{
    if (virRegisterDriver (&driver) == -1) return -1;
    if (virRegisterNetworkDriver (&network_driver) == -1) return -1;
5457
    if (virRegisterStorageDriver (&storage_driver) == -1) return -1;
5458
    if (virRegisterDeviceMonitor (&dev_monitor) == -1) return -1;
A
Atsushi SAKAI 已提交
5459
#ifdef WITH_LIBVIRTD
5460
    if (virRegisterStateDriver (&state_driver) == -1) return -1;
A
Atsushi SAKAI 已提交
5461
#endif
5462 5463 5464

    return 0;
}
5465 5466 5467 5468 5469 5470 5471 5472

/**
 * remoteDomainReadEvent
 *
 * Read the event data off the wire
 */
static int
remoteDomainReadEvent(virConnectPtr conn, XDR *xdr,
5473
                      virDomainPtr *dom, int *event, int *detail)
5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486
{
    remote_domain_event_ret ret;
    memset (&ret, 0, sizeof ret);

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

    *dom = get_nonnull_domain(conn,ret.dom);
    *event = ret.event;
5487
    *detail = ret.detail;
5488 5489 5490 5491 5492 5493 5494 5495

    return 0;
}

static void
remoteDomainProcessEvent(virConnectPtr conn, XDR *xdr)
{
    virDomainPtr dom;
5496
    int event, detail, i;
5497 5498
    struct private_data *priv = conn->privateData;

5499
    if(!remoteDomainReadEvent(conn, xdr, &dom, &event, &detail)) {
5500 5501
        DEBUG0("Calling domain event callbacks (no queue)");
        for(i=0 ; i < priv->callbackList->count ; i++) {
5502 5503 5504 5505
            if (priv->callbackList->callbacks[i] )
                priv->callbackList->callbacks[i]->cb(
                    conn, dom, event, detail,
                    priv->callbackList->callbacks[i]->opaque);
5506 5507 5508 5509 5510 5511 5512 5513
        }
    }
}

static void
remoteDomainQueueEvent(virConnectPtr conn, XDR *xdr)
{
    virDomainPtr dom;
5514
    int event, detail;
5515 5516
    struct private_data *priv = conn->privateData;

5517
    if(!remoteDomainReadEvent(conn, xdr, &dom, &event, &detail))
5518 5519
    {
        if( virDomainEventCallbackQueuePush(priv->domainEvents,
5520
                                            dom, event, detail) < 0 ) {
5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531
            DEBUG("%s", "Error adding event to queue");
        }
    }
}

/** remoteDomainEventFired:
 *
 * The callback for monitoring the remote socket
 * for event data
 */
void
5532 5533
remoteDomainEventFired(int watch,
                       int fd,
5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545
                       int event,
                       void *opaque)
{
    char buffer[REMOTE_MESSAGE_MAX];
    char buffer2[4];
    struct remote_message_header hdr;
    XDR xdr;
    int len;

    virConnectPtr        conn = opaque;
    struct private_data *priv = conn->privateData;

5546
    DEBUG("Event fired %d %d %d %X", watch, fd, event, event);
5547 5548 5549 5550

    if (event & (VIR_EVENT_HANDLE_HANGUP | VIR_EVENT_HANDLE_ERROR)) {
         DEBUG("%s : VIR_EVENT_HANDLE_HANGUP or "
               "VIR_EVENT_HANDLE_ERROR encountered", __FUNCTION__);
5551
         virEventRemoveHandle(watch);
5552 5553 5554
         return;
    }

5555 5556 5557 5558 5559
    if (fd != priv->sock) {
        virEventRemoveHandle(watch);
        return;
    }

5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618
    /* Read and deserialise length word. */
    if (really_read (conn, priv, 0, buffer2, sizeof buffer2) == -1)
        return;

    xdrmem_create (&xdr, buffer2, sizeof buffer2, XDR_DECODE);
    if (!xdr_int (&xdr, &len)) {
        error (conn, VIR_ERR_RPC, _("xdr_int (length word, reply)"));
        return;
    }
    xdr_destroy (&xdr);

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

    if (len < 0 || len > REMOTE_MESSAGE_MAX) {
        error (conn, VIR_ERR_RPC, _("packet received from server too large"));
        return;
    }

    /* Read reply header and what follows (either a ret or an error). */
    if (really_read (conn, priv, 0, buffer, len) == -1) {
        error (conn, VIR_ERR_RPC, _("error reading buffer from memory"));
        return;
    }

    /* Deserialise reply header. */
    xdrmem_create (&xdr, buffer, len, XDR_DECODE);
    if (!xdr_remote_message_header (&xdr, &hdr)) {
        error (conn, VIR_ERR_RPC, _("invalid header in event firing"));
        return;
    }

    if (hdr.proc == REMOTE_PROC_DOMAIN_EVENT &&
        hdr.direction == REMOTE_MESSAGE) {
        DEBUG0("Encountered an async event");
        remoteDomainProcessEvent(conn, &xdr);
    } else {
        DEBUG0("invalid proc in event firing");
        error (conn, VIR_ERR_RPC, _("invalid proc in event firing"));
    }
}

void
remoteDomainEventQueueFlush(int timer ATTRIBUTE_UNUSED, void *opaque)
{
    int i;
    virDomainEventPtr domEvent;
    void *user_data = NULL;
    virConnectPtr conn = opaque;
    struct private_data *priv = conn->privateData;

    while( (domEvent = virDomainEventCallbackQueuePop(priv->domainEvents)) ) {
        DEBUG("   Flushing %p", domEvent);
        for (i=0 ; i < priv->callbackList->count ; i++) {
           if( priv->callbackList->callbacks[i] ) {
               user_data = priv->callbackList->callbacks[i]->opaque;
               priv->callbackList->callbacks[i]->cb(domEvent->dom->conn,
                                                    domEvent->dom,
                                                    domEvent->event,
5619
                                                    domEvent->detail,
5620 5621 5622 5623 5624 5625 5626 5627
                                                    user_data);
           }
        }
        VIR_FREE(domEvent);
    }

    virEventUpdateTimeout(priv->eventFlushTimer, -1);
}