virnetsocket.c 55.4 KB
Newer Older
1 2 3
/*
 * virnetsocket.c: generic network socket handling
 *
4
 * Copyright (C) 2006-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25 26 27 28 29
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/wait.h>
30
#include <signal.h>
31
#include <fcntl.h>
32 33 34
#ifdef HAVE_IFADDRS_H
# include <ifaddrs.h>
#endif
35
#include <netdb.h>
36 37 38 39 40

#ifdef HAVE_NETINET_TCP_H
# include <netinet/tcp.h>
#endif

41 42 43 44
#ifdef HAVE_SYS_UCRED_H
# include <sys/ucred.h>
#endif

45
#include "c-ctype.h"
46
#ifdef WITH_SELINUX
47 48 49
# include <selinux/selinux.h>
#endif

50
#include "virnetsocket.h"
51
#include "virutil.h"
52
#include "viralloc.h"
53
#include "virerror.h"
54
#include "virlog.h"
E
Eric Blake 已提交
55
#include "virfile.h"
56
#include "virthread.h"
57
#include "virpidfile.h"
58
#include "virprobe.h"
59
#include "virprocess.h"
60
#include "virstring.h"
61
#include "dirname.h"
62 63
#include "passfd.h"

64
#if WITH_SSH2
65 66 67
# include "virnetsshsession.h"
#endif

68 69
#define VIR_FROM_THIS VIR_FROM_RPC

70
VIR_LOG_INIT("rpc.netsocket");
71 72

struct _virNetSocket {
73
    virObjectLockable parent;
74

75 76 77 78 79
    int fd;
    int watch;
    pid_t pid;
    int errfd;
    bool client;
80 81

    /* Event callback fields */
82 83
    virNetSocketIOFunc func;
    void *opaque;
84 85
    virFreeCallback ff;

86 87 88 89
    virSocketAddr localAddr;
    virSocketAddr remoteAddr;
    char *localAddrStr;
    char *remoteAddrStr;
90

91
#if WITH_GNUTLS
92
    virNetTLSSessionPtr tlsSession;
93
#endif
94
#if WITH_SASL
95 96 97 98 99 100 101 102 103 104
    virNetSASLSessionPtr saslSession;

    const char *saslDecoded;
    size_t saslDecodedLength;
    size_t saslDecodedOffset;

    const char *saslEncoded;
    size_t saslEncodedLength;
    size_t saslEncodedOffset;
#endif
105
#if WITH_SSH2
106 107
    virNetSSHSessionPtr sshSession;
#endif
108 109 110
};


111 112 113 114 115
static virClassPtr virNetSocketClass;
static void virNetSocketDispose(void *obj);

static int virNetSocketOnceInit(void)
{
116
    if (!(virNetSocketClass = virClassNew(virClassForObjectLockable(),
117
                                          "virNetSocket",
118 119 120 121 122 123 124 125 126 127
                                          sizeof(virNetSocket),
                                          virNetSocketDispose)))
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(virNetSocket)


128
#ifndef WIN32
129
static int virNetSocketForkDaemon(const char *binary)
130 131 132 133 134 135 136
{
    int ret;
    virCommandPtr cmd = virCommandNewArgList(binary,
                                             "--timeout=30",
                                             NULL);

    virCommandAddEnvPassCommon(cmd);
137 138 139
    virCommandAddEnvPassBlockSUID(cmd, "XDG_CACHE_HOME", NULL);
    virCommandAddEnvPassBlockSUID(cmd, "XDG_CONFIG_HOME", NULL);
    virCommandAddEnvPassBlockSUID(cmd, "XDG_RUNTIME_DIR", NULL);
140 141 142 143 144 145 146 147
    virCommandClearCaps(cmd);
    virCommandDaemonize(cmd);
    ret = virCommandRun(cmd, NULL);
    virCommandFree(cmd);
    return ret;
}
#endif

148 149 150 151 152 153 154 155 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
int virNetSocketCheckProtocols(bool *hasIPv4,
                               bool *hasIPv6)
{
#ifdef HAVE_IFADDRS_H
    struct ifaddrs *ifaddr = NULL, *ifa;
    struct addrinfo hints;
    struct addrinfo *ai = NULL;
    int ret = -1;
    int gaierr;

    memset(&hints, 0, sizeof(hints));

    *hasIPv4 = *hasIPv6 = false;

    if (getifaddrs(&ifaddr) < 0) {
        virReportSystemError(errno, "%s",
                             _("Cannot get host interface addresses"));
        goto cleanup;
    }

    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
        if (!ifa->ifa_addr)
            continue;

        if (ifa->ifa_addr->sa_family == AF_INET)
            *hasIPv4 = true;
        if (ifa->ifa_addr->sa_family == AF_INET6)
            *hasIPv6 = true;
    }

    freeifaddrs(ifaddr);

    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
    hints.ai_family = AF_INET6;
    hints.ai_socktype = SOCK_STREAM;

    if ((gaierr = getaddrinfo("::1", NULL, &hints, &ai)) != 0) {
        if (gaierr == EAI_ADDRFAMILY ||
186 187
            gaierr == EAI_FAMILY ||
            gaierr == EAI_NONAME) {
188 189 190 191 192 193 194 195 196 197 198
            *hasIPv6 = false;
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot resolve ::1 address: %s"),
                           gai_strerror(gaierr));
            goto cleanup;
        }
    }

    freeaddrinfo(ai);

J
Jiri Denemark 已提交
199
    VIR_DEBUG("Protocols: v4 %d v6 %d", *hasIPv4, *hasIPv6);
200 201 202 203 204 205 206 207 208 209 210 211

    ret = 0;
 cleanup:
    return ret;
#else
    *hasIPv4 = *hasIPv6 = false;
    virReportError(VIR_ERR_NO_SUPPORT, "%s",
                   _("Cannot check address family on this platform"));
    return -1;
#endif
}

212 213 214 215 216 217 218 219 220

static virNetSocketPtr virNetSocketNew(virSocketAddrPtr localAddr,
                                       virSocketAddrPtr remoteAddr,
                                       bool isClient,
                                       int fd, int errfd, pid_t pid)
{
    virNetSocketPtr sock;
    int no_slow_start = 1;

221 222 223
    if (virNetSocketInitialize() < 0)
        return NULL;

E
Eric Blake 已提交
224
    VIR_DEBUG("localAddr=%p remoteAddr=%p fd=%d errfd=%d pid=%lld",
225
              localAddr, remoteAddr,
E
Eric Blake 已提交
226
              fd, errfd, (long long) pid);
227 228 229 230 231 232 233 234 235 236 237 238

    if (virSetCloseExec(fd) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to set close-on-exec flag"));
       return NULL;
    }
    if (virSetNonBlock(fd) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to enable non-blocking flag"));
        return NULL;
    }

239
    if (!(sock = virObjectLockableNew(virNetSocketClass)))
240 241
        return NULL;

242 243 244 245 246 247 248
    if (localAddr)
        sock->localAddr = *localAddr;
    if (remoteAddr)
        sock->remoteAddr = *remoteAddr;
    sock->fd = fd;
    sock->errfd = errfd;
    sock->pid = pid;
249
    sock->watch = -1;
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264

    /* Disable nagle for TCP sockets */
    if (sock->localAddr.data.sa.sa_family == AF_INET ||
        sock->localAddr.data.sa.sa_family == AF_INET6) {
        if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
                       &no_slow_start,
                       sizeof(no_slow_start)) < 0) {
            virReportSystemError(errno, "%s",
                                 _("Unable to disable nagle algorithm"));
            goto error;
        }
    }


    if (localAddr &&
265
        !(sock->localAddrStr = virSocketAddrFormatFull(localAddr, true, ";")))
266 267 268
        goto error;

    if (remoteAddr &&
269
        !(sock->remoteAddrStr = virSocketAddrFormatFull(remoteAddr, true, ";")))
270 271 272 273
        goto error;

    sock->client = isClient;

274
    PROBE(RPC_SOCKET_NEW,
275 276
          "sock=%p fd=%d errfd=%d pid=%lld localAddr=%s, remoteAddr=%s",
          sock, fd, errfd, (long long) pid,
E
Eric Blake 已提交
277
          NULLSTR(sock->localAddrStr), NULLSTR(sock->remoteAddrStr));
278 279 280

    return sock;

281
 error:
282
    sock->fd = sock->errfd = -1; /* Caller owns fd/errfd on failure */
283
    virObjectUnref(sock);
284 285 286 287 288 289
    return NULL;
}


