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

#include <config.h>

#include <unistd.h>
#include <poll.h>
#include <signal.h>
#include <fcntl.h>

#include "virnetclient.h"
#include "virnetsocket.h"
32
#include "virkeepalive.h"
33
#include "viralloc.h"
34
#include "virthread.h"
E
Eric Blake 已提交
35
#include "virfile.h"
36
#include "virlog.h"
37
#include "virutil.h"
38
#include "virerror.h"
39
#include "virprobe.h"
40
#include "virstring.h"
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

#define VIR_FROM_THIS VIR_FROM_RPC

typedef struct _virNetClientCall virNetClientCall;
typedef virNetClientCall *virNetClientCallPtr;

enum {
    VIR_NET_CLIENT_MODE_WAIT_TX,
    VIR_NET_CLIENT_MODE_WAIT_RX,
    VIR_NET_CLIENT_MODE_COMPLETE,
};

struct _virNetClientCall {
    int mode;

    virNetMessagePtr msg;
    bool expectReply;
58 59
    bool nonBlock;
    bool haveThread;
60 61 62 63 64 65 66 67

    virCond cond;

    virNetClientCallPtr next;
};


struct _virNetClient {
68
    virObjectLockable parent;
69 70

    virNetSocketPtr sock;
71
    bool asyncIO;
72

73
#if WITH_GNUTLS
74
    virNetTLSSessionPtr tls;
75
#endif
76 77 78 79 80 81 82 83
    char *hostname;

    virNetClientProgramPtr *programs;
    size_t nprograms;

    /* For incoming message packets */
    virNetMessage msg;

84
#if WITH_SASL
85 86 87 88 89 90 91
    virNetSASLSessionPtr sasl;
#endif

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

92 93 94 95 96 97
    /*
     * List of calls currently waiting for dispatch
     * The calls should all have threads waiting for
     * them, except possibly the first call in the list
     * which might be a partially sent non-blocking call.
     */
98
    virNetClientCallPtr waitDispatch;
99 100
    /* True if a thread holds the buck */
    bool haveTheBuck;
101 102 103

    size_t nstreams;
    virNetClientStreamPtr *streams;
104

105
    virKeepAlivePtr keepalive;
106
    bool wantClose;
107
    int closeReason;
108 109 110 111

    virNetClientCloseFunc closeCb;
    void *closeOpaque;
    virFreeCallback closeFf;
112 113 114
};


115 116 117 118 119
static virClassPtr virNetClientClass;
static void virNetClientDispose(void *obj);

