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

#include <config.h>

#include <sys/stat.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/wait.h>
30
#include <signal.h>
31
#include <fcntl.h>
32
#include <netdb.h>
33 34 35 36 37

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

38
#include "c-ctype.h"
39 40 41 42 43
#include "virnetsocket.h"
#include "util.h"
#include "memory.h"
#include "virterror_internal.h"
#include "logging.h"
E
Eric Blake 已提交
44
#include "virfile.h"
45
#include "event.h"
46
#include "threads.h"
47

48 49
#include "passfd.h"

50 51 52 53
#define VIR_FROM_THIS VIR_FROM_RPC


struct _virNetSocket {
54 55 56
    virMutex lock;
    int refs;

57 58 59 60 61
    int fd;
    int watch;
    pid_t pid;
    int errfd;
    bool client;
62 63

    /* Event callback fields */
64 65
    virNetSocketIOFunc func;
    void *opaque;
66 67
    virFreeCallback ff;

68 69 70 71
    virSocketAddr localAddr;
    virSocketAddr remoteAddr;
    char *localAddrStr;
    char *remoteAddrStr;
72 73 74 75 76 77 78 79 80 81 82 83 84

    virNetTLSSessionPtr tlsSession;
#if HAVE_SASL
    virNetSASLSessionPtr saslSession;

    const char *saslDecoded;
    size_t saslDecodedLength;
    size_t saslDecodedOffset;

    const char *saslEncoded;
    size_t saslEncodedLength;
    size_t saslEncodedOffset;
#endif
85 86 87 88 89 90 91 92 93 94 95 96
};


#ifndef WIN32
static int virNetSocketForkDaemon(const char *binary)
{
    int ret;
    virCommandPtr cmd = virCommandNewArgList(binary,
                                             "--timeout=30",
                                             NULL);

    virCommandAddEnvPassCommon(cmd);
C
Christophe Fergeau 已提交
97 98 99
    virCommandAddEnvPass(cmd, "XDG_CACHE_HOME");
    virCommandAddEnvPass(cmd, "XDG_CONFIG_HOME");
    virCommandAddEnvPass(cmd, "XDG_RUNTIME_DIR");
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    virCommandClearCaps(cmd);
    virCommandDaemonize(cmd);
    ret = virCommandRun(cmd, NULL);
    virCommandFree(cmd);
    return ret;
}
#endif


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

E
Eric Blake 已提交
117
    VIR_DEBUG("localAddr=%p remoteAddr=%p fd=%d errfd=%d pid=%lld",
118
              localAddr, remoteAddr,
E
Eric Blake 已提交
119
              fd, errfd, (long long) pid);
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

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

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

137 138 139 140 141 142 143 144
    if (virMutexInit(&sock->lock) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to initialize mutex"));
        VIR_FREE(sock);
        return NULL;
    }
    sock->refs = 1;

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
    if (localAddr)
        sock->localAddr = *localAddr;
    if (remoteAddr)
        sock->remoteAddr = *remoteAddr;
    sock->fd = fd;
    sock->errfd = errfd;
    sock->pid = pid;

    /* 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 &&
167
        !(sock->localAddrStr = virSocketAddrFormatFull(localAddr, true, ";")))
168 169 170
        goto error;

    if (remoteAddr &&
171
        !(sock->remoteAddrStr = virSocketAddrFormatFull(remoteAddr, true, ";")))
172 173 174 175
        goto error;

    sock->client = isClient;

176
    PROBE(RPC_SOCKET_NEW,
E
Eric Blake 已提交
177 178 179
          "sock=%p refs=%d fd=%d errfd=%d pid=%lld localAddr=%s, remoteAddr=%s",
          sock, sock->refs, fd, errfd, (long long) pid,
          NULLSTR(sock->localAddrStr), NULLSTR(sock->remoteAddrStr));
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

    return sock;

error:
    sock->fd = sock->errfd = -1; /* Caller owns fd/errfd on failure */
    virNetSocketFree(sock);
    return NULL;
}


