virnetserverclient.c 42.3 KB
Newer Older
1 2 3
/*
 * virnetserverclient.c: generic network RPC server client
 *
4
 * Copyright (C) 2006-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

26
#include "internal.h"
27
#if WITH_SASL
28 29 30 31 32
# include <sasl/sasl.h>
#endif

#include "virnetserverclient.h"

33
#include "virlog.h"
34
#include "virerror.h"
35
#include "viralloc.h"
36
#include "virthread.h"
37
#include "virkeepalive.h"
38
#include "virprobe.h"
39 40
#include "virstring.h"
#include "virutil.h"
41 42 43

#define VIR_FROM_THIS VIR_FROM_RPC

44 45
VIR_LOG_INIT("rpc.netserverclient");

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
/* Allow for filtering of incoming messages to a custom
 * dispatch processing queue, instead of the workers.
 * This allows for certain types of messages to be handled
 * strictly "in order"
 */

typedef struct _virNetServerClientFilter virNetServerClientFilter;
typedef virNetServerClientFilter *virNetServerClientFilterPtr;

struct _virNetServerClientFilter {
    int id;
    virNetServerClientFilterFunc func;
    void *opaque;

    virNetServerClientFilterPtr next;
};


struct _virNetServerClient
{
66
    virObjectLockable parent;
67

68
    bool wantClose;
69
    bool delayedClose;
70 71 72
    virNetSocketPtr sock;
    int auth;
    bool readonly;
73
#if WITH_GNUTLS
74 75
    virNetTLSContextPtr tlsCtxt;
    virNetTLSSessionPtr tls;
76
#endif
77
#if WITH_SASL
78 79
    virNetSASLSessionPtr sasl;
#endif
M
Michal Privoznik 已提交
80 81
    int sockTimer; /* Timer to be fired upon cached data,
                    * so we jump out from poll() immediately */
82

83 84 85

    virIdentityPtr identity;

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
    /* Count of messages in the 'tx' queue,
     * and the server worker pool queue
     * ie RPC calls in progress. Does not count
     * async events which are not used for
     * throttling calculations */
    size_t nrequests;
    size_t nrequests_max;
    /* Zero or one messages being received. Zero if
     * nrequests >= max_clients and throttling */
    virNetMessagePtr rx;
    /* Zero or many messages waiting for transmit
     * back to client, including async events */
    virNetMessagePtr tx;

    /* Filters to capture messages that would otherwise
     * end up on the 'dx' queue */
    virNetServerClientFilterPtr filters;
    int nextFilterID;

    virNetServerClientDispatchFunc dispatchFunc;
    void *dispatchOpaque;

    void *privateData;
109
    virFreeCallback privateDataFreeFunc;
110
    virNetServerClientPrivPreExecRestart privateDataPreExecRestart;
111
    virNetServerClientCloseFunc privateDataCloseFunc;
112 113

    virKeepAlivePtr keepalive;
114 115 116
};


117 118 119 120 121
static virClassPtr virNetServerClientClass;
static void virNetServerClientDispose(void *obj);