static int virNetClientOnceInit(void)
{
120
    if (!(virNetClientClass = virClassNew(virClassForObjectLockable(),
121
                                          "virNetClient",
122 123 124 125 126 127 128 129 130
                                          sizeof(virNetClient),
                                          virNetClientDispose)))
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(virNetClient)

131 132
static void virNetClientIOEventLoopPassTheBuck(virNetClientPtr client,
                                               virNetClientCallPtr thiscall);
133 134
static int virNetClientQueueNonBlocking(virNetClientPtr client,
                                        virNetMessagePtr msg);
135 136
static void virNetClientCloseInternal(virNetClientPtr client,
                                      int reason);
137 138


139 140 141 142 143
void virNetClientSetCloseCallback(virNetClientPtr client,
                                  virNetClientCloseFunc cb,
                                  void *opaque,
                                  virFreeCallback ff)
{
144
    virObjectLock(client);
145 146 147
    client->closeCb = cb;
    client->closeOpaque = opaque;
    client->closeFf = ff;
148
    virObjectUnlock(client);
149 150 151
}


152 153 154 155
static void virNetClientIncomingEvent(virNetSocketPtr sock,
                                      int events,
                                      void *opaque);

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 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
/* Append a call to the end of the list */
static void virNetClientCallQueue(virNetClientCallPtr *head,
                                  virNetClientCallPtr call)
{
    virNetClientCallPtr tmp = *head;
    while (tmp && tmp->next) {
        tmp = tmp->next;
    }
    if (tmp)
        tmp->next = call;
    else
        *head = call;
    call->next = NULL;
}

#if 0
/* Obtain a call from the head of the list */
static virNetClientCallPtr virNetClientCallServe(virNetClientCallPtr *head)
{
    virNetClientCallPtr tmp = *head;
    if (tmp)
        *head = tmp->next;
    else
        *head = NULL;
    tmp->next = NULL;
    return tmp;
}
#endif

/* Remove a call from anywhere in the list */
static void virNetClientCallRemove(virNetClientCallPtr *head,
                                   virNetClientCallPtr call)
{
    virNetClientCallPtr tmp = *head;
    virNetClientCallPtr prev = NULL;
    while (tmp) {
        if (tmp == call) {
            if (prev)
                prev->next = tmp->next;
            else
                *head = tmp->next;
            tmp->next = NULL;
            return;
        }
        prev = tmp;
        tmp = tmp->next;
    }
}

/* Predicate returns true if matches */
typedef bool (*virNetClientCallPredicate)(virNetClientCallPtr call, void *opaque);

/* Remove a list of calls from the list based on a predicate */
static void virNetClientCallRemovePredicate(virNetClientCallPtr *head,
                                            virNetClientCallPredicate pred,
                                            void *opaque)
{
    virNetClientCallPtr tmp = *head;
    virNetClientCallPtr prev = NULL;
    while (tmp) {
        virNetClientCallPtr next = tmp->next;
        tmp->next = NULL; /* Temp unlink */
        if (pred(tmp, opaque)) {
            if (prev)
                prev->next = next;
            else
                *head = next;
        } else {
            tmp->next = next; /* Reverse temp unlink */
            prev = tmp;
        }
        tmp = next;
    }
}

/* Returns true if the predicate matches at least one call in the list */
static bool virNetClientCallMatchPredicate(virNetClientCallPtr head,
                                           virNetClientCallPredicate pred,
                                           void *opaque)
{
    virNetClientCallPtr tmp = head;
    while (tmp) {
        if (pred(tmp, opaque)) {
            return true;
        }
        tmp = tmp->next;
    }
    return false;
}


247 248 249 250 251
bool
virNetClientKeepAliveIsSupported(virNetClientPtr client)
{
    bool supported;

252
    virObjectLock(client);
253
    supported = !!client->keepalive;
254
    virObjectUnlock(client);
255 256 257 258 259 260 261 262 263 264 265

    return supported;
}

int
virNetClientKeepAliveStart(virNetClientPtr client,
                           int interval,
                           unsigned int count)
{
    int ret;

266
    virObjectLock(client);
267
    ret = virKeepAliveStart(client->keepalive, interval, count);
268
    virObjectUnlock(client);
269 270 271 272

    return ret;
}

273 274 275
void
virNetClientKeepAliveStop(virNetClientPtr client)
{
276
    virObjectLock(client);
277
    virKeepAliveStop(client->keepalive);
278
    virObjectUnlock(client);
279 280
}

281 282 283
static void
virNetClientKeepAliveDeadCB(void *opaque)
{
284
    virNetClientCloseInternal(opaque, VIR_CONNECT_CLOSE_REASON_KEEPALIVE);
285 286 287 288 289 290 291 292 293 294 295 296 297 298
}

static int
virNetClientKeepAliveSendCB(void *opaque,
                            virNetMessagePtr msg)
{
    int ret;

    ret = virNetClientSendNonBlock(opaque, msg);
    if (ret != -1 && ret != 1)
        virNetMessageFree(msg);
    return ret;
}

299 300 301
static virNetClientPtr virNetClientNew(virNetSocketPtr sock,
                                       const char *hostname)
{
302
    virNetClientPtr client = NULL;
303 304
    int wakeupFD[2] = { -1, -1 };

305 306 307
    if (virNetClientInitialize() < 0)
        return NULL;

308 309 310 311 312 313
    if (pipe2(wakeupFD, O_CLOEXEC) < 0) {
        virReportSystemError(errno, "%s",
                             _("unable to make pipe"));
        goto error;
    }

314
    if (!(client = virObjectLockableNew(virNetClientClass)))
315
        goto error;
316 317 318 319 320 321

    client->sock = sock;
    client->wakeupReadFD = wakeupFD[0];
    client->wakeupSendFD = wakeupFD[1];
    wakeupFD[0] = wakeupFD[1] = -1;

322 323
    if (VIR_STRDUP(client->hostname, hostname) < 0)
        goto error;
324

325
    PROBE(RPC_CLIENT_NEW,
326 327
          "client=%p sock=%p",
          client, client->sock);
328 329 330 331 332
    return client;

error:
    VIR_FORCE_CLOSE(wakeupFD[0]);
    VIR_FORCE_CLOSE(wakeupFD[1]);
333
    virObjectUnref(client);
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    return NULL;
}


virNetClientPtr virNetClientNewUNIX(const char *path,
                                    bool spawnDaemon,
                                    const char *binary)
{
    virNetSocketPtr sock;

    if (virNetSocketNewConnectUNIX(path, spawnDaemon, binary, &sock) < 0)
        return NULL;

    return virNetClientNew(sock, NULL);
}


virNetClientPtr virNetClientNewTCP(const char *nodename,
                                   const char *service)
{
    virNetSocketPtr sock;

    if (virNetSocketNewConnectTCP(nodename, service, &sock) < 0)
        return NULL;

    return virNetClientNew(sock, nodename);
}

virNetClientPtr virNetClientNewSSH(const char *nodename,
                                   const char *service,
                                   const char *binary,
                                   const char *username,
                                   bool noTTY,
367
                                   bool noVerify,
368
                                   const char *netcat,
369
                                   const char *keyfile,
370 371 372 373
                                   const char *path)
{
    virNetSocketPtr sock;

374 375
    if (virNetSocketNewConnectSSH(nodename, service, binary, username, noTTY,
                                  noVerify, netcat, keyfile, path, &sock) < 0)
376 377 378 379 380
        return NULL;

    return virNetClientNew(sock, NULL);
}

381 382 383 384 385 386 387 388 389 390 391 392
#define DEFAULT_VALUE(VAR, VAL)             \
    if (!VAR)                               \
        VAR = VAL;
virNetClientPtr virNetClientNewLibSSH2(const char *host,
                                       const char *port,
                                       const char *username,
                                       const char *privkeyPath,
                                       const char *knownHostsPath,
                                       const char *knownHostsVerify,
                                       const char *authMethods,
                                       const char *netcatPath,
                                       const char *socketPath,
393 394
                                       virConnectAuthPtr authPtr,
                                       virURIPtr uri)
395 396 397 398 399 400 401 402 403
{
    virNetSocketPtr sock = NULL;
    virNetClientPtr ret = NULL;

    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *nc = NULL;
    char *command = NULL;

    char *homedir = virGetUserDirectory();
404
    char *confdir = virGetUserConfigDirectory();
405 406 407 408
    char *knownhosts = NULL;
    char *privkey = NULL;

    /* Use default paths for known hosts an public keys if not provided */
409
    if (confdir) {
410
        if (!knownHostsPath) {
411 412 413 414 415
            if (virFileExists(confdir)) {
                virBufferAsprintf(&buf, "%s/known_hosts", confdir);
                if (!(knownhosts = virBufferContentAndReset(&buf)))
                    goto no_memory;
            }
416
        } else {
417 418
            if (VIR_STRDUP(knownhosts, knownHostsPath) < 0)
                goto cleanup;
419
        }
420
    }
421

422
    if (homedir) {
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
        if (!privkeyPath) {
            /* RSA */
            virBufferAsprintf(&buf, "%s/.ssh/id_rsa", homedir);
            if (!(privkey = virBufferContentAndReset(&buf)))
                goto no_memory;

            if (!(virFileExists(privkey)))
                VIR_FREE(privkey);
            /* DSA */
            if (!privkey) {
                virBufferAsprintf(&buf, "%s/.ssh/id_dsa", homedir);
                if (!(privkey = virBufferContentAndReset(&buf)))
                    goto no_memory;

                if (!(virFileExists(privkey)))
                    VIR_FREE(privkey);
            }
        } else {
441 442
            if (VIR_STRDUP(privkey, privkeyPath) < 0)
                goto cleanup;
443 444 445 446 447
        }
    }

    if (!authMethods) {
        if (privkey)
448
            authMethods = "agent,privkey,password,keyboard-interactive";
449
        else
450
            authMethods = "agent,password,keyboard-interactive";
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
    }

    DEFAULT_VALUE(host, "localhost");
    DEFAULT_VALUE(port, "22");
    DEFAULT_VALUE(username, "root");
    DEFAULT_VALUE(netcatPath, "nc");
    DEFAULT_VALUE(knownHostsVerify, "normal");

    virBufferEscapeShell(&buf, netcatPath);
    if (!(nc = virBufferContentAndReset(&buf)))
        goto no_memory;

    virBufferAsprintf(&buf,
         "sh -c "
         "'if '%s' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
             "ARG=-q0;"
         "else "
             "ARG=;"
         "fi;"
         "'%s' $ARG -U %s'",
         nc, nc, socketPath);

    if (!(command = virBufferContentAndReset(&buf)))
        goto no_memory;

476
    if (virNetSocketNewConnectLibSSH2(host, port, username, privkey,
477
                                      knownhosts, knownHostsVerify, authMethods,
478
                                      command, authPtr, uri, &sock) != 0)
479 480 481 482 483 484 485 486 487 488 489
        goto cleanup;

    if (!(ret = virNetClientNew(sock, NULL)))
        goto cleanup;
    sock = NULL;

cleanup:
    VIR_FREE(command);
    VIR_FREE(privkey);
    VIR_FREE(knownhosts);
    VIR_FREE(homedir);
490
    VIR_FREE(confdir);
491 492 493 494 495 496 497 498 499 500
    VIR_FREE(nc);
    virObjectUnref(sock);
    return ret;

no_memory:
    virReportOOMError();
    goto cleanup;
}
#undef DEFAULT_VALUE

501 502 503 504 505 506 507 508 509 510 511
virNetClientPtr virNetClientNewExternal(const char **cmdargv)
{
    virNetSocketPtr sock;

    if (virNetSocketNewConnectExternal(cmdargv, &sock) < 0)
        return NULL;

    return virNetClientNew(sock, NULL);
}


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 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
int virNetClientRegisterAsyncIO(virNetClientPtr client)
{
    if (client->asyncIO)
        return 0;

    /* Set up a callback to listen on the socket data */
    virObjectRef(client);
    if (virNetSocketAddIOCallback(client->sock,
                                  VIR_EVENT_HANDLE_READABLE,
                                  virNetClientIncomingEvent,
                                  client,
                                  virObjectFreeCallback) < 0) {
        virObjectUnref(client);
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to register async IO callback"));
        return -1;
    }

    client->asyncIO = true;
    return 0;
}


int virNetClientRegisterKeepAlive(virNetClientPtr client)
{
    virKeepAlivePtr ka;

    if (client->keepalive)
        return 0;

    if (!client->asyncIO) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Unable to enable keepalives without async IO support"));
        return -1;
    }

    /* Keepalive protocol consists of async messages so it can only be used
     * if the client supports them */
    if (!(ka = virKeepAliveNew(-1, 0, client,
                               virNetClientKeepAliveSendCB,
                               virNetClientKeepAliveDeadCB,
                               virObjectFreeCallback)))
        return -1;

    /* keepalive object has a reference to client */
    virObjectRef(client);

    client->keepalive = ka;
    return 0;
}


564 565 566
int virNetClientGetFD(virNetClientPtr client)
{
    int fd;
567
    virObjectLock(client);
568
    fd = virNetSocketGetFD(client->sock);
569
    virObjectUnlock(client);
570 571 572 573 574 575 576
    return fd;
}


int virNetClientDupFD(virNetClientPtr client, bool cloexec)
{
    int fd;
577
    virObjectLock(client);
578
    fd = virNetSocketDupFD(client->sock, cloexec);
579
    virObjectUnlock(client);
580 581 582 583
    return fd;
}


584 585 586
bool virNetClientHasPassFD(virNetClientPtr client)
{
    bool hasPassFD;
587
    virObjectLock(client);
588
    hasPassFD = virNetSocketHasPassFD(client->sock);
589
    virObjectUnlock(client);
590 591 592 593
    return hasPassFD;
}