int virNetSocketNewListenTCP(const char *nodename,
                             const char *service,
290
                             int family,
291 292 293 294 295 296 297 298
                             virNetSocketPtr **retsocks,
                             size_t *nretsocks)
{
    virNetSocketPtr *socks = NULL;
    size_t nsocks = 0;
    struct addrinfo *ai = NULL;
    struct addrinfo hints;
    int fd = -1;
299
    size_t i;
300 301 302
    bool addrInUse = false;
    bool familyNotSupported = false;
    virSocketAddr tmp_addr;
303 304 305 306

    *retsocks = NULL;
    *nretsocks = 0;

307
    memset(&hints, 0, sizeof(hints));
308
    hints.ai_family = family;
309
    hints.ai_flags = AI_PASSIVE;
310 311
    hints.ai_socktype = SOCK_STREAM;

312 313 314 315 316 317 318 319 320 321 322 323
    /* Don't use ADDRCONFIG for binding to the wildcard address.
     * Just catch the error returned by socket() if the system has
     * no IPv6 support.
     *
     * This allows libvirtd to be started in parallel with the network
     * startup in most cases.
     */
    if (nodename &&
        !(virSocketAddrParse(&tmp_addr, nodename, AF_UNSPEC) > 0 &&
          virSocketAddrIsWildcard(&tmp_addr)))
        hints.ai_flags |= AI_ADDRCONFIG;

324 325
    int e = getaddrinfo(nodename, service, &hints, &ai);
    if (e != 0) {
326 327 328
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Unable to resolve address '%s' service '%s': %s"),
                       nodename, service, gai_strerror(e));
329 330 331 332 333 334 335 336 337 338 339
        return -1;
    }

    struct addrinfo *runp = ai;
    while (runp) {
        virSocketAddr addr;

        memset(&addr, 0, sizeof(addr));

        if ((fd = socket(runp->ai_family, runp->ai_socktype,
                         runp->ai_protocol)) < 0) {
340 341 342 343 344
            if (errno == EAFNOSUPPORT) {
                familyNotSupported = true;
                runp = runp->ai_next;
                continue;
            }
345 346 347 348
            virReportSystemError(errno, "%s", _("Unable to create socket"));
            goto error;
        }

349
        if (virSetSockReuseAddr(fd, true) < 0)
350 351 352 353 354 355 356 357 358 359 360 361 362
            goto error;

#ifdef IPV6_V6ONLY
        if (runp->ai_family == PF_INET6) {
            int on = 1;
            /*
             * Normally on Linux an INET6 socket will bind to the INET4
             * address too. If getaddrinfo returns results with INET4
             * first though, this will result in INET6 binding failing.
             * We can trivially cope with multiple server sockets, so
             * we force it to only listen on IPv6
             */
            if (setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY,
363
                           (void*)&on, sizeof(on)) < 0) {
364 365 366 367 368 369 370 371 372 373 374 375
                virReportSystemError(errno, "%s",
                                     _("Unable to force bind to IPv6 only"));
                goto error;
            }
        }
#endif

        if (bind(fd, runp->ai_addr, runp->ai_addrlen) < 0) {
            if (errno != EADDRINUSE) {
                virReportSystemError(errno, "%s", _("Unable to bind to port"));
                goto error;
            }
376
            addrInUse = true;
377
            VIR_FORCE_CLOSE(fd);
378
            runp = runp->ai_next;
379 380 381 382 383 384 385 386 387 388 389
            continue;
        }

        addr.len = sizeof(addr.data);
        if (getsockname(fd, &addr.data.sa, &addr.len) < 0) {
            virReportSystemError(errno, "%s", _("Unable to get local socket name"));
            goto error;
        }

        VIR_DEBUG("%p f=%d f=%d", &addr, runp->ai_family, addr.data.sa.sa_family);

390
        if (VIR_EXPAND_N(socks, nsocks, 1) < 0)
391 392 393 394 395 396 397 398
            goto error;

        if (!(socks[nsocks-1] = virNetSocketNew(&addr, NULL, false, fd, -1, 0)))
            goto error;
        runp = runp->ai_next;
        fd = -1;
    }

399 400 401 402 403
    if (nsocks == 0 && familyNotSupported) {
        virReportSystemError(EAFNOSUPPORT, "%s", _("Unable to bind to port"));
        goto error;
    }

404 405 406 407 408 409
    if (nsocks == 0 &&
        addrInUse) {
        virReportSystemError(EADDRINUSE, "%s", _("Unable to bind to port"));
        goto error;
    }

410 411 412 413 414 415
    freeaddrinfo(ai);

    *retsocks = socks;
    *nretsocks = nsocks;
    return 0;

416
 error:
417
    for (i = 0; i < nsocks; i++)
418
        virObjectUnref(socks[i]);
419 420 421 422 423 424 425 426 427 428
    VIR_FREE(socks);
    freeaddrinfo(ai);
    VIR_FORCE_CLOSE(fd);
    return -1;
}


#if HAVE_SYS_UN_H
int virNetSocketNewListenUNIX(const char *path,
                              mode_t mask,
429
                              uid_t user,
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
                              gid_t grp,
                              virNetSocketPtr *retsock)
{
    virSocketAddr addr;
    mode_t oldmask;
    int fd;

    *retsock = NULL;

    memset(&addr, 0, sizeof(addr));

    addr.len = sizeof(addr.data.un);

    if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
        virReportSystemError(errno, "%s", _("Failed to create socket"));
        goto error;
    }

    addr.data.un.sun_family = AF_UNIX;
    if (virStrcpyStatic(addr.data.un.sun_path, path) == NULL) {
450 451
        virReportSystemError(ENAMETOOLONG,
                             _("Path %s too long for unix socket"), path);
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
        goto error;
    }
    if (addr.data.un.sun_path[0] == '@')
        addr.data.un.sun_path[0] = '\0';
    else
        unlink(addr.data.un.sun_path);

    oldmask = umask(~mask);

    if (bind(fd, &addr.data.sa, addr.len) < 0) {
        umask(oldmask);
        virReportSystemError(errno,
                             _("Failed to bind socket to '%s'"),
                             path);
        goto error;
    }
    umask(oldmask);

    /* chown() doesn't work for abstract sockets but we use them only
     * if libvirtd runs unprivileged
     */
473
    if (grp != 0 && chown(path, user, grp)) {
474
        virReportSystemError(errno,
475 476
                             _("Failed to change ownership of '%s' to %d:%d"),
                             path, (int) user, (int) grp);
477 478 479 480 481 482 483 484
        goto error;
    }

    if (!(*retsock = virNetSocketNew(&addr, NULL, false, fd, -1, 0)))
        goto error;

    return 0;

485
 error:
486 487 488 489 490 491 492 493
    if (path[0] != '@')
        unlink(path);
    VIR_FORCE_CLOSE(fd);
    return -1;
}
#else
int virNetSocketNewListenUNIX(const char *path ATTRIBUTE_UNUSED,
                              mode_t mask ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
494
                              uid_t user ATTRIBUTE_UNUSED,
495 496 497 498 499 500 501 502 503
                              gid_t grp ATTRIBUTE_UNUSED,
                              virNetSocketPtr *retsock ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("UNIX sockets are not supported on this platform"));
    return -1;
}
#endif

504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
int virNetSocketNewListenFD(int fd,
                            virNetSocketPtr *retsock)
{
    virSocketAddr addr;
    *retsock = NULL;

    memset(&addr, 0, sizeof(addr));

    addr.len = sizeof(addr.data);
    if (getsockname(fd, &addr.data.sa, &addr.len) < 0) {
        virReportSystemError(errno, "%s", _("Unable to get local socket name"));
        return -1;
    }

    if (!(*retsock = virNetSocketNew(&addr, NULL, false, fd, -1, 0)))
        return -1;

    return 0;
}

524 525 526

