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

#include <config.h>

#if HAVE_SASL
# include <sasl/sasl.h>
#endif

#include "virnetserverclient.h"

#include "logging.h"
#include "virterror_internal.h"
#include "memory.h"
#include "threads.h"
36
#include "virkeepalive.h"
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

#define VIR_FROM_THIS VIR_FROM_RPC

/* 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
{
60 61
    virObject object;

62
    bool wantClose;
63
    bool delayedClose;
64 65 66 67 68 69 70 71 72 73
    virMutex lock;
    virNetSocketPtr sock;
    int auth;
    bool readonly;
    char *identity;
    virNetTLSContextPtr tlsCtxt;
    virNetTLSSessionPtr tls;
#if HAVE_SASL
    virNetSASLSessionPtr sasl;
#endif
M
Michal Privoznik 已提交
74 75
    int sockTimer; /* Timer to be fired upon cached data,
                    * so we jump out from poll() immediately */
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

    /* 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;
100
    virFreeCallback privateDataFreeFunc;
101
    virNetServerClientCloseFunc privateDataCloseFunc;
102 103

    virKeepAlivePtr keepalive;
104 105 106
};


107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
static virClassPtr virNetServerClientClass;
static void virNetServerClientDispose(void *obj);

static int virNetServerClientOnceInit(void)
{
    if (!(virNetServerClientClass = virClassNew("virNetServerClient",
                                                sizeof(virNetServerClient),
                                                virNetServerClientDispose)))
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(virNetServerClient)


123 124
static void virNetServerClientDispatchEvent(virNetSocketPtr sock, int events, void *opaque);
static void virNetServerClientUpdateEvent(virNetServerClientPtr client);
M
Michal Privoznik 已提交
125
static void virNetServerClientDispatchRead(virNetServerClientPtr client);
126 127
static int virNetServerClientSendMessageLocked(virNetServerClientPtr client,
                                               virNetMessagePtr msg);
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

static void virNetServerClientLock(virNetServerClientPtr client)
{
    virMutexLock(&client->lock);
}

static void virNetServerClientUnlock(virNetServerClientPtr client)
{
    virMutexUnlock(&client->lock);
}


/*
 * @client: a locked client object
 */
static int
virNetServerClientCalculateHandleMode(virNetServerClientPtr client) {
    int mode = 0;


    VIR_DEBUG("tls=%p hs=%d, rx=%p tx=%p",
              client->tls,
              client->tls ? virNetTLSSessionGetHandshakeStatus(client->tls) : -1,
              client->rx,
              client->tx);
    if (!client->sock || client->wantClose)
        return 0;

    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 {
172 173
        /* If there is a message on the rx queue, and
         * we're not in middle of a delayedClose, then
174
         * we're wanting more input */
175
        if (client->rx && !client->delayedClose)
176 177 178 179 180 181 182
            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;
    }
183
    VIR_DEBUG("mode=%o", mode);
184 185 186 187 188 189 190 191 192 193 194
    return mode;
}

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

195 196 197 198
    if (!client->sock)
        return -1;

    virObjectRef(client);
199
    VIR_DEBUG("Registering client event callback %d", mode);
200
    if (virNetSocketAddIOCallback(client->sock,
201 202
                                  mode,
                                  virNetServerClientDispatchEvent,
203
                                  client,
204 205
                                  virObjectFreeCallback) < 0) {
        virObjectUnref(client);
206
        return -1;
207
    }
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

    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 已提交
225 226 227

    if (client->rx && virNetSocketHasCachedData(client->sock))
        virEventUpdateTimeout(client->sockTimer, 0);
228 229 230
}


231 232 233
int virNetServerClientAddFilter(virNetServerClientPtr client,
                                virNetServerClientFilterFunc func,
                                void *opaque)