594
void virNetClientDispose(void *obj)
595
{
596
    virNetClientPtr client = obj;
597
    size_t i;
598

599 600 601
    PROBE(RPC_CLIENT_DISPOSE,
          "client=%p", client);

602 603 604
    if (client->closeFf)
        client->closeFf(client->closeOpaque);

605
    for (i = 0; i < client->nprograms; i++)
606
        virObjectUnref(client->programs[i]);
607 608 609 610 611 612 613
    VIR_FREE(client->programs);

    VIR_FORCE_CLOSE(client->wakeupSendFD);
    VIR_FORCE_CLOSE(client->wakeupReadFD);

    VIR_FREE(client->hostname);

614 615
    if (client->sock)
        virNetSocketRemoveIOCallback(client->sock);
616
    virObjectUnref(client->sock);
617
#if WITH_GNUTLS
618
    virObjectUnref(client->tls);
619
#endif
620
#if WITH_SASL
621
    virObjectUnref(client->sasl);
622
#endif
623 624 625

    virNetMessageClear(&client->msg);

626
    virObjectUnlock(client);
627 628 629
}


630 631 632 633 634
static void
virNetClientMarkClose(virNetClientPtr client,
                      int reason)
{
    VIR_DEBUG("client=%p, reason=%d", client, reason);
635 636
    if (client->sock)
        virNetSocketRemoveIOCallback(client->sock);
637 638 639 640 641
    client->wantClose = true;
    client->closeReason = reason;
}


642 643
static void
virNetClientCloseLocked(virNetClientPtr client)
644
{
645 646
    virKeepAlivePtr ka;

647
    VIR_DEBUG("client=%p, sock=%p, reason=%d", client, client->sock, client->closeReason);
648 649

    if (!client->sock)
650 651
        return;

652
    virObjectUnref(client->sock);
653
    client->sock = NULL;
654
#if WITH_GNUTLS
655
    virObjectUnref(client->tls);
656
    client->tls = NULL;
657
#endif
658
#if WITH_SASL
659
    virObjectUnref(client->sasl);
660 661
    client->sasl = NULL;
#endif
662 663
    ka = client->keepalive;
    client->keepalive = NULL;
664
    client->wantClose = false;
665

666 667 668 669
    if (ka || client->closeCb) {
        virNetClientCloseFunc closeCb = client->closeCb;
        void *closeOpaque = client->closeOpaque;
        int closeReason = client->closeReason;
670
        virObjectRef(client);
671
        virObjectUnlock(client);
672

673 674
        if (ka) {
            virKeepAliveStop(ka);
675
            virObjectUnref(ka);
676 677 678
        }
        if (closeCb)
            closeCb(client, closeReason, closeOpaque);
679

680
        virObjectLock(client);
681
        virObjectUnref(client);
682
    }
683 684
}

685 686
static void virNetClientCloseInternal(virNetClientPtr client,
                                      int reason)
687
{
688
    VIR_DEBUG("client=%p wantclose=%d", client, client ? client->wantClose : false);
689

690 691 692
    if (!client)
        return;

693 694 695 696
    if (!client->sock ||
        client->wantClose)
        return;

697
    virObjectLock(client);
698

699
    virNetClientMarkClose(client, reason);
700 701 702 703 704

    /* If there is a thread polling for data on the socket, wake the thread up
     * otherwise try to pass the buck to a possibly waiting thread. If no
     * thread is waiting, virNetClientIOEventLoopPassTheBuck will clean the
     * queue and close the client because we set client->wantClose.
705
     */
706
    if (client->haveTheBuck) {
707 708 709 710 711 712
        char ignore = 1;
        size_t len = sizeof(ignore);

        if (safewrite(client->wakeupSendFD, &ignore, len) != len)
            VIR_ERROR(_("failed to wake up polling thread"));
    } else {
713
        virNetClientIOEventLoopPassTheBuck(client, NULL);
714 715
    }

716
    virObjectUnlock(client);
717 718 719
}


720 721 722 723 724 725
void virNetClientClose(virNetClientPtr client)
{
    virNetClientCloseInternal(client, VIR_CONNECT_CLOSE_REASON_CLIENT);
}


726
#if WITH_SASL
727 728 729
void virNetClientSetSASLSession(virNetClientPtr client,
                                virNetSASLSessionPtr sasl)
{
730
    virObjectLock(client);
731
    client->sasl = virObjectRef(sasl);
732
    virNetSocketSetSASLSession(client->sock, client->sasl);
733
    virObjectUnlock(client);
734 735 736 737
}
#endif


738
#if WITH_GNUTLS
739 740 741 742 743 744 745 746 747
int virNetClientSetTLSSession(virNetClientPtr client,
                              virNetTLSContextPtr tls)
{
    int ret;
    char buf[1];
    int len;
    struct pollfd fds[1];
    sigset_t oldmask, blockedsigs;

748
    sigemptyset(&blockedsigs);
749
# ifdef SIGWINCH
750
    sigaddset(&blockedsigs, SIGWINCH);
751 752
# endif
# ifdef SIGCHLD
753
    sigaddset(&blockedsigs, SIGCHLD);
754
# endif
755
    sigaddset(&blockedsigs, SIGPIPE);
756

757
    virObjectLock(client);
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789

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

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

    for (;;) {
        ret = virNetTLSSessionHandshake(client->tls);

        if (ret < 0)
            goto error;
        if (ret == 0)
            break;

        fds[0].fd = virNetSocketGetFD(client->sock);
        fds[0].revents = 0;
        if (virNetTLSSessionGetHandshakeStatus(client->tls) ==
            VIR_NET_TLS_HANDSHAKE_RECVING)
            fds[0].events = POLLIN;
        else
            fds[0].events = POLLOUT;

        /* Block SIGWINCH from interrupting poll in curses programs,
         * then restore the original signal mask again immediately
         * after the call (RHBZ#567931).  Same for SIGCHLD and SIGPIPE
         * at the suggestion of Paolo Bonzini and Daniel Berrange.
         */
        ignore_value(pthread_sigmask(SIG_BLOCK, &blockedsigs, &oldmask));

    repoll:
        ret = poll(fds, ARRAY_CARDINALITY(fds), -1);
790
        if (ret < 0 && (errno == EAGAIN || errno == EINTR))
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
            goto repoll;

        ignore_value(pthread_sigmask(SIG_BLOCK, &oldmask, NULL));
    }

    ret = virNetTLSContextCheckCertificate(tls, client->tls);

    if (ret < 0)
        goto error;

    /* At this point, the server is verifying _our_ certificate, IP address,
     * etc.  If we make the grade, it will send us a '\1' byte.
     */

    fds[0].fd = virNetSocketGetFD(client->sock);
    fds[0].revents = 0;
    fds[0].events = POLLIN;

    /* Block SIGWINCH from interrupting poll in curses programs */
    ignore_value(pthread_sigmask(SIG_BLOCK, &blockedsigs, &oldmask));

    repoll2:
    ret = poll(fds, ARRAY_CARDINALITY(fds), -1);
814
    if (ret < 0 && (errno == EAGAIN || errno == EINTR))
815 816 817 818 819
        goto repoll2;

    ignore_value(pthread_sigmask(SIG_BLOCK, &oldmask, NULL));

    len = virNetTLSSessionRead(client->tls, buf, 1);
820
    if (len < 0 && errno != ENOMSG) {
821 822 823 824 825
        virReportSystemError(errno, "%s",
                             _("Unable to read TLS confirmation"));
        goto error;
    }
    if (len != 1 || buf[0] != '\1') {
826 827 828
        virReportError(VIR_ERR_RPC, "%s",
                       _("server verification (of our certificate or IP "
                         "address) failed"));
829 830 831
        goto error;
    }

832
    virObjectUnlock(client);
833 834 835
    return 0;

error:
836
    virObjectUnref(client->tls);
837
    client->tls = NULL;
838
    virObjectUnlock(client);
839 840
    return -1;
}
841
#endif
842 843 844 845

bool virNetClientIsEncrypted(virNetClientPtr client)
{
    bool ret = false;
846
    virObjectLock(client);
847
#if WITH_GNUTLS
848 849
    if (client->tls)
        ret = true;
850
#endif
851
#if WITH_SASL
852 853 854
    if (client->sasl)
        ret = true;
#endif
855
    virObjectUnlock(client);
856
    return ret;
857 858 859 860 861 862 863 864 865 866
}


bool virNetClientIsOpen(virNetClientPtr client)
{
    bool ret;

    if (!client)
        return false;

867
    virObjectLock(client);
868
    ret = client->sock && !client->wantClose;
869
    virObjectUnlock(client);
870
    return ret;
871 872 873 874 875 876
}