int virNetSocketNewConnectTCP(const char *nodename,
                              const char *service,
527
                              int family,
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
                              virNetSocketPtr *retsock)
{
    struct addrinfo *ai = NULL;
    struct addrinfo hints;
    int fd = -1;
    virSocketAddr localAddr;
    virSocketAddr remoteAddr;
    struct addrinfo *runp;
    int savedErrno = ENOENT;

    *retsock = NULL;

    memset(&localAddr, 0, sizeof(localAddr));
    memset(&remoteAddr, 0, sizeof(remoteAddr));

543
    memset(&hints, 0, sizeof(hints));
544
    hints.ai_family = family;
545 546 547 548 549
    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
    hints.ai_socktype = SOCK_STREAM;

    int e = getaddrinfo(nodename, service, &hints, &ai);
    if (e != 0) {
550 551
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Unable to resolve address '%s' service '%s': %s"),
552
                       nodename, service, gai_strerror(e));
553 554 555 556 557 558 559 560 561 562 563
        return -1;
    }

    runp = ai;
    while (runp) {
        if ((fd = socket(runp->ai_family, runp->ai_socktype,
                         runp->ai_protocol)) < 0) {
            virReportSystemError(errno, "%s", _("Unable to create socket"));
            goto error;
        }

564
        if (virSetSockReuseAddr(fd, false) < 0)
565
            VIR_WARN("Unable to enable port reuse");
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600

        if (connect(fd, runp->ai_addr, runp->ai_addrlen) >= 0)
            break;

        savedErrno = errno;
        VIR_FORCE_CLOSE(fd);
        runp = runp->ai_next;
    }

    if (fd == -1) {
        virReportSystemError(savedErrno,
                             _("unable to connect to server at '%s:%s'"),
                             nodename, service);
        goto error;
    }

    localAddr.len = sizeof(localAddr.data);
    if (getsockname(fd, &localAddr.data.sa, &localAddr.len) < 0) {
        virReportSystemError(errno, "%s", _("Unable to get local socket name"));
        goto error;
    }

    remoteAddr.len = sizeof(remoteAddr.data);
    if (getpeername(fd, &remoteAddr.data.sa, &remoteAddr.len) < 0) {
        virReportSystemError(errno, "%s", _("Unable to get remote socket name"));
        goto error;
    }

    if (!(*retsock = virNetSocketNew(&localAddr, &remoteAddr, true, fd, -1, 0)))
        goto error;

    freeaddrinfo(ai);

    return 0;

601
 error:
602 603 604 605 606 607
    freeaddrinfo(ai);
    VIR_FORCE_CLOSE(fd);
    return -1;
}


608
#ifdef HAVE_SYS_UN_H
609 610 611 612 613
int virNetSocketNewConnectUNIX(const char *path,
                               bool spawnDaemon,
                               const char *binary,
                               virNetSocketPtr *retsock)
{
614 615 616 617
    char *lockpath = NULL;
    int lockfd = -1;
    int fd = -1;
    int retries = 100;
618 619
    virSocketAddr localAddr;
    virSocketAddr remoteAddr;
620
    char *rundir = NULL;
621
    int ret = -1;
622
    bool daemonLaunched = false;
623

C
Cole Robinson 已提交
624 625 626
    VIR_DEBUG("path=%s spawnDaemon=%d binary=%s", path, spawnDaemon,
        NULLSTR(binary));

627 628 629 630 631
    memset(&localAddr, 0, sizeof(localAddr));
    memset(&remoteAddr, 0, sizeof(remoteAddr));

    remoteAddr.len = sizeof(remoteAddr.data.un);

632 633
    if (spawnDaemon) {
        const char *binname;
634

635 636 637 638
        if (spawnDaemon && !binary) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Auto-spawn of daemon requested, "
                             "but no binary specified"));
639
            goto cleanup;
640
        }
641

642 643 644 645
        if (!(binname = last_component(binary)) || binname[0] == '\0') {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot determine basename for binary '%s'"),
                           binary);
646
            goto cleanup;
647 648
        }

649
        if (!(rundir = virGetUserRuntimeDirectory()))
650
            goto cleanup;
651

652 653 654 655
        if (virFileMakePathWithMode(rundir, 0700) < 0) {
            virReportSystemError(errno,
                                 _("Cannot create user runtime directory '%s'"),
                                 rundir);
656
            goto cleanup;
657
        }
658

659
        if (virAsprintf(&lockpath, "%s/%s.lock", rundir, binname) < 0)
660
            goto cleanup;
661

662 663 664
        if ((lockfd = open(lockpath, O_RDWR | O_CREAT, 0600)) < 0 ||
            virSetCloseExec(lockfd) < 0) {
            virReportSystemError(errno, _("Unable to create lock '%s'"), lockpath);
665
            goto cleanup;
666
        }
667

668 669
        if (virFileLock(lockfd, false, 0, 1, true) < 0) {
            virReportSystemError(errno, _("Unable to lock '%s'"), lockpath);
670
            goto cleanup;
671
        }
672
    }
673

674 675
    if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
        virReportSystemError(errno, "%s", _("Failed to create socket"));
676
        goto cleanup;
677 678 679 680 681
    }

    remoteAddr.data.un.sun_family = AF_UNIX;
    if (virStrcpyStatic(remoteAddr.data.un.sun_path, path) == NULL) {
        virReportSystemError(ENOMEM, _("Path %s too long for unix socket"), path);
682
        goto cleanup;
683 684 685 686
    }
    if (remoteAddr.data.un.sun_path[0] == '@')
        remoteAddr.data.un.sun_path[0] = '\0';

C
Cole Robinson 已提交
687 688 689 690 691 692 693
    while (retries) {
        if (connect(fd, &remoteAddr.data.sa, remoteAddr.len) == 0) {
            VIR_DEBUG("connect() succeeded");
            break;
        }
        VIR_DEBUG("connect() failed: retries=%d errno=%d", retries, errno);

694
        retries--;
C
Cole Robinson 已提交
695
        if (!spawnDaemon ||
696
            retries == 0 ||
C
Cole Robinson 已提交
697
            (errno != ENOENT && errno != ECONNREFUSED)) {
698 699
            virReportSystemError(errno, _("Failed to connect socket to '%s'"),
                                 path);
700
            goto cleanup;
701
        }
702

703 704 705 706 707 708
        if (!daemonLaunched) {
            if (virNetSocketForkDaemon(binary) < 0)
                goto cleanup;

            daemonLaunched = true;
        }
709 710 711 712

        usleep(5000);
    }

713 714 715
    localAddr.len = sizeof(localAddr.data);
    if (getsockname(fd, &localAddr.data.sa, &localAddr.len) < 0) {
        virReportSystemError(errno, "%s", _("Unable to get local socket name"));
716
        goto cleanup;
717 718 719
    }

    if (!(*retsock = virNetSocketNew(&localAddr, &remoteAddr, true, fd, -1, 0)))
720
        goto cleanup;
721

722
    ret = 0;
723

724
 cleanup:
725
    if (lockfd != -1) {
726
        unlink(lockpath);
727 728
        VIR_FORCE_CLOSE(lockfd);
    }
729 730
    VIR_FREE(lockpath);
    VIR_FREE(rundir);
731 732 733 734 735

    if (ret < 0)
        VIR_FORCE_CLOSE(fd);

    return ret;
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
}
#else
int virNetSocketNewConnectUNIX(const char *path ATTRIBUTE_UNUSED,
                               bool spawnDaemon ATTRIBUTE_UNUSED,
                               const char *binary ATTRIBUTE_UNUSED,
                               virNetSocketPtr *retsock ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("UNIX sockets are not supported on this platform"));
    return -1;
}
#endif


#ifndef WIN32
int virNetSocketNewConnectCommand(virCommandPtr cmd,
                                  virNetSocketPtr *retsock)
{
    pid_t pid = 0;
755 756
    int sv[2] = { -1, -1 };
    int errfd[2] = { -1, -1 };
757 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 790 791 792 793

    *retsock = NULL;

    /* Fork off the external process.  Use socketpair to create a private
     * (unnamed) Unix domain socket to the child process so we don't have
     * to faff around with two file descriptors (a la 'pipe(2)').
     */
    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) < 0) {
        virReportSystemError(errno, "%s",
                             _("unable to create socket pair"));
        goto error;
    }

    if (pipe(errfd) < 0) {
        virReportSystemError(errno, "%s",
                             _("unable to create socket pair"));
        goto error;
    }

    virCommandSetInputFD(cmd, sv[1]);
    virCommandSetOutputFD(cmd, &sv[1]);
    virCommandSetErrorFD(cmd, &errfd[1]);

    if (virCommandRunAsync(cmd, &pid) < 0)
        goto error;

    /* Parent continues here. */
    VIR_FORCE_CLOSE(sv[1]);
    VIR_FORCE_CLOSE(errfd[1]);

    if (!(*retsock = virNetSocketNew(NULL, NULL, true, sv[0], errfd[0], pid)))
        goto error;

    virCommandFree(cmd);

    return 0;

