virnetsocket.c 63.6 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
 */

#include <config.h>

#include <sys/stat.h>
#include <unistd.h>
#include <sys/wait.h>
27
#include <signal.h>
28
#include <fcntl.h>
29 30 31
#ifdef HAVE_IFADDRS_H
# include <ifaddrs.h>
#endif
32

33 34 35 36
#ifdef HAVE_SYS_UCRED_H
# include <sys/ucred.h>
#endif

37
#ifdef WITH_SELINUX
38 39 40
# include <selinux/selinux.h>
#endif

41
#include "virsocket.h"
42
#include "virnetsocket.h"
43
#include "virutil.h"
44
#include "viralloc.h"
45
#include "virerror.h"
46
#include "virlog.h"
E
Eric Blake 已提交
47
#include "virfile.h"
48
#include "virthread.h"
49
#include "virpidfile.h"
50
#include "virprobe.h"
51
#include "virprocess.h"
52
#include "virstring.h"
53

54
#if WITH_SSH2
55 56 57
# include "virnetsshsession.h"
#endif

58 59 60 61
#if WITH_LIBSSH
# include "virnetlibsshsession.h"
#endif

62 63
#define VIR_FROM_THIS VIR_FROM_RPC

64
VIR_LOG_INIT("rpc.netsocket");
65 66

struct _virNetSocket {
67
    virObjectLockable parent;
68

69 70 71 72
    int fd;
    int watch;
    pid_t pid;
    int errfd;
73
    bool isClient;
P
Pino Toscano 已提交
74
    bool ownsFd;
75
    bool quietEOF;
76
    bool unlinkUNIX;
77 78

    /* Event callback fields */
79 80
    virNetSocketIOFunc func;
    void *opaque;
81 82
    virFreeCallback ff;

83 84
    virSocketAddr localAddr;
    virSocketAddr remoteAddr;
85 86
    char *localAddrStrSASL;
    char *remoteAddrStrSASL;
87
    char *remoteAddrStrURI;
88 89

    virNetTLSSessionPtr tlsSession;
90
#if WITH_SASL
91 92 93 94 95 96 97 98
    virNetSASLSessionPtr saslSession;

    const char *saslDecoded;
    size_t saslDecodedLength;
    size_t saslDecodedOffset;

    const char *saslEncoded;
    size_t saslEncodedLength;
99
    size_t saslEncodedRawLength;
100 101
    size_t saslEncodedOffset;
#endif
102
#if WITH_SSH2
103 104
    virNetSSHSessionPtr sshSession;
#endif
105 106 107
#if WITH_LIBSSH
    virNetLibsshSessionPtr libsshSession;
#endif
108 109 110
};


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

static int virNetSocketOnceInit(void)
{
116
    if (!VIR_CLASS_NEW(virNetSocket, virClassForObjectLockable()))
117 118 119 120 121
        return -1;

    return 0;
}

122
VIR_ONCE_GLOBAL_INIT(virNetSocket);
123 124


125
#ifndef WIN32
126
static int virNetSocketForkDaemon(const char *binary)
127 128 129
{
    int ret;
    virCommandPtr cmd = virCommandNewArgList(binary,
130
                                             "--timeout=120",
131 132 133
                                             NULL);

    virCommandAddEnvPassCommon(cmd);
134 135 136
    virCommandAddEnvPass(cmd, "XDG_CACHE_HOME");
    virCommandAddEnvPass(cmd, "XDG_CONFIG_HOME");
    virCommandAddEnvPass(cmd, "XDG_RUNTIME_DIR");
137 138 139 140 141 142 143 144
    virCommandClearCaps(cmd);
    virCommandDaemonize(cmd);
    ret = virCommandRun(cmd, NULL);
    virCommandFree(cmd);
    return ret;
}
#endif

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
int virNetSocketCheckProtocols(bool *hasIPv4,
                               bool *hasIPv6)
{
#ifdef HAVE_IFADDRS_H
    struct ifaddrs *ifaddr = NULL, *ifa;
    struct addrinfo hints;
    struct addrinfo *ai = NULL;
    int gaierr;

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

    *hasIPv4 = *hasIPv6 = false;

    if (getifaddrs(&ifaddr) < 0) {
        virReportSystemError(errno, "%s",
                             _("Cannot get host interface addresses"));
161
        return -1;
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    }

    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) {
181 182 183 184
        if (gaierr == EAI_FAMILY ||
# ifdef EAI_ADDRFAMILY
            gaierr == EAI_ADDRFAMILY ||
# endif
185
            gaierr == EAI_NONAME) {
186 187 188 189 190
            *hasIPv6 = false;
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Cannot resolve ::1 address: %s"),
                           gai_strerror(gaierr));
191
            return -1;
192 193 194 195 196
        }
    }

    freeaddrinfo(ai);

J
Jiri Denemark 已提交
197
    VIR_DEBUG("Protocols: v4 %d v6 %d", *hasIPv4, *hasIPv6);
198

199
    return 0;
200 201 202 203 204 205 206 207
#else
    *hasIPv4 = *hasIPv6 = false;
    virReportError(VIR_ERR_NO_SUPPORT, "%s",
                   _("Cannot check address family on this platform"));
    return -1;
#endif
}

208

209 210 211 212 213 214 215 216
static virNetSocketPtr
virNetSocketNew(virSocketAddrPtr localAddr,
                virSocketAddrPtr remoteAddr,
                bool isClient,
                int fd,
                int errfd,
                pid_t pid,
                bool unlinkUNIX)
217 218 219 220
{
    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,
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;
P
Pino Toscano 已提交
250
    sock->ownsFd = true;
251 252
    sock->isClient = isClient;
    sock->unlinkUNIX = unlinkUNIX;
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267

    /* 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 &&
268
        !(sock->localAddrStrSASL = virSocketAddrFormatFull(localAddr, true, ";")))
269 270 271
        goto error;

    if (remoteAddr &&
272
        !(sock->remoteAddrStrSASL = virSocketAddrFormatFull(remoteAddr, true, ";")))
273 274
        goto error;

275 276 277 278
    if (remoteAddr &&
        !(sock->remoteAddrStrURI = virSocketAddrFormatFull(remoteAddr, true, NULL)))
        goto error;

279
    PROBE(RPC_SOCKET_NEW,
280
          "sock=%p fd=%d errfd=%d pid=%lld localAddr=%s, remoteAddr=%s",
281
          sock, fd, errfd, (long long)pid,
282
          NULLSTR(sock->localAddrStrSASL), NULLSTR(sock->remoteAddrStrSASL));
283 284 285

    return sock;

286
 error:
287
    sock->fd = sock->errfd = -1; /* Caller owns fd/errfd on failure */
288
    virObjectUnref(sock);
289 290 291 292 293 294
    return NULL;
}