int virNetClientAddProgram(virNetClientPtr client,
                           virNetClientProgramPtr prog)
{
877
    virObjectLock(client);
878 879

    if (VIR_EXPAND_N(client->programs, client->nprograms, 1) < 0)
880
        goto error;
881

882
    client->programs[client->nprograms-1] = virObjectRef(prog);
883

884
    virObjectUnlock(client);
885 886
    return 0;

887
error:
888
    virObjectUnlock(client);
889 890 891 892 893 894 895
    return -1;
}


int virNetClientAddStream(virNetClientPtr client,
                          virNetClientStreamPtr st)
{
896
    virObjectLock(client);
897 898

    if (VIR_EXPAND_N(client->streams, client->nstreams, 1) < 0)
899
        goto error;
900

901
    client->streams[client->nstreams-1] = virObjectRef(st);
902

903
    virObjectUnlock(client);
904 905
    return 0;

906
error:
907
    virObjectUnlock(client);
908 909 910 911 912 913 914
    return -1;
}


void virNetClientRemoveStream(virNetClientPtr client,
                              virNetClientStreamPtr st)
{
915
    virObjectLock(client);
916
    size_t i;
917
    for (i = 0; i < client->nstreams; i++) {
918 919 920 921 922 923
        if (client->streams[i] == st)
            break;
    }
    if (i == client->nstreams)
        goto cleanup;

924
    VIR_DELETE_ELEMENT(client->streams, i, client->nstreams);
925
    virObjectUnref(st);
926 927

cleanup:
928
    virObjectUnlock(client);
929 930 931 932 933 934 935 936 937 938 939 940 941
}


const char *virNetClientLocalAddrString(virNetClientPtr client)
{
    return virNetSocketLocalAddrString(client->sock);
}

const char *virNetClientRemoteAddrString(virNetClientPtr client)
{
    return virNetSocketRemoteAddrString(client->sock);
}

942
#if WITH_GNUTLS
943 944 945
int virNetClientGetTLSKeySize(virNetClientPtr client)
{
    int ret = 0;
946
    virObjectLock(client);
947 948
    if (client->tls)
        ret = virNetTLSSessionGetKeySize(client->tls);
949
    virObjectUnlock(client);
950 951
    return ret;
}
952
#endif
953 954 955 956 957 958 959

static int
virNetClientCallDispatchReply(virNetClientPtr client)
{
    virNetClientCallPtr thecall;

    /* Ok, definitely got an RPC reply now find
960
       out which waiting call is associated with it */
961 962 963 964 965 966 967 968
    thecall = client->waitDispatch;
    while (thecall &&
           !(thecall->msg->header.prog == client->msg.header.prog &&
             thecall->msg->header.vers == client->msg.header.vers &&
             thecall->msg->header.serial == client->msg.header.serial))
        thecall = thecall->next;

    if (!thecall) {
969 970 971
        virReportError(VIR_ERR_RPC,
                       _("no call waiting for reply with prog %d vers %d serial %d"),
                       client->msg.header.prog, client->msg.header.vers, client->msg.header.serial);
972 973 974
        return -1;
    }

975
    if (VIR_REALLOC_N(thecall->msg->buffer, client->msg.bufferLength) < 0)
976 977 978
        return -1;

    memcpy(thecall->msg->buffer, client->msg.buffer, client->msg.bufferLength);
979 980 981 982
    memcpy(&thecall->msg->header, &client->msg.header, sizeof(client->msg.header));
    thecall->msg->bufferLength = client->msg.bufferLength;
    thecall->msg->bufferOffset = client->msg.bufferOffset;

983 984 985 986 987
    thecall->msg->nfds = client->msg.nfds;
    thecall->msg->fds = client->msg.fds;
    client->msg.nfds = 0;
    client->msg.fds = NULL;

988 989 990 991 992 993 994 995 996 997
    thecall->mode = VIR_NET_CLIENT_MODE_COMPLETE;

    return 0;
}

static int virNetClientCallDispatchMessage(virNetClientPtr client)
{
    size_t i;
    virNetClientProgramPtr prog = NULL;

998
    for (i = 0; i < client->nprograms; i++) {
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        if (virNetClientProgramMatches(client->programs[i],
                                       &client->msg)) {
            prog = client->programs[i];
            break;
        }
    }
    if (!prog) {
        VIR_DEBUG("No program found for event with prog=%d vers=%d",
                  client->msg.header.prog, client->msg.header.vers);
        return -1;
    }

    virNetClientProgramDispatch(prog, client, &client->msg);

    return 0;
}

static int virNetClientCallDispatchStream(virNetClientPtr client)
{
    size_t i;
    virNetClientStreamPtr st = NULL;
    virNetClientCallPtr thecall;

    /* First identify what stream this packet is directed at */
1023
    for (i = 0; i < client->nstreams; i++) {
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
        if (virNetClientStreamMatches(client->streams[i],
                                      &client->msg)) {
            st = client->streams[i];
            break;
        }
    }
    if (!st) {
        VIR_DEBUG("No stream found for packet with prog=%d vers=%d serial=%u proc=%u",
                  client->msg.header.prog, client->msg.header.vers,
                  client->msg.header.serial, client->msg.header.proc);
1034 1035 1036
        /* Don't return -1, because we expect to see further stream packets
         * after we've shut it down sometimes */
        return 0;
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    }

    /* Finish/Abort are synchronous, so also see if there's an
     * (optional) call waiting for this stream packet */
    thecall = client->waitDispatch;
    while (thecall &&
           !(thecall->msg->header.prog == client->msg.header.prog &&
             thecall->msg->header.vers == client->msg.header.vers &&
             thecall->msg->header.serial == client->msg.header.serial))
        thecall = thecall->next;

    VIR_DEBUG("Found call %p", thecall);

    /* Status is either
     *   - REMOTE_OK - no payload for streams
     *   - REMOTE_ERROR - followed by a remote_error struct
     *   - REMOTE_CONTINUE - followed by a raw data packet
     */
    switch (client->msg.header.status) {
    case VIR_NET_CONTINUE: {
        if (virNetClientStreamQueuePacket(st, &client->msg) < 0)
            return -1;
1059 1060 1061 1062 1063 1064 1065 1066 1067

        if (thecall && thecall->expectReply) {
            if (thecall->msg->header.status == VIR_NET_CONTINUE) {
                VIR_DEBUG("Got a synchronous confirm");
                thecall->mode = VIR_NET_CLIENT_MODE_COMPLETE;
            } else {
                VIR_DEBUG("Not completing call with status %d", thecall->msg->header.status);
            }
        }
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
        return 0;
    }

    case VIR_NET_OK:
        if (thecall && thecall->expectReply) {
            VIR_DEBUG("Got a synchronous confirm");
            thecall->mode = VIR_NET_CLIENT_MODE_COMPLETE;
        } else {
            VIR_DEBUG("Got unexpected async stream finish confirmation");
            return -1;
        }
        return 0;

    case VIR_NET_ERROR:
        /* No call, so queue the error against the stream */
        if (virNetClientStreamSetError(st, &client->msg) < 0)
            return -1;

        if (thecall && thecall->expectReply) {
            VIR_DEBUG("Got a synchronous error");
            /* Raise error now, so that this call will see it immediately */
E
Eric Blake 已提交
1089 1090
            if (!virNetClientStreamRaiseError(st))
                VIR_DEBUG("unable to raise synchronous error");
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
            thecall->mode = VIR_NET_CLIENT_MODE_COMPLETE;
        }
        return 0;

    default:
        VIR_WARN("Stream with unexpected serial=%d, proc=%d, status=%d",
                 client->msg.header.serial, client->msg.header.proc,
                 client->msg.header.status);
        return -1;
    }

    return 0;
}