794
 error:
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
    VIR_FORCE_CLOSE(sv[0]);
    VIR_FORCE_CLOSE(sv[1]);
    VIR_FORCE_CLOSE(errfd[0]);
    VIR_FORCE_CLOSE(errfd[1]);

    virCommandAbort(cmd);
    virCommandFree(cmd);

    return -1;
}
#else
int virNetSocketNewConnectCommand(virCommandPtr cmd ATTRIBUTE_UNUSED,
                                  virNetSocketPtr *retsock ATTRIBUTE_UNUSED)
{
    virReportSystemError(errno, "%s",
                         _("Tunnelling sockets not supported on this platform"));
    return -1;
}
#endif

int virNetSocketNewConnectSSH(const char *nodename,
                              const char *service,
                              const char *binary,
                              const char *username,
                              bool noTTY,
820
                              bool noVerify,
821
                              const char *netcat,
822
                              const char *keyfile,
823 824 825
                              const char *path,
                              virNetSocketPtr *retsock)
{
826
    char *quoted;
827
    virCommandPtr cmd;
828 829
    virBuffer buf = VIR_BUFFER_INITIALIZER;

830 831 832 833
    *retsock = NULL;

    cmd = virCommandNew(binary ? binary : "ssh");
    virCommandAddEnvPassCommon(cmd);
834 835 836 837 838
    virCommandAddEnvPassBlockSUID(cmd, "KRB5CCNAME", NULL);
    virCommandAddEnvPassBlockSUID(cmd, "SSH_AUTH_SOCK", NULL);
    virCommandAddEnvPassBlockSUID(cmd, "SSH_ASKPASS", NULL);
    virCommandAddEnvPassBlockSUID(cmd, "DISPLAY", NULL);
    virCommandAddEnvPassBlockSUID(cmd, "XAUTHORITY", NULL);
839 840 841 842 843 844
    virCommandClearCaps(cmd);

    if (service)
        virCommandAddArgList(cmd, "-p", service, NULL);
    if (username)
        virCommandAddArgList(cmd, "-l", username, NULL);
845 846
    if (keyfile)
        virCommandAddArgList(cmd, "-i", keyfile, NULL);
847 848 849
    if (noTTY)
        virCommandAddArgList(cmd, "-T", "-o", "BatchMode=yes",
                             "-e", "none", NULL);
850 851
    if (noVerify)
        virCommandAddArgList(cmd, "-o", "StrictHostKeyChecking=no", NULL);
852 853 854 855 856

    if (!netcat)
        netcat = "nc";

    virCommandAddArgList(cmd, nodename, "sh", "-c", NULL);
857 858

    virBufferEscapeShell(&buf, netcat);
859
    if (virBufferCheckError(&buf) < 0) {
860
        virCommandFree(cmd);
861 862 863
        return -1;
    }
    quoted = virBufferContentAndReset(&buf);
864 865 866 867 868 869 870 871 872 873 874
    /*
     * This ugly thing is a shell script to detect availability of
     * the -q option for 'nc': debian and suse based distros need this
     * flag to ensure the remote nc will exit on EOF, so it will go away
     * when we close the connection tunnel. If it doesn't go away, subsequent
     * connection attempts will hang.
     *
     * Fedora's 'nc' doesn't have this option, and defaults to the desired
     * behavior.
     */
    virCommandAddArgFormat(cmd,
875
         "'if '%s' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
876 877 878 879
             "ARG=-q0;"
         "else "
             "ARG=;"
         "fi;"
880 881
         "'%s' $ARG -U %s'",
         quoted, quoted, path);
882

883
    VIR_FREE(quoted);
884 885 886
    return virNetSocketNewConnectCommand(cmd, retsock);
}

887
#if WITH_SSH2
888 889 890
int
virNetSocketNewConnectLibSSH2(const char *host,
                              const char *port,
891
                              int family,
892 893 894 895 896 897 898
                              const char *username,
                              const char *privkey,
                              const char *knownHosts,
                              const char *knownHostsVerify,
                              const char *authMethods,
                              const char *command,
                              virConnectAuthPtr auth,
899
                              virURIPtr uri,
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
                              virNetSocketPtr *retsock)
{
    virNetSocketPtr sock = NULL;
    virNetSSHSessionPtr sess = NULL;
    unsigned int verify;
    int ret = -1;
    int portN;

    char *authMethodNext = NULL;
    char *authMethodsCopy = NULL;
    char *authMethod;

    /* port number will be verified while opening the socket */
    if (virStrToLong_i(port, NULL, 10, &portN) < 0) {
        virReportError(VIR_ERR_SSH, "%s",
                       _("Failed to parse port number"));
        goto error;
    }

    /* create ssh session context */
    if (!(sess = virNetSSHSessionNew()))
        goto error;

    /* set ssh session parameters */
    if (virNetSSHSessionAuthSetCallback(sess, auth) != 0)
        goto error;

927
    if (STRCASEEQ("auto", knownHostsVerify)) {
928
        verify = VIR_NET_SSH_HOSTKEY_VERIFY_AUTO_ADD;
929
    } else if (STRCASEEQ("ignore", knownHostsVerify)) {
930
        verify = VIR_NET_SSH_HOSTKEY_VERIFY_IGNORE;
931
    } else if (STRCASEEQ("normal", knownHostsVerify)) {
932
        verify = VIR_NET_SSH_HOSTKEY_VERIFY_NORMAL;
933
    } else {
934 935 936 937 938 939 940 941 942 943
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Invalid host key verification method: '%s'"),
                       knownHostsVerify);
        goto error;
    }

    if (virNetSSHSessionSetHostKeyVerification(sess,
                                               host,
                                               portN,
                                               knownHosts,
944 945
                                               verify,
                                               VIR_NET_SSH_HOSTKEY_FILE_CREATE) != 0)
946 947 948 949 950
        goto error;

    if (virNetSSHSessionSetChannelCommand(sess, command) != 0)
        goto error;

951
    if (VIR_STRDUP(authMethodsCopy, authMethods) < 0)
952
        goto error;
953 954

    authMethodNext = authMethodsCopy;
955 956

    while ((authMethod = strsep(&authMethodNext, ","))) {
957
        if (STRCASEEQ(authMethod, "keyboard-interactive")) {
958
            ret = virNetSSHSessionAuthAddKeyboardAuth(sess, username, -1);
959
        } else if (STRCASEEQ(authMethod, "password")) {
960
            ret = virNetSSHSessionAuthAddPasswordAuth(sess,
961 962
                                                      uri,
                                                      username);
963
        } else if (STRCASEEQ(authMethod, "privkey")) {
964 965 966 967
            ret = virNetSSHSessionAuthAddPrivKeyAuth(sess,
                                                     username,
                                                     privkey,
                                                     NULL);
968
        } else if (STRCASEEQ(authMethod, "agent")) {
969
            ret = virNetSSHSessionAuthAddAgentAuth(sess, username);
970
        } else {
971 972 973 974 975 976 977 978 979 980 981 982
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Invalid authentication method: '%s'"),
                           authMethod);
            ret = -1;
            goto error;
        }

        if (ret != 0)
            goto error;
    }

    /* connect to remote server */
983
    if ((ret = virNetSocketNewConnectTCP(host, port, family, &sock)) < 0)
984 985 986 987 988 989 990 991 992 993 994 995
        goto error;

    /* connect to the host using ssh */
    if ((ret = virNetSSHSessionConnect(sess, virNetSocketGetFD(sock))) != 0)
        goto error;

    sock->sshSession = sess;
    *retsock = sock;

    VIR_FREE(authMethodsCopy);
    return 0;

996
 error:
997 998 999 1000 1001 1002 1003 1004 1005
    virObjectUnref(sock);
    virObjectUnref(sess);
    VIR_FREE(authMethodsCopy);
    return ret;
}
#else
int
virNetSocketNewConnectLibSSH2(const char *host ATTRIBUTE_UNUSED,
                              const char *port ATTRIBUTE_UNUSED,
1006
                              int family ATTRIBUTE_UNUSED,
1007 1008 1009 1010 1011 1012 1013
                              const char *username ATTRIBUTE_UNUSED,
                              const char *privkey ATTRIBUTE_UNUSED,
                              const char *knownHosts ATTRIBUTE_UNUSED,
                              const char *knownHostsVerify ATTRIBUTE_UNUSED,
                              const char *authMethods ATTRIBUTE_UNUSED,
                              const char *command ATTRIBUTE_UNUSED,
                              virConnectAuthPtr auth ATTRIBUTE_UNUSED,
1014
                              virURIPtr uri ATTRIBUTE_UNUSED,
1015 1016 1017 1018 1019 1020
                              virNetSocketPtr *retsock ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("libssh2 transport support was not enabled"));
    return -1;
}
1021
#endif /* WITH_SSH2 */
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037