static int virNetServerClientOnceInit(void)
{
122
    if (!(virNetServerClientClass = virClassNew(virClassForObjectLockable(),
123
                                                "virNetServerClient",
124 125 126 127 128 129 130 131 132 133
                                                sizeof(virNetServerClient),
                                                virNetServerClientDispose)))
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(virNetServerClient)


134 135
static void virNetServerClientDispatchEvent(virNetSocketPtr sock, int events, void *opaque);
static void virNetServerClientUpdateEvent(virNetServerClientPtr client);
M
Michal Privoznik 已提交
136
static void virNetServerClientDispatchRead(virNetServerClientPtr client);
137 138
static int virNetServerClientSendMessageLocked(virNetServerClientPtr client,
                                               virNetMessagePtr msg);
139 140 141 142 143

/*
 * @client: a locked client object
 */
static int
144 145
virNetServerClientCalculateHandleMode(virNetServerClientPtr client)
{
146 147 148 149
    int mode = 0;


    VIR_DEBUG("tls=%p hs=%d, rx=%p tx=%p",
150
#ifdef WITH_GNUTLS
151 152
              client->tls,
              client->tls ? virNetTLSSessionGetHandshakeStatus(client->tls) : -1,
153 154 155
#else
              NULL, -1,
#endif
156 157 158 159 160
              client->rx,
              client->tx);
    if (!client->sock || client->wantClose)
        return 0;

161
#if WITH_GNUTLS
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
    if (client->tls) {
        switch (virNetTLSSessionGetHandshakeStatus(client->tls)) {
        case VIR_NET_TLS_HANDSHAKE_RECVING:
            mode |= VIR_EVENT_HANDLE_READABLE;
            break;
        case VIR_NET_TLS_HANDSHAKE_SENDING:
            mode |= VIR_EVENT_HANDLE_WRITABLE;
            break;
        default:
        case VIR_NET_TLS_HANDSHAKE_COMPLETE:
            if (client->rx)
                mode |= VIR_EVENT_HANDLE_READABLE;
            if (client->tx)
                mode |= VIR_EVENT_HANDLE_WRITABLE;
        }
    } else {
178
#endif
179 180
        /* If there is a message on the rx queue, and
         * we're not in middle of a delayedClose, then
181
         * we're wanting more input */
182
        if (client->rx && !client->delayedClose)
183 184 185 186 187 188
            mode |= VIR_EVENT_HANDLE_READABLE;

        /* If there are one or more messages to send back to client,
           then monitor for writability on socket */
        if (client->tx)
            mode |= VIR_EVENT_HANDLE_WRITABLE;
189
#if WITH_GNUTLS
190
    }
191
#endif
192
    VIR_DEBUG("mode=%o", mode);
193 194 195 196 197 198 199 200 201 202 203
    return mode;
}

/*
 * @server: a locked or unlocked server object
 * @client: a locked client object
 */
static int virNetServerClientRegisterEvent(virNetServerClientPtr client)
{
    int mode = virNetServerClientCalculateHandleMode(client);

204 205 206 207
    if (!client->sock)
        return -1;

    virObjectRef(client);
208
    VIR_DEBUG("Registering client event callback %d", mode);
209
    if (virNetSocketAddIOCallback(client->sock,
210 211
                                  mode,
                                  virNetServerClientDispatchEvent,
212
                                  client,
213 214
                                  virObjectFreeCallback) < 0) {
        virObjectUnref(client);
215
        return -1;
216
    }
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233

    return 0;
}

/*
 * @client: a locked client object
 */
static void virNetServerClientUpdateEvent(virNetServerClientPtr client)
{
    int mode;

    if (!client->sock)
        return;

    mode = virNetServerClientCalculateHandleMode(client);

    virNetSocketUpdateIOCallback(client->sock, mode);
M
Michal Privoznik 已提交
234 235 236

    if (client->rx && virNetSocketHasCachedData(client->sock))
        virEventUpdateTimeout(client->sockTimer, 0);
237 238 239
}


240 241 242
int virNetServerClientAddFilter(virNetServerClientPtr client,
                                virNetServerClientFilterFunc func,
                                void *opaque)
243 244
{
    virNetServerClientFilterPtr filter;
245
    virNetServerClientFilterPtr *place;
246
    int ret;
247

248
    if (VIR_ALLOC(filter) < 0)
249
        return -1;
250

251
    virObjectLock(client);
252

253 254 255 256
    filter->id = client->nextFilterID++;
    filter->func = func;
    filter->opaque = opaque;

257 258 259 260
    place = &client->filters;
    while (*place)
        place = &(*place)->next;
    *place = filter;
261 262 263

    ret = filter->id;

264
    virObjectUnlock(client);
265

266 267 268
    return ret;
}

269 270
void virNetServerClientRemoveFilter(virNetServerClientPtr client,
                                    int filterID)
271 272 273
{
    virNetServerClientFilterPtr tmp, prev;

274
    virObjectLock(client);
275

276 277 278 279 280 281 282 283 284 285 286 287
    prev = NULL;
    tmp = client->filters;
    while (tmp) {
        if (tmp->id == filterID) {
            if (prev)
                prev->next = tmp->next;
            else
                client->filters = tmp->next;

            VIR_FREE(tmp);
            break;
        }
E
Eric Blake 已提交
288
        prev = tmp;
289 290 291
        tmp = tmp->next;
    }

292
    virObjectUnlock(client);
293 294 295
}


296
#ifdef WITH_GNUTLS
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
/* Check the client's access. */
static int
virNetServerClientCheckAccess(virNetServerClientPtr client)
{
    virNetMessagePtr confirm;

    /* Verify client certificate. */
    if (virNetTLSContextCheckCertificate(client->tlsCtxt, client->tls) < 0)
        return -1;

    if (client->tx) {
        VIR_DEBUG("client had unexpected data pending tx after access check");
        return -1;
    }

312
    if (!(confirm = virNetMessageNew(false)))
313 314 315 316 317 318 319
        return -1;

    /* Checks have succeeded.  Write a '\1' byte back to the client to
     * indicate this (otherwise the socket is abruptly closed).
     * (NB. The '\1' byte is sent in an encrypted record).
     */
    confirm->bufferLength = 1;
320 321 322 323
    if (VIR_ALLOC_N(confirm->buffer, confirm->bufferLength) < 0) {
        virNetMessageFree(confirm);
        return -1;
    }
324 325 326 327 328 329 330
    confirm->bufferOffset = 0;
    confirm->buffer[0] = '\1';

    client->tx = confirm;

    return 0;
}
331 332
#endif

333

M
Michal Privoznik 已提交
334 335 336 337
static void virNetServerClientSockTimerFunc(int timer,
                                            void *opaque)
{
    virNetServerClientPtr client = opaque;
338
    virObjectLock(client);
M
Michal Privoznik 已提交
339 340 341 342 343
    virEventUpdateTimeout(timer, -1);
    /* Although client->rx != NULL when this timer is enabled, it might have
     * changed since the client was unlocked in the meantime. */
    if (client->rx)
        virNetServerClientDispatchRead(client);
344
    virObjectUnlock(client);
M
Michal Privoznik 已提交
345 346
}

347

348 349 350
static virNetServerClientPtr
virNetServerClientNewInternal(virNetSocketPtr sock,
                              int auth,
351
#ifdef WITH_GNUTLS
352 353
                              virNetTLSContextPtr tls,
#endif
354
                              bool readonly,
355
                              size_t nrequests_max)
356 357 358
{
    virNetServerClientPtr client;

359
    if (virNetServerClientInitialize() < 0)
360 361
        return NULL;

362
    if (!(client = virObjectLockableNew(virNetServerClientClass)))
363 364
        return NULL;

365
    client->sock = virObjectRef(sock);
366 367
    client->auth = auth;
    client->readonly = readonly;
368
#ifdef WITH_GNUTLS
369
    client->tlsCtxt = virObjectRef(tls);
370
#endif
371
    client->nrequests_max = nrequests_max;
372

M
Michal Privoznik 已提交
373 374 375 376 377
    client->sockTimer = virEventAddTimeout(-1, virNetServerClientSockTimerFunc,
                                           client, NULL);
    if (client->sockTimer < 0)
        goto error;

378
    /* Prepare one for packet receive */
379
    if (!(client->rx = virNetMessageNew(true)))
380 381
        goto error;
    client->rx->bufferLength = VIR_NET_MESSAGE_LEN_MAX;
382
    if (VIR_ALLOC_N(client->rx->buffer, client->rx->bufferLength) < 0)
383
        goto error;
384 385
    client->nrequests = 1;

386
    PROBE(RPC_SERVER_CLIENT_NEW,
387 388
          "client=%p sock=%p",
          client, client->sock);
389 390 391

    return client;

392
 error:
393
    virObjectUnref(client);
394 395 396 397
    return NULL;
}


398 399 400 401
virNetServerClientPtr virNetServerClientNew(virNetSocketPtr sock,
                                            int auth,
                                            bool readonly,
                                            size_t nrequests_max,
402
#ifdef WITH_GNUTLS
403
                                            virNetTLSContextPtr tls,
404
#endif
405
                                            virNetServerClientPrivNew privNew,
406
                                            virNetServerClientPrivPreExecRestart privPreExecRestart,
407 408 409 410 411
                                            virFreeCallback privFree,
                                            void *privOpaque)
{
    virNetServerClientPtr client;

412
    VIR_DEBUG("sock=%p auth=%d tls=%p", sock, auth,
413
#ifdef WITH_GNUTLS
414 415 416 417 418
              tls
#else
              NULL
#endif
        );
419

420
    if (!(client = virNetServerClientNewInternal(sock, auth,
421
#ifdef WITH_GNUTLS
422 423 424
                                                 tls,
#endif
                                                 readonly, nrequests_max)))
425 426 427 428 429 430 431 432
        return NULL;

    if (privNew) {
        if (!(client->privateData = privNew(client, privOpaque))) {
            virObjectUnref(client);
            return NULL;
        }
        client->privateDataFreeFunc = privFree;
433
        client->privateDataPreExecRestart = privPreExecRestart;
434 435 436 437 438 439
    }

    return client;
}


440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
virNetServerClientPtr virNetServerClientNewPostExecRestart(virJSONValuePtr object,
                                                           virNetServerClientPrivNewPostExecRestart privNew,
                                                           virNetServerClientPrivPreExecRestart privPreExecRestart,
                                                           virFreeCallback privFree,
                                                           void *privOpaque)
{
    virJSONValuePtr child;
    virNetServerClientPtr client = NULL;
    virNetSocketPtr sock;
    int auth;
    bool readonly;
    unsigned int nrequests_max;

    if (virJSONValueObjectGetNumberInt(object, "auth", &auth) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing auth field in JSON state document"));
        return NULL;
    }
    if (virJSONValueObjectGetBoolean(object, "readonly", &readonly) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing readonly field in JSON state document"));
        return NULL;
    }
    if (virJSONValueObjectGetNumberUint(object, "nrequests_max",
                                        (unsigned int *)&nrequests_max) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing nrequests_client_max field in JSON state document"));
        return NULL;
    }

    if (!(child = virJSONValueObjectGet(object, "sock"))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing sock field in JSON state document"));
        return NULL;
    }

    if (!(sock = virNetSocketNewPostExecRestart(child))) {
        virObjectUnref(sock);
        return NULL;
    }

    if (!(client = virNetServerClientNewInternal(sock,
                                                 auth,
483
#ifdef WITH_GNUTLS
484 485
                                                 NULL,
#endif
486
                                                 readonly,
487
                                                 nrequests_max))) {
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
        virObjectUnref(sock);
        return NULL;
    }
    virObjectUnref(sock);

    if (privNew) {
        if (!(child = virJSONValueObjectGet(object, "privateData"))) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing privateData field in JSON state document"));
            goto error;
        }
        if (!(client->privateData = privNew(client, child, privOpaque))) {
            goto error;
        }
        client->privateDataFreeFunc = privFree;
        client->privateDataPreExecRestart = privPreExecRestart;
    }


    return client;

509
 error:
510 511 512 513 514 515 516 517 518 519 520 521 522
    virObjectUnref(client);
    return NULL;
}