static int
virNetClientCallDispatch(virNetClientPtr client)
{
1109 1110
    virNetMessagePtr response = NULL;

1111 1112 1113 1114 1115
    PROBE(RPC_CLIENT_MSG_RX,
          "client=%p len=%zu prog=%u vers=%u proc=%u type=%u status=%u serial=%u",
          client, client->msg.bufferLength,
          client->msg.header.prog, client->msg.header.vers, client->msg.header.proc,
          client->msg.header.type, client->msg.header.status, client->msg.header.serial);
1116

1117 1118 1119 1120 1121 1122
    if (virKeepAliveCheckMessage(client->keepalive, &client->msg, &response)) {
        if (response &&
            virNetClientQueueNonBlocking(client, response) < 0) {
            VIR_WARN("Could not queue keepalive response");
            virNetMessageFree(response);
        }
1123
        return 0;
1124
    }
1125

1126 1127
    switch (client->msg.header.type) {
    case VIR_NET_REPLY: /* Normal RPC replies */
1128 1129 1130
    case VIR_NET_REPLY_WITH_FDS: /* Normal RPC replies with FDs */
        return virNetClientCallDispatchReply(client);

1131 1132 1133 1134 1135 1136 1137
    case VIR_NET_MESSAGE: /* Async notifications */
        return virNetClientCallDispatchMessage(client);

    case VIR_NET_STREAM: /* Stream protocol */
        return virNetClientCallDispatchStream(client);

    default:
1138 1139 1140 1141
        virReportError(VIR_ERR_RPC,
                       _("got unexpected RPC call prog %d vers %d proc %d type %d"),
                       client->msg.header.prog, client->msg.header.vers,
                       client->msg.header.proc, client->msg.header.type);
1142 1143 1144 1145 1146 1147 1148 1149 1150
        return -1;
    }
}


static ssize_t
virNetClientIOWriteMessage(virNetClientPtr client,
                           virNetClientCallPtr thecall)
{
1151
    ssize_t ret = 0;
1152

1153 1154 1155 1156 1157 1158
    if (thecall->msg->bufferOffset < thecall->msg->bufferLength) {
        ret = virNetSocketWrite(client->sock,
                                thecall->msg->buffer + thecall->msg->bufferOffset,
                                thecall->msg->bufferLength - thecall->msg->bufferOffset);
        if (ret <= 0)
            return ret;
1159

1160 1161
        thecall->msg->bufferOffset += ret;
    }
1162 1163

    if (thecall->msg->bufferOffset == thecall->msg->bufferLength) {
1164
        size_t i;
1165
        for (i = thecall->msg->donefds; i < thecall->msg->nfds; i++) {
1166 1167
            int rv;
            if ((rv = virNetSocketSendFD(client->sock, thecall->msg->fds[i])) < 0)
1168
                return -1;
1169 1170 1171
            if (rv == 0) /* Blocking */
                return 0;
            thecall->msg->donefds++;
1172
        }
1173
        thecall->msg->donefds = 0;
1174
        thecall->msg->bufferOffset = thecall->msg->bufferLength = 0;
1175
        VIR_FREE(thecall->msg->fds);
1176
        VIR_FREE(thecall->msg->buffer);
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
        if (thecall->expectReply)
            thecall->mode = VIR_NET_CLIENT_MODE_WAIT_RX;
        else
            thecall->mode = VIR_NET_CLIENT_MODE_COMPLETE;
    }

    return ret;
}


static ssize_t
virNetClientIOHandleOutput(virNetClientPtr client)
{
    virNetClientCallPtr thecall = client->waitDispatch;

    while (thecall &&
           thecall->mode != VIR_NET_CLIENT_MODE_WAIT_TX)
        thecall = thecall->next;

    if (!thecall)
1197 1198 1199 1200
        return 0; /* This can happen if another thread raced with us and
                   * completed the call between the time this thread woke
                   * up from poll()ing and the time we locked the client
                   */
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222

    while (thecall) {
        ssize_t ret = virNetClientIOWriteMessage(client, thecall);
        if (ret < 0)
            return ret;

        if (thecall->mode == VIR_NET_CLIENT_MODE_WAIT_TX)
            return 0; /* Blocking write, to back to event loop */

        thecall = thecall->next;
    }

    return 0; /* No more calls to send, all done */
}

static ssize_t
virNetClientIOReadMessage(virNetClientPtr client)
{
    size_t wantData;
    ssize_t ret;

    /* Start by reading length word */
1223
    if (client->msg.bufferLength == 0) {
1224
        client->msg.bufferLength = 4;
1225
        if (VIR_ALLOC_N(client->msg.buffer, client->msg.bufferLength) < 0)
1226 1227
            return -ENOMEM;
    }
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249

    wantData = client->msg.bufferLength - client->msg.bufferOffset;

    ret = virNetSocketRead(client->sock,
                           client->msg.buffer + client->msg.bufferOffset,
                           wantData);
    if (ret <= 0)
        return ret;

    client->msg.bufferOffset += ret;

    return ret;
}


static ssize_t
virNetClientIOHandleInput(virNetClientPtr client)
{
    /* Read as much data as is available, until we get
     * EAGAIN
     */
    for (;;) {
1250
        ssize_t ret;
1251

1252 1253 1254 1255 1256 1257 1258 1259
        if (client->msg.nfds == 0) {
            ret = virNetClientIOReadMessage(client);

            if (ret < 0)
                return -1;
            if (ret == 0)
                return 0;  /* Blocking on read */
        }
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274

        /* Check for completion of our goal */
        if (client->msg.bufferOffset == client->msg.bufferLength) {
            if (client->msg.bufferOffset == 4) {
                ret = virNetMessageDecodeLength(&client->msg);
                if (ret < 0)
                    return -1;

                /*
                 * We'll carry on around the loop to immediately
                 * process the message body, because it has probably
                 * already arrived. Worst case, we'll get EAGAIN on
                 * next iteration.
                 */
            } else {
1275 1276 1277 1278 1279
                if (virNetMessageDecodeHeader(&client->msg) < 0)
                    return -1;

                if (client->msg.header.type == VIR_NET_REPLY_WITH_FDS) {
                    size_t i;
1280 1281 1282

                    if (client->msg.nfds == 0 &&
                        virNetMessageDecodeNumFDs(&client->msg) < 0)
1283 1284
                        return -1;

1285
                    for (i = client->msg.donefds; i < client->msg.nfds; i++) {
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
                        int rv;
                        if ((rv = virNetSocketRecvFD(client->sock, &(client->msg.fds[i]))) < 0)
                            return -1;
                        if (rv == 0) /* Blocking */
                            break;
                        client->msg.donefds++;
                    }

                    if (client->msg.donefds < client->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->msg.bufferOffset = client->msg.bufferLength;
                        return 0; /* Blocking on more fds */
                    }
                }

1304
                ret = virNetClientCallDispatch(client);
1305
                virNetMessageClear(&client->msg);
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
                /*
                 * We've completed one call, but we don't want to
                 * spin around the loop forever if there are many
                 * incoming async events, or replies for other
                 * thread's RPC calls. We want to get out & let
                 * any other thread take over as soon as we've
                 * got our reply. When SASL is active though, we
                 * may have read more data off the wire than we
                 * initially wanted & cached it in memory. In this
                 * case, poll() would not detect that there is more
                 * ready todo.
                 *
                 * So if SASL is active *and* some SASL data is
                 * already cached, then we'll process that now,
                 * before returning.
                 */
                if (ret == 0 &&
                    virNetSocketHasCachedData(client->sock))
                    continue;
                return ret;
            }
        }
    }
}


1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
static bool virNetClientIOEventLoopPollEvents(virNetClientCallPtr call,
                                              void *opaque)
{
    struct pollfd *fd = opaque;

    if (call->mode == VIR_NET_CLIENT_MODE_WAIT_RX)
        fd->events |= POLLIN;
    if (call->mode == VIR_NET_CLIENT_MODE_WAIT_TX)
        fd->events |= POLLOUT;

    return false;
}


static bool virNetClientIOEventLoopRemoveDone(virNetClientCallPtr call,
                                              void *opaque)
{
    virNetClientCallPtr thiscall = opaque;

    if (call == thiscall)
        return false;

    if (call->mode != VIR_NET_CLIENT_MODE_COMPLETE)
        return false;

    /*
1358 1359 1360 1361 1362 1363
     * ...if the call being removed from the list
     * still has a thread, then wake that thread up,
     * otherwise free the call. The latter should
     * only happen for calls without replies.
     *
     * ...the threads won't actually wakeup until
1364 1365 1366
     * we release our mutex a short while
     * later...
     */
1367 1368 1369 1370
    if (call->haveThread) {
        VIR_DEBUG("Waking up sleep %p", call);
        virCondSignal(&call->cond);
    } else {
1371
        VIR_DEBUG("Removing completed call %p", call);
1372 1373
        if (call->expectReply)
            VIR_WARN("Got a call expecting a reply but without a waiting thread");
1374
        virCondDestroy(&call->cond);
1375 1376 1377
        VIR_FREE(call->msg);
        VIR_FREE(call);
    }
1378 1379 1380 1381

    return true;
}