int virNetSocketNewListenTCP(const char *nodename,
                             const char *service,
295
                             int family,
296 297 298 299 300 301 302 303
                             virNetSocketPtr **retsocks,
                             size_t *nretsocks)
{
    virNetSocketPtr *socks = NULL;
    size_t nsocks = 0;
    struct addrinfo *ai = NULL;
    struct addrinfo hints;
    int fd = -1;
304
    size_t i;
305 306
    int socketErrno = 0;
    int bindErrno = 0;
307
    virSocketAddr tmp_addr;
308
    int port = 0;
309 310 311 312

    *retsocks = NULL;
    *nretsocks = 0;

313
    memset(&hints, 0, sizeof(hints));
314
    hints.ai_family = family;
315
    hints.ai_flags = AI_PASSIVE;
316 317
    hints.ai_socktype = SOCK_STREAM;

318 319 320 321 322 323 324 325
    /* 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 &&
326
        !(virSocketAddrParseAny(&tmp_addr, nodename, AF_UNSPEC, false) > 0 &&
327 328 329
          virSocketAddrIsWildcard(&tmp_addr)))
        hints.ai_flags |= AI_ADDRCONFIG;

330 331
    int e = getaddrinfo(nodename, service, &hints, &ai);
    if (e != 0) {
332 333 334
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Unable to resolve address '%s' service '%s': %s"),
                       nodename, service, gai_strerror(e));
335 336 337 338 339 340 341 342 343 344 345
        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) {
346
            if (errno == EAFNOSUPPORT) {
347
                socketErrno = errno;
348 349 350
                runp = runp->ai_next;
                continue;
            }
351 352 353 354
            virReportSystemError(errno, "%s", _("Unable to create socket"));
            goto error;
        }

355
        if (virSetSockReuseAddr(fd, true) < 0)
356 357 358 359 360 361 362 363 364 365 366 367 368
            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,
369
                           (void*)&on, sizeof(on)) < 0) {
370 371 372 373 374 375 376
                virReportSystemError(errno, "%s",
                                     _("Unable to force bind to IPv6 only"));
                goto error;
            }
        }
#endif

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
        addr.len = runp->ai_addrlen;
        memcpy(&addr.data.sa, runp->ai_addr, runp->ai_addrlen);

        /* When service is NULL, we let the kernel auto-select the
         * port. Once we've selected a port for one IP protocol
         * though, we want to ensure we pick the same port for the
         * other IP protocol
         */
        if (port != 0 && service == NULL) {
            if (addr.data.sa.sa_family == AF_INET) {
                addr.data.inet4.sin_port = port;
            } else if (addr.data.sa.sa_family == AF_INET6) {
                addr.data.inet6.sin6_port = port;
            }
            VIR_DEBUG("Used saved port %d", port);
        }

        if (bind(fd, &addr.data.sa, addr.len) < 0) {
395
            if (errno != EADDRINUSE && errno != EADDRNOTAVAIL) {
396 397 398
                virReportSystemError(errno, "%s", _("Unable to bind to port"));
                goto error;
            }
399
            bindErrno = errno;
400 401
            closesocket(fd);
            fd = -1;
402
            runp = runp->ai_next;
403 404 405 406 407 408 409 410 411
            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;
        }

412 413 414 415 416 417 418 419
        if (port == 0 && service == NULL) {
            if (addr.data.sa.sa_family == AF_INET)
                port = addr.data.inet4.sin_port;
            else if (addr.data.sa.sa_family == AF_INET6)
                port = addr.data.inet6.sin6_port;
            VIR_DEBUG("Saved port %d", port);
        }

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

422
        if (VIR_EXPAND_N(socks, nsocks, 1) < 0)
423 424
            goto error;

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

431 432 433 434 435 436 437
    if (nsocks == 0) {
        if (bindErrno)
            virReportSystemError(bindErrno, "%s", _("Unable to bind to port"));
        else if (socketErrno)
            virReportSystemError(socketErrno, "%s", _("Unable to create socket"));
        else
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("No addresses to bind to"));
438 439 440
        goto error;
    }

441 442 443 444 445 446
    freeaddrinfo(ai);

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

447
 error:
448
    for (i = 0; i < nsocks; i++)
449
        virObjectUnref(socks[i]);
450 451
    VIR_FREE(socks);
    freeaddrinfo(ai);
452 453
    if (fd != -1)
        closesocket(fd);
454 455 456 457
    return -1;
}


458
#ifndef WIN32
459 460
int virNetSocketNewListenUNIX(const char *path,
                              mode_t mask,
461
                              uid_t user,
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
                              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;
481
    if (virStrcpyStatic(addr.data.un.sun_path, path) < 0) {
482 483
        virReportSystemError(ENAMETOOLONG,
                             _("Path %s too long for unix socket"), path);
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
        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
     */
505
    if (grp != 0 && chown(path, user, grp)) {
506
        virReportSystemError(errno,
507
                             _("Failed to change ownership of '%s' to %d:%d"),
508
                             path, (int)user, (int)grp);
509 510 511
        goto error;
    }

512
    if (!(*retsock = virNetSocketNew(&addr, NULL, false, fd, -1, 0, true)))
513 514 515 516
        goto error;

    return 0;

517
 error:
518 519
    if (path[0] != '@')
        unlink(path);
520 521
    if (fd != -1)
        closesocket(fd);
522 523 524
    return -1;
}
#else
J
Ján Tomko 已提交
525 526 527 528 529
int virNetSocketNewListenUNIX(const char *path G_GNUC_UNUSED,
                              mode_t mask G_GNUC_UNUSED,
                              uid_t user G_GNUC_UNUSED,
                              gid_t grp G_GNUC_UNUSED,
                              virNetSocketPtr *retsock G_GNUC_UNUSED)
530 531 532 533 534 535 536
{
    virReportSystemError(ENOSYS, "%s",
                         _("UNIX sockets are not supported on this platform"));
    return -1;
}
#endif

537
int virNetSocketNewListenFD(int fd,
538
                            bool unlinkUNIX,
539 540 541 542 543 544 545 546 547 548 549 550 551
                            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;
    }

552
    if (!(*retsock = virNetSocketNew(&addr, NULL, false, fd, -1, 0, unlinkUNIX)))
553 554 555 556 557
        return -1;

    return 0;
}

558 559 560

int virNetSocketNewConnectTCP(const char *nodename,
                              const char *service,
561
                              int family,
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
                              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));

577
    memset(&hints, 0, sizeof(hints));
578
    hints.ai_family = family;
579 580 581 582 583
    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
    hints.ai_socktype = SOCK_STREAM;

    int e = getaddrinfo(nodename, service, &hints, &ai);
    if (e != 0) {
584 585
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Unable to resolve address '%s' service '%s': %s"),
586
                       nodename, service, gai_strerror(e));
587 588 589 590 591 592 593 594 595 596 597
        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;
        }

598
        if (virSetSockReuseAddr(fd, false) < 0)
599
            VIR_WARN("Unable to enable port reuse");
600 601 602 603 604

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

        savedErrno = errno;
605 606
        closesocket(fd);
        fd = -1;
607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
        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;
    }

629
    if (!(*retsock = virNetSocketNew(&localAddr, &remoteAddr, true, fd, -1, 0, false)))
630 631 632 633 634 635
        goto error;

    freeaddrinfo(ai);

    return 0;

636
 error:
637
    freeaddrinfo(ai);
638 639
    if (fd != -1)
        closesocket(fd);
640 641 642 643
    return -1;
}


