virnetserverclient.c 30.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
/*
 * 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
 * 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: 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"

#define VIR_FROM_THIS VIR_FROM_RPC
#define virNetError(code, ...)                                    \
    virReportErrorHelper(VIR_FROM_THIS, code, __FILE__,           \
                         __FUNCTION__, __LINE__, __VA_ARGS__)

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

    /* 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;
    virNetServerClientFreeFunc privateDataFreeFunc;
102
    virNetServerClientCloseFunc privateDataCloseFunc;
103 104 105 106 107
};


static void virNetServerClientDispatchEvent(virNetSocketPtr sock, int events, void *opaque);
static void virNetServerClientUpdateEvent(virNetServerClientPtr client);
M
Michal Privoznik 已提交
108
static void virNetServerClientDispatchRead(virNetServerClientPtr client);
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 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

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 {
        /* If there is a message on the rx queue then
         * we're wanting more input */
        if (client->rx)
            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;
    }
163
    VIR_DEBUG("mode=%o", mode);
164 165 166
    return mode;
}

167 168 169 170 171 172 173
static void virNetServerClientEventFree(void *opaque)
{
    virNetServerClientPtr client = opaque;

    virNetServerClientFree(client);
}

174 175 176 177 178 179 180 181
/*
 * @server: a locked or unlocked server object
 * @client: a locked client object
 */
static int virNetServerClientRegisterEvent(virNetServerClientPtr client)
{
    int mode = virNetServerClientCalculateHandleMode(client);

182
    client->refs++;
183
    VIR_DEBUG("Registering client event callback %d", mode);
184 185
    if (!client->sock ||
        virNetSocketAddIOCallback(client->sock,
186 187
                                  mode,
                                  virNetServerClientDispatchEvent,
188 189 190
                                  client,
                                  virNetServerClientEventFree) < 0) {
        client->refs--;
191
        return -1;
192
    }
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209

    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 已提交
210 211 212

    if (client->rx && virNetSocketHasCachedData(client->sock))
        virEventUpdateTimeout(client->sockTimer, 0);
213 214 215 216 217 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 250 251 252 253 254 255 256 257 258 259 260 261 262
}


int virNetServerClientAddFilter(virNetServerClientPtr client,
                                virNetServerClientFilterFunc func,
                                void *opaque)
{
    virNetServerClientFilterPtr filter;
    int ret = -1;

    virNetServerClientLock(client);

    if (VIR_ALLOC(filter) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    filter->id = client->nextFilterID++;
    filter->func = func;
    filter->opaque = opaque;

    filter->next = client->filters;
    client->filters = filter;

    ret = filter->id;

cleanup:
    virNetServerClientUnlock(client);
    return ret;
}


void virNetServerClientRemoveFilter(virNetServerClientPtr client,
                                    int filterID)
{
    virNetServerClientFilterPtr tmp, prev;
    virNetServerClientLock(client);

    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 已提交
263
        prev = tmp;
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
        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;
    }

286
    if (!(confirm = virNetMessageNew(false)))
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
        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;
    confirm->bufferOffset = 0;
    confirm->buffer[0] = '\1';

    client->tx = confirm;

    return 0;
}

M
Michal Privoznik 已提交
302 303 304 305 306 307 308 309 310 311 312 313 314
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);
}

315 316 317 318

virNetServerClientPtr virNetServerClientNew(virNetSocketPtr sock,
                                            int auth,
                                            bool readonly,
319
                                            size_t nrequests_max,
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
                                            virNetTLSContextPtr tls)
{
    virNetServerClientPtr client;

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

    if (VIR_ALLOC(client) < 0) {
        virReportOOMError();
        return NULL;
    }

    if (virMutexInit(&client->lock) < 0)
        goto error;

    client->refs = 1;
    client->sock = sock;
    client->auth = auth;
    client->readonly = readonly;
    client->tlsCtxt = tls;
339
    client->nrequests_max = nrequests_max;
340

M
Michal Privoznik 已提交
341 342 343 344 345
    client->sockTimer = virEventAddTimeout(-1, virNetServerClientSockTimerFunc,
                                           client, NULL);
    if (client->sockTimer < 0)
        goto error;

346 347 348 349
    if (tls)
        virNetTLSContextRef(tls);

    /* Prepare one for packet receive */
350
    if (!(client->rx = virNetMessageNew(true)))
351 352 353 354
        goto error;
    client->rx->bufferLength = VIR_NET_MESSAGE_LEN_MAX;
    client->nrequests = 1;

355 356 357
    PROBE(RPC_SERVER_CLIENT_NEW,
          "client=%p refs=%d sock=%p",
          client, client->refs, client->sock);
358 359 360 361 362 363 364 365 366 367 368 369 370 371

    return client;

error:
    /* XXX ref counting is better than this */
    client->sock = NULL; /* Caller owns 'sock' upon failure */
    virNetServerClientFree(client);
    return NULL;
}