1382

1383 1384
static void
virNetClientIODetachNonBlocking(virNetClientCallPtr call)
1385
{
1386 1387
    VIR_DEBUG("Keeping unfinished non-blocking call %p in the queue", call);
    call->haveThread = false;
1388 1389 1390
}


1391 1392 1393
static bool
virNetClientIOEventLoopRemoveAll(virNetClientCallPtr call,
                                 void *opaque)
1394
{
1395
    virNetClientCallPtr thiscall = opaque;
1396

1397 1398 1399 1400
    if (call == thiscall)
        return false;

    VIR_DEBUG("Removing call %p", call);
1401
    virCondDestroy(&call->cond);
1402 1403 1404
    VIR_FREE(call->msg);
    VIR_FREE(call);
    return true;
1405 1406 1407
}


1408 1409 1410
static void
virNetClientIOEventLoopPassTheBuck(virNetClientPtr client,
                                   virNetClientCallPtr thiscall)
1411 1412 1413 1414 1415 1416
{
    VIR_DEBUG("Giving up the buck %p", thiscall);
    virNetClientCallPtr tmp = client->waitDispatch;
    /* See if someone else is still waiting
     * and if so, then pass the buck ! */
    while (tmp) {
1417
        if (tmp != thiscall && tmp->haveThread) {
1418 1419
            VIR_DEBUG("Passing the buck to %p", tmp);
            virCondSignal(&tmp->cond);
1420
            return;
1421 1422 1423
        }
        tmp = tmp->next;
    }
1424
    client->haveTheBuck = false;
1425

1426
    VIR_DEBUG("No thread to pass the buck to");
1427 1428
    if (client->wantClose) {
        virNetClientCloseLocked(client);
1429 1430 1431
        virNetClientCallRemovePredicate(&client->waitDispatch,
                                        virNetClientIOEventLoopRemoveAll,
                                        thiscall);
1432
    }
1433 1434 1435
}


1436 1437 1438 1439
/*
 * Process all calls pending dispatch/receive until we
 * get a reply to our own call. Then quit and pass the buck
 * to someone else.
1440
 *
1441
 * Returns 1 if the call was queued and will be completed later (only
1442
 * for nonBlock == true), 0 if the call was completed and -1 on error.
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
 */
static int virNetClientIOEventLoop(virNetClientPtr client,
                                   virNetClientCallPtr thiscall)
{
    struct pollfd fds[2];
    int ret;

    fds[0].fd = virNetSocketGetFD(client->sock);
    fds[1].fd = client->wakeupReadFD;

    for (;;) {
        char ignore;
        sigset_t oldmask, blockedsigs;
        int timeout = -1;
1457
        virNetMessagePtr msg = NULL;
1458

1459 1460 1461 1462
        /* If we have existing SASL decoded data we don't want to sleep in
         * the poll(), just check if any other FDs are also ready.
         * If the connection is going to be closed, we don't want to sleep in
         * poll() either.
1463
         */
1464
        if (virNetSocketHasCachedData(client->sock) || client->wantClose)
1465 1466
            timeout = 0;

1467 1468
        /* If we are non-blocking, then we don't want to sleep in poll() */
        if (thiscall->nonBlock)
1469 1470
            timeout = 0;

1471 1472 1473 1474
        /* Limit timeout so that we can send keepalive request in time */
        if (timeout == -1)
            timeout = virKeepAliveTimeout(client->keepalive);

1475 1476 1477 1478 1479
        fds[0].events = fds[0].revents = 0;
        fds[1].events = fds[1].revents = 0;

        fds[1].events = POLLIN;

1480 1481 1482 1483
        /* Calculate poll events for calls */
        virNetClientCallMatchPredicate(client->waitDispatch,
                                       virNetClientIOEventLoopPollEvents,
                                       &fds[0]);
1484 1485 1486 1487 1488 1489 1490 1491 1492 1493

        /* We have to be prepared to receive stream data
         * regardless of whether any of the calls waiting
         * for dispatch are for streams.
         */
        if (client->nstreams)
            fds[0].events |= POLLIN;

        /* Release lock while poll'ing so other threads
         * can stuff themselves on the queue */
1494
        virObjectUnlock(client);
1495 1496 1497 1498 1499 1500

        /* Block SIGWINCH from interrupting poll in curses programs,
         * then restore the original signal mask again immediately
         * after the call (RHBZ#567931).  Same for SIGCHLD and SIGPIPE
         * at the suggestion of Paolo Bonzini and Daniel Berrange.
         */
1501
        sigemptyset(&blockedsigs);
E
Eric Blake 已提交
1502
#ifdef SIGWINCH
1503
        sigaddset(&blockedsigs, SIGWINCH);
E
Eric Blake 已提交
1504 1505
#endif
#ifdef SIGCHLD
1506
        sigaddset(&blockedsigs, SIGCHLD);
E
Eric Blake 已提交
1507
#endif
1508
        sigaddset(&blockedsigs, SIGPIPE);
1509 1510 1511 1512
        ignore_value(pthread_sigmask(SIG_BLOCK, &blockedsigs, &oldmask));

    repoll:
        ret = poll(fds, ARRAY_CARDINALITY(fds), timeout);
1513
        if (ret < 0 && (errno == EAGAIN || errno == EINTR))
1514 1515 1516 1517
            goto repoll;

        ignore_value(pthread_sigmask(SIG_SETMASK, &oldmask, NULL));

1518
        virObjectLock(client);
1519

1520 1521 1522 1523 1524 1525
        if (ret < 0) {
            virReportSystemError(errno,
                                 "%s", _("poll on socket failed"));
            goto error;
        }

1526
        if (virKeepAliveTrigger(client->keepalive, &msg)) {
1527
            virNetClientMarkClose(client, VIR_CONNECT_CLOSE_REASON_KEEPALIVE);
1528 1529 1530 1531 1532
        } else if (msg && virNetClientQueueNonBlocking(client, msg) < 0) {
            VIR_WARN("Could not queue keepalive request");
            virNetMessageFree(msg);
        }

1533 1534 1535
        /* If we have existing SASL decoded data, pretend
         * the socket became readable so we consume it
         */
1536
        if (virNetSocketHasCachedData(client->sock)) {
1537
            fds[0].revents |= POLLIN;
1538
        }
1539

1540 1541 1542 1543 1544
        /* If wantClose flag is set, pretend there was an error on the socket
         */
        if (client->wantClose)
            fds[0].revents = POLLERR;

1545 1546 1547 1548 1549
        if (fds[1].revents) {
            VIR_DEBUG("Woken up from poll by other thread");
            if (saferead(client->wakeupReadFD, &ignore, sizeof(ignore)) != sizeof(ignore)) {
                virReportSystemError(errno, "%s",
                                     _("read on wakeup fd failed"));
1550
                virNetClientMarkClose(client, VIR_CONNECT_CLOSE_REASON_ERROR);
1551 1552 1553 1554 1555
                goto error;
            }
        }

        if (fds[0].revents & POLLOUT) {
1556 1557
            if (virNetClientIOHandleOutput(client) < 0) {
                virNetClientMarkClose(client, VIR_CONNECT_CLOSE_REASON_ERROR);
1558
                goto error;
1559
            }
1560 1561 1562
        }

        if (fds[0].revents & POLLIN) {
1563 1564
            if (virNetClientIOHandleInput(client) < 0) {
                virNetClientMarkClose(client, VIR_CONNECT_CLOSE_REASON_ERROR);
1565
                goto error;
1566
            }
1567 1568
        }

1569
        /* Iterate through waiting calls and if any are
1570
         * complete, remove them from the dispatch list.
1571
         */
1572 1573 1574
        virNetClientCallRemovePredicate(&client->waitDispatch,
                                        virNetClientIOEventLoopRemoveDone,
                                        thiscall);
1575 1576 1577

        /* Now see if *we* are done */
        if (thiscall->mode == VIR_NET_CLIENT_MODE_COMPLETE) {
1578
            virNetClientCallRemove(&client->waitDispatch, thiscall);
1579
            virNetClientIOEventLoopPassTheBuck(client, thiscall);
1580
            return 0;
1581 1582
        }

1583
        /* We're not done, but we're non-blocking; keep the call queued */
1584
        if (thiscall->nonBlock) {
1585
            virNetClientIODetachNonBlocking(thiscall);
1586
            virNetClientIOEventLoopPassTheBuck(client, thiscall);
1587
            return 1;
1588
        }
1589 1590

        if (fds[0].revents & (POLLHUP | POLLERR)) {
1591
            virNetClientMarkClose(client, VIR_CONNECT_CLOSE_REASON_EOF);
1592 1593
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("received hangup / error event on socket"));
1594 1595 1596 1597 1598
            goto error;
        }
    }