644
#ifndef WIN32
645 646 647 648 649
int virNetSocketNewConnectUNIX(const char *path,
                               bool spawnDaemon,
                               const char *binary,
                               virNetSocketPtr *retsock)
{
650 651 652
    char *lockpath = NULL;
    int lockfd = -1;
    int fd = -1;
653
    int retries = 500;
654 655
    virSocketAddr localAddr;
    virSocketAddr remoteAddr;
656
    char *rundir = NULL;
657
    int ret = -1;
658
    bool daemonLaunched = false;
659

C
Cole Robinson 已提交
660 661 662
    VIR_DEBUG("path=%s spawnDaemon=%d binary=%s", path, spawnDaemon,
        NULLSTR(binary));

663 664 665 666 667
    memset(&localAddr, 0, sizeof(localAddr));
    memset(&remoteAddr, 0, sizeof(remoteAddr));

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

668
    if (spawnDaemon) {
669
        g_autofree char *binname = NULL;
670

671 672 673 674
        if (spawnDaemon && !binary) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Auto-spawn of daemon requested, "
                             "but no binary specified"));
675
            goto cleanup;
676
        }
677

678
        binname = g_path_get_basename(binary);
679
        rundir = virGetUserRuntimeDirectory();
680

681 682 683 684
        if (virFileMakePathWithMode(rundir, 0700) < 0) {
            virReportSystemError(errno,
                                 _("Cannot create user runtime directory '%s'"),
                                 rundir);
685
            goto cleanup;
686
        }
687

688
        lockpath = g_strdup_printf("%s/%s.lock", rundir, binname);
689

690 691 692
        if ((lockfd = open(lockpath, O_RDWR | O_CREAT, 0600)) < 0 ||
            virSetCloseExec(lockfd) < 0) {
            virReportSystemError(errno, _("Unable to create lock '%s'"), lockpath);
693
            goto cleanup;
694
        }
695

696 697
        if (virFileLock(lockfd, false, 0, 1, true) < 0) {
            virReportSystemError(errno, _("Unable to lock '%s'"), lockpath);
698
            goto cleanup;
699
        }
700
    }
701

702 703
    if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
        virReportSystemError(errno, "%s", _("Failed to create socket"));
704
        goto cleanup;
705 706 707
    }

    remoteAddr.data.un.sun_family = AF_UNIX;
708
    if (virStrcpyStatic(remoteAddr.data.un.sun_path, path) < 0) {
709
        virReportSystemError(ENOMEM, _("Path %s too long for unix socket"), path);
710
        goto cleanup;
711 712 713 714
    }
    if (remoteAddr.data.un.sun_path[0] == '@')
        remoteAddr.data.un.sun_path[0] = '\0';

C
Cole Robinson 已提交
715 716 717 718 719 720 721
    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);

722
        retries--;
C
Cole Robinson 已提交
723
        if (!spawnDaemon ||
724
            retries == 0 ||
C
Cole Robinson 已提交
725
            (errno != ENOENT && errno != ECONNREFUSED)) {
726 727
            virReportSystemError(errno, _("Failed to connect socket to '%s'"),
                                 path);
728
            goto cleanup;
729
        }
730

731 732 733 734 735 736
        if (!daemonLaunched) {
            if (virNetSocketForkDaemon(binary) < 0)
                goto cleanup;

            daemonLaunched = true;
        }
737

738
        g_usleep(10000);
739 740
    }

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

747
    if (!(*retsock = virNetSocketNew(&localAddr, &remoteAddr, true, fd, -1, 0, false)))
748
        goto cleanup;
749

750
    ret = 0;
751

752
 cleanup:
753
    if (lockfd != -1) {
754
        unlink(lockpath);
755 756
        VIR_FORCE_CLOSE(lockfd);
    }
757 758
    VIR_FREE(lockpath);
    VIR_FREE(rundir);
759

760 761
    if (ret < 0 && fd != -1)
        closesocket(fd);
762 763

    return ret;
764 765
}
#else
J
Ján Tomko 已提交
766 767 768 769
int virNetSocketNewConnectUNIX(const char *path G_GNUC_UNUSED,
                               bool spawnDaemon G_GNUC_UNUSED,
                               const char *binary G_GNUC_UNUSED,
                               virNetSocketPtr *retsock G_GNUC_UNUSED)
770 771 772 773 774 775 776 777 778 779 780 781 782
{
    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;
783 784
    int sv[2] = { -1, -1 };
    int errfd[2] = { -1, -1 };
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814

    *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]);

815
    if (!(*retsock = virNetSocketNew(NULL, NULL, true, sv[0], errfd[0], pid, false)))
816 817 818 819 820 821
        goto error;

    virCommandFree(cmd);

    return 0;

822
 error:
823 824 825 826 827 828 829 830 831 832 833
    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
J
Ján Tomko 已提交
834 835
int virNetSocketNewConnectCommand(virCommandPtr cmd G_GNUC_UNUSED,
                                  virNetSocketPtr *retsock G_GNUC_UNUSED)