int virNetSocketNewListenTCP(const char *nodename,
                             const char *service,
                             virNetSocketPtr **retsocks,
                             size_t *nretsocks)
{
    virNetSocketPtr *socks = NULL;
    size_t nsocks = 0;
    struct addrinfo *ai = NULL;
    struct addrinfo hints;
    int fd = -1;
    int i;
201
    int addrInUse = false;
202 203 204 205

    *retsocks = NULL;
    *nretsocks = 0;

206
    memset(&hints, 0, sizeof(hints));
207 208 209 210 211
    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
    hints.ai_socktype = SOCK_STREAM;

    int e = getaddrinfo(nodename, service, &hints, &ai);
    if (e != 0) {
212 213 214
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Unable to resolve address '%s' service '%s': %s"),
                       nodename, service, gai_strerror(e));
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
        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) {
            virReportSystemError(errno, "%s", _("Unable to create socket"));
            goto error;
        }

        int opt = 1;
231
        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0) {
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
            virReportSystemError(errno, "%s", _("Unable to enable port reuse"));
            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,
247
                           (void*)&on, sizeof(on)) < 0) {
248 249 250 251 252 253 254 255 256 257 258 259
                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;
            }
260
            addrInUse = true;
261
            VIR_FORCE_CLOSE(fd);
262
            runp = runp->ai_next;
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
            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);

        if (VIR_EXPAND_N(socks, nsocks, 1) < 0) {
            virReportOOMError();
            goto error;
        }

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

285 286 287 288 289 290
    if (nsocks == 0 &&
        addrInUse) {
        virReportSystemError(EADDRINUSE, "%s", _("Unable to bind to port"));
        goto error;
    }

291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    freeaddrinfo(ai);

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

error:
    for (i = 0 ; i < nsocks ; i++)
        virNetSocketFree(socks[i]);
    VIR_FREE(socks);
    freeaddrinfo(ai);
    VIR_FORCE_CLOSE(fd);
    return -1;
}


#if HAVE_SYS_UN_H
int virNetSocketNewListenUNIX(const char *path,
                              mode_t mask,
310
                              uid_t user,
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
                              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) {
331 332
        virReportSystemError(ENAMETOOLONG,
                             _("Path %s too long for unix socket"), path);
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
        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
     */
354
    if (grp != 0 && chown(path, user, grp)) {
355
        virReportSystemError(errno,
356 357
                             _("Failed to change ownership of '%s' to %d:%d"),
                             path, (int) user, (int) grp);
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
        goto error;
    }

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

    return 0;

error:
    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 已提交
375
                              uid_t user ATTRIBUTE_UNUSED,
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
                              gid_t grp ATTRIBUTE_UNUSED,
                              virNetSocketPtr *retsock ATTRIBUTE_UNUSED)
{
    virReportSystemError(ENOSYS, "%s",
                         _("UNIX sockets are not supported on this platform"));
    return -1;
}
#endif


int virNetSocketNewConnectTCP(const char *nodename,
                              const char *service,
                              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));

403
    memset(&hints, 0, sizeof(hints));
404 405 406 407 408
    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
    hints.ai_socktype = SOCK_STREAM;

    int e = getaddrinfo(nodename, service, &hints, &ai);
    if (e != 0) {
409 410 411
        virReportError(VIR_ERR_SYSTEM_ERROR,
                       _("Unable to resolve address '%s' service '%s': %s"),
                       nodename, service, gai_strerror (e));
412 413 414 415 416 417 418 419 420 421 422 423 424
        return -1;
    }

    runp = ai;
    while (runp) {
        int opt = 1;

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

425
        setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467

        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;

error:
    freeaddrinfo(ai);
    VIR_FORCE_CLOSE(fd);
    return -1;
}


468
#ifdef HAVE_SYS_UN_H
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
int virNetSocketNewConnectUNIX(const char *path,
                               bool spawnDaemon,
                               const char *binary,
                               virNetSocketPtr *retsock)
{
    virSocketAddr localAddr;
    virSocketAddr remoteAddr;
    int fd;
    int retries = 0;

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

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

484
    if (spawnDaemon && !binary) {
485 486
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Auto-spawn of daemon requested, but no binary specified"));
487 488 489
        return -1;
    }

490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    if ((fd = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
        virReportSystemError(errno, "%s", _("Failed to create socket"));
        goto error;
    }

    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);
        goto error;
    }
    if (remoteAddr.data.un.sun_path[0] == '@')
        remoteAddr.data.un.sun_path[0] = '\0';