virJSONValuePtr virNetServerClientPreExecRestart(virNetServerClientPtr client)
{
    virJSONValuePtr object = virJSONValueNewObject();
    virJSONValuePtr child;

    if (!object)
        return NULL;

523
    virObjectLock(client);
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548

    if (virJSONValueObjectAppendNumberInt(object, "auth", client->auth) < 0)
        goto error;
    if (virJSONValueObjectAppendBoolean(object, "readonly", client->readonly) < 0)
        goto error;
    if (virJSONValueObjectAppendNumberUint(object, "nrequests_max", client->nrequests_max) < 0)
        goto error;

    if (!(child = virNetSocketPreExecRestart(client->sock)))
        goto error;

    if (virJSONValueObjectAppend(object, "sock", child) < 0) {
        virJSONValueFree(child);
        goto error;
    }

    if (client->privateData && client->privateDataPreExecRestart &&
        !(child = client->privateDataPreExecRestart(client, client->privateData)))
        goto error;

    if (virJSONValueObjectAppend(object, "privateData", child) < 0) {
        virJSONValueFree(child);
        goto error;
    }

549
    virObjectUnlock(client);
550 551
    return object;

552
 error:
553
    virObjectUnlock(client);
554 555 556 557 558
    virJSONValueFree(object);
    return NULL;
}


559 560 561
int virNetServerClientGetAuth(virNetServerClientPtr client)
{
    int auth;
562
    virObjectLock(client);
563
    auth = client->auth;
564
    virObjectUnlock(client);
565 566 567
    return auth;
}

568 569 570 571 572 573 574
void virNetServerClientSetAuth(virNetServerClientPtr client, int auth)
{
    virObjectLock(client);
    client->auth = auth;
    virObjectUnlock(client);
}

575 576 577
bool virNetServerClientGetReadonly(virNetServerClientPtr client)
{
    bool readonly;
578
    virObjectLock(client);
579
    readonly = client->readonly;
580
    virObjectUnlock(client);
581 582 583 584
    return readonly;
}


585
#ifdef WITH_GNUTLS
586 587 588
bool virNetServerClientHasTLSSession(virNetServerClientPtr client)
{
    bool has;
589
    virObjectLock(client);
590
    has = client->tls ? true : false;
591
    virObjectUnlock(client);
592 593 594
    return has;
}

595 596 597 598 599 600 601 602 603 604

virNetTLSSessionPtr virNetServerClientGetTLSSession(virNetServerClientPtr client)
{
    virNetTLSSessionPtr tls;
    virObjectLock(client);
    tls = client->tls;
    virObjectUnlock(client);
    return tls;
}

605 606 607
int virNetServerClientGetTLSKeySize(virNetServerClientPtr client)
{
    int size = 0;
608
    virObjectLock(client);
609 610
    if (client->tls)
        size = virNetTLSSessionGetKeySize(client->tls);
611
    virObjectUnlock(client);
612 613
    return size;
}
614
#endif
615 616 617