void virNetServerClientRef(virNetServerClientPtr client)
{
    virNetServerClientLock(client);
    client->refs++;
372 373 374
    PROBE(RPC_SERVER_CLIENT_REF,
          "client=%p refs=%d",
          client, client->refs);
375 376 377 378 379 380 381 382 383 384 385 386 387 388 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
    virNetServerClientUnlock(client);
}


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)
{
419
    int fd = -1;
420
    virNetServerClientLock(client);
421 422
    if (client->sock)
        fd = virNetSocketGetFD(client->sock);
423 424 425 426 427 428 429
    virNetServerClientUnlock(client);
    return fd;
}

int virNetServerClientGetLocalIdentity(virNetServerClientPtr client,
                                       uid_t *uid, pid_t *pid)
{
430
    int ret = -1;
431
    virNetServerClientLock(client);
432 433
    if (client->sock)
        ret = virNetSocketGetLocalIdentity(client->sock, uid, pid);
434 435 436 437 438 439 440 441 442 443 444 445 446 447
    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
448
    if (client->sock && virNetSocketIsLocal(client->sock))
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 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
        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);
    client->sasl = sasl;
    virNetSASLSessionRef(sasl);
    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 virNetServerClientSetPrivateData(virNetServerClientPtr client,
                                      void *opaque,
                                      virNetServerClientFreeFunc ff)
{
    virNetServerClientLock(client);

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

    client->privateData = opaque;
    client->privateDataFreeFunc = ff;

    virNetServerClientUnlock(client);
}


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


524 525 526 527 528 529 530 531 532
void virNetServerClientSetCloseHook(virNetServerClientPtr client,
                                    virNetServerClientCloseFunc cf)
{
    virNetServerClientLock(client);
    client->privateDataCloseFunc = cf;
    virNetServerClientUnlock(client);
}


533 534 535 536 537 538 539 540 541 542 543 544 545
void virNetServerClientSetDispatcher(virNetServerClientPtr client,
                                     virNetServerClientDispatchFunc func,
                                     void *opaque)
{
    virNetServerClientLock(client);
    client->dispatchFunc = func;
    client->dispatchOpaque = opaque;
    virNetServerClientUnlock(client);
}


const char *virNetServerClientLocalAddrString(virNetServerClientPtr client)
{
546 547
    if (!client->sock)
        return NULL;
548 549 550 551 552 553
    return virNetSocketLocalAddrString(client->sock);
}


const char *virNetServerClientRemoteAddrString(virNetServerClientPtr client)
{
554 555
    if (!client->sock)
        return NULL;
556 557 558 559 560 561 562 563 564 565
    return virNetSocketRemoteAddrString(client->sock);
}


void virNetServerClientFree(virNetServerClientPtr client)
{
    if (!client)
        return;

    virNetServerClientLock(client);
566 567 568
    PROBE(RPC_SERVER_CLIENT_FREE,
          "client=%p refs=%d",
          client, client->refs);
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583

    client->refs--;
    if (client->refs > 0) {
        virNetServerClientUnlock(client);
        return;
    }

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

    VIR_FREE(client->identity);
#if HAVE_SASL
    virNetSASLSessionFree(client->sasl);
#endif
M
Michal Privoznik 已提交
584 585
    if (client->sockTimer > 0)
        virEventRemoveTimeout(client->sockTimer);
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
    virNetTLSSessionFree(client->tls);
    virNetTLSContextFree(client->tlsCtxt);
    virNetSocketFree(client->sock);
    virNetServerClientUnlock(client);
    virMutexDestroy(&client->lock);
    VIR_FREE(client);
}


/*
 *
 * 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)
{
605 606
    virNetServerClientCloseFunc cf;

607 608 609 610 611 612 613
    virNetServerClientLock(client);
    VIR_DEBUG("client=%p refs=%d", client, client->refs);
    if (!client->sock) {
        virNetServerClientUnlock(client);
        return;
    }

614 615 616 617 618 619 620 621 622
    if (client->privateDataCloseFunc) {
        cf = client->privateDataCloseFunc;
        client->refs++;
        virNetServerClientUnlock(client);
        (cf)(client);
        virNetServerClientLock(client);
        client->refs--;
    }

623 624 625 626 627 628 629 630 631 632
    /* 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) {
        virNetTLSSessionFree(client->tls);
        client->tls = NULL;
    }
633
    client->wantClose = true;
634 635 636 637 638 639 640 641 642 643 644 645

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

646 647 648 649 650
    if (client->sock) {
        virNetSocketFree(client->sock);
        client->sock = NULL;
    }

651 652 653 654 655 656 657 658 659 660 661 662 663
    virNetServerClientUnlock(client);
}


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

664 665 666 667 668 669 670 671
void virNetServerClientDelayedClose(virNetServerClientPtr client)
{
    virNetServerClientLock(client);
    client->delayedClose = true;
    virNetServerClientUnlock(client);
}

void virNetServerClientImmediateClose(virNetServerClientPtr client)
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 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 772 773
{
    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) {
        virNetError(VIR_ERR_RPC,
                    _("unexpected zero/negative length request %lld"),
                    (long long int)(client->rx->bufferLength - client->rx->bufferOffset));
        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:
774 775 776 777 778
    if (client->rx->nfds == 0) {
        if (virNetServerClientRead(client) < 0) {
            client->wantClose = true;
            return; /* Error */
        }