int virNetSocketNewConnectExternal(const char **cmdargv,
                                   virNetSocketPtr *retsock)
{
    virCommandPtr cmd;

    *retsock = NULL;

    cmd = virCommandNewArgs(cmdargv);
    virCommandAddEnvPassCommon(cmd);
    virCommandClearCaps(cmd);

    return virNetSocketNewConnectCommand(cmd, retsock);
}


1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
int virNetSocketNewConnectSockFD(int sockfd,
                                 virNetSocketPtr *retsock)
{
    virSocketAddr localAddr;

    localAddr.len = sizeof(localAddr.data);
    if (getsockname(sockfd, &localAddr.data.sa, &localAddr.len) < 0) {
        virReportSystemError(errno, "%s", _("Unable to get local socket name"));
        return -1;
    }

    if (!(*retsock = virNetSocketNew(&localAddr, NULL, true, sockfd, -1, -1)))
        return -1;

    return 0;
}


1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
virNetSocketPtr virNetSocketNewPostExecRestart(virJSONValuePtr object)
{
    virSocketAddr localAddr;
    virSocketAddr remoteAddr;
    int fd, thepid, errfd;
    bool isClient;

    if (virJSONValueObjectGetNumberInt(object, "fd", &fd) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing fd data in JSON document"));
        return NULL;
    }

    if (virJSONValueObjectGetNumberInt(object, "pid", &thepid) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing pid data in JSON document"));
        return NULL;
    }

    if (virJSONValueObjectGetNumberInt(object, "errfd", &errfd) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing errfd data in JSON document"));
        return NULL;
    }
    if (virJSONValueObjectGetBoolean(object, "isClient", &isClient) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing isClient data in JSON document"));
        return NULL;
    }

    memset(&localAddr, 0, sizeof(localAddr));
    memset(&remoteAddr, 0, sizeof(remoteAddr));

    remoteAddr.len = sizeof(remoteAddr.data.stor);
    if (getsockname(fd, &remoteAddr.data.sa, &remoteAddr.len) < 0) {
        virReportSystemError(errno, "%s", _("Unable to get peer socket name"));
        return NULL;
    }

    localAddr.len = sizeof(localAddr.data.stor);
    if (getsockname(fd, &localAddr.data.sa, &localAddr.len) < 0) {
        virReportSystemError(errno, "%s", _("Unable to get local socket name"));
        return NULL;
    }

    return virNetSocketNew(&localAddr, &remoteAddr,
                           isClient, fd, errfd, thepid);
}


virJSONValuePtr virNetSocketPreExecRestart(virNetSocketPtr sock)
{
    virJSONValuePtr object = NULL;

1110
    virObjectLock(sock);
1111

1112
#if WITH_SASL
1113 1114 1115 1116 1117 1118
    if (sock->saslSession) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Unable to save socket state when SASL session is active"));
        goto error;
    }
#endif
1119
#if WITH_GNUTLS
1120 1121 1122 1123 1124
    if (sock->tlsSession) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Unable to save socket state when TLS session is active"));
        goto error;
    }
1125
#endif
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155

    if (!(object = virJSONValueNewObject()))
        goto error;

    if (virJSONValueObjectAppendNumberInt(object, "fd", sock->fd) < 0)
        goto error;

    if (virJSONValueObjectAppendNumberInt(object, "errfd", sock->errfd) < 0)
        goto error;

    if (virJSONValueObjectAppendNumberInt(object, "pid", sock->pid) < 0)
        goto error;

    if (virJSONValueObjectAppendBoolean(object, "isClient", sock->client) < 0)
        goto error;

    if (virSetInherit(sock->fd, true) < 0) {
        virReportSystemError(errno,
                             _("Cannot disable close-on-exec flag on socket %d"),
                             sock->fd);
        goto error;
    }
    if (sock->errfd != -1 &&
        virSetInherit(sock->errfd, true) < 0) {
        virReportSystemError(errno,
                             _("Cannot disable close-on-exec flag on pipe %d"),
                             sock->errfd);
        goto error;
    }

1156
    virObjectUnlock(sock);
1157 1158
    return object;

1159
 error:
1160
    virObjectUnlock(sock);
1161 1162 1163 1164 1165
    virJSONValueFree(object);
    return NULL;
}


1166
void virNetSocketDispose(void *obj)
1167
{
1168
    virNetSocketPtr sock = obj;
1169

1170 1171 1172
    PROBE(RPC_SOCKET_DISPOSE,
          "sock=%p", sock);

1173
    if (sock->watch >= 0) {
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
        virEventRemoveHandle(sock->watch);
        sock->watch = -1;
    }

#ifdef HAVE_SYS_UN_H
    /* If a server socket, then unlink UNIX path */
    if (!sock->client &&
        sock->localAddr.data.sa.sa_family == AF_UNIX &&
        sock->localAddr.data.un.sun_path[0] != '\0')
        unlink(sock->localAddr.data.un.sun_path);
#endif

1186
#if WITH_GNUTLS
1187 1188 1189
    /* Make sure it can't send any more I/O during shutdown */
    if (sock->tlsSession)
        virNetTLSSessionSetIOCallbacks(sock->tlsSession, NULL, NULL, NULL);
1190
    virObjectUnref(sock->tlsSession);
1191
#endif
1192
#if WITH_SASL
1193
    virObjectUnref(sock->saslSession);
1194 1195
#endif

1196
#if WITH_SSH2
1197 1198 1199
    virObjectUnref(sock->sshSession);
#endif

1200 1201 1202
    VIR_FORCE_CLOSE(sock->fd);
    VIR_FORCE_CLOSE(sock->errfd);

1203
    virProcessAbort(sock->pid);
1204 1205 1206 1207 1208 1209 1210 1211

    VIR_FREE(sock->localAddrStr);
    VIR_FREE(sock->remoteAddrStr);
}


int virNetSocketGetFD(virNetSocketPtr sock)
{
1212
    int fd;
1213
    virObjectLock(sock);
1214
    fd = sock->fd;
1215
    virObjectUnlock(sock);
1216
    return fd;
1217 1218 1219
}


1220 1221 1222 1223 1224
int virNetSocketDupFD(virNetSocketPtr sock, bool cloexec)
{
    int fd;

    if (cloexec)
1225
        fd = fcntl(sock->fd, F_DUPFD_CLOEXEC, 0);
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
    else
        fd = dup(sock->fd);
    if (fd < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to copy socket file handle"));
        return -1;
    }
    return fd;
}


1237 1238
bool virNetSocketIsLocal(virNetSocketPtr sock)
{
1239
    bool isLocal = false;
1240
    virObjectLock(sock);
1241
    if (sock->localAddr.data.sa.sa_family == AF_UNIX)
1242
        isLocal = true;
1243
    virObjectUnlock(sock);
1244
    return isLocal;
1245 1246 1247
}


1248 1249 1250
bool virNetSocketHasPassFD(virNetSocketPtr sock)
{
    bool hasPassFD = false;
1251
    virObjectLock(sock);
1252 1253
    if (sock->localAddr.data.sa.sa_family == AF_UNIX)
        hasPassFD = true;
1254
    virObjectUnlock(sock);
1255 1256 1257 1258
    return hasPassFD;
}


1259 1260
int virNetSocketGetPort(virNetSocketPtr sock)
{
1261
    int port;
1262
    virObjectLock(sock);
1263
    port = virSocketAddrGetPort(&sock->localAddr);
1264
    virObjectUnlock(sock);
1265
    return port;
1266 1267 1268
}


1269
#if defined(SO_PEERCRED)
1270 1271 1272
int virNetSocketGetUNIXIdentity(virNetSocketPtr sock,
                                uid_t *uid,
                                gid_t *gid,
1273 1274
                                pid_t *pid,
                                unsigned long long *timestamp)