int virNetServerClientGetFD(virNetServerClientPtr client)
{
618
    int fd = -1;
619
    virObjectLock(client);
620 621
    if (client->sock)
        fd = virNetSocketGetFD(client->sock);
622
    virObjectUnlock(client);
623 624 625
    return fd;
}

626 627 628 629 630 631 632 633 634 635 636 637

bool virNetServerClientIsLocal(virNetServerClientPtr client)
{
    bool local = false;
    virObjectLock(client);
    if (client->sock)
        local = virNetSocketIsLocal(client->sock);
    virObjectUnlock(client);
    return local;
}


638
int virNetServerClientGetUNIXIdentity(virNetServerClientPtr client,
639 640
                                      uid_t *uid, gid_t *gid, pid_t *pid,
                                      unsigned long long *timestamp)
641
{
642
    int ret = -1;
643
    virObjectLock(client);
644
    if (client->sock)
645 646 647
        ret = virNetSocketGetUNIXIdentity(client->sock,
                                          uid, gid, pid,
                                          timestamp);
648
    virObjectUnlock(client);
649 650 651
    return ret;
}

652

653 654 655 656
static virIdentityPtr
virNetServerClientCreateIdentity(virNetServerClientPtr client)
{
    char *processid = NULL;
657
    char *processtime = NULL;
658
    char *username = NULL;
659
    char *userid = NULL;
660
    char *groupname = NULL;
661
    char *groupid = NULL;
662 663 664
#if WITH_SASL
    char *saslname = NULL;
#endif
665
#if WITH_GNUTLS
666
    char *x509dname = NULL;
667
#endif
668 669 670 671 672 673 674
    char *seccontext = NULL;
    virIdentityPtr ret = NULL;

    if (client->sock && virNetSocketIsLocal(client->sock)) {
        gid_t gid;
        uid_t uid;
        pid_t pid;
675 676 677 678
        unsigned long long timestamp;
        if (virNetSocketGetUNIXIdentity(client->sock,
                                        &uid, &gid, &pid,
                                        &timestamp) < 0)
679 680 681 682
            goto cleanup;

        if (!(username = virGetUserName(uid)))
            goto cleanup;
683 684
        if (virAsprintf(&userid, "%d", (int)uid) < 0)
            goto cleanup;
685 686
        if (!(groupname = virGetGroupName(gid)))
            goto cleanup;
687
        if (virAsprintf(&groupid, "%d", (int)gid) < 0)
688
            goto cleanup;
689
        if (virAsprintf(&processid, "%llu",
690
                        (unsigned long long)pid) < 0)
691 692
            goto cleanup;
        if (virAsprintf(&processtime, "%llu",
693
                        timestamp) < 0)
694 695 696 697 698 699
            goto cleanup;
    }

#if WITH_SASL
    if (client->sasl) {
        const char *identity = virNetSASLSessionGetIdentity(client->sasl);
700
        if (VIR_STRDUP(saslname, identity) < 0)
701 702 703 704
            goto cleanup;
    }
#endif

705
#if WITH_GNUTLS
706 707
    if (client->tls) {
        const char *identity = virNetTLSSessionGetX509DName(client->tls);
708
        if (VIR_STRDUP(x509dname, identity) < 0)
709 710
            goto cleanup;
    }
711
#endif
712 713

    if (client->sock &&
714
        virNetSocketGetSELinuxContext(client->sock, &seccontext) < 0)
715 716 717 718 719 720 721 722 723 724
        goto cleanup;

    if (!(ret = virIdentityNew()))
        goto cleanup;

    if (username &&
        virIdentitySetAttr(ret,
                           VIR_IDENTITY_ATTR_UNIX_USER_NAME,
                           username) < 0)
        goto error;
725 726 727 728 729
    if (userid &&
        virIdentitySetAttr(ret,
                           VIR_IDENTITY_ATTR_UNIX_USER_ID,
                           userid) < 0)
        goto error;
730 731 732 733 734
    if (groupname &&
        virIdentitySetAttr(ret,
                           VIR_IDENTITY_ATTR_UNIX_GROUP_NAME,
                           groupname) < 0)
        goto error;
735 736 737 738 739
    if (groupid &&
        virIdentitySetAttr(ret,
                           VIR_IDENTITY_ATTR_UNIX_GROUP_ID,
                           groupid) < 0)
        goto error;
740 741 742 743 744
    if (processid &&
        virIdentitySetAttr(ret,
                           VIR_IDENTITY_ATTR_UNIX_PROCESS_ID,
                           processid) < 0)
        goto error;
745 746 747 748 749
    if (processtime &&
        virIdentitySetAttr(ret,
                           VIR_IDENTITY_ATTR_UNIX_PROCESS_TIME,
                           processtime) < 0)
        goto error;
750
#if WITH_SASL
751 752 753 754 755 756
    if (saslname &&
        virIdentitySetAttr(ret,
                           VIR_IDENTITY_ATTR_SASL_USER_NAME,
                           saslname) < 0)
        goto error;
#endif
757
#if WITH_GNUTLS
758 759 760 761 762
    if (x509dname &&
        virIdentitySetAttr(ret,
                           VIR_IDENTITY_ATTR_X509_DISTINGUISHED_NAME,
                           x509dname) < 0)
        goto error;
763
#endif
764 765
    if (seccontext &&
        virIdentitySetAttr(ret,
766
                           VIR_IDENTITY_ATTR_SELINUX_CONTEXT,
767 768 769
                           seccontext) < 0)
        goto error;

770
 cleanup:
771
    VIR_FREE(username);
772
    VIR_FREE(userid);
773
    VIR_FREE(groupname);
774
    VIR_FREE(groupid);
775
    VIR_FREE(processid);
776
    VIR_FREE(processtime);
777
    VIR_FREE(seccontext);
778
#if WITH_SASL
779 780
    VIR_FREE(saslname);
#endif
781
#if WITH_GNUTLS
782
    VIR_FREE(x509dname);
783
#endif
784 785
    return ret;

786
 error:
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
    virObjectUnref(ret);
    ret = NULL;
    goto cleanup;
}