retry:
    if (connect(fd, &remoteAddr.data.sa, remoteAddr.len) < 0) {
505 506 507 508 509
        if ((errno == ECONNREFUSED ||
             errno == ENOENT) &&
            spawnDaemon && retries < 20) {
            VIR_DEBUG("Connection refused for %s, trying to spawn %s",
                      path, binary);
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
            if (retries == 0 &&
                virNetSocketForkDaemon(binary) < 0)
                goto error;

            retries++;
            usleep(1000 * 100 * retries);
            goto retry;
        }

        virReportSystemError(errno,
                             _("Failed to connect socket to '%s'"),
                             path);
        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;
    }

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

    return 0;

error:
    VIR_FORCE_CLOSE(fd);
    return -1;
}
#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;
558 559
    int sv[2] = { -1, -1 };
    int errfd[2] = { -1, -1 };
560 561 562 563 564 565 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 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622

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

error:
    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,
623
                              bool noVerify,
624
                              const char *netcat,
625
                              const char *keyfile,
626 627 628
                              const char *path,
                              virNetSocketPtr *retsock)
{
629
    char *quoted;
630
    virCommandPtr cmd;
631 632
    virBuffer buf = VIR_BUFFER_INITIALIZER;

633 634 635 636
    *retsock = NULL;

    cmd = virCommandNew(binary ? binary : "ssh");
    virCommandAddEnvPassCommon(cmd);
637
    virCommandAddEnvPass(cmd, "KRB5CCNAME");
638 639
    virCommandAddEnvPass(cmd, "SSH_AUTH_SOCK");
    virCommandAddEnvPass(cmd, "SSH_ASKPASS");
640
    virCommandAddEnvPass(cmd, "DISPLAY");
641
    virCommandAddEnvPass(cmd, "XAUTHORITY");
642 643 644 645 646 647
    virCommandClearCaps(cmd);

    if (service)
        virCommandAddArgList(cmd, "-p", service, NULL);
    if (username)
        virCommandAddArgList(cmd, "-l", username, NULL);
648 649
    if (keyfile)
        virCommandAddArgList(cmd, "-i", keyfile, NULL);
650 651 652
    if (noTTY)
        virCommandAddArgList(cmd, "-T", "-o", "BatchMode=yes",
                             "-e", "none", NULL);
653 654
    if (noVerify)
        virCommandAddArgList(cmd, "-o", "StrictHostKeyChecking=no", NULL);
655 656 657 658 659

    if (!netcat)
        netcat = "nc";

    virCommandAddArgList(cmd, nodename, "sh", "-c", NULL);
660 661 662 663 664 665 666 667

    virBufferEscapeShell(&buf, netcat);
    if (virBufferError(&buf)) {
        virBufferFreeAndReset(&buf);
        virReportOOMError();
        return -1;
    }
    quoted = virBufferContentAndReset(&buf);
668 669 670 671 672 673 674 675 676 677 678
    /*
     * 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,
679
         "'if '%s' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
680 681 682 683
             "ARG=-q0;"
         "else "
             "ARG=;"
         "fi;"
684 685
         "'%s' $ARG -U %s'",
         quoted, quoted, path);
686

687
    VIR_FREE(quoted);
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
    return virNetSocketNewConnectCommand(cmd, retsock);
}


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

    *retsock = NULL;

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

    return virNetSocketNewConnectCommand(cmd, retsock);
}


707 708 709 710
void virNetSocketRef(virNetSocketPtr sock)
{
    virMutexLock(&sock->lock);
    sock->refs++;
711 712 713
    PROBE(RPC_SOCKET_REF,
          "sock=%p refs=%d",
          sock, sock->refs);
714 715 716 717
    virMutexUnlock(&sock->lock);
}


718 719 720 721 722
void virNetSocketFree(virNetSocketPtr sock)
{
    if (!sock)
        return;

723
    virMutexLock(&sock->lock);
724 725 726 727
    PROBE(RPC_SOCKET_FREE,
          "sock=%p refs=%d",
          sock, sock->refs);

728 729 730 731 732 733
    sock->refs--;
    if (sock->refs > 0) {
        virMutexUnlock(&sock->lock);
        return;
    }

734 735 736 737 738 739 740 741 742 743 744 745 746 747
    VIR_DEBUG("sock=%p fd=%d", sock, sock->fd);
    if (sock->watch > 0) {
        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

748 749 750 751 752 753 754 755
    /* Make sure it can't send any more I/O during shutdown */
    if (sock->tlsSession)
        virNetTLSSessionSetIOCallbacks(sock->tlsSession, NULL, NULL, NULL);
    virNetTLSSessionFree(sock->tlsSession);
#if HAVE_SASL
    virNetSASLSessionFree(sock->saslSession);
#endif

756 757 758
    VIR_FORCE_CLOSE(sock->fd);
    VIR_FORCE_CLOSE(sock->errfd);

759
    virPidAbort(sock->pid);
760 761 762 763

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

764 765 766
    virMutexUnlock(&sock->lock);
    virMutexDestroy(&sock->lock);

767 768 769 770 771 772
    VIR_FREE(sock);
}