1275
{
1276 1277 1278
# if defined(HAVE_STRUCT_SOCKPEERCRED)
    struct sockpeercred cr;
# else
1279
    struct ucred cr;
1280
# endif
1281
    socklen_t cr_len = sizeof(cr);
1282 1283
    int ret = -1;

1284
    virObjectLock(sock);
1285 1286 1287 1288

    if (getsockopt(sock->fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) < 0) {
        virReportSystemError(errno, "%s",
                             _("Failed to get client socket identity"));
1289
        goto cleanup;
1290 1291
    }

1292 1293
    *timestamp = -1;
    if (cr.pid && virProcessGetStartTime(cr.pid, timestamp) < 0)
1294 1295
        goto cleanup;

1296 1297 1298 1299
    if (cr.pid)
        *pid = cr.pid;
    else
        *pid = -1;
1300
    *uid = cr.uid;
1301
    *gid = cr.gid;
1302

1303 1304
    ret = 0;

1305
 cleanup:
1306
    virObjectUnlock(sock);
1307
    return ret;
1308
}
1309
#elif defined(LOCAL_PEERCRED)
1310

1311 1312 1313
/* VIR_SOL_PEERCRED - the value needed to let getsockopt() work with
 * LOCAL_PEERCRED
 */
1314 1315 1316 1317

/* Mac OS X 10.8 provides SOL_LOCAL for LOCAL_PEERCRED */
# ifdef SOL_LOCAL
#  define VIR_SOL_PEERCRED SOL_LOCAL
1318
# else
1319 1320 1321 1322 1323 1324
/* FreeBSD and Mac OS X prior to 10.7, SOL_LOCAL is not defined and
 * users are expected to supply 0 as the second value for getsockopt()
 * when using LOCAL_PEERCRED. NB SOL_SOCKET cannot be used instead
 * of SOL_LOCAL
 */
#  define VIR_SOL_PEERCRED 0
1325 1326
# endif

1327 1328 1329
int virNetSocketGetUNIXIdentity(virNetSocketPtr sock,
                                uid_t *uid,
                                gid_t *gid,
1330
                                pid_t *pid,
1331
                                unsigned long long *timestamp)
1332 1333 1334
{
    struct xucred cr;
    socklen_t cr_len = sizeof(cr);
1335 1336
    int ret = -1;

1337
    virObjectLock(sock);
1338

1339
    cr.cr_ngroups = -1;
1340
    if (getsockopt(sock->fd, VIR_SOL_PEERCRED, LOCAL_PEERCRED, &cr, &cr_len) < 0) {
1341 1342
        virReportSystemError(errno, "%s",
                             _("Failed to get client socket identity"));
1343
        goto cleanup;
1344 1345
    }

1346 1347 1348
    if (cr.cr_version != XUCRED_VERSION) {
        virReportError(VIR_ERR_SYSTEM_ERROR, "%s",
                       _("Failed to get valid client socket identity"));
1349
        goto cleanup;
1350 1351
    }

1352
    if (cr.cr_ngroups <= 0 || cr.cr_ngroups > NGROUPS) {
1353 1354
        virReportError(VIR_ERR_SYSTEM_ERROR, "%s",
                       _("Failed to get valid client socket identity groups"));
1355
        goto cleanup;
1356 1357
    }

1358 1359 1360
    /* PID and process creation time are not supported on BSDs by
     * LOCAL_PEERCRED.
     */
1361
    *pid = -1;
1362
    *timestamp = -1;
1363 1364 1365
    *uid = cr.cr_uid;
    *gid = cr.cr_gid;

1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
# ifdef LOCAL_PEERPID
    /* Exists on Mac OS X 10.8 for retrieving the peer's PID */
    cr_len = sizeof(*pid);

    if (getsockopt(sock->fd, VIR_SOL_PEERCRED, LOCAL_PEERPID, pid, &cr_len) < 0) {
        /* Ensure this is set to something sane as there are no guarantees
         * as to what its set to now.
         */
        *pid = -1;

        /* If this was built on a system with LOCAL_PEERPID defined but
         * the kernel doesn't support it we'll get back EOPNOTSUPP so
         * treat all errors but EOPNOTSUPP as fatal
         */
        if (errno != EOPNOTSUPP) {
            virReportSystemError(errno, "%s",
                    _("Failed to get client socket PID"));
            goto cleanup;
        }
    }
# endif

1388 1389
    ret = 0;

1390
 cleanup:
1391
    virObjectUnlock(sock);
1392
    return ret;
1393
}
1394
#else
1395 1396 1397
int virNetSocketGetUNIXIdentity(virNetSocketPtr sock ATTRIBUTE_UNUSED,
                                uid_t *uid ATTRIBUTE_UNUSED,
                                gid_t *gid ATTRIBUTE_UNUSED,
1398 1399
                                pid_t *pid ATTRIBUTE_UNUSED,
                                unsigned long long *timestamp ATTRIBUTE_UNUSED)
1400 1401 1402 1403 1404 1405 1406 1407
{
    /* XXX Many more OS support UNIX socket credentials we could port to. See dbus ....*/
    virReportSystemError(ENOSYS, "%s",
                         _("Client socket identity not available"));
    return -1;
}
#endif

1408
#ifdef WITH_SELINUX
1409 1410
int virNetSocketGetSELinuxContext(virNetSocketPtr sock,
                                  char **context)
1411 1412 1413 1414 1415 1416
{
    security_context_t seccon = NULL;
    int ret = -1;

    *context = NULL;

1417
    virObjectLock(sock);
1418
    if (getpeercon(sock->fd, &seccon) < 0) {
1419
        if (errno == ENOSYS || errno == ENOPROTOOPT) {
1420 1421 1422 1423 1424 1425 1426 1427
            ret = 0;
            goto cleanup;
        }
        virReportSystemError(errno, "%s",
                             _("Unable to query peer security context"));
        goto cleanup;
    }

1428
    if (VIR_STRDUP(*context, seccon) < 0)
1429 1430 1431
        goto cleanup;

    ret = 0;
1432
 cleanup:
1433
    freecon(seccon);
1434
    virObjectUnlock(sock);
1435 1436 1437
    return ret;
}
#else
1438 1439
int virNetSocketGetSELinuxContext(virNetSocketPtr sock ATTRIBUTE_UNUSED,
                                  char **context)
1440 1441 1442 1443 1444 1445
{
    *context = NULL;
    return 0;
}
#endif

1446 1447 1448 1449

int virNetSocketSetBlocking(virNetSocketPtr sock,
                            bool blocking)
{
1450
    int ret;
1451
    virObjectLock(sock);
1452
    ret = virSetBlocking(sock->fd, blocking);
1453
    virObjectUnlock(sock);
1454
    return ret;
1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
}


const char *virNetSocketLocalAddrString(virNetSocketPtr sock)
{
    return sock->localAddrStr;
}

const char *virNetSocketRemoteAddrString(virNetSocketPtr sock)
{
    return sock->remoteAddrStr;
}

1468

1469
#if WITH_GNUTLS
1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
static ssize_t virNetSocketTLSSessionWrite(const char *buf,
                                           size_t len,
                                           void *opaque)
{
    virNetSocketPtr sock = opaque;
    return write(sock->fd, buf, len);
}


static ssize_t virNetSocketTLSSessionRead(char *buf,
                                          size_t len,
                                          void *opaque)
{
    virNetSocketPtr sock = opaque;
    return read(sock->fd, buf, len);
}


void virNetSocketSetTLSSession(virNetSocketPtr sock,
                               virNetTLSSessionPtr sess)
{
1491
    virObjectLock(sock);
1492 1493
    virObjectUnref(sock->tlsSession);
    sock->tlsSession = virObjectRef(sess);
1494 1495 1496 1497
    virNetTLSSessionSetIOCallbacks(sess,
                                   virNetSocketTLSSessionWrite,
                                   virNetSocketTLSSessionRead,
                                   sock);
1498
    virObjectUnlock(sock);
1499
}
1500
#endif
1501

1502
#if WITH_SASL
1503 1504 1505
void virNetSocketSetSASLSession(virNetSocketPtr sock,
                                virNetSASLSessionPtr sess)
{
1506
    virObjectLock(sock);
1507 1508
    virObjectUnref(sock->saslSession);
    sock->saslSession = virObjectRef(sess);
1509
    virObjectUnlock(sock);
1510 1511 1512 1513 1514 1515
}
#endif


bool virNetSocketHasCachedData(virNetSocketPtr sock ATTRIBUTE_UNUSED)
{
1516
    bool hasCached = false;
1517
    virObjectLock(sock);
1518

1519
#if WITH_SSH2
1520 1521 1522 1523
    if (virNetSSHSessionHasCachedData(sock->sshSession))
        hasCached = true;
#endif

1524
#if WITH_SASL
1525
    if (sock->saslDecoded)
1526
        hasCached = true;
1527
#endif
1528
    virObjectUnlock(sock);
1529
    return hasCached;
1530 1531
}