virIdentityPtr virNetServerClientGetIdentity(virNetServerClientPtr client)
{
    virIdentityPtr ret = NULL;
    virObjectLock(client);
    if (!client->identity)
        client->identity = virNetServerClientCreateIdentity(client);
    if (client->identity)
        ret = virObjectRef(client->identity);
    virObjectUnlock(client);
    return ret;
}


806 807
int virNetServerClientGetSELinuxContext(virNetServerClientPtr client,
                                        char **context)
808 809 810 811 812
{
    int ret = 0;
    *context = NULL;
    virObjectLock(client);
    if (client->sock)
813
        ret = virNetSocketGetSELinuxContext(client->sock, context);
814 815 816 817 818
    virObjectUnlock(client);
    return ret;
}


819 820 821
bool virNetServerClientIsSecure(virNetServerClientPtr client)
{
    bool secure = false;
822
    virObjectLock(client);
823
#if WITH_GNUTLS
824 825
    if (client->tls)
        secure = true;
826
#endif
827
#if WITH_SASL
828 829 830
    if (client->sasl)
        secure = true;
#endif
831
    if (client->sock && virNetSocketIsLocal(client->sock))
832
        secure = true;
833
    virObjectUnlock(client);
834 835 836 837
    return secure;
}


838
#if WITH_SASL
839 840 841 842 843 844 845 846
void virNetServerClientSetSASLSession(virNetServerClientPtr client,
                                      virNetSASLSessionPtr sasl)
{
    /* We don't set the sasl session on the socket here
     * because we need to send out the auth confirmation
     * in the clear. Only once we complete the next 'tx'
     * operation do we switch to SASL mode
     */
847
    virObjectLock(client);
848
    client->sasl = virObjectRef(sasl);
849
    virObjectUnlock(client);
850
}
851 852 853 854 855 856 857 858 859 860


virNetSASLSessionPtr virNetServerClientGetSASLSession(virNetServerClientPtr client)
{
    virNetSASLSessionPtr sasl;
    virObjectLock(client);
    sasl = client->sasl;
    virObjectUnlock(client);
    return sasl;
}
861 862 863 864 865 866
#endif


void *virNetServerClientGetPrivateData(virNetServerClientPtr client)
{
    void *data;
867
    virObjectLock(client);
868
    data = client->privateData;
869
    virObjectUnlock(client);
870 871 872 873
    return data;
}


874 875 876
void virNetServerClientSetCloseHook(virNetServerClientPtr client,
                                    virNetServerClientCloseFunc cf)
{
877
    virObjectLock(client);
878
    client->privateDataCloseFunc = cf;
879
    virObjectUnlock(client);
880 881 882
}


883 884 885 886
void virNetServerClientSetDispatcher(virNetServerClientPtr client,
                                     virNetServerClientDispatchFunc func,
                                     void *opaque)
{
887
    virObjectLock(client);
888 889
    client->dispatchFunc = func;
    client->dispatchOpaque = opaque;
890
    virObjectUnlock(client);
891 892 893 894 895
}


const char *virNetServerClientLocalAddrString(virNetServerClientPtr client)
{
896 897
    if (!client->sock)
        return NULL;
898 899 900 901 902 903
    return virNetSocketLocalAddrString(client->sock);
}


const char *virNetServerClientRemoteAddrString(virNetServerClientPtr client)
{
904 905
    if (!client->sock)
        return NULL;
906 907 908 909
    return virNetSocketRemoteAddrString(client->sock);
}


910
void virNetServerClientDispose(void *obj)
911
{
912
    virNetServerClientPtr client = obj;
913

914 915 916
    PROBE(RPC_SERVER_CLIENT_DISPOSE,
          "client=%p", client);

917 918
    virObjectUnref(client->identity);

919 920 921 922
    if (client->privateData &&
        client->privateDataFreeFunc)
        client->privateDataFreeFunc(client->privateData);

923
#if WITH_SASL
924
    virObjectUnref(client->sasl);
925
#endif
M
Michal Privoznik 已提交
926 927
    if (client->sockTimer > 0)
        virEventRemoveTimeout(client->sockTimer);
928
#if WITH_GNUTLS
929 930
    virObjectUnref(client->tls);
    virObjectUnref(client->tlsCtxt);
931
#endif
932
    virObjectUnref(client->sock);
933
    virObjectUnlock(client);
934 935 936 937 938 939 940 941 942 943 944 945 946
}


/*
 *
 * We don't free stuff here, merely disconnect the client's
 * network socket & resources.
 *
 * Full free of the client is done later in a safe point
 * where it can be guaranteed it is no longer in use
 */
void virNetServerClientClose(virNetServerClientPtr client)
{
947
    virNetServerClientCloseFunc cf;
948
    virKeepAlivePtr ka;
949

950
    virObjectLock(client);
951
    VIR_DEBUG("client=%p", client);
952
    if (!client->sock) {
953
        virObjectUnlock(client);
954 955 956
        return;
    }

957 958 959 960
    if (client->keepalive) {
        virKeepAliveStop(client->keepalive);
        ka = client->keepalive;
        client->keepalive = NULL;
961
        virObjectRef(client);
962
        virObjectUnlock(client);
963
        virObjectUnref(ka);
964
        virObjectLock(client);
965
        virObjectUnref(client);
966 967
    }

968 969
    if (client->privateDataCloseFunc) {
        cf = client->privateDataCloseFunc;
970
        virObjectRef(client);
971
        virObjectUnlock(client);
972
        (cf)(client);
973
        virObjectLock(client);
974
        virObjectUnref(client);
975 976
    }

977 978 979 980 981 982
    /* Do now, even though we don't close the socket
     * until end, to ensure we don't get invoked
     * again due to tls shutdown */
    if (client->sock)
        virNetSocketRemoveIOCallback(client->sock);

983
#if WITH_GNUTLS
984
    if (client->tls) {
985
        virObjectUnref(client->tls);
986 987
        client->tls = NULL;
    }
988
#endif
989
    client->wantClose = true;
990 991 992 993 994 995 996 997 998 999 1000 1001

    while (client->rx) {
        virNetMessagePtr msg
            = virNetMessageQueueServe(&client->rx);
        virNetMessageFree(msg);
    }
    while (client->tx) {
        virNetMessagePtr msg
            = virNetMessageQueueServe(&client->tx);
        virNetMessageFree(msg);
    }

1002
    if (client->sock) {
1003
        virObjectUnref(client->sock);
1004 1005 1006
        client->sock = NULL;
    }

1007
    virObjectUnlock(client);
1008 1009 1010 1011 1012 1013
}