int virNetSocketGetFD(virNetSocketPtr sock)
{
773 774 775 776 777
    int fd;
    virMutexLock(&sock->lock);
    fd = sock->fd;
    virMutexUnlock(&sock->lock);
    return fd;
778 779 780
}


781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
int virNetSocketDupFD(virNetSocketPtr sock, bool cloexec)
{
    int fd;

    if (cloexec)
        fd = fcntl(sock->fd, F_DUPFD_CLOEXEC);
    else
        fd = dup(sock->fd);
    if (fd < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to copy socket file handle"));
        return -1;
    }
    return fd;
}


798 799
bool virNetSocketIsLocal(virNetSocketPtr sock)
{
800 801
    bool isLocal = false;
    virMutexLock(&sock->lock);
802
    if (sock->localAddr.data.sa.sa_family == AF_UNIX)
803 804 805
        isLocal = true;
    virMutexUnlock(&sock->lock);
    return isLocal;
806 807 808
}


809 810 811 812 813 814 815 816 817 818 819
bool virNetSocketHasPassFD(virNetSocketPtr sock)
{
    bool hasPassFD = false;
    virMutexLock(&sock->lock);
    if (sock->localAddr.data.sa.sa_family == AF_UNIX)
        hasPassFD = true;
    virMutexUnlock(&sock->lock);
    return hasPassFD;
}


820 821
int virNetSocketGetPort(virNetSocketPtr sock)
{
822 823
    int port;
    virMutexLock(&sock->lock);
824
    port = virSocketAddrGetPort(&sock->localAddr);
825 826
    virMutexUnlock(&sock->lock);
    return port;
827 828 829
}


830
#ifdef SO_PEERCRED
831 832 833 834
int virNetSocketGetUNIXIdentity(virNetSocketPtr sock,
                                uid_t *uid,
                                gid_t *gid,
                                pid_t *pid)
835 836
{
    struct ucred cr;
837
    socklen_t cr_len = sizeof(cr);
838
    virMutexLock(&sock->lock);
839 840 841 842

    if (getsockopt(sock->fd, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) < 0) {
        virReportSystemError(errno, "%s",
                             _("Failed to get client socket identity"));
843
        virMutexUnlock(&sock->lock);
844 845 846 847 848
        return -1;
    }

    *pid = cr.pid;
    *uid = cr.uid;
849
    *gid = cr.gid;
850 851

    virMutexUnlock(&sock->lock);
852 853 854
    return 0;
}
#else
855 856 857 858
int virNetSocketGetUNIXIdentity(virNetSocketPtr sock ATTRIBUTE_UNUSED,
                                uid_t *uid ATTRIBUTE_UNUSED,
                                gid_t *gid ATTRIBUTE_UNUSED,
                                pid_t *pid ATTRIBUTE_UNUSED)