836 837 838 839 840 841 842 843 844 845 846 847
{
    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,
848
                              bool noVerify,
849
                              const char *netcat,
850
                              const char *keyfile,
851 852 853
                              const char *path,
                              virNetSocketPtr *retsock)
{
854
    char *quoted;
855
    virCommandPtr cmd;
856 857
    virBuffer buf = VIR_BUFFER_INITIALIZER;

858 859 860 861
    *retsock = NULL;

    cmd = virCommandNew(binary ? binary : "ssh");
    virCommandAddEnvPassCommon(cmd);
862 863 864 865 866
    virCommandAddEnvPass(cmd, "KRB5CCNAME");
    virCommandAddEnvPass(cmd, "SSH_AUTH_SOCK");
    virCommandAddEnvPass(cmd, "SSH_ASKPASS");
    virCommandAddEnvPass(cmd, "DISPLAY");
    virCommandAddEnvPass(cmd, "XAUTHORITY");
867 868 869 870 871 872
    virCommandClearCaps(cmd);

    if (service)
        virCommandAddArgList(cmd, "-p", service, NULL);
    if (username)
        virCommandAddArgList(cmd, "-l", username, NULL);
873 874
    if (keyfile)
        virCommandAddArgList(cmd, "-i", keyfile, NULL);
875
    virCommandAddArgList(cmd, "-T", "-e", "none", NULL);
876
    if (noTTY)
877
        virCommandAddArgList(cmd, "-o", "BatchMode=yes", NULL);
878 879
    if (noVerify)
        virCommandAddArgList(cmd, "-o", "StrictHostKeyChecking=no", NULL);
880 881 882 883

    if (!netcat)
        netcat = "nc";

884
    virCommandAddArgList(cmd, "--", nodename, "sh", "-c", NULL);
885 886 887

    virBufferEscapeShell(&buf, netcat);
    quoted = virBufferContentAndReset(&buf);
888 889 890 891 892

    virBufferEscapeShell(&buf, quoted);
    VIR_FREE(quoted);
    quoted = virBufferContentAndReset(&buf);

893 894 895 896 897 898 899 900 901 902 903
    /*
     * 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,
904
         "'if '%s' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
905 906 907 908
             "ARG=-q0;"
         "else "
             "ARG=;"
         "fi;"
909 910
         "'%s' $ARG -U %s'",
         quoted, quoted, path);
911

912
    VIR_FREE(quoted);
913 914 915
    return virNetSocketNewConnectCommand(cmd, retsock);
}

916
#if WITH_SSH2
917 918 919
int
virNetSocketNewConnectLibSSH2(const char *host,
                              const char *port,
920
                              int family,
921 922 923 924 925 926 927
                              const char *username,
                              const char *privkey,
                              const char *knownHosts,
                              const char *knownHostsVerify,
                              const char *authMethods,
                              const char *command,
                              virConnectAuthPtr auth,
928
                              virURIPtr uri,
929 930 931 932 933 934 935 936
                              virNetSocketPtr *retsock)
{
    virNetSocketPtr sock = NULL;
    virNetSSHSessionPtr sess = NULL;
    unsigned int verify;
    int ret = -1;
    int portN;

937 938
    VIR_AUTOSTRINGLIST authMethodList = NULL;
    char **authMethodNext;
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954

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

955
    if (STRCASEEQ("auto", knownHostsVerify)) {
956
        verify = VIR_NET_SSH_HOSTKEY_VERIFY_AUTO_ADD;
957
    } else if (STRCASEEQ("ignore", knownHostsVerify)) {
958
        verify = VIR_NET_SSH_HOSTKEY_VERIFY_IGNORE;
959
    } else if (STRCASEEQ("normal", knownHostsVerify)) {
960
        verify = VIR_NET_SSH_HOSTKEY_VERIFY_NORMAL;
961
    } else {
962 963 964 965 966 967 968 969 970 971
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Invalid host key verification method: '%s'"),
                       knownHostsVerify);
        goto error;
    }

    if (virNetSSHSessionSetHostKeyVerification(sess,
                                               host,
                                               portN,
                                               knownHosts,
972 973
                                               verify,
                                               VIR_NET_SSH_HOSTKEY_FILE_CREATE) != 0)
974 975 976 977 978
        goto error;

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

979 980
    if (!(authMethodList = virStringSplit(authMethods, ",", 0)))
        goto error;
981

982 983
    for (authMethodNext = authMethodList; *authMethodNext; authMethodNext++) {
        const char *authMethod = *authMethodNext;
984

985
        if (STRCASEEQ(authMethod, "keyboard-interactive")) {
986
            ret = virNetSSHSessionAuthAddKeyboardAuth(sess, username, -1);
987
        } else if (STRCASEEQ(authMethod, "password")) {
988
            ret = virNetSSHSessionAuthAddPasswordAuth(sess,
989 990
                                                      uri,
                                                      username);
991
        } else if (STRCASEEQ(authMethod, "privkey")) {
992 993 994 995
            ret = virNetSSHSessionAuthAddPrivKeyAuth(sess,
                                                     username,
                                                     privkey,
                                                     NULL);
996
        } else if (STRCASEEQ(authMethod, "agent")) {
997
            ret = virNetSSHSessionAuthAddAgentAuth(sess, username);
998
        } else {
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Invalid authentication method: '%s'"),
                           authMethod);
            ret = -1;
            goto error;
        }

        if (ret != 0)
            goto error;
    }

    /* connect to remote server */
1011
    if ((ret = virNetSocketNewConnectTCP(host, port, family, &sock)) < 0)
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        goto error;

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

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

    return 0;

1023
 error:
1024 1025 1026 1027 1028 1029
    virObjectUnref(sock);
    virObjectUnref(sess);
    return ret;
}
#else
int
J
Ján Tomko 已提交
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
virNetSocketNewConnectLibSSH2(const char *host G_GNUC_UNUSED,
                              const char *port G_GNUC_UNUSED,
                              int family G_GNUC_UNUSED,
                              const char *username G_GNUC_UNUSED,
                              const char *privkey G_GNUC_UNUSED,
                              const char *knownHosts G_GNUC_UNUSED,
                              const char *knownHostsVerify G_GNUC_UNUSED,
                              const char *authMethods G_GNUC_UNUSED,
                              const char *command G_GNUC_UNUSED,
                              virConnectAuthPtr auth G_GNUC_UNUSED,
                              virURIPtr uri G_GNUC_UNUSED,
                              virNetSocketPtr *retsock G_GNUC_UNUSED)
1042 1043 1044 1045 1046
{
    virReportSystemError(ENOSYS, "%s",
                         _("libssh2 transport support was not enabled"));
    return -1;
}
1047
#endif /* WITH_SSH2 */
1048

1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
#if WITH_LIBSSH
int
virNetSocketNewConnectLibssh(const char *host,
                             const char *port,
                             int family,
                             const char *username,
                             const char *privkey,
                             const char *knownHosts,
                             const char *knownHostsVerify,
                             const char *authMethods,
                             const char *command,
                             virConnectAuthPtr auth,
                             virURIPtr uri,
                             virNetSocketPtr *retsock)
{
    virNetSocketPtr sock = NULL;
    virNetLibsshSessionPtr sess = NULL;
    unsigned int verify;
    int ret = -1;
    int portN;

1070 1071
    VIR_AUTOSTRINGLIST authMethodList = NULL;
    char **authMethodNext;
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 1110

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

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

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

    if (STRCASEEQ("auto", knownHostsVerify)) {
        verify = VIR_NET_LIBSSH_HOSTKEY_VERIFY_AUTO_ADD;
    } else if (STRCASEEQ("ignore", knownHostsVerify)) {
        verify = VIR_NET_LIBSSH_HOSTKEY_VERIFY_IGNORE;
    } else if (STRCASEEQ("normal", knownHostsVerify)) {
        verify = VIR_NET_LIBSSH_HOSTKEY_VERIFY_NORMAL;
    } else {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("Invalid host key verification method: '%s'"),
                       knownHostsVerify);
        goto error;
    }

    if (virNetLibsshSessionSetHostKeyVerification(sess,
                                                  host,
                                                  portN,
                                                  knownHosts,
                                                  verify) != 0)
        goto error;

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

1111 1112
    if (!(authMethodList = virStringSplit(authMethods, ",", 0)))
        goto error;
1113

1114 1115
    for (authMethodNext = authMethodList; *authMethodNext; authMethodNext++) {
        const char *authMethod = *authMethodNext;
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 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 1156 1157 1158 1159 1160 1161 1162 1163

        if (STRCASEEQ(authMethod, "keyboard-interactive")) {
            ret = virNetLibsshSessionAuthAddKeyboardAuth(sess, -1);
        } else if (STRCASEEQ(authMethod, "password")) {
            ret = virNetLibsshSessionAuthAddPasswordAuth(sess, uri);
        } else if (STRCASEEQ(authMethod, "privkey")) {
            ret = virNetLibsshSessionAuthAddPrivKeyAuth(sess,
                                                        privkey,
                                                        NULL);
        } else if (STRCASEEQ(authMethod, "agent")) {
            ret = virNetLibsshSessionAuthAddAgentAuth(sess);
        } else {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Invalid authentication method: '%s'"),
                           authMethod);
            ret = -1;
            goto error;
        }

        if (ret != 0)
            goto error;
    }

    /* connect to remote server */
    if ((ret = virNetSocketNewConnectTCP(host, port, family, &sock)) < 0)
        goto error;

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

    sock->libsshSession = sess;
    /* libssh owns the FD and closes it on its own, and thus
     * we must not close it (otherwise there are warnings about
     * trying to close an invalid FD).
     */
    sock->ownsFd = false;
    *retsock = sock;

    return 0;

 error:
    virObjectUnref(sock);
    virObjectUnref(sess);
    return ret;
}
#else
int
J
Ján Tomko 已提交
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
virNetSocketNewConnectLibssh(const char *host G_GNUC_UNUSED,
                             const char *port G_GNUC_UNUSED,
                             int family G_GNUC_UNUSED,
                             const char *username G_GNUC_UNUSED,
                             const char *privkey G_GNUC_UNUSED,
                             const char *knownHosts G_GNUC_UNUSED,
                             const char *knownHostsVerify G_GNUC_UNUSED,
                             const char *authMethods G_GNUC_UNUSED,
                             const char *command G_GNUC_UNUSED,
                             virConnectAuthPtr auth G_GNUC_UNUSED,
                             virURIPtr uri G_GNUC_UNUSED,
                             virNetSocketPtr *retsock G_GNUC_UNUSED)