bool virNetServerClientIsClosed(virNetServerClientPtr client)
{
    bool closed;
1014
    virObjectLock(client);
1015
    closed = client->sock == NULL ? true : false;
1016
    virObjectUnlock(client);
1017 1018 1019
    return closed;
}

1020 1021
void virNetServerClientDelayedClose(virNetServerClientPtr client)
{
1022
    virObjectLock(client);
1023
    client->delayedClose = true;
1024
    virObjectUnlock(client);
1025 1026 1027
}

void virNetServerClientImmediateClose(virNetServerClientPtr client)
1028
{
1029
    virObjectLock(client);
1030
    client->wantClose = true;
1031
    virObjectUnlock(client);
1032 1033 1034 1035 1036
}

bool virNetServerClientWantClose(virNetServerClientPtr client)
{
    bool wantClose;
1037
    virObjectLock(client);
1038
    wantClose = client->wantClose;
1039
    virObjectUnlock(client);
1040 1041 1042 1043 1044 1045
    return wantClose;
}


int virNetServerClientInit(virNetServerClientPtr client)
{
1046
    virObjectLock(client);
1047

1048
#if WITH_GNUTLS
1049
    if (!client->tlsCtxt) {
1050
#endif
1051 1052 1053
        /* Plain socket, so prepare to read first message */
        if (virNetServerClientRegisterEvent(client) < 0)
            goto error;
1054
#if WITH_GNUTLS
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
    } else {
        int ret;

        if (!(client->tls = virNetTLSSessionNew(client->tlsCtxt,
                                                NULL)))
            goto error;

        virNetSocketSetTLSSession(client->sock,
                                  client->tls);

        /* Begin the TLS handshake. */
        ret = virNetTLSSessionHandshake(client->tls);
        if (ret == 0) {
            /* Unlikely, but ...  Next step is to check the certificate. */
            if (virNetServerClientCheckAccess(client) < 0)
                goto error;

            /* Handshake & cert check OK,  so prepare to read first message */
            if (virNetServerClientRegisterEvent(client) < 0)
                goto error;
        } else if (ret > 0) {
            /* Most likely, need to do more handshake data */
            if (virNetServerClientRegisterEvent(client) < 0)
                goto error;
        } else {
            goto error;
        }
    }
1083
#endif
1084

1085
    virObjectUnlock(client);
1086 1087
    return 0;

1088
 error:
1089
    client->wantClose = true;
1090
    virObjectUnlock(client);
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    return -1;
}



/*
 * Read data into buffer using wire decoding (plain or TLS)
 *
 * Returns:
 *   -1 on error or EOF
 *    0 on EAGAIN
 *    n number of bytes
 */
static ssize_t virNetServerClientRead(virNetServerClientPtr client)
{
    ssize_t ret;

    if (client->rx->bufferLength <= client->rx->bufferOffset) {
1109 1110 1111
        virReportError(VIR_ERR_RPC,
                       _("unexpected zero/negative length request %lld"),
                       (long long int)(client->rx->bufferLength - client->rx->bufferOffset));
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
        client->wantClose = true;
        return -1;
    }

    ret = virNetSocketRead(client->sock,
                           client->rx->buffer + client->rx->bufferOffset,
                           client->rx->bufferLength - client->rx->bufferOffset);

    if (ret <= 0)
        return ret;

    client->rx->bufferOffset += ret;
    return ret;
}


/*
 * Read data until we get a complete message to process
 */