234 235
{
    virNetServerClientFilterPtr filter;
236
    virNetServerClientFilterPtr *place;
237
    int ret;
238 239 240

    if (VIR_ALLOC(filter) < 0) {
        virReportOOMError();
241
        return -1;
242 243
    }

244 245
    virNetServerClientLock(client);

246 247 248 249
    filter->id = client->nextFilterID++;
    filter->func = func;
    filter->opaque = opaque;

250 251 252 253
    place = &client->filters;
    while (*place)
        place = &(*place)->next;
    *place = filter;
254 255 256

    ret = filter->id;

257
    virNetServerClientUnlock(client);
258

259 260 261
    return ret;
}

262 263
void virNetServerClientRemoveFilter(virNetServerClientPtr client,
                                    int filterID)
264 265 266
{
    virNetServerClientFilterPtr tmp, prev;

267 268
    virNetServerClientLock(client);

269 270 271 272 273 274 275 276 277 278 279 280
    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 已提交
281
        prev = tmp;
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
        tmp = tmp->next;
    }

    virNetServerClientUnlock(client);
}


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

304
    if (!(confirm = virNetMessageNew(false)))
305 306 307 308 309 310 311
        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;
312 313 314 315 316
    if (VIR_ALLOC_N(confirm->buffer, confirm->bufferLength) < 0) {
        virReportOOMError();
        virNetMessageFree(confirm);
        return -1;
    }
317 318 319 320 321 322 323 324
    confirm->bufferOffset = 0;
    confirm->buffer[0] = '\1';

    client->tx = confirm;

    return 0;
}

M
Michal Privoznik 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337
static void virNetServerClientSockTimerFunc(int timer,
                                            void *opaque)
{
    virNetServerClientPtr client = opaque;
    virNetServerClientLock(client);
    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);
    virNetServerClientUnlock(client);
}

338

339 340 341 342 343 344
static virNetServerClientPtr
virNetServerClientNewInternal(virNetSocketPtr sock,
                              int auth,
                              bool readonly,
                              size_t nrequests_max,
                              virNetTLSContextPtr tls)
345 346 347
{
    virNetServerClientPtr client;

348
    if (virNetServerClientInitialize() < 0)
349 350
        return NULL;

351 352 353 354 355 356 357
    if (!(client = virObjectNew(virNetServerClientClass)))
        return NULL;

    if (virMutexInit(&client->lock) < 0) {
        VIR_FREE(client);
        return NULL;
    }
358

359
    client->sock = virObjectRef(sock);
360 361
    client->auth = auth;
    client->readonly = readonly;
362
    client->tlsCtxt = virObjectRef(tls);
363
    client->nrequests_max = nrequests_max;
364

M
Michal Privoznik 已提交
365 366 367 368 369
    client->sockTimer = virEventAddTimeout(-1, virNetServerClientSockTimerFunc,
                                           client, NULL);
    if (client->sockTimer < 0)
        goto error;

370
    /* Prepare one for packet receive */
371
    if (!(client->rx = virNetMessageNew(true)))
372 373
        goto error;
    client->rx->bufferLength = VIR_NET_MESSAGE_LEN_MAX;
374 375 376 377
    if (VIR_ALLOC_N(client->rx->buffer, client->rx->bufferLength) < 0) {
        virReportOOMError();
        goto error;
    }
378 379
    client->nrequests = 1;

380
    PROBE(RPC_SERVER_CLIENT_NEW,
381 382
          "client=%p sock=%p",
          client, client->sock);
383 384 385 386

    return client;

error:
387
    virObjectUnref(client);
388 389 390 391
    return NULL;
}


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
virNetServerClientPtr virNetServerClientNew(virNetSocketPtr sock,
                                            int auth,
                                            bool readonly,
                                            size_t nrequests_max,
                                            virNetTLSContextPtr tls,
                                            virNetServerClientPrivNew privNew,
                                            virFreeCallback privFree,
                                            void *privOpaque)
{
    virNetServerClientPtr client;

    VIR_DEBUG("sock=%p auth=%d tls=%p", sock, auth, tls);

    if (!(client = virNetServerClientNewInternal(sock, auth, readonly, nrequests_max, tls)))
        return NULL;

    if (privNew) {
        if (!(client->privateData = privNew(client, privOpaque))) {
            virObjectUnref(client);
            return NULL;
        }
        client->privateDataFreeFunc = privFree;
    }

    return client;
}