1176 1177 1178 1179 1180 1181 1182
{
    virReportSystemError(ENOSYS, "%s",
                         _("libssh transport support was not enabled"));
    return -1;
}
#endif /* WITH_LIBSSH */

1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
int virNetSocketNewConnectExternal(const char **cmdargv,
                                   virNetSocketPtr *retsock)
{
    virCommandPtr cmd;

    *retsock = NULL;

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

    return virNetSocketNewConnectCommand(cmd, retsock);
}


1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
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;
    }

1209
    if (!(*retsock = virNetSocketNew(&localAddr, NULL, true, sockfd, -1, -1, false)))
1210 1211 1212 1213 1214 1215
        return -1;

    return 0;
}


1216 1217 1218 1219 1220 1221
virNetSocketPtr virNetSocketNewPostExecRestart(virJSONValuePtr object)
{
    virSocketAddr localAddr;
    virSocketAddr remoteAddr;
    int fd, thepid, errfd;
    bool isClient;
1222
    bool unlinkUNIX;
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240

    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;
    }
1241

1242 1243 1244 1245 1246 1247
    if (virJSONValueObjectGetBoolean(object, "isClient", &isClient) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Missing isClient data in JSON document"));
        return NULL;
    }

1248 1249 1250
    if (virJSONValueObjectGetBoolean(object, "unlinkUNIX", &unlinkUNIX) < 0)
        unlinkUNIX = !isClient;

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
    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;
    }

1266 1267
    return virNetSocketNew(&localAddr, &remoteAddr, isClient,
                           fd, errfd, thepid, unlinkUNIX);
1268 1269 1270 1271 1272 1273 1274
}


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

1275
    virObjectLock(sock);
1276

1277
#if WITH_SASL
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
    if (sock->saslSession) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Unable to save socket state when SASL session is active"));
        goto error;
    }
#endif
    if (sock->tlsSession) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Unable to save socket state when TLS session is active"));
        goto error;
    }

    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;

1302 1303 1304 1305
    if (virJSONValueObjectAppendBoolean(object, "isClient", sock->isClient) < 0)
        goto error;

    if (virJSONValueObjectAppendBoolean(object, "unlinkUNIX", sock->unlinkUNIX) < 0)
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
        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;
    }

1322
    virObjectUnlock(sock);
1323 1324
    return object;

1325
 error:
1326
    virObjectUnlock(sock);
1327 1328 1329 1330 1331
    virJSONValueFree(object);
    return NULL;
}


1332
void virNetSocketDispose(void *obj)
1333
{
1334
    virNetSocketPtr sock = obj;
1335

1336 1337 1338
    PROBE(RPC_SOCKET_DISPOSE,
          "sock=%p", sock);

1339
    if (sock->watch >= 0) {
1340 1341 1342 1343
        virEventRemoveHandle(sock->watch);
        sock->watch = -1;
    }

1344
#ifndef WIN32
1345
    /* If a server socket, then unlink UNIX path */
1346
    if (sock->unlinkUNIX &&
1347 1348 1349 1350 1351
        sock->localAddr.data.sa.sa_family == AF_UNIX &&
        sock->localAddr.data.un.sun_path[0] != '\0')
        unlink(sock->localAddr.data.un.sun_path);
#endif

1352 1353 1354
    /* Make sure it can't send any more I/O during shutdown */
    if (sock->tlsSession)
        virNetTLSSessionSetIOCallbacks(sock->tlsSession, NULL, NULL, NULL);
1355
    virObjectUnref(sock->tlsSession);
1356
#if WITH_SASL
1357
    virObjectUnref(sock->saslSession);
1358 1359
#endif

1360
#if WITH_SSH2
1361 1362 1363
    virObjectUnref(sock->sshSession);
#endif

1364 1365 1366 1367
#if WITH_LIBSSH
    virObjectUnref(sock->libsshSession);
#endif

1368 1369 1370 1371
    if (sock->ownsFd && sock->fd != -1) {
        closesocket(sock->fd);
        sock->fd = -1;
    }
1372 1373
    VIR_FORCE_CLOSE(sock->errfd);

1374
    virProcessAbort(sock->pid);
1375

1376 1377
    VIR_FREE(sock->localAddrStrSASL);
    VIR_FREE(sock->remoteAddrStrSASL);
1378
    VIR_FREE(sock->remoteAddrStrURI);
1379 1380 1381 1382 1383
}


int virNetSocketGetFD(virNetSocketPtr sock)
{
1384
    int fd;
1385
    virObjectLock(sock);
1386
    fd = sock->fd;
1387
    virObjectUnlock(sock);
1388
    return fd;
1389 1390 1391
}


1392 1393 1394 1395
int virNetSocketDupFD(virNetSocketPtr sock, bool cloexec)
{
    int fd;

1396
#ifdef F_DUPFD_CLOEXEC
1397
    if (cloexec)
1398
        fd = fcntl(sock->fd, F_DUPFD_CLOEXEC, 0);
1399
    else
1400
#endif /* F_DUPFD_CLOEXEC */
1401 1402 1403 1404 1405 1406
        fd = dup(sock->fd);
    if (fd < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to copy socket file handle"));
        return -1;
    }
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
#ifndef F_DUPFD_CLOEXEC
    if (cloexec &&
        virSetCloseExec(fd < 0)) {
        int saveerr = errno;
        closesocket(fd);
        errno = saveerr;
        return -1;
    }
#endif /* F_DUPFD_CLOEXEC */

1417 1418 1419 1420
    return fd;
}


1421 1422
bool virNetSocketIsLocal(virNetSocketPtr sock)
{
1423
    bool isLocal = false;
1424
    virObjectLock(sock);
1425
    if (sock->localAddr.data.sa.sa_family == AF_UNIX)
1426
        isLocal = true;
1427
    virObjectUnlock(sock);
1428
    return isLocal;
1429 1430 1431
}


1432 1433 1434
bool virNetSocketHasPassFD(virNetSocketPtr sock)
{
    bool hasPassFD = false;
1435
    virObjectLock(sock);
1436 1437
    if (sock->localAddr.data.sa.sa_family == AF_UNIX)
        hasPassFD = true;
1438
    virObjectUnlock(sock);
1439 1440 1441
    return hasPassFD;
}