error:
1599
    virNetClientCallRemove(&client->waitDispatch, thiscall);
1600
    virNetClientIOEventLoopPassTheBuck(client, thiscall);
1601 1602 1603 1604
    return -1;
}


1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617
static bool
virNetClientIOUpdateEvents(virNetClientCallPtr call,
                           void *opaque)
{
    int *events = opaque;

    if (call->mode == VIR_NET_CLIENT_MODE_WAIT_TX)
        *events |= VIR_EVENT_HANDLE_WRITABLE;

    return false;
}


1618 1619 1620 1621
static void virNetClientIOUpdateCallback(virNetClientPtr client,
                                         bool enableCallback)
{
    int events = 0;
1622

1623 1624 1625
    if (client->wantClose)
        return;

1626
    if (enableCallback) {
1627
        events |= VIR_EVENT_HANDLE_READABLE;
1628 1629 1630 1631
        virNetClientCallMatchPredicate(client->waitDispatch,
                                       virNetClientIOUpdateEvents,
                                       &events);
    }
1632 1633 1634 1635 1636

    virNetSocketUpdateIOCallback(client->sock, events);
}


1637 1638 1639 1640 1641 1642 1643 1644
/*
 * This function sends a message to remote server and awaits a reply
 *
 * NB. This does not free the args structure (not desirable, since you
 * often want this allocated on the stack or else it contains strings
 * which come from the user).  It does however free any intermediate
 * results, eg. the error structure if there is one.
 *
1645
 * NB(2). Make sure to memset (&ret, 0, sizeof(ret)) before calling,
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
 * else Bad Things will happen in the XDR code.
 *
 * NB(3) You must have the client lock before calling this
 *
 * NB(4) This is very complicated. Multiple threads are allowed to
 * use the client for RPC at the same time. Obviously only one of
 * them can. So if someone's using the socket, other threads are put
 * to sleep on condition variables. The existing thread may completely
 * send & receive their RPC call/reply while they're asleep. Or it
 * may only get around to dealing with sending the call. Or it may
 * get around to neither. So upon waking up from slumber, the other
 * thread may or may not have more work todo.
 *
 * We call this dance  'passing the buck'
 *
 *      http://en.wikipedia.org/wiki/Passing_the_buck
 *
 *   "Buck passing or passing the buck is the action of transferring
 *    responsibility or blame unto another person. It is also used as
 *    a strategy in power politics when the actions of one country/
 *    nation are blamed on another, providing an opportunity for war."
 *
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690
 * NB(5) If the 'thiscall' has the 'nonBlock' flag set, the caller
 * must *NOT* free it, if this returns '1' (ie partial send).
 *
 * NB(6) The following input states are valid if *no* threads
 *       are currently executing this method
 *
 *   - waitDispatch == NULL,
 *   - waitDispatch != NULL, waitDispatch.nonBlock == true
 *
 * The following input states are valid, if n threads are currently
 * executing
 *
 *   - waitDispatch != NULL
 *   - 0 or 1  waitDispatch.nonBlock == false, without any threads
 *   - 0 or more waitDispatch.nonBlock == false, with threads
 *
 * The following output states are valid when all threads are done
 *
 *   - waitDispatch == NULL,
 *   - waitDispatch != NULL, waitDispatch.nonBlock == true
 *
 * NB(7) Don't Panic!
 *
1691
 * Returns 1 if the call was queued and will be completed later (only
1692
 * for nonBlock == true), 0 if the call was completed and -1 on error.
1693 1694 1695 1696 1697 1698
 */
static int virNetClientIO(virNetClientPtr client,
                          virNetClientCallPtr thiscall)
{
    int rv = -1;

1699
    VIR_DEBUG("Outgoing message prog=%u version=%u serial=%u proc=%d type=%d length=%zu dispatch=%p",
1700 1701 1702 1703 1704 1705 1706 1707
              thiscall->msg->header.prog,
              thiscall->msg->header.vers,
              thiscall->msg->header.serial,
              thiscall->msg->header.proc,
              thiscall->msg->header.type,
              thiscall->msg->bufferLength,
              client->waitDispatch);

1708 1709 1710
    /* Stick ourselves on the end of the wait queue */
    virNetClientCallQueue(&client->waitDispatch, thiscall);

1711
    /* Check to see if another thread is dispatching */
1712
    if (client->haveTheBuck) {
1713 1714 1715 1716
        char ignore = 1;

        /* Force other thread to wakeup from poll */
        if (safewrite(client->wakeupSendFD, &ignore, sizeof(ignore)) != sizeof(ignore)) {
1717
            virNetClientCallRemove(&client->waitDispatch, thiscall);
1718 1719 1720 1721 1722
            virReportSystemError(errno, "%s",
                                 _("failed to wake up polling thread"));
            return -1;
        }

1723 1724 1725 1726 1727 1728 1729 1730
        /* If we are non-blocking, detach the thread and keep the call in the
         * queue. */
        if (thiscall->nonBlock) {
            virNetClientIODetachNonBlocking(thiscall);
            rv = 1;
            goto cleanup;
        }

1731 1732
        VIR_DEBUG("Going to sleep head=%p call=%p",
                  client->waitDispatch, thiscall);
1733
        /* Go to sleep while other thread is working... */
1734
        if (virCondWait(&thiscall->cond, &client->parent.lock) < 0) {
1735
            virNetClientCallRemove(&client->waitDispatch, thiscall);
1736 1737
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("failed to wait on condition"));
1738 1739 1740
            return -1;
        }

1741 1742
        VIR_DEBUG("Woken up from sleep head=%p call=%p",
                  client->waitDispatch, thiscall);
1743
        /* Three reasons we can be woken up
1744 1745 1746 1747 1748 1749
         *  1. Other thread has got our reply ready for us
         *  2. Other thread is all done, and it is our turn to
         *     be the dispatcher to finish waiting for
         *     our reply
         */
        if (thiscall->mode == VIR_NET_CLIENT_MODE_COMPLETE) {
1750
            rv = 0;
1751 1752 1753 1754 1755 1756 1757 1758
            /*
             * We avoided catching the buck and our reply is ready !
             * We've already had 'thiscall' removed from the list
             * so just need to (maybe) handle errors & free it
             */
            goto cleanup;
        }

E
Eric Blake 已提交
1759
        /* Grr, someone passed the buck to us ... */
1760 1761
    } else {
        client->haveTheBuck = true;
1762 1763
    }

1764 1765
    VIR_DEBUG("We have the buck head=%p call=%p",
              client->waitDispatch, thiscall);
1766

1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780
    /*
     * The buck stops here!
     *
     * At this point we're about to own the dispatch
     * process...
     */

    /*
     * Avoid needless wake-ups of the event loop in the
     * case where this call is being made from a different
     * thread than the event loop. These wake-ups would
     * cause the event loop thread to be blocked on the
     * mutex for the duration of the call
     */
1781
    virNetClientIOUpdateCallback(client, false);
1782

1783
    virResetLastError();
1784 1785
    rv = virNetClientIOEventLoop(client, thiscall);

1786 1787
    if (client->sock)
        virNetClientIOUpdateCallback(client, true);
1788

1789 1790 1791 1792
    if (rv == 0 &&
        virGetLastError())
        rv = -1;

1793
cleanup:
1794 1795
    VIR_DEBUG("All done with our call head=%p call=%p rv=%d",
              client->waitDispatch, thiscall, rv);
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
    return rv;
}