859 860 861 862 863 864 865 866 867 868 869 870
{
    /* 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


int virNetSocketSetBlocking(virNetSocketPtr sock,
                            bool blocking)
{
871 872 873 874 875
    int ret;
    virMutexLock(&sock->lock);
    ret = virSetBlocking(sock->fd, blocking);
    virMutexUnlock(&sock->lock);
    return ret;
876 877 878 879 880 881 882 883 884 885 886 887 888
}


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

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

889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910

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)
{
911
    virMutexLock(&sock->lock);
912 913 914 915 916 917 918
    virNetTLSSessionFree(sock->tlsSession);
    sock->tlsSession = sess;
    virNetTLSSessionSetIOCallbacks(sess,
                                   virNetSocketTLSSessionWrite,
                                   virNetSocketTLSSessionRead,
                                   sock);
    virNetTLSSessionRef(sess);
919
    virMutexUnlock(&sock->lock);
920 921 922 923 924 925 926
}


#if HAVE_SASL
void virNetSocketSetSASLSession(virNetSocketPtr sock,
                                virNetSASLSessionPtr sess)
{
927
    virMutexLock(&sock->lock);
928 929 930
    virNetSASLSessionFree(sock->saslSession);
    sock->saslSession = sess;
    virNetSASLSessionRef(sess);
931
    virMutexUnlock(&sock->lock);
932 933 934 935 936 937
}
#endif


bool virNetSocketHasCachedData(virNetSocketPtr sock ATTRIBUTE_UNUSED)
{
938 939
    bool hasCached = false;
    virMutexLock(&sock->lock);
940 941
#if HAVE_SASL
    if (sock->saslDecoded)
942
        hasCached = true;
943
#endif
944 945
    virMutexUnlock(&sock->lock);
    return hasCached;
946 947 948
}


949 950 951 952 953 954 955 956 957 958 959 960 961
bool virNetSocketHasPendingData(virNetSocketPtr sock ATTRIBUTE_UNUSED)
{
    bool hasPending = false;
    virMutexLock(&sock->lock);
#if HAVE_SASL
    if (sock->saslEncoded)
        hasPending = true;
#endif
    virMutexUnlock(&sock->lock);
    return hasPending;
}


962
static ssize_t virNetSocketReadWire(virNetSocketPtr sock, char *buf, size_t len)
963 964 965 966
{
    char *errout = NULL;
    ssize_t ret;
reread:
967 968 969 970 971 972 973
    if (sock->tlsSession &&
        virNetTLSSessionGetHandshakeStatus(sock->tlsSession) ==
        VIR_NET_TLS_HANDSHAKE_COMPLETE) {
        ret = virNetTLSSessionRead(sock->tlsSession, buf, len);
    } else {
        ret = read(sock->fd, buf, len);
    }
974 975 976 977 978

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

980 981 982 983 984
    if (ret <= 0 &&
        sock->errfd != -1 &&
        virFileReadLimFD(sock->errfd, 1024, &errout) >= 0 &&
        errout != NULL) {
        size_t elen = strlen(errout);
985 986 987
        /* remove trailing whitespace */
        while (elen && c_isspace(errout[elen - 1]))
            errout[--elen] = '\0';
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    }

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