779 780 781 782 783 784 785
    }

    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) {
786 787
        if (virNetMessageDecodeLength(client->rx) < 0) {
            client->wantClose = true;
788
            return;
789
        }
790 791 792 793 794 795 796 797 798

        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 */
799
        virNetMessagePtr msg = client->rx;
800
        virNetServerClientFilterPtr filter;
801
        size_t i;
802 803 804 805 806 807 808 809

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

810 811
        /* Now figure out if we need to read more data to get some
         * file descriptors */
812 813 814 815
        if (msg->header.type == VIR_NET_CALL_WITH_FDS &&
            virNetMessageDecodeNumFDs(msg) < 0) {
            virNetMessageFree(msg);
            client->wantClose = true;
816
            return; /* Error */
817
        }
818 819 820 821 822

        /* 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) {
823 824 825 826
                virNetMessageFree(msg);
                client->wantClose = true;
                return;
            }
827 828 829 830 831 832 833 834 835 836 837 838 839
            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;
840 841
        }

842 843
        /* Definitely finished reading, so remove from queue */
        virNetMessageQueueServe(&client->rx);
844 845 846 847 848 849
        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);

850 851 852 853
        /* Maybe send off for queue against a filter */
        filter = client->filters;
        while (filter) {
            int ret = filter->func(client, msg, filter->opaque);
854
            if (ret < 0) {
855 856 857 858 859 860
                virNetMessageFree(msg);
                msg = NULL;
                if (ret < 0)
                    client->wantClose = true;
                break;
            }
861 862 863 864
            if (ret > 0) {
                msg = NULL;
                break;
            }
865 866 867 868 869 870

            filter = filter->next;
        }

        /* Send off to for normal dispatch to workers */
        if (msg) {
871
            client->refs++;
872 873 874 875
            if (!client->dispatchFunc ||
                client->dispatchFunc(client, msg, client->dispatchOpaque) < 0) {
                virNetMessageFree(msg);
                client->wantClose = true;
876
                client->refs--;
877 878 879 880 881 882
                return;
            }
        }

        /* Possibly need to create another receive buffer */
        if (client->nrequests < client->nrequests_max) {
883
            if (!(client->rx = virNetMessageNew(true))) {
884
                client->wantClose = true;
E
Eric Blake 已提交
885 886 887
            } else {
                client->rx->bufferLength = VIR_NET_MESSAGE_LEN_MAX;
                client->nrequests++;
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
            }
        }
        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) {
        virNetError(VIR_ERR_RPC,
                    _("unexpected zero/negative length request %lld"),
                    (long long int)(client->tx->bufferLength - client->tx->bufferOffset));
        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) {
937 938 939 940 941 942 943 944 945
        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 */
946 947 948 949
        }

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

952 953 954
            for (i = client->tx->donefds ; i < client->tx->nfds ; i++) {
                int rv;
                if ((rv = virNetSocketSendFD(client->sock, client->tx->fds[i])) < 0) {
955 956 957
                    client->wantClose = true;
                    return;
                }
958 959 960
                if (rv == 0) /* Blocking */
                    return;
                client->tx->donefds++;
961 962
            }

963 964 965 966 967 968 969 970 971 972 973 974 975 976
#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);
                virNetSASLSessionFree(client->sasl);
                client->sasl = NULL;
            }
#endif

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

977
            if (msg->tracked) {
978 979 980 981 982
                client->nrequests--;
                /* See if the recv queue is currently throttled */
                if (!client->rx &&
                    client->nrequests < client->nrequests_max) {
                    /* Ready to recv more messages */
983
                    virNetMessageClear(msg);
984 985 986 987 988 989 990 991 992 993
                    client->rx = msg;
                    client->rx->bufferLength = VIR_NET_MESSAGE_LEN_MAX;
                    msg = NULL;
                    client->nrequests++;
                }
            }

            virNetMessageFree(msg);

            virNetServerClientUpdateEvent(client);
994 995 996

            if (client->delayedClose)
                client->wantClose = true;
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
         }
    }
}

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 已提交
1046 1047
            if (events & VIR_EVENT_HANDLE_READABLE &&
                client->rx)
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
                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);
}


int virNetServerClientSendMessage(virNetServerClientPtr client,
                                  virNetMessagePtr msg)
{
    int ret = -1;
    VIR_DEBUG("msg=%p proc=%d len=%zu offset=%zu",
              msg, msg->header.proc,
              msg->bufferLength, msg->bufferOffset);
    virNetServerClientLock(client);

1071
    msg->donefds = 0;
1072
    if (client->sock && !client->wantClose) {
1073 1074 1075 1076 1077
        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);
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
        virNetMessageQueuePush(&client->tx, msg);

        virNetServerClientUpdateEvent(client);
        ret = 0;
    }

    virNetServerClientUnlock(client);
    return ret;
}


bool virNetServerClientNeedAuth(virNetServerClientPtr client)
{
    bool need = false;
    virNetServerClientLock(client);
    if (client->auth && !client->identity)
        need = true;
    virNetServerClientUnlock(client);
    return need;
}