void virNetClientIncomingEvent(virNetSocketPtr sock,
                               int events,
                               void *opaque)
{
    virNetClientPtr client = opaque;

1806
    virObjectLock(client);
1807

1808 1809
    VIR_DEBUG("client=%p wantclose=%d", client, client ? client->wantClose : false);

1810 1811 1812
    if (!client->sock)
        goto done;

1813
    if (client->haveTheBuck || client->wantClose)
1814 1815 1816 1817
        goto done;

    VIR_DEBUG("Event fired %p %d", sock, events);

1818 1819
    if (events & VIR_EVENT_HANDLE_WRITABLE) {
        if (virNetClientIOHandleOutput(client) < 0)
1820
            virNetClientMarkClose(client, VIR_CONNECT_CLOSE_REASON_ERROR);
1821 1822 1823 1824
    }

    if (events & VIR_EVENT_HANDLE_READABLE) {
        if (virNetClientIOHandleInput(client) < 0)
1825
            virNetClientMarkClose(client, VIR_CONNECT_CLOSE_REASON_ERROR);
1826
    }
1827

1828 1829 1830 1831 1832 1833 1834 1835 1836 1837
    if (events & (VIR_EVENT_HANDLE_HANGUP | VIR_EVENT_HANDLE_ERROR)) {
        VIR_DEBUG("VIR_EVENT_HANDLE_HANGUP or "
                  "VIR_EVENT_HANDLE_ERROR encountered");
        virNetClientMarkClose(client,
                              (events & VIR_EVENT_HANDLE_HANGUP) ?
                              VIR_CONNECT_CLOSE_REASON_EOF :
                              VIR_CONNECT_CLOSE_REASON_ERROR);
        goto done;
    }

1838 1839 1840 1841
    /* Remove completed calls or signal their threads. */
    virNetClientCallRemovePredicate(&client->waitDispatch,
                                    virNetClientIOEventLoopRemoveDone,
                                    NULL);
1842 1843
    virNetClientIOUpdateCallback(client, true);

1844
done:
1845
    if (client->wantClose && !client->haveTheBuck) {
1846
        virNetClientCloseLocked(client);
1847 1848 1849 1850
        virNetClientCallRemovePredicate(&client->waitDispatch,
                                        virNetClientIOEventLoopRemoveAll,
                                        NULL);
    }
1851
    virObjectUnlock(client);
1852 1853 1854
}


1855 1856 1857 1858
static virNetClientCallPtr
virNetClientCallNew(virNetMessagePtr msg,
                    bool expectReply,
                    bool nonBlock)
1859
{
1860
    virNetClientCallPtr call = NULL;
1861

1862
    if (expectReply &&
1863
        (msg->bufferLength != 0) &&
1864
        (msg->header.status == VIR_NET_CONTINUE)) {
1865 1866 1867
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Attempt to send an asynchronous message with"
                         " a synchronous reply"));
1868
        goto error;
1869 1870
    }

1871
    if (expectReply && nonBlock) {
1872 1873 1874
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Attempt to send a non-blocking message with"
                         " a synchronous reply"));
1875
        goto error;
1876 1877
    }

1878
    if (VIR_ALLOC(call) < 0)
1879
        goto error;
1880

1881
    if (virCondInit(&call->cond) < 0) {
1882 1883
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot initialize condition variable"));
1884
        goto error;
1885 1886
    }

1887
    msg->donefds = 0;
1888 1889 1890 1891 1892 1893
    if (msg->bufferLength)
        call->mode = VIR_NET_CLIENT_MODE_WAIT_TX;
    else
        call->mode = VIR_NET_CLIENT_MODE_WAIT_RX;
    call->msg = msg;
    call->expectReply = expectReply;
1894
    call->nonBlock = nonBlock;
1895

1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
    VIR_DEBUG("New call %p: msg=%p, expectReply=%d, nonBlock=%d",
              call, msg, expectReply, nonBlock);

    return call;

error:
    VIR_FREE(call);
    return NULL;
}


1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
static int
virNetClientQueueNonBlocking(virNetClientPtr client,
                             virNetMessagePtr msg)
{
    virNetClientCallPtr call;

    PROBE(RPC_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);

    if (!(call = virNetClientCallNew(msg, false, true)))
        return -1;

    virNetClientCallQueue(&client->waitDispatch, call);
    return 0;
}


1928 1929
/*
 * Returns 1 if the call was queued and will be completed later (only
1930
 * for nonBlock == true), 0 if the call was completed and -1 on error.
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946
 */
static int virNetClientSendInternal(virNetClientPtr client,
                                    virNetMessagePtr msg,
                                    bool expectReply,
                                    bool nonBlock)
{
    virNetClientCallPtr call;
    int ret = -1;

    PROBE(RPC_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);

    if (!client->sock || client->wantClose) {
1947 1948
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("client socket is closed"));
1949 1950 1951
        return -1;
    }

1952
    if (!(call = virNetClientCallNew(msg, expectReply, nonBlock)))
1953 1954 1955
        return -1;

    call->haveThread = true;
1956 1957
    ret = virNetClientIO(client, call);

1958 1959 1960 1961 1962
    /* If queued, the call will be finished and freed later by another thread;
     * we're done. */
    if (ret == 1)
        return 1;

1963
    virCondDestroy(&call->cond);
1964
    VIR_FREE(call);
1965 1966
    return ret;
}
1967

1968

1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
/*
 * @msg: a message allocated on heap or stack
 *
 * Send a message synchronously, and wait for the reply synchronously
 *
 * The caller is responsible for free'ing @msg if it was allocated
 * on the heap
 *
 * Returns 0 on success, -1 on failure
 */
int virNetClientSendWithReply(virNetClientPtr client,
                              virNetMessagePtr msg)
{
M
Michal Privoznik 已提交
1982
    int ret;
1983
    virObjectLock(client);
M
Michal Privoznik 已提交
1984
    ret = virNetClientSendInternal(client, msg, true, false);
1985
    virObjectUnlock(client);
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
    if (ret < 0)
        return -1;
    return 0;
}


/*
 * @msg: a message allocated on heap or stack
 *
 * Send a message synchronously, without any reply
 *
 * The caller is responsible for free'ing @msg if it was allocated
 * on the heap
 *
 * Returns 0 on success, -1 on failure
 */
int virNetClientSendNoReply(virNetClientPtr client,
                            virNetMessagePtr msg)
{
M
Michal Privoznik 已提交
2005
    int ret;
2006
    virObjectLock(client);
M
Michal Privoznik 已提交
2007
    ret = virNetClientSendInternal(client, msg, false, false);
2008
    virObjectUnlock(client);
2009 2010 2011 2012
    if (ret < 0)
        return -1;
    return 0;
}
2013 2014 2015 2016 2017 2018 2019

/*
 * @msg: a message allocated on the heap.
 *
 * Send a message asynchronously, without any reply
 *
 * The caller is responsible for free'ing @msg, *except* if
2020
 * this method returns 1.
2021
 *
2022
 * Returns 1 if the message was queued and will be completed later (only
2023
 * for nonBlock == true), 0 if the message was completed and -1 on error.
2024 2025 2026 2027
 */
int virNetClientSendNonBlock(virNetClientPtr client,
                             virNetMessagePtr msg)
{
M
Michal Privoznik 已提交
2028
    int ret;
2029
    virObjectLock(client);
M
Michal Privoznik 已提交
2030
    ret = virNetClientSendInternal(client, msg, false, true);
2031
    virObjectUnlock(client);
M
Michal Privoznik 已提交
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
    return ret;
}

/*
 * @msg: a message allocated on heap or stack
 *
 * Send a message synchronously, and wait for the reply synchronously
 *
 * The caller is responsible for free'ing @msg if it was allocated
 * on the heap
 *
 * Returns 0 on success, -1 on failure
 */
int virNetClientSendWithReplyStream(virNetClientPtr client,
                                    virNetMessagePtr msg,
                                    virNetClientStreamPtr st)
{
    int ret;
2050
    virObjectLock(client);
M
Michal Privoznik 已提交
2051 2052 2053 2054 2055
    /* Other thread might have already received
     * stream EOF so we don't want sent anything.
     * Server won't respond anyway.
     */
    if (virNetClientStreamEOF(st)) {
2056
        virObjectUnlock(client);
M
Michal Privoznik 已提交
2057 2058 2059 2060
        return 0;
    }

    ret = virNetClientSendInternal(client, msg, true, false);
2061
    virObjectUnlock(client);
M
Michal Privoznik 已提交
2062 2063 2064
    if (ret < 0)
        return -1;
    return 0;
2065
}