1012
static ssize_t virNetSocketWriteWire(virNetSocketPtr sock, const char *buf, size_t len)
1013 1014 1015
{
    ssize_t ret;
rewrite:
1016 1017 1018 1019 1020 1021 1022
    if (sock->tlsSession &&
        virNetTLSSessionGetHandshakeStatus(sock->tlsSession) ==
        VIR_NET_TLS_HANDSHAKE_COMPLETE) {
        ret = virNetTLSSessionWrite(sock->tlsSession, buf, len);
    } else {
        ret = write(sock->fd, buf, len);
    }
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043

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


1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 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
#if HAVE_SASL
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;
        if (VIR_ALLOC_N(encoded, encodedLen) < 0) {
            virReportOOMError();
            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)
{
1146 1147
    ssize_t ret;
    virMutexLock(&sock->lock);
1148 1149
#if HAVE_SASL
    if (sock->saslSession)
1150
        ret = virNetSocketReadSASL(sock, buf, len);
1151 1152
    else
#endif
1153 1154 1155
        ret = virNetSocketReadWire(sock, buf, len);
    virMutexUnlock(&sock->lock);
    return ret;
1156 1157 1158 1159
}

ssize_t virNetSocketWrite(virNetSocketPtr sock, const char *buf, size_t len)
{
1160 1161 1162
    ssize_t ret;

    virMutexLock(&sock->lock);
1163 1164
#if HAVE_SASL
    if (sock->saslSession)
1165
        ret = virNetSocketWriteSASL(sock, buf, len);
1166 1167
    else
#endif
1168 1169 1170
        ret = virNetSocketWriteWire(sock, buf, len);
    virMutexUnlock(&sock->lock);
    return ret;
1171 1172 1173
}


1174 1175 1176
/*
 * Returns 1 if an FD was sent, 0 if it would block, -1 on error
 */
1177 1178 1179 1180
int virNetSocketSendFD(virNetSocketPtr sock, int fd)
{
    int ret = -1;
    if (!virNetSocketHasPassFD(sock)) {
1181 1182
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Sending file descriptors is not supported on this socket"));
1183 1184 1185 1186 1187 1188
        return -1;
    }
    virMutexLock(&sock->lock);
    PROBE(RPC_SOCKET_SEND_FD,
          "sock=%p fd=%d", sock, fd);
    if (sendfd(sock->fd, fd) < 0) {
1189 1190 1191 1192 1193 1194
        if (errno == EAGAIN)
            ret = 0;
        else
            virReportSystemError(errno,
                                 _("Failed to send file descriptor %d"),
                                 fd);
1195 1196
        goto cleanup;
    }
1197
    ret = 1;
1198 1199 1200 1201 1202 1203 1204

cleanup:
    virMutexUnlock(&sock->lock);
    return ret;
}


1205 1206 1207 1208
/*
 * Returns 1 if an FD was read, 0 if it would block, -1 on error
 */
int virNetSocketRecvFD(virNetSocketPtr sock, int *fd)
1209 1210
{
    int ret = -1;
1211 1212 1213

    *fd = -1;

1214
    if (!virNetSocketHasPassFD(sock)) {
1215 1216
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Receiving file descriptors is not supported on this socket"));
1217 1218 1219 1220
        return -1;
    }
    virMutexLock(&sock->lock);

1221 1222 1223 1224 1225 1226
    if ((*fd = recvfd(sock->fd, O_CLOEXEC)) < 0) {
        if (errno == EAGAIN)
            ret = 0;
        else
            virReportSystemError(errno, "%s",
                                 _("Failed to recv file descriptor"));
1227 1228 1229
        goto cleanup;
    }
    PROBE(RPC_SOCKET_RECV_FD,
1230 1231
          "sock=%p fd=%d", sock, *fd);
    ret = 1;
1232 1233 1234 1235 1236 1237 1238

cleanup:
    virMutexUnlock(&sock->lock);
    return ret;
}


1239
int virNetSocketListen(virNetSocketPtr sock, int backlog)
1240
{
1241
    virMutexLock(&sock->lock);
1242
    if (listen(sock->fd, backlog > 0 ? backlog : 30) < 0) {
1243
        virReportSystemError(errno, "%s", _("Unable to listen on socket"));
1244
        virMutexUnlock(&sock->lock);
1245 1246
        return -1;
    }
1247
    virMutexUnlock(&sock->lock);
1248 1249 1250 1251 1252
    return 0;
}

int virNetSocketAccept(virNetSocketPtr sock, virNetSocketPtr *clientsock)
{
1253
    int fd = -1;
1254 1255
    virSocketAddr localAddr;
    virSocketAddr remoteAddr;
1256 1257 1258
    int ret = -1;

    virMutexLock(&sock->lock);
1259 1260 1261 1262 1263 1264 1265 1266 1267

    *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 ||
1268 1269 1270 1271
            errno == EAGAIN) {
            ret = 0;
            goto cleanup;
        }
1272 1273 1274

        virReportSystemError(errno, "%s",
                             _("Unable to accept client"));
1275
        goto cleanup;
1276 1277 1278 1279 1280
    }

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

    if (!(*clientsock = virNetSocketNew(&localAddr,
                                        &remoteAddr,
                                        true,
1287 1288
                                        fd, -1, 0)))
        goto cleanup;