static void virNetServerClientDispatchRead(virNetServerClientPtr client)
{
1133
 readmore:
1134 1135 1136 1137 1138
    if (client->rx->nfds == 0) {
        if (virNetServerClientRead(client) < 0) {
            client->wantClose = true;
            return; /* Error */
        }
1139 1140 1141 1142 1143 1144 1145
    }

    if (client->rx->bufferOffset < client->rx->bufferLength)
        return; /* Still not read enough */

    /* Either done with length word header */
    if (client->rx->bufferLength == VIR_NET_MESSAGE_LEN_MAX) {
1146 1147
        if (virNetMessageDecodeLength(client->rx) < 0) {
            client->wantClose = true;
1148
            return;
1149
        }
1150 1151 1152 1153 1154 1155 1156 1157 1158

        virNetServerClientUpdateEvent(client);

        /* Try and read payload immediately instead of going back
           into poll() because chances are the data is already
           waiting for us */
        goto readmore;
    } else {
        /* Grab the completed message */
1159
        virNetMessagePtr msg = client->rx;
1160
        virNetMessagePtr response = NULL;
1161
        virNetServerClientFilterPtr filter;
1162
        size_t i;
1163 1164 1165

        /* Decode the header so we can use it for routing decisions */
        if (virNetMessageDecodeHeader(msg) < 0) {
1166
            virNetMessageQueueServe(&client->rx);
1167 1168 1169 1170 1171
            virNetMessageFree(msg);
            client->wantClose = true;
            return;
        }

1172 1173
        /* Now figure out if we need to read more data to get some
         * file descriptors */
1174 1175
        if (msg->header.type == VIR_NET_CALL_WITH_FDS &&
            virNetMessageDecodeNumFDs(msg) < 0) {
1176
            virNetMessageQueueServe(&client->rx);
1177 1178
            virNetMessageFree(msg);
            client->wantClose = true;
1179
            return; /* Error */
1180
        }
1181 1182

        /* Try getting the file descriptors (may fail if blocking) */
1183
        for (i = msg->donefds; i < msg->nfds; i++) {
1184 1185
            int rv;
            if ((rv = virNetSocketRecvFD(client->sock, &(msg->fds[i]))) < 0) {
1186
                virNetMessageQueueServe(&client->rx);
1187 1188 1189 1190
                virNetMessageFree(msg);
                client->wantClose = true;
                return;
            }
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
            if (rv == 0) /* Blocking */
                break;
            msg->donefds++;
        }

        /* Need to poll() until FDs arrive */
        if (msg->donefds < msg->nfds) {
            /* Because DecodeHeader/NumFDs reset bufferOffset, we
             * put it back to what it was, so everything works
             * again next time we run this method
             */
            client->rx->bufferOffset = client->rx->bufferLength;
            return;
1204 1205
        }

1206 1207
        /* Definitely finished reading, so remove from queue */
        virNetMessageQueueServe(&client->rx);
1208 1209 1210 1211 1212 1213
        PROBE(RPC_SERVER_CLIENT_MSG_RX,
              "client=%p len=%zu prog=%u vers=%u proc=%u type=%u status=%u serial=%u",
              client, msg->bufferLength,
              msg->header.prog, msg->header.vers, msg->header.proc,
              msg->header.type, msg->header.status, msg->header.serial);

1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
        if (virKeepAliveCheckMessage(client->keepalive, msg, &response)) {
            virNetMessageFree(msg);
            client->nrequests--;
            msg = NULL;

            if (response &&
                virNetServerClientSendMessageLocked(client, response) < 0)
                virNetMessageFree(response);
        }

1224
        /* Maybe send off for queue against a filter */
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
        if (msg) {
            filter = client->filters;
            while (filter) {
                int ret = filter->func(client, msg, filter->opaque);
                if (ret < 0) {
                    virNetMessageFree(msg);
                    msg = NULL;
                    if (ret < 0)
                        client->wantClose = true;
                    break;
                }
                if (ret > 0) {
                    msg = NULL;
                    break;
                }
1240

1241 1242
                filter = filter->next;
            }
1243 1244 1245 1246
        }

        /* Send off to for normal dispatch to workers */
        if (msg) {
1247
            virObjectRef(client);
1248 1249 1250 1251
            if (!client->dispatchFunc ||
                client->dispatchFunc(client, msg, client->dispatchOpaque) < 0) {
                virNetMessageFree(msg);
                client->wantClose = true;
1252
                virObjectUnref(client);
1253 1254 1255 1256 1257 1258
                return;
            }
        }

        /* Possibly need to create another receive buffer */
        if (client->nrequests < client->nrequests_max) {
1259
            if (!(client->rx = virNetMessageNew(true))) {
1260
                client->wantClose = true;
E
Eric Blake 已提交
1261 1262
            } else {
                client->rx->bufferLength = VIR_NET_MESSAGE_LEN_MAX;
1263 1264 1265 1266 1267 1268
                if (VIR_ALLOC_N(client->rx->buffer,
                                client->rx->bufferLength) < 0) {
                    client->wantClose = true;
                } else {
                    client->nrequests++;
                }
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
            }
        }
        virNetServerClientUpdateEvent(client);
    }
}


/*
 * Send client->tx using no encoding
 *
 * Returns:
 *   -1 on error or EOF
 *    0 on EAGAIN
 *    n number of bytes
 */
static ssize_t virNetServerClientWrite(virNetServerClientPtr client)
{
    ssize_t ret;

    if (client->tx->bufferLength < client->tx->bufferOffset) {
1289 1290 1291
        virReportError(VIR_ERR_RPC,
                       _("unexpected zero/negative length request %lld"),
                       (long long int)(client->tx->bufferLength - client->tx->bufferOffset));
1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
        client->wantClose = true;
        return -1;
    }

    if (client->tx->bufferLength == client->tx->bufferOffset)
        return 1;

    ret = virNetSocketWrite(client->sock,
                            client->tx->buffer + client->tx->bufferOffset,
                            client->tx->bufferLength - client->tx->bufferOffset);
    if (ret <= 0)
        return ret; /* -1 error, 0 = egain */

    client->tx->bufferOffset += ret;
    return ret;
}


/*
 * Process all queued client->tx messages until
 * we would block on I/O
 */
static void
virNetServerClientDispatchWrite(virNetServerClientPtr client)
{
    while (client->tx) {
1318 1319 1320 1321 1322 1323 1324 1325 1326
        if (client->tx->bufferOffset < client->tx->bufferLength) {
            ssize_t ret;
            ret = virNetServerClientWrite(client);
            if (ret < 0) {
                client->wantClose = true;
                return;
            }
            if (ret == 0)
                return; /* Would block on write EAGAIN */
1327 1328 1329 1330
        }

        if (client->tx->bufferOffset == client->tx->bufferLength) {
            virNetMessagePtr msg;
1331 1332
            size_t i;

1333
            for (i = client->tx->donefds; i < client->tx->nfds; i++) {
1334 1335
                int rv;
                if ((rv = virNetSocketSendFD(client->sock, client->tx->fds[i])) < 0) {
1336 1337 1338
                    client->wantClose = true;
                    return;
                }
1339 1340 1341
                if (rv == 0) /* Blocking */
                    return;
                client->tx->donefds++;
1342 1343
            }

1344
#if WITH_SASL
1345 1346 1347 1348 1349
            /* Completed this 'tx' operation, so now read for all
             * future rx/tx to be under a SASL SSF layer
             */
            if (client->sasl) {
                virNetSocketSetSASLSession(client->sock, client->sasl);
1350
                virObjectUnref(client->sasl);
1351 1352 1353 1354 1355 1356 1357
                client->sasl = NULL;
            }
#endif

            /* Get finished msg from head of tx queue */
            msg = virNetMessageQueueServe(&client->tx);

1358
            if (msg->tracked) {
1359 1360 1361 1362 1363
                client->nrequests--;
                /* See if the recv queue is currently throttled */
                if (!client->rx &&
                    client->nrequests < client->nrequests_max) {
                    /* Ready to recv more messages */
1364
                    virNetMessageClear(msg);
1365 1366 1367 1368 1369
                    msg->bufferLength = VIR_NET_MESSAGE_LEN_MAX;
                    if (VIR_ALLOC_N(msg->buffer, msg->bufferLength) < 0) {
                        virNetMessageFree(msg);
                        return;
                    }
1370 1371 1372 1373 1374 1375 1376 1377 1378
                    client->rx = msg;
                    msg = NULL;
                    client->nrequests++;
                }
            }

            virNetMessageFree(msg);

            virNetServerClientUpdateEvent(client);
1379 1380 1381

            if (client->delayedClose)
                client->wantClose = true;
1382 1383 1384 1385
         }
    }
}