1532
#if WITH_SSH2
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
static ssize_t virNetSocketLibSSH2Read(virNetSocketPtr sock,
                                       char *buf,
                                       size_t len)
{
    return virNetSSHChannelRead(sock->sshSession, buf, len);
}

static ssize_t virNetSocketLibSSH2Write(virNetSocketPtr sock,
                                        const char *buf,
                                        size_t len)
{
    return virNetSSHChannelWrite(sock->sshSession, buf, len);
}
#endif
1547

1548 1549 1550
bool virNetSocketHasPendingData(virNetSocketPtr sock ATTRIBUTE_UNUSED)
{
    bool hasPending = false;
1551
    virObjectLock(sock);
1552
#if WITH_SASL
1553 1554 1555
    if (sock->saslEncoded)
        hasPending = true;
#endif
1556
    virObjectUnlock(sock);
1557 1558 1559 1560
    return hasPending;
}


1561
static ssize_t virNetSocketReadWire(virNetSocketPtr sock, char *buf, size_t len)
1562 1563 1564
{
    char *errout = NULL;
    ssize_t ret;
1565

1566
#if WITH_SSH2
1567 1568 1569 1570
    if (sock->sshSession)
        return virNetSocketLibSSH2Read(sock, buf, len);
#endif

1571
 reread:
1572
#if WITH_GNUTLS
1573 1574 1575 1576 1577
    if (sock->tlsSession &&
        virNetTLSSessionGetHandshakeStatus(sock->tlsSession) ==
        VIR_NET_TLS_HANDSHAKE_COMPLETE) {
        ret = virNetTLSSessionRead(sock->tlsSession, buf, len);
    } else {
1578
#endif
1579
        ret = read(sock->fd, buf, len);
1580
#if WITH_GNUTLS
1581
    }
1582
#endif
1583 1584 1585 1586 1587

    if ((ret < 0) && (errno == EINTR))
        goto reread;
    if ((ret < 0) && (errno == EAGAIN))
        return 0;
1588

1589 1590 1591 1592 1593
    if (ret <= 0 &&
        sock->errfd != -1 &&
        virFileReadLimFD(sock->errfd, 1024, &errout) >= 0 &&
        errout != NULL) {
        size_t elen = strlen(errout);
1594 1595 1596
        /* remove trailing whitespace */
        while (elen && c_isspace(errout[elen - 1]))
            errout[--elen] = '\0';
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
    }

    if (ret < 0) {
        if (errout)
            virReportSystemError(errno,
                                 _("Cannot recv data: %s"), errout);
        else
            virReportSystemError(errno, "%s",
                                 _("Cannot recv data"));
        ret = -1;
    } else if (ret == 0) {
        if (errout)
            virReportSystemError(EIO,
                                 _("End of file while reading data: %s"), errout);
        else
            virReportSystemError(EIO, "%s",
                                 _("End of file while reading data"));
        ret = -1;
    }

    VIR_FREE(errout);
    return ret;
}

1621
static ssize_t virNetSocketWriteWire(virNetSocketPtr sock, const char *buf, size_t len)
1622 1623
{
    ssize_t ret;
1624

1625
#if WITH_SSH2
1626 1627 1628 1629
    if (sock->sshSession)
        return virNetSocketLibSSH2Write(sock, buf, len);
#endif

1630
 rewrite:
1631
#if WITH_GNUTLS
1632 1633 1634 1635 1636
    if (sock->tlsSession &&
        virNetTLSSessionGetHandshakeStatus(sock->tlsSession) ==
        VIR_NET_TLS_HANDSHAKE_COMPLETE) {
        ret = virNetTLSSessionWrite(sock->tlsSession, buf, len);
    } else {
1637
#endif
1638
        ret = write(sock->fd, buf, len);
1639
#if WITH_GNUTLS
1640
    }
1641
#endif
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662

    if (ret < 0) {
        if (errno == EINTR)
            goto rewrite;
        if (errno == EAGAIN)
            return 0;

        virReportSystemError(errno, "%s",
                             _("Cannot write data"));
        return -1;
    }
    if (ret == 0) {
        virReportSystemError(EIO, "%s",
                             _("End of file while writing data"));
        return -1;
    }

    return ret;
}


1663
#if WITH_SASL
1664 1665 1666 1667 1668 1669 1670 1671
static ssize_t virNetSocketReadSASL(virNetSocketPtr sock, char *buf, size_t len)
{
    ssize_t got;

    /* Need to read some more data off the wire */
    if (sock->saslDecoded == NULL) {
        ssize_t encodedLen = virNetSASLSessionGetMaxBufSize(sock->saslSession);
        char *encoded;
1672
        if (VIR_ALLOC_N(encoded, encodedLen) < 0)
1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
            return -1;
        encodedLen = virNetSocketReadWire(sock, encoded, encodedLen);

        if (encodedLen <= 0) {
            VIR_FREE(encoded);
            return encodedLen;
        }

        if (virNetSASLSessionDecode(sock->saslSession,
                                    encoded, encodedLen,
                                    &sock->saslDecoded, &sock->saslDecodedLength) < 0) {
            VIR_FREE(encoded);
            return -1;
        }
        VIR_FREE(encoded);

        sock->saslDecodedOffset = 0;
    }

    /* Some buffered decoded data to return now */
    got = sock->saslDecodedLength - sock->saslDecodedOffset;

    if (len > got)
        len = got;

    memcpy(buf, sock->saslDecoded + sock->saslDecodedOffset, len);
    sock->saslDecodedOffset += len;

    if (sock->saslDecodedOffset == sock->saslDecodedLength) {
        sock->saslDecoded = NULL;
        sock->saslDecodedOffset = sock->saslDecodedLength = 0;
    }

    return len;
}


static ssize_t virNetSocketWriteSASL(virNetSocketPtr sock, const char *buf, size_t len)
{
    int ret;
    size_t tosend = virNetSASLSessionGetMaxBufSize(sock->saslSession);

    /* SASL doesn't necessarily let us send the whole
       buffer at once */
    if (tosend > len)
        tosend = len;

    /* Not got any pending encoded data, so we need to encode raw stuff */
    if (sock->saslEncoded == NULL) {
        if (virNetSASLSessionEncode(sock->saslSession,
                                    buf, tosend,
                                    &sock->saslEncoded,
                                    &sock->saslEncodedLength) < 0)
            return -1;

        sock->saslEncodedOffset = 0;
    }

    /* Send some of the encoded stuff out on the wire */
    ret = virNetSocketWriteWire(sock,
                                sock->saslEncoded + sock->saslEncodedOffset,
                                sock->saslEncodedLength - sock->saslEncodedOffset);

    if (ret <= 0)
        return ret; /* -1 error, 0 == egain */

    /* Note how much we sent */
    sock->saslEncodedOffset += ret;

    /* Sent all encoded, so update raw buffer to indicate completion */
    if (sock->saslEncodedOffset == sock->saslEncodedLength) {
        sock->saslEncoded = NULL;
        sock->saslEncodedOffset = sock->saslEncodedLength = 0;

        /* Mark as complete, so caller detects completion */
        return tosend;
    } else {
        /* Still have stuff pending in saslEncoded buffer.
         * Pretend to caller that we didn't send any yet.
         * The caller will then retry with same buffer
         * shortly, which lets us finish saslEncoded.
         */
        return 0;
    }
}
#endif

ssize_t virNetSocketRead(virNetSocketPtr sock, char *buf, size_t len)
{
1762
    ssize_t ret;
1763
    virObjectLock(sock);
1764
#if WITH_SASL
1765
    if (sock->saslSession)
1766
        ret = virNetSocketReadSASL(sock, buf, len);
1767 1768
    else
#endif
1769
        ret = virNetSocketReadWire(sock, buf, len);
1770
    virObjectUnlock(sock);
1771
    return ret;
1772 1773 1774 1775
}

ssize_t virNetSocketWrite(virNetSocketPtr sock, const char *buf, size_t len)
{
1776 1777
    ssize_t ret;

1778
    virObjectLock(sock);
1779
#if WITH_SASL
1780
    if (sock->saslSession)
1781
        ret = virNetSocketWriteSASL(sock, buf, len);
1782 1783
    else
#endif
1784
        ret = virNetSocketWriteWire(sock, buf, len);
1785
    virObjectUnlock(sock);
1786
    return ret;
1787 1788 1789
}


1790 1791 1792
/*
 * Returns 1 if an FD was sent, 0 if it would block, -1 on error
 */