420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
int virNetServerClientGetAuth(virNetServerClientPtr client)
{
    int auth;
    virNetServerClientLock(client);
    auth = client->auth;
    virNetServerClientUnlock(client);
    return auth;
}

bool virNetServerClientGetReadonly(virNetServerClientPtr client)
{
    bool readonly;
    virNetServerClientLock(client);
    readonly = client->readonly;
    virNetServerClientUnlock(client);
    return readonly;
}


bool virNetServerClientHasTLSSession(virNetServerClientPtr client)
{
    bool has;
    virNetServerClientLock(client);
    has = client->tls ? true : false;
    virNetServerClientUnlock(client);
    return has;
}

int virNetServerClientGetTLSKeySize(virNetServerClientPtr client)
{
    int size = 0;
    virNetServerClientLock(client);
    if (client->tls)
        size = virNetTLSSessionGetKeySize(client->tls);
    virNetServerClientUnlock(client);
    return size;
}

int virNetServerClientGetFD(virNetServerClientPtr client)
{
460
    int fd = -1;
461
    virNetServerClientLock(client);
462 463
    if (client->sock)
        fd = virNetSocketGetFD(client->sock);
464 465 466 467
    virNetServerClientUnlock(client);
    return fd;
}

468 469
int virNetServerClientGetUNIXIdentity(virNetServerClientPtr client,
                                      uid_t *uid, gid_t *gid, pid_t *pid)
470
{
471
    int ret = -1;
472
    virNetServerClientLock(client);
473
    if (client->sock)
474
        ret = virNetSocketGetUNIXIdentity(client->sock, uid, gid, pid);
475 476 477 478 479 480 481 482 483 484 485 486 487 488
    virNetServerClientUnlock(client);
    return ret;
}

bool virNetServerClientIsSecure(virNetServerClientPtr client)
{
    bool secure = false;
    virNetServerClientLock(client);
    if (client->tls)
        secure = true;
#if HAVE_SASL
    if (client->sasl)
        secure = true;
#endif
489
    if (client->sock && virNetSocketIsLocal(client->sock))
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
        secure = true;
    virNetServerClientUnlock(client);
    return secure;
}


#if HAVE_SASL
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
     */
    virNetServerClientLock(client);
506
    client->sasl = virObjectRef(sasl);
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
    virNetServerClientUnlock(client);
}
#endif


int virNetServerClientSetIdentity(virNetServerClientPtr client,
                                  const char *identity)
{
    int ret = -1;
    virNetServerClientLock(client);
    if (!(client->identity = strdup(identity))) {
        virReportOOMError();
        goto error;
    }
    ret = 0;

error:
    virNetServerClientUnlock(client);
    return ret;
}

const char *virNetServerClientGetIdentity(virNetServerClientPtr client)
{
    const char *identity;
    virNetServerClientLock(client);
    identity = client->identity;
    virNetServerClientLock(client);
    return identity;
}


void *virNetServerClientGetPrivateData(virNetServerClientPtr client)
{
    void *data;
    virNetServerClientLock(client);
    data = client->privateData;
    virNetServerClientUnlock(client);
    return data;
}


548 549 550 551 552 553 554 555 556
void virNetServerClientSetCloseHook(virNetServerClientPtr client,
                                    virNetServerClientCloseFunc cf)
{
    virNetServerClientLock(client);
    client->privateDataCloseFunc = cf;
    virNetServerClientUnlock(client);
}


557 558 559 560 561 562 563 564 565 566 567 568 569
void virNetServerClientSetDispatcher(virNetServerClientPtr client,
                                     virNetServerClientDispatchFunc func,
                                     void *opaque)
{
    virNetServerClientLock(client);
    client->dispatchFunc = func;
    client->dispatchOpaque = opaque;
    virNetServerClientUnlock(client);
}


const char *virNetServerClientLocalAddrString(virNetServerClientPtr client)
{
570 571
    if (!client->sock)
        return NULL;
572 573 574 575 576 577
    return virNetSocketLocalAddrString(client->sock);
}