1442 1443 1444 1445 1446 1447 1448 1449
char *virNetSocketGetPath(virNetSocketPtr sock)
{
    char *path = NULL;
    virObjectLock(sock);
    path = virSocketAddrGetPath(&sock->localAddr);
    virObjectUnlock(sock);
    return path;
}
1450

1451 1452
int virNetSocketGetPort(virNetSocketPtr sock)
{
1453
    int port;
1454
    virObjectLock(sock);
1455
    port = virSocketAddrGetPort(&sock->localAddr);
1456
    virObjectUnlock(sock);
1457
    return port;
1458 1459 1460
}


1461
#if defined(SO_PEERCRED)
1462 1463 1464
int virNetSocketGetUNIXIdentity(virNetSocketPtr sock,
                                uid_t *uid,
                                gid_t *gid,
1465 1466
                                pid_t *pid,
                                unsigned long long *timestamp)
1467
{
1468 1469 1470
# if defined(HAVE_STRUCT_SOCKPEERCRED)
    struct sockpeercred cr;
# else
1471
    struct ucred cr;
1472
# endif
1473
    socklen_t cr_len = sizeof(cr);
1474 1475
    int ret = -1;

1476
    virObjectLock(sock);
1477 1478 1479 1480

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

1484 1485
    *timestamp = -1;
    if (cr.pid && virProcessGetStartTime(cr.pid, timestamp) < 0)
1486 1487
        goto cleanup;

1488 1489 1490 1491
    if (cr.pid)
        *pid = cr.pid;
    else
        *pid = -1;
1492
    *uid = cr.uid;
1493
    *gid = cr.gid;
1494

1495 1496
    ret = 0;

1497
 cleanup:
1498
    virObjectUnlock(sock);
1499
    return ret;
1500
}
1501
#elif defined(LOCAL_PEERCRED)
1502

1503 1504 1505
/* VIR_SOL_PEERCRED - the value needed to let getsockopt() work with
 * LOCAL_PEERCRED
 */
1506 1507 1508 1509

/* Mac OS X 10.8 provides SOL_LOCAL for LOCAL_PEERCRED */
# ifdef SOL_LOCAL
#  define VIR_SOL_PEERCRED SOL_LOCAL
1510
# else
1511 1512 1513 1514 1515 1516
/* 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
1517 1518
# endif

1519 1520 1521
int virNetSocketGetUNIXIdentity(virNetSocketPtr sock,
                                uid_t *uid,
                                gid_t *gid,
1522
                                pid_t *pid,
1523
                                unsigned long long *timestamp)
1524 1525 1526
{
    struct xucred cr;
    socklen_t cr_len = sizeof(cr);
1527 1528
    int ret = -1;

1529
    virObjectLock(sock);
1530

1531
    cr.cr_ngroups = -1;
1532
    if (getsockopt(sock->fd, VIR_SOL_PEERCRED, LOCAL_PEERCRED, &cr, &cr_len) < 0) {
1533 1534
        virReportSystemError(errno, "%s",
                             _("Failed to get client socket identity"));
1535
        goto cleanup;
1536 1537
    }

1538 1539 1540
    if (cr.cr_version != XUCRED_VERSION) {
        virReportError(VIR_ERR_SYSTEM_ERROR, "%s",
                       _("Failed to get valid client socket identity"));
1541
        goto cleanup;
1542 1543
    }

1544
    if (cr.cr_ngroups <= 0 || cr.cr_ngroups > NGROUPS) {
1545 1546
        virReportError(VIR_ERR_SYSTEM_ERROR, "%s",
                       _("Failed to get valid client socket identity groups"));
1547
        goto cleanup;
1548 1549
    }

1550 1551 1552
    /* PID and process creation time are not supported on BSDs by
     * LOCAL_PEERCRED.
     */
1553
    *pid = -1;
1554
    *timestamp = -1;
1555 1556 1557
    *uid = cr.cr_uid;
    *gid = cr.cr_gid;

1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
# 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

1580 1581
    ret = 0;

1582
 cleanup:
1583
    virObjectUnlock(sock);
1584
    return ret;
1585
}
1586
#else
J
Ján Tomko 已提交
1587 1588 1589 1590 1591
int virNetSocketGetUNIXIdentity(virNetSocketPtr sock G_GNUC_UNUSED,
                                uid_t *uid G_GNUC_UNUSED,
                                gid_t *gid G_GNUC_UNUSED,
                                pid_t *pid G_GNUC_UNUSED,
                                unsigned long long *timestamp G_GNUC_UNUSED)