1793 1794 1795 1796
int virNetSocketSendFD(virNetSocketPtr sock, int fd)
{
    int ret = -1;
    if (!virNetSocketHasPassFD(sock)) {
1797
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1798
                       _("Sending file descriptors is not supported on this socket"));
1799 1800
        return -1;
    }
1801
    virObjectLock(sock);
1802 1803 1804
    PROBE(RPC_SOCKET_SEND_FD,
          "sock=%p fd=%d", sock, fd);
    if (sendfd(sock->fd, fd) < 0) {
1805 1806 1807 1808 1809 1810
        if (errno == EAGAIN)
            ret = 0;
        else
            virReportSystemError(errno,
                                 _("Failed to send file descriptor %d"),
                                 fd);
1811 1812
        goto cleanup;
    }
1813
    ret = 1;
1814

1815
 cleanup:
1816
    virObjectUnlock(sock);
1817 1818 1819 1820
    return ret;
}


1821 1822 1823 1824
/*
 * Returns 1 if an FD was read, 0 if it would block, -1 on error
 */
int virNetSocketRecvFD(virNetSocketPtr sock, int *fd)
1825 1826
{
    int ret = -1;
1827 1828 1829

    *fd = -1;

1830
    if (!virNetSocketHasPassFD(sock)) {
1831
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1832
                       _("Receiving file descriptors is not supported on this socket"));
1833 1834
        return -1;
    }
1835
    virObjectLock(sock);
1836

1837 1838 1839 1840 1841 1842
    if ((*fd = recvfd(sock->fd, O_CLOEXEC)) < 0) {
        if (errno == EAGAIN)
            ret = 0;
        else
            virReportSystemError(errno, "%s",
                                 _("Failed to recv file descriptor"));
1843 1844 1845
        goto cleanup;
    }
    PROBE(RPC_SOCKET_RECV_FD,
1846 1847
          "sock=%p fd=%d", sock, *fd);
    ret = 1;
1848

1849
 cleanup:
1850
    virObjectUnlock(sock);
1851 1852 1853 1854
    return ret;
}


1855
int virNetSocketListen(virNetSocketPtr sock, int backlog)
1856
{
1857
    virObjectLock(sock);
1858
    if (listen(sock->fd, backlog > 0 ? backlog : 30) < 0) {
1859
        virReportSystemError(errno, "%s", _("Unable to listen on socket"));
1860
        virObjectUnlock(sock);
1861 1862
        return -1;
    }
1863
    virObjectUnlock(sock);
1864 1865 1866 1867 1868
    return 0;
}

int virNetSocketAccept(virNetSocketPtr sock, virNetSocketPtr *clientsock)
{
1869
    int fd = -1;
1870 1871
    virSocketAddr localAddr;
    virSocketAddr remoteAddr;
1872 1873
    int ret = -1;

1874
    virObjectLock(sock);
1875 1876 1877 1878 1879 1880 1881 1882 1883

    *clientsock = NULL;

    memset(&localAddr, 0, sizeof(localAddr));
    memset(&remoteAddr, 0, sizeof(remoteAddr));

    remoteAddr.len = sizeof(remoteAddr.data.stor);
    if ((fd = accept(sock->fd, &remoteAddr.data.sa, &remoteAddr.len)) < 0) {
        if (errno == ECONNABORTED ||
1884 1885 1886 1887
            errno == EAGAIN) {
            ret = 0;
            goto cleanup;
        }
1888 1889 1890

        virReportSystemError(errno, "%s",
                             _("Unable to accept client"));
1891
        goto cleanup;
1892 1893 1894 1895 1896
    }

    localAddr.len = sizeof(localAddr.data);
    if (getsockname(fd, &localAddr.data.sa, &localAddr.len) < 0) {
        virReportSystemError(errno, "%s", _("Unable to get local socket name"));
1897
        goto cleanup;
1898 1899 1900 1901 1902
    }

    if (!(*clientsock = virNetSocketNew(&localAddr,
                                        &remoteAddr,
                                        true,
1903 1904
                                        fd, -1, 0)))
        goto cleanup;
1905

1906 1907 1908
    fd = -1;
    ret = 0;

1909
 cleanup:
1910
    VIR_FORCE_CLOSE(fd);
1911
    virObjectUnlock(sock);
1912
    return ret;
1913 1914 1915
}


W
Wen Congyang 已提交
1916 1917
static void virNetSocketEventHandle(int watch ATTRIBUTE_UNUSED,
                                    int fd ATTRIBUTE_UNUSED,
1918 1919 1920 1921
                                    int events,
                                    void *opaque)
{
    virNetSocketPtr sock = opaque;
1922 1923
    virNetSocketIOFunc func;
    void *eopaque;
1924

1925
    virObjectLock(sock);
1926 1927
    func = sock->func;
    eopaque = sock->opaque;
1928
    virObjectUnlock(sock);
1929 1930 1931

    if (func)
        func(sock, events, eopaque);
1932 1933
}

1934

1935 1936 1937 1938 1939 1940
static void virNetSocketEventFree(void *opaque)
{
    virNetSocketPtr sock = opaque;
    virFreeCallback ff;
    void *eopaque;

1941
    virObjectLock(sock);
1942 1943 1944 1945 1946
    ff = sock->ff;
    eopaque = sock->opaque;
    sock->func = NULL;
    sock->ff = NULL;
    sock->opaque = NULL;
1947
    virObjectUnlock(sock);
1948 1949 1950 1951

    if (ff)
        ff(eopaque);

1952
    virObjectUnref(sock);
1953 1954
}

1955 1956 1957
int virNetSocketAddIOCallback(virNetSocketPtr sock,
                              int events,
                              virNetSocketIOFunc func,
1958 1959
                              void *opaque,
                              virFreeCallback ff)
1960
{
1961 1962
    int ret = -1;

1963
    virObjectRef(sock);
1964
    virObjectLock(sock);
1965
    if (sock->watch >= 0) {
1966
        VIR_DEBUG("Watch already registered on socket %p", sock);
1967
        goto cleanup;
1968 1969 1970 1971 1972 1973
    }

    if ((sock->watch = virEventAddHandle(sock->fd,
                                         events,
                                         virNetSocketEventHandle,
                                         sock,
1974
                                         virNetSocketEventFree)) < 0) {
1975
        VIR_DEBUG("Failed to register watch on socket %p", sock);
1976
        goto cleanup;
1977 1978 1979
    }
    sock->func = func;
    sock->opaque = opaque;
1980
    sock->ff = ff;
1981

1982 1983
    ret = 0;

1984
 cleanup:
1985
    virObjectUnlock(sock);
1986
    if (ret != 0)
1987
        virObjectUnref(sock);
1988
    return ret;
1989 1990 1991 1992 1993
}

void virNetSocketUpdateIOCallback(virNetSocketPtr sock,
                                  int events)
{
1994
    virObjectLock(sock);
1995
    if (sock->watch < 0) {
1996
        VIR_DEBUG("Watch not registered on socket %p", sock);
1997
        virObjectUnlock(sock);
1998 1999 2000 2001
        return;
    }

    virEventUpdateHandle(sock->watch, events);
2002

2003
    virObjectUnlock(sock);
2004 2005 2006 2007
}

void virNetSocketRemoveIOCallback(virNetSocketPtr sock)
{
2008
    virObjectLock(sock);
2009

2010
    if (sock->watch < 0) {
2011
        VIR_DEBUG("Watch not registered on socket %p", sock);
2012
        virObjectUnlock(sock);
2013 2014 2015 2016
        return;
    }

    virEventRemoveHandle(sock->watch);
2017
    /* Don't unref @sock, it's done via eventloop callback. */
2018
    sock->watch = -1;
2019

2020
    virObjectUnlock(sock);
2021
}
2022 2023 2024 2025 2026 2027

void virNetSocketClose(virNetSocketPtr sock)
{
    if (!sock)
        return;

2028
    virObjectLock(sock);
2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041

    VIR_FORCE_CLOSE(sock->fd);

#ifdef HAVE_SYS_UN_H
    /* If a server socket, then unlink UNIX path */
    if (!sock->client &&
        sock->localAddr.data.sa.sa_family == AF_UNIX &&
        sock->localAddr.data.un.sun_path[0] != '\0') {
        if (unlink(sock->localAddr.data.un.sun_path) == 0)
            sock->localAddr.data.un.sun_path[0] = '\0';
    }
#endif

2042
    virObjectUnlock(sock);
2043
}