const char *virNetServerClientRemoteAddrString(virNetServerClientPtr client)
{
578 579
    if (!client->sock)
        return NULL;
580 581 582 583
    return virNetSocketRemoteAddrString(client->sock);
}


584
void virNetServerClientDispose(void *obj)
585
{
586
    virNetServerClientPtr client = obj;
587 588 589 590 591 592 593

    if (client->privateData &&
        client->privateDataFreeFunc)
        client->privateDataFreeFunc(client->privateData);

    VIR_FREE(client->identity);
#if HAVE_SASL
594
    virObjectUnref(client->sasl);
595
#endif
M
Michal Privoznik 已提交
596 597
    if (client->sockTimer > 0)
        virEventRemoveTimeout(client->sockTimer);
598 599
    virObjectUnref(client->tls);
    virObjectUnref(client->tlsCtxt);
600
    virObjectUnref(client->sock);
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
    virNetServerClientUnlock(client);
    virMutexDestroy(&client->lock);
}


/*
 *
 * 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)
{
616
    virNetServerClientCloseFunc cf;
617
    virKeepAlivePtr ka;
618

619
    virNetServerClientLock(client);
620
    VIR_DEBUG("client=%p", client);
621 622 623 624 625
    if (!client->sock) {
        virNetServerClientUnlock(client);
        return;
    }

626 627 628 629
    if (client->keepalive) {
        virKeepAliveStop(client->keepalive);
        ka = client->keepalive;
        client->keepalive = NULL;
630
        virObjectRef(client);
631
        virNetServerClientUnlock(client);
632
        virObjectUnref(ka);
633
        virNetServerClientLock(client);
634
        virObjectUnref(client);
635 636
    }

637 638
    if (client->privateDataCloseFunc) {
        cf = client->privateDataCloseFunc;
639
        virObjectRef(client);
640 641 642
        virNetServerClientUnlock(client);
        (cf)(client);
        virNetServerClientLock(client);
643
        virObjectUnref(client);
644 645
    }

646 647 648 649 650 651 652
    /* 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);

    if (client->tls) {
653
        virObjectUnref(client->tls);
654 655
        client->tls = NULL;
    }
656
    client->wantClose = true;
657 658 659 660 661 662 663 664 665 666 667 668

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

669
    if (client->sock) {
670
        virObjectUnref(client->sock);
671 672 673
        client->sock = NULL;
    }

674 675 676 677 678 679 680 681 682 683 684 685 686
    virNetServerClientUnlock(client);
}


bool virNetServerClientIsClosed(virNetServerClientPtr client)
{
    bool closed;
    virNetServerClientLock(client);
    closed = client->sock == NULL ? true : false;
    virNetServerClientUnlock(client);
    return closed;
}

687 688 689 690 691 692 693 694
void virNetServerClientDelayedClose(virNetServerClientPtr client)
{
    virNetServerClientLock(client);
    client->delayedClose = true;
    virNetServerClientUnlock(client);
}

void virNetServerClientImmediateClose(virNetServerClientPtr client)
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 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 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
{
    virNetServerClientLock(client);
    client->wantClose = true;
    virNetServerClientUnlock(client);
}

bool virNetServerClientWantClose(virNetServerClientPtr client)
{
    bool wantClose;
    virNetServerClientLock(client);
    wantClose = client->wantClose;
    virNetServerClientUnlock(client);
    return wantClose;
}


int virNetServerClientInit(virNetServerClientPtr client)
{
    virNetServerClientLock(client);

    if (!client->tlsCtxt) {
        /* Plain socket, so prepare to read first message */
        if (virNetServerClientRegisterEvent(client) < 0)
            goto error;
    } 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;
        }
    }

    virNetServerClientUnlock(client);
    return 0;