1592 1593 1594 1595 1596 1597 1598 1599
{
    /* 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

1600
#ifdef WITH_SELINUX
1601 1602
int virNetSocketGetSELinuxContext(virNetSocketPtr sock,
                                  char **context)
1603 1604 1605 1606 1607 1608
{
    security_context_t seccon = NULL;
    int ret = -1;

    *context = NULL;

1609
    virObjectLock(sock);
1610
    if (getpeercon(sock->fd, &seccon) < 0) {
1611
        if (errno == ENOSYS || errno == ENOPROTOOPT) {
1612 1613 1614 1615 1616 1617 1618 1619
            ret = 0;
            goto cleanup;
        }
        virReportSystemError(errno, "%s",
                             _("Unable to query peer security context"));
        goto cleanup;
    }

1620
    *context = g_strdup(seccon);
1621 1622

    ret = 0;
1623
 cleanup:
1624
    freecon(seccon);
1625
    virObjectUnlock(sock);
1626 1627 1628
    return ret;
}
#else
J
Ján Tomko 已提交
1629
int virNetSocketGetSELinuxContext(virNetSocketPtr sock G_GNUC_UNUSED,
1630
                                  char **context)
1631 1632 1633 1634 1635 1636
{
    *context = NULL;
    return 0;
}
#endif

1637 1638 1639 1640

int virNetSocketSetBlocking(virNetSocketPtr sock,
                            bool blocking)
{
1641
    int ret;
1642
    virObjectLock(sock);
1643
    ret = virSetBlocking(sock->fd, blocking);
1644
    virObjectUnlock(sock);
1645
    return ret;
1646 1647 1648
}


1649
const char *virNetSocketLocalAddrStringSASL(virNetSocketPtr sock)
1650
{
1651
    return sock->localAddrStrSASL;
1652 1653
}

1654
const char *virNetSocketRemoteAddrStringSASL(virNetSocketPtr sock)
1655
{
1656
    return sock->remoteAddrStrSASL;
1657 1658
}

1659 1660 1661 1662
const char *virNetSocketRemoteAddrStringURI(virNetSocketPtr sock)
{
    return sock->remoteAddrStrURI;
}
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684

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)
{
1685
    virObjectLock(sock);
1686 1687
    virObjectUnref(sock->tlsSession);
    sock->tlsSession = virObjectRef(sess);
1688 1689 1690 1691
    virNetTLSSessionSetIOCallbacks(sess,
                                   virNetSocketTLSSessionWrite,
                                   virNetSocketTLSSessionRead,
                                   sock);
1692
    virObjectUnlock(sock);
1693 1694
}

1695
#if WITH_SASL
1696 1697 1698
void virNetSocketSetSASLSession(virNetSocketPtr sock,
                                virNetSASLSessionPtr sess)
{
1699
    virObjectLock(sock);
1700 1701
    virObjectUnref(sock->saslSession);
    sock->saslSession = virObjectRef(sess);
1702
    virObjectUnlock(sock);
1703 1704 1705 1706
}
#endif


J
Ján Tomko 已提交
1707
bool virNetSocketHasCachedData(virNetSocketPtr sock G_GNUC_UNUSED)
1708
{
1709
    bool hasCached = false;
1710
    virObjectLock(sock);
1711

1712
#if WITH_SSH2
1713 1714 1715 1716
    if (virNetSSHSessionHasCachedData(sock->sshSession))
        hasCached = true;
#endif

1717 1718 1719 1720 1721
#if WITH_LIBSSH
    if (virNetLibsshSessionHasCachedData(sock->libsshSession))
        hasCached = true;
#endif

1722
#if WITH_SASL
1723
    if (sock->saslDecoded)
1724
        hasCached = true;
1725
#endif
1726
    virObjectUnlock(sock);
1727
    return hasCached;
1728 1729
}

1730
#if WITH_SSH2
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
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
1745

1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
#if WITH_LIBSSH
static ssize_t virNetSocketLibsshRead(virNetSocketPtr sock,
                                      char *buf,
                                      size_t len)
{
    return virNetLibsshChannelRead(sock->libsshSession, buf, len);
}

static ssize_t virNetSocketLibsshWrite(virNetSocketPtr sock,
                                       const char *buf,
                                       size_t len)
{
    return virNetLibsshChannelWrite(sock->libsshSession, buf, len);
}
#endif

J
Ján Tomko 已提交
1762
bool virNetSocketHasPendingData(virNetSocketPtr sock G_GNUC_UNUSED)
1763 1764
{
    bool hasPending = false;
1765
    virObjectLock(sock);
1766
#if WITH_SASL
1767 1768 1769
    if (sock->saslEncoded)
        hasPending = true;
#endif
1770
    virObjectUnlock(sock);
1771 1772 1773 1774
    return hasPending;
}


1775
static ssize_t virNetSocketReadWire(virNetSocketPtr sock, char *buf, size_t len)
1776 1777 1778
{
    char *errout = NULL;
    ssize_t ret;
1779

1780
#if WITH_SSH2
1781 1782 1783 1784
    if (sock->sshSession)
        return virNetSocketLibSSH2Read(sock, buf, len);
#endif

1785 1786 1787 1788 1789
#if WITH_LIBSSH
    if (sock->libsshSession)
        return virNetSocketLibsshRead(sock, buf, len);
#endif

1790
 reread:
1791 1792 1793 1794 1795 1796 1797
    if (sock->tlsSession &&
        virNetTLSSessionGetHandshakeStatus(sock->tlsSession) ==
        VIR_NET_TLS_HANDSHAKE_COMPLETE) {
        ret = virNetTLSSessionRead(sock->tlsSession, buf, len);
    } else {
        ret = read(sock->fd, buf, len);
    }
1798 1799 1800 1801 1802

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

1804 1805 1806 1807 1808
    if (ret <= 0 &&
        sock->errfd != -1 &&
        virFileReadLimFD(sock->errfd, 1024, &errout) >= 0 &&
        errout != NULL) {
        size_t elen = strlen(errout);
1809
        /* remove trailing whitespace */
1810
        while (elen && g_ascii_isspace(errout[elen - 1]))
1811
            errout[--elen] = '\0';
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
    }

    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) {
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
        if (sock->quietEOF) {
            VIR_DEBUG("socket='%p' EOF while reading: errout='%s'",
                      socket, NULLSTR(errout));

            ret = -2;
        } else {
            if (errout)
                virReportSystemError(EIO,
                                     _("End of file while reading data: %s"),
                                     errout);
            else
                virReportSystemError(EIO, "%s",
                                     _("End of file while reading data"));

            ret = -1;
        }
1839 1840 1841 1842 1843 1844
    }

    VIR_FREE(errout);
    return ret;
}

1845
static ssize_t virNetSocketWriteWire(virNetSocketPtr sock, const char *buf, size_t len)
1846 1847
{
    ssize_t ret;
1848

1849
#if WITH_SSH2
1850 1851 1852 1853
    if (sock->sshSession)
        return virNetSocketLibSSH2Write(sock, buf, len);
#endif

1854 1855 1856 1857 1858
#if WITH_LIBSSH
    if (sock->libsshSession)
        return virNetSocketLibsshWrite(sock, buf, len);
#endif

1859
 rewrite:
1860 1861 1862 1863 1864 1865 1866
    if (sock->tlsSession &&
        virNetTLSSessionGetHandshakeStatus(sock->tlsSession) ==
        VIR_NET_TLS_HANDSHAKE_COMPLETE) {
        ret = virNetTLSSessionWrite(sock->tlsSession, buf, len);
    } else {
        ret = write(sock->fd, buf, len);
    }
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887

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


1888
#if WITH_SASL
1889 1890 1891 1892 1893 1894 1895 1896
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;
1897
        if (VIR_ALLOC_N(encoded, encodedLen) < 0)
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
            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;

1953
        sock->saslEncodedRawLength = tosend;
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
        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) {
1970
        ssize_t done = sock->saslEncodedRawLength;
1971
        sock->saslEncoded = NULL;
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983
        sock->saslEncodedOffset = sock->saslEncodedLength = sock->saslEncodedRawLength = 0;

        /* Mark as complete, so caller detects completion.
         *
         * Note that 'done' is possibly less than our current
         * 'tosend' value, since if virNetSocketWriteWire
         * only partially sent the data, we might have been
         * called a 2nd time to write remaining cached
         * encoded data. This means that the caller might
         * also have further raw data pending that's included
         * in 'tosend' */
        return done;
1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
    } 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)
{
1997
    ssize_t ret;
1998
    virObjectLock(sock);
1999
#if WITH_SASL
2000
    if (sock->saslSession)
2001
        ret = virNetSocketReadSASL(sock, buf, len);
2002 2003
    else
#endif
2004
        ret = virNetSocketReadWire(sock, buf, len);
2005
    virObjectUnlock(sock);
2006
    return ret;
2007 2008 2009 2010
}

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

2013
    virObjectLock(sock);
2014
#if WITH_SASL
2015
    if (sock->saslSession)
2016
        ret = virNetSocketWriteSASL(sock, buf, len);
2017 2018
    else
#endif
2019
        ret = virNetSocketWriteWire(sock, buf, len);
2020
    virObjectUnlock(sock);
2021
    return ret;
2022 2023 2024
}


2025 2026 2027
/*
 * Returns 1 if an FD was sent, 0 if it would block, -1 on error
 */
2028 2029 2030 2031
int virNetSocketSendFD(virNetSocketPtr sock, int fd)
{
    int ret = -1;
    if (!virNetSocketHasPassFD(sock)) {
2032
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2033
                       _("Sending file descriptors is not supported on this socket"));
2034 2035
        return -1;
    }
2036
    virObjectLock(sock);
2037 2038
    PROBE(RPC_SOCKET_SEND_FD,
          "sock=%p fd=%d", sock, fd);