1289

1290 1291 1292 1293 1294 1295 1296
    fd = -1;
    ret = 0;

cleanup:
    VIR_FORCE_CLOSE(fd);
    virMutexUnlock(&sock->lock);
    return ret;
1297 1298 1299
}


W
Wen Congyang 已提交
1300 1301
static void virNetSocketEventHandle(int watch ATTRIBUTE_UNUSED,
                                    int fd ATTRIBUTE_UNUSED,
1302 1303 1304 1305
                                    int events,
                                    void *opaque)
{
    virNetSocketPtr sock = opaque;
1306 1307
    virNetSocketIOFunc func;
    void *eopaque;
1308

1309 1310 1311 1312 1313 1314 1315
    virMutexLock(&sock->lock);
    func = sock->func;
    eopaque = sock->opaque;
    virMutexUnlock(&sock->lock);

    if (func)
        func(sock, events, eopaque);
1316 1317
}

1318

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
static void virNetSocketEventFree(void *opaque)
{
    virNetSocketPtr sock = opaque;
    virFreeCallback ff;
    void *eopaque;

    virMutexLock(&sock->lock);
    ff = sock->ff;
    eopaque = sock->opaque;
    sock->func = NULL;
    sock->ff = NULL;
    sock->opaque = NULL;
    virMutexUnlock(&sock->lock);

    if (ff)
        ff(eopaque);

    virNetSocketFree(sock);
}

1339 1340 1341
int virNetSocketAddIOCallback(virNetSocketPtr sock,
                              int events,
                              virNetSocketIOFunc func,
1342 1343
                              void *opaque,
                              virFreeCallback ff)
1344
{
1345 1346
    int ret = -1;

1347
    virNetSocketRef(sock);
1348
    virMutexLock(&sock->lock);
1349 1350
    if (sock->watch > 0) {
        VIR_DEBUG("Watch already registered on socket %p", sock);
1351
        goto cleanup;
1352 1353 1354 1355 1356 1357
    }

    if ((sock->watch = virEventAddHandle(sock->fd,
                                         events,
                                         virNetSocketEventHandle,
                                         sock,
1358
                                         virNetSocketEventFree)) < 0) {
1359
        VIR_DEBUG("Failed to register watch on socket %p", sock);
1360
        goto cleanup;
1361 1362 1363
    }
    sock->func = func;
    sock->opaque = opaque;
1364
    sock->ff = ff;
1365

1366 1367 1368 1369
    ret = 0;

cleanup:
    virMutexUnlock(&sock->lock);
1370 1371
    if (ret != 0)
        virNetSocketFree(sock);
1372
    return ret;
1373 1374 1375 1376 1377
}

void virNetSocketUpdateIOCallback(virNetSocketPtr sock,
                                  int events)
{
1378
    virMutexLock(&sock->lock);
1379 1380
    if (sock->watch <= 0) {
        VIR_DEBUG("Watch not registered on socket %p", sock);
1381
        virMutexUnlock(&sock->lock);
1382 1383 1384 1385
        return;
    }

    virEventUpdateHandle(sock->watch, events);
1386 1387

    virMutexUnlock(&sock->lock);
1388 1389 1390 1391
}

void virNetSocketRemoveIOCallback(virNetSocketPtr sock)
{
1392 1393
    virMutexLock(&sock->lock);

1394 1395
    if (sock->watch <= 0) {
        VIR_DEBUG("Watch not registered on socket %p", sock);
1396
        virMutexUnlock(&sock->lock);
1397 1398 1399 1400
        return;
    }

    virEventRemoveHandle(sock->watch);
1401 1402

    virMutexUnlock(&sock->lock);
1403
}
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425

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

    virMutexLock(&sock->lock);

    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

    virMutexUnlock(&sock->lock);
}