1386

1387
#if WITH_GNUTLS
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
static void
virNetServerClientDispatchHandshake(virNetServerClientPtr client)
{
    int ret;
    /* Continue the handshake. */
    ret = virNetTLSSessionHandshake(client->tls);
    if (ret == 0) {
        /* Finished.  Next step is to check the certificate. */
        if (virNetServerClientCheckAccess(client) < 0)
            client->wantClose = true;
        else
            virNetServerClientUpdateEvent(client);
    } else if (ret > 0) {
        /* Carry on waiting for more handshake. Update
           the events just in case handshake data flow
           direction has changed */
1404
        virNetServerClientUpdateEvent(client);
1405 1406 1407 1408 1409
    } else {
        /* Fatal error in handshake */
        client->wantClose = true;
    }
}
1410
#endif
1411 1412 1413 1414 1415 1416

static void
virNetServerClientDispatchEvent(virNetSocketPtr sock, int events, void *opaque)
{
    virNetServerClientPtr client = opaque;

1417
    virObjectLock(client);
1418 1419 1420

    if (client->sock != sock) {
        virNetSocketRemoveIOCallback(sock);
1421
        virObjectUnlock(client);
1422 1423 1424 1425 1426
        return;
    }

    if (events & (VIR_EVENT_HANDLE_WRITABLE |
                  VIR_EVENT_HANDLE_READABLE)) {
1427
#if WITH_GNUTLS
1428 1429 1430 1431 1432
        if (client->tls &&
            virNetTLSSessionGetHandshakeStatus(client->tls) !=
            VIR_NET_TLS_HANDSHAKE_COMPLETE) {
            virNetServerClientDispatchHandshake(client);
        } else {
1433
#endif
1434 1435
            if (events & VIR_EVENT_HANDLE_WRITABLE)
                virNetServerClientDispatchWrite(client);
M
Michal Privoznik 已提交
1436 1437
            if (events & VIR_EVENT_HANDLE_READABLE &&
                client->rx)
1438
                virNetServerClientDispatchRead(client);
1439
#if WITH_GNUTLS
1440
        }
1441
#endif
1442 1443 1444 1445 1446 1447 1448 1449
    }

    /* NB, will get HANGUP + READABLE at same time upon
     * disconnect */
    if (events & (VIR_EVENT_HANDLE_ERROR |
                  VIR_EVENT_HANDLE_HANGUP))
        client->wantClose = true;

1450
    virObjectUnlock(client);
1451 1452 1453
}


1454 1455 1456
static int
virNetServerClientSendMessageLocked(virNetServerClientPtr client,
                                    virNetMessagePtr msg)
1457 1458 1459 1460 1461
{
    int ret = -1;
    VIR_DEBUG("msg=%p proc=%d len=%zu offset=%zu",
              msg, msg->header.proc,
              msg->bufferLength, msg->bufferOffset);
1462

1463
    msg->donefds = 0;
1464
    if (client->sock && !client->wantClose) {
1465 1466 1467 1468 1469
        PROBE(RPC_SERVER_CLIENT_MSG_TX_QUEUE,
              "client=%p len=%zu prog=%u vers=%u proc=%u type=%u status=%u serial=%u",
              client, msg->bufferLength,
              msg->header.prog, msg->header.vers, msg->header.proc,
              msg->header.type, msg->header.status, msg->header.serial);
1470 1471 1472 1473 1474 1475
        virNetMessageQueuePush(&client->tx, msg);

        virNetServerClientUpdateEvent(client);
        ret = 0;
    }

1476 1477 1478 1479 1480 1481 1482 1483
    return ret;
}

int virNetServerClientSendMessage(virNetServerClientPtr client,
                                  virNetMessagePtr msg)
{
    int ret;

1484
    virObjectLock(client);
1485
    ret = virNetServerClientSendMessageLocked(client, msg);
1486
    virObjectUnlock(client);
1487

1488 1489 1490 1491 1492 1493 1494
    return ret;
}


bool virNetServerClientNeedAuth(virNetServerClientPtr client)
{
    bool need = false;
1495
    virObjectLock(client);
1496
    if (client->auth)
1497
        need = true;
1498
    virObjectUnlock(client);
1499 1500
    return need;
}
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524


static void
virNetServerClientKeepAliveDeadCB(void *opaque)
{
    virNetServerClientImmediateClose(opaque);
}

static int
virNetServerClientKeepAliveSendCB(void *opaque,
                                  virNetMessagePtr msg)
{
    return virNetServerClientSendMessage(opaque, msg);
}


int
virNetServerClientInitKeepAlive(virNetServerClientPtr client,
                                int interval,
                                unsigned int count)
{
    virKeepAlivePtr ka;
    int ret = -1;

1525
    virObjectLock(client);
1526 1527 1528 1529

    if (!(ka = virKeepAliveNew(interval, count, client,
                               virNetServerClientKeepAliveSendCB,
                               virNetServerClientKeepAliveDeadCB,
1530
                               virObjectFreeCallback)))
1531 1532
        goto cleanup;
    /* keepalive object has a reference to client */
1533
    virObjectRef(client);
1534 1535 1536

    client->keepalive = ka;

1537
 cleanup:
1538
    virObjectUnlock(client);
1539 1540 1541 1542 1543 1544 1545

    return ret;
}

int
virNetServerClientStartKeepAlive(virNetServerClientPtr client)
{
1546 1547
    int ret = -1;

1548
    virObjectLock(client);
1549 1550 1551 1552

    /* The connection might have been closed before we got here and thus the
     * keepalive object could have been removed too.
     */
1553
    if (!client->keepalive) {
1554 1555 1556 1557 1558
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("connection not open"));
        goto cleanup;
    }

1559
    ret = virKeepAliveStart(client->keepalive, 0, 0);
1560

1561
 cleanup:
1562
    virObjectUnlock(client);
1563 1564
    return ret;
}