2039
    if (virSocketSendFD(sock->fd, fd) < 0) {
2040 2041 2042 2043 2044 2045
        if (errno == EAGAIN)
            ret = 0;
        else
            virReportSystemError(errno,
                                 _("Failed to send file descriptor %d"),
                                 fd);
2046 2047
        goto cleanup;
    }
2048
    ret = 1;
2049

2050
 cleanup:
2051
    virObjectUnlock(sock);
2052 2053 2054 2055
    return ret;
}


2056 2057 2058 2059
/*
 * Returns 1 if an FD was read, 0 if it would block, -1 on error
 */
int virNetSocketRecvFD(virNetSocketPtr sock, int *fd)
2060 2061
{
    int ret = -1;
2062 2063 2064

    *fd = -1;

2065
    if (!virNetSocketHasPassFD(sock)) {
2066
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2067
                       _("Receiving file descriptors is not supported on this socket"));
2068 2069
        return -1;
    }
2070
    virObjectLock(sock);
2071

2072
    if ((*fd = virSocketRecvFD(sock->fd, O_CLOEXEC)) < 0) {
2073 2074 2075 2076 2077
        if (errno == EAGAIN)
            ret = 0;
        else
            virReportSystemError(errno, "%s",
                                 _("Failed to recv file descriptor"));
2078 2079 2080
        goto cleanup;
    }
    PROBE(RPC_SOCKET_RECV_FD,
2081 2082
          "sock=%p fd=%d", sock, *fd);
    ret = 1;
2083

2084
 cleanup:
2085
    virObjectUnlock(sock);
2086 2087 2088 2089
    return ret;
}


2090
int virNetSocketListen(virNetSocketPtr sock, int backlog)
2091
{
2092
    virObjectLock(sock);
2093
    if (listen(sock->fd, backlog > 0 ? backlog : 30) < 0) {
2094
        virReportSystemError(errno, "%s", _("Unable to listen on socket"));
2095
        virObjectUnlock(sock);
2096 2097
        return -1;
    }
2098
    virObjectUnlock(sock);
2099 2100 2101 2102 2103
    return 0;
}

int virNetSocketAccept(virNetSocketPtr sock, virNetSocketPtr *clientsock)
{
2104
    int fd = -1;
2105 2106
    virSocketAddr localAddr;
    virSocketAddr remoteAddr;
2107 2108
    int ret = -1;

2109
    virObjectLock(sock);
2110 2111 2112 2113 2114 2115 2116 2117 2118

    *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 ||
2119 2120 2121 2122
            errno == EAGAIN) {
            ret = 0;
            goto cleanup;
        }
2123 2124 2125

        virReportSystemError(errno, "%s",
                             _("Unable to accept client"));
2126
        goto cleanup;
2127 2128 2129 2130 2131
    }

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

    if (!(*clientsock = virNetSocketNew(&localAddr,
                                        &remoteAddr,
                                        true,
2138 2139
                                        fd, -1, 0,
                                        false)))
2140
        goto cleanup;
2141

2142 2143 2144
    fd = -1;
    ret = 0;

2145
 cleanup:
2146 2147
    if (fd != -1)
        closesocket(fd);
2148
    virObjectUnlock(sock);
2149
    return ret;
2150 2151 2152
}


J
Ján Tomko 已提交
2153 2154
static void virNetSocketEventHandle(int watch G_GNUC_UNUSED,
                                    int fd G_GNUC_UNUSED,
2155 2156 2157 2158
                                    int events,
                                    void *opaque)
{
    virNetSocketPtr sock = opaque;
2159 2160
    virNetSocketIOFunc func;
    void *eopaque;
2161

2162
    virObjectLock(sock);
2163 2164
    func = sock->func;
    eopaque = sock->opaque;
2165
    virObjectUnlock(sock);
2166 2167 2168

    if (func)
        func(sock, events, eopaque);
2169 2170
}

2171

2172 2173 2174 2175 2176 2177
static void virNetSocketEventFree(void *opaque)
{
    virNetSocketPtr sock = opaque;
    virFreeCallback ff;
    void *eopaque;

2178
    virObjectLock(sock);
2179 2180 2181 2182 2183
    ff = sock->ff;
    eopaque = sock->opaque;
    sock->func = NULL;
    sock->ff = NULL;
    sock->opaque = NULL;
2184
    virObjectUnlock(sock);
2185 2186 2187 2188

    if (ff)
        ff(eopaque);

2189
    virObjectUnref(sock);
2190 2191
}

2192 2193 2194
int virNetSocketAddIOCallback(virNetSocketPtr sock,
                              int events,
                              virNetSocketIOFunc func,
2195 2196
                              void *opaque,
                              virFreeCallback ff)
2197
{
2198 2199
    int ret = -1;

2200
    virObjectRef(sock);
2201
    virObjectLock(sock);
2202
    if (sock->watch >= 0) {
2203
        VIR_DEBUG("Watch already registered on socket %p", sock);
2204
        goto cleanup;
2205 2206 2207 2208 2209 2210
    }

    if ((sock->watch = virEventAddHandle(sock->fd,
                                         events,
                                         virNetSocketEventHandle,
                                         sock,
2211
                                         virNetSocketEventFree)) < 0) {
2212
        VIR_DEBUG("Failed to register watch on socket %p", sock);
2213
        goto cleanup;
2214 2215 2216
    }
    sock->func = func;
    sock->opaque = opaque;
2217
    sock->ff = ff;
2218

2219 2220
    ret = 0;

2221
 cleanup:
2222
    virObjectUnlock(sock);
2223
    if (ret != 0)
2224
        virObjectUnref(sock);
2225
    return ret;
2226 2227 2228 2229 2230
}

void virNetSocketUpdateIOCallback(virNetSocketPtr sock,
                                  int events)
{
2231
    virObjectLock(sock);
2232
    if (sock->watch < 0) {
2233
        VIR_DEBUG("Watch not registered on socket %p", sock);
2234
        virObjectUnlock(sock);
2235 2236 2237 2238
        return;
    }

    virEventUpdateHandle(sock->watch, events);
2239

2240
    virObjectUnlock(sock);
2241 2242 2243 2244
}

void virNetSocketRemoveIOCallback(virNetSocketPtr sock)
{
2245
    virObjectLock(sock);
2246

2247
    if (sock->watch < 0) {
2248
        VIR_DEBUG("Watch not registered on socket %p", sock);
2249
        virObjectUnlock(sock);
2250 2251 2252 2253
        return;
    }

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

2257
    virObjectUnlock(sock);
2258
}
2259 2260 2261 2262 2263 2264

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

2265
    virObjectLock(sock);
2266

2267 2268 2269 2270
    if (sock->fd != -1) {
        closesocket(sock->fd);
        sock->fd = -1;
    }
2271

2272
#ifndef WIN32
2273
    /* If a server socket, then unlink UNIX path */
2274
    if (sock->unlinkUNIX &&
2275 2276 2277 2278 2279 2280 2281
        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

2282
    virObjectUnlock(sock);
2283
}
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297


/**
 * virNetSocketSetQuietEOF:
 * @sock: socket object pointer
 *
 * Disables reporting I/O errors as a virError when @socket is closed while
 * reading data.
 */
void
virNetSocketSetQuietEOF(virNetSocketPtr sock)
{
    sock->quietEOF = true;
}