error:
    client->wantClose = true;
    virNetServerClientUnlock(client);
    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) {
772 773 774
        virReportError(VIR_ERR_RPC,
                       _("unexpected zero/negative length request %lld"),
                       (long long int)(client->rx->bufferLength - client->rx->bufferOffset));
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
        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)
{
readmore:
797 798 799 800 801
    if (client->rx->nfds == 0) {
        if (virNetServerClientRead(client) < 0) {
            client->wantClose = true;
            return; /* Error */
        }
802 803 804 805 806 807 808
    }

    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) {
809 810
        if (virNetMessageDecodeLength(client->rx) < 0) {
            client->wantClose = true;
811
            return;
812
        }
813 814 815 816 817 818 819 820 821

        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 */
822
        virNetMessagePtr msg = client->rx;
823
        virNetMessagePtr response = NULL;
824
        virNetServerClientFilterPtr filter;
825
        size_t i;
826 827 828 829 830 831 832 833

        /* Decode the header so we can use it for routing decisions */
        if (virNetMessageDecodeHeader(msg) < 0) {
            virNetMessageFree(msg);
            client->wantClose = true;
            return;
        }

834 835
        /* Now figure out if we need to read more data to get some
         * file descriptors */
836 837 838 839
        if (msg->header.type == VIR_NET_CALL_WITH_FDS &&
            virNetMessageDecodeNumFDs(msg) < 0) {
            virNetMessageFree(msg);
            client->wantClose = true;
840
            return; /* Error */
841
        }
842 843 844 845 846

        /* Try getting the file descriptors (may fail if blocking) */
        for (i = msg->donefds ; i < msg->nfds ; i++) {
            int rv;
            if ((rv = virNetSocketRecvFD(client->sock, &(msg->fds[i]))) < 0) {
847 848 849 850
                virNetMessageFree(msg);
                client->wantClose = true;
                return;
            }
851 852 853 854 855 856 857 858 859 860 861 862 863
            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;
864 865
        }

866 867
        /* Definitely finished reading, so remove from queue */
        virNetMessageQueueServe(&client->rx);
868 869 870 871 872 873
        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);

874 875 876 877 878 879 880 881 882 883
        if (virKeepAliveCheckMessage(client->keepalive, msg, &response)) {
            virNetMessageFree(msg);
            client->nrequests--;
            msg = NULL;

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

884
        /* Maybe send off for queue against a filter */
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
        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;
                }
900

901 902
                filter = filter->next;
            }
903 904 905 906
        }

        /* Send off to for normal dispatch to workers */
        if (msg) {
907
            virObjectRef(client);
908 909 910 911
            if (!client->dispatchFunc ||
                client->dispatchFunc(client, msg, client->dispatchOpaque) < 0) {
                virNetMessageFree(msg);
                client->wantClose = true;
912
                virObjectUnref(client);
913 914 915 916 917 918
                return;
            }
        }

        /* Possibly need to create another receive buffer */
        if (client->nrequests < client->nrequests_max) {
919
            if (!(client->rx = virNetMessageNew(true))) {
920
                client->wantClose = true;
E
Eric Blake 已提交
921 922
            } else {
                client->rx->bufferLength = VIR_NET_MESSAGE_LEN_MAX;
923 924 925 926 927 928 929
                if (VIR_ALLOC_N(client->rx->buffer,
                                client->rx->bufferLength) < 0) {
                    virReportOOMError();
                    client->wantClose = true;
                } else {
                    client->nrequests++;
                }
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
            }
        }
        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) {
950 951 952
        virReportError(VIR_ERR_RPC,
                       _("unexpected zero/negative length request %lld"),
                       (long long int)(client->tx->bufferLength - client->tx->bufferOffset));
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
        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) {
979 980 981 982 983 984 985 986 987
        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 */
988 989 990 991
        }

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

994 995 996
            for (i = client->tx->donefds ; i < client->tx->nfds ; i++) {
                int rv;
                if ((rv = virNetSocketSendFD(client->sock, client->tx->fds[i])) < 0) {
997 998 999
                    client->wantClose = true;
                    return;
                }
1000 1001 1002
                if (rv == 0) /* Blocking */
                    return;
                client->tx->donefds++;
1003 1004
            }

1005 1006 1007 1008 1009 1010
#if HAVE_SASL
            /* 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);
1011
                virObjectUnref(client->sasl);
1012 1013 1014 1015 1016 1017 1018
                client->sasl = NULL;
            }
#endif

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

1019
            if (msg->tracked) {
1020 1021 1022 1023 1024
                client->nrequests--;
                /* See if the recv queue is currently throttled */
                if (!client->rx &&
                    client->nrequests < client->nrequests_max) {
                    /* Ready to recv more messages */
1025
                    virNetMessageClear(msg);
1026 1027 1028 1029 1030 1031
                    msg->bufferLength = VIR_NET_MESSAGE_LEN_MAX;
                    if (VIR_ALLOC_N(msg->buffer, msg->bufferLength) < 0) {
                        virReportOOMError();
                        virNetMessageFree(msg);
                        return;
                    }
1032 1033 1034 1035 1036 1037 1038 1039 1040
                    client->rx = msg;
                    msg = NULL;
                    client->nrequests++;
                }
            }

            virNetMessageFree(msg);

            virNetServerClientUpdateEvent(client);
1041 1042 1043

            if (client->delayedClose)
                client->wantClose = true;
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 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 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
         }
    }
}

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 */
        virNetServerClientUpdateEvent (client);
    } else {
        /* Fatal error in handshake */
        client->wantClose = true;
    }
}

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

    virNetServerClientLock(client);

    if (client->sock != sock) {
        virNetSocketRemoveIOCallback(sock);
        virNetServerClientUnlock(client);
        return;
    }

    if (events & (VIR_EVENT_HANDLE_WRITABLE |
                  VIR_EVENT_HANDLE_READABLE)) {
        if (client->tls &&
            virNetTLSSessionGetHandshakeStatus(client->tls) !=
            VIR_NET_TLS_HANDSHAKE_COMPLETE) {
            virNetServerClientDispatchHandshake(client);
        } else {
            if (events & VIR_EVENT_HANDLE_WRITABLE)
                virNetServerClientDispatchWrite(client);
M
Michal Privoznik 已提交
1093 1094
            if (events & VIR_EVENT_HANDLE_READABLE &&
                client->rx)
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
                virNetServerClientDispatchRead(client);
        }
    }

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

    virNetServerClientUnlock(client);
}


1109 1110 1111
static int
virNetServerClientSendMessageLocked(virNetServerClientPtr client,
                                    virNetMessagePtr msg)
1112 1113 1114 1115 1116
{
    int ret = -1;
    VIR_DEBUG("msg=%p proc=%d len=%zu offset=%zu",
              msg, msg->header.proc,
              msg->bufferLength, msg->bufferOffset);
1117

1118
    msg->donefds = 0;
1119
    if (client->sock && !client->wantClose) {
1120 1121 1122 1123 1124
        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);
1125 1126 1127 1128 1129 1130
        virNetMessageQueuePush(&client->tx, msg);

        virNetServerClientUpdateEvent(client);
        ret = 0;
    }

1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    return ret;
}

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

    virNetServerClientLock(client);
    ret = virNetServerClientSendMessageLocked(client, msg);
1141
    virNetServerClientUnlock(client);
1142

1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
    return ret;
}


bool virNetServerClientNeedAuth(virNetServerClientPtr client)
{
    bool need = false;
    virNetServerClientLock(client);
    if (client->auth && !client->identity)
        need = true;
    virNetServerClientUnlock(client);
    return need;
}
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184


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;

    virNetServerClientLock(client);

    if (!(ka = virKeepAliveNew(interval, count, client,
                               virNetServerClientKeepAliveSendCB,
                               virNetServerClientKeepAliveDeadCB,
1185
                               virObjectFreeCallback)))
1186 1187
        goto cleanup;
    /* keepalive object has a reference to client */
1188
    virObjectRef(client);
1189 1190 1191 1192 1193 1194 1195 1196

    client->keepalive = ka;
    ka = NULL;

cleanup:
    virNetServerClientUnlock(client);
    if (ka)
        virKeepAliveStop(ka);
1197
    virObjectUnref(ka);
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210

    return ret;
}

int
virNetServerClientStartKeepAlive(virNetServerClientPtr client)
{
    int ret;
    virNetServerClientLock(client);
    ret = virKeepAliveStart(client->keepalive, 0, 0);
    virNetServerClientUnlock(client);
    return ret;
}