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

#include <config.h>

#include <stdlib.h>
#include <signal.h>
#ifdef HAVE_IFADDRS_H
# include <ifaddrs.h>
#endif
28
#include <netdb.h>
29 30

#include "testutils.h"
31
#include "virutil.h"
32
#include "virerror.h"
33
#include "viralloc.h"
34
#include "virlog.h"
E
Eric Blake 已提交
35
#include "virfile.h"
36
#include "virstring.h"
37 38 39 40 41 42 43 44 45 46 47 48 49

#include "rpc/virnetsocket.h"

#define VIR_FROM_THIS VIR_FROM_RPC

#if HAVE_IFADDRS_H
# define BASE_PORT 5672

static int
checkProtocols(bool *hasIPv4, bool *hasIPv6,
               int *freePort)
{
    struct ifaddrs *ifaddr = NULL, *ifa;
50 51
    struct addrinfo hints;
    struct addrinfo *ai = NULL;
52 53 54
    struct sockaddr_in in4;
    struct sockaddr_in6 in6;
    int s4 = -1, s6 = -1;
55
    size_t i;
56 57
    int ret = -1;

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

60 61 62
    *hasIPv4 = *hasIPv6 = false;
    *freePort = 0;

63
    if (getifaddrs(&ifaddr) < 0) {
E
Eric Blake 已提交
64
        perror("getifaddrs");
65
        goto cleanup;
66
    }
67 68 69 70 71 72 73 74 75 76 77

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

78 79 80 81 82 83 84 85 86
    hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG;
    hints.ai_family = AF_INET6;
    hints.ai_socktype = SOCK_STREAM;

    if (getaddrinfo("::1", "5672", &hints, &ai) != 0)
        *hasIPv6 = false;

    freeaddrinfo(ai);

87 88 89 90
    VIR_DEBUG("Protocols: v4 %d v6 %d\n", *hasIPv4, *hasIPv6);

    freeifaddrs(ifaddr);

91
    for (i = 0; i < 50; i++) {
92 93 94 95
        int only = 1;
        if ((s4 = socket(AF_INET, SOCK_STREAM, 0)) < 0)
            goto cleanup;

96 97 98
        if (*hasIPv6) {
            if ((s6 = socket(AF_INET6, SOCK_STREAM, 0)) < 0)
                goto cleanup;
99

100 101 102
            if (setsockopt(s6, IPPROTO_IPV6, IPV6_V6ONLY, &only, sizeof(only)) < 0)
                goto cleanup;
        }
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121

        memset(&in4, 0, sizeof(in4));
        memset(&in6, 0, sizeof(in6));

        in4.sin_family = AF_INET;
        in4.sin_port = htons(BASE_PORT + i);
        in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
        in6.sin6_family = AF_INET6;
        in6.sin6_port = htons(BASE_PORT + i);
        in6.sin6_addr = in6addr_loopback;

        if (bind(s4, (struct sockaddr *)&in4, sizeof(in4)) < 0) {
            if (errno == EADDRINUSE) {
                VIR_FORCE_CLOSE(s4);
                VIR_FORCE_CLOSE(s6);
                continue;
            }
            goto cleanup;
        }
122 123 124 125 126 127 128 129 130

        if (*hasIPv6) {
            if (bind(s6, (struct sockaddr *)&in6, sizeof(in6)) < 0) {
                if (errno == EADDRINUSE) {
                    VIR_FORCE_CLOSE(s4);
                    VIR_FORCE_CLOSE(s6);
                    continue;
                }
                goto cleanup;
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
            }
        }

        *freePort = BASE_PORT + i;
        break;
    }

    VIR_DEBUG("Choose port %d\n", *freePort);

    ret = 0;

cleanup:
    VIR_FORCE_CLOSE(s4);
    VIR_FORCE_CLOSE(s6);
    return ret;
}


struct testTCPData {
    const char *lnode;
    int port;
    const char *cnode;
};

static int testSocketTCPAccept(const void *opaque)
{
    virNetSocketPtr *lsock = NULL; /* Listen socket */
    size_t nlsock = 0, i;
    virNetSocketPtr ssock = NULL; /* Server socket */
    virNetSocketPtr csock = NULL; /* Client socket */
    const struct testTCPData *data = opaque;
    int ret = -1;
    char portstr[100];

    snprintf(portstr, sizeof(portstr), "%d", data->port);

    if (virNetSocketNewListenTCP(data->lnode, portstr, &lsock, &nlsock) < 0)
        goto cleanup;

170
    for (i = 0; i < nlsock; i++) {
171
        if (virNetSocketListen(lsock[i], 0) < 0)
172 173 174 175 176 177
            goto cleanup;
    }

    if (virNetSocketNewConnectTCP(data->cnode, portstr, &csock) < 0)
        goto cleanup;

178
    virObjectUnref(csock);
179

180
    for (i = 0; i < nlsock; i++) {
181 182 183 184 185 186 187 188
        if (virNetSocketAccept(lsock[i], &ssock) != -1 && ssock) {
            char c = 'a';
            if (virNetSocketWrite(ssock, &c, 1) != -1 &&
                virNetSocketRead(ssock, &c, 1) != -1) {
                VIR_DEBUG("Unexpected client socket present");
                goto cleanup;
            }
        }
189
        virObjectUnref(ssock);
190 191 192 193 194 195
        ssock = NULL;
    }

    ret = 0;

cleanup:
196
    virObjectUnref(ssock);
197
    for (i = 0; i < nlsock; i++)
198
        virObjectUnref(lsock[i]);
199 200 201 202 203 204 205 206 207 208 209 210 211 212
    VIR_FREE(lsock);
    return ret;
}
#endif


#ifndef WIN32
static int testSocketUNIXAccept(const void *data ATTRIBUTE_UNUSED)
{
    virNetSocketPtr lsock = NULL; /* Listen socket */
    virNetSocketPtr ssock = NULL; /* Server socket */
    virNetSocketPtr csock = NULL; /* Client socket */
    int ret = -1;

213
    char *path = NULL;
214 215 216 217 218
    char *tmpdir;
    char template[] = "/tmp/libvirt_XXXXXX";

    tmpdir = mkdtemp(template);
    if (tmpdir == NULL) {
219
        VIR_WARN("Failed to create temporary directory");
220 221
        goto cleanup;
    }
222
    if (virAsprintf(&path, "%s/test.sock", tmpdir) < 0)
223
        goto cleanup;
224

225
    if (virNetSocketNewListenUNIX(path, 0700, -1, getegid(), &lsock) < 0)
226 227
        goto cleanup;

228
    if (virNetSocketListen(lsock, 0) < 0)
229 230 231 232 233
        goto cleanup;

    if (virNetSocketNewConnectUNIX(path, false, NULL, &csock) < 0)
        goto cleanup;

234
    virObjectUnref(csock);
235 236 237 238 239 240 241 242 243 244 245 246 247

    if (virNetSocketAccept(lsock, &ssock) != -1) {
        char c = 'a';
        if (virNetSocketWrite(ssock, &c, 1) != -1) {
            VIR_DEBUG("Unexpected client socket present");
            goto cleanup;
        }
    }

    ret = 0;

cleanup:
    VIR_FREE(path);
248 249
    virObjectUnref(lsock);
    virObjectUnref(ssock);
250 251
    if (tmpdir)
        rmdir(tmpdir);
252 253 254 255 256 257 258 259 260 261 262
    return ret;
}


static int testSocketUNIXAddrs(const void *data ATTRIBUTE_UNUSED)
{
    virNetSocketPtr lsock = NULL; /* Listen socket */
    virNetSocketPtr ssock = NULL; /* Server socket */
    virNetSocketPtr csock = NULL; /* Client socket */
    int ret = -1;

263
    char *path = NULL;
264 265 266 267 268
    char *tmpdir;
    char template[] = "/tmp/libvirt_XXXXXX";

    tmpdir = mkdtemp(template);
    if (tmpdir == NULL) {
269
        VIR_WARN("Failed to create temporary directory");
270 271
        goto cleanup;
    }
272
    if (virAsprintf(&path, "%s/test.sock", tmpdir) < 0)
273
        goto cleanup;
274

275
    if (virNetSocketNewListenUNIX(path, 0700, -1, getegid(), &lsock) < 0)
276 277 278 279 280 281 282 283 284 285 286 287
        goto cleanup;

    if (STRNEQ(virNetSocketLocalAddrString(lsock), "127.0.0.1;0")) {
        VIR_DEBUG("Unexpected local address");
        goto cleanup;
    }

    if (virNetSocketRemoteAddrString(lsock) != NULL) {
        VIR_DEBUG("Unexpected remote address");
        goto cleanup;
    }

288
    if (virNetSocketListen(lsock, 0) < 0)
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
        goto cleanup;

    if (virNetSocketNewConnectUNIX(path, false, NULL, &csock) < 0)
        goto cleanup;

    if (STRNEQ(virNetSocketLocalAddrString(csock), "127.0.0.1;0")) {
        VIR_DEBUG("Unexpected local address");
        goto cleanup;
    }

    if (STRNEQ(virNetSocketRemoteAddrString(csock), "127.0.0.1;0")) {
        VIR_DEBUG("Unexpected local address");
        goto cleanup;
    }


    if (virNetSocketAccept(lsock, &ssock) < 0) {
        VIR_DEBUG("Unexpected client socket missing");
        goto cleanup;
    }


    if (STRNEQ(virNetSocketLocalAddrString(ssock), "127.0.0.1;0")) {
        VIR_DEBUG("Unexpected local address");
        goto cleanup;
    }

    if (STRNEQ(virNetSocketRemoteAddrString(ssock), "127.0.0.1;0")) {
        VIR_DEBUG("Unexpected local address");
        goto cleanup;
    }


    ret = 0;

cleanup:
    VIR_FREE(path);
326 327 328
    virObjectUnref(lsock);
    virObjectUnref(ssock);
    virObjectUnref(csock);
329 330
    if (tmpdir)
        rmdir(tmpdir);
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    return ret;
}

static int testSocketCommandNormal(const void *data ATTRIBUTE_UNUSED)
{
    virNetSocketPtr csock = NULL; /* Client socket */
    char buf[100];
    size_t i;
    int ret = -1;
    virCommandPtr cmd = virCommandNewArgList("/bin/cat", "/dev/zero", NULL);
    virCommandAddEnvPassCommon(cmd);

    if (virNetSocketNewConnectCommand(cmd, &csock) < 0)
        goto cleanup;

    virNetSocketSetBlocking(csock, true);

    if (virNetSocketRead(csock, buf, sizeof(buf)) < 0)
        goto cleanup;

351
    for (i = 0; i < sizeof(buf); i++)
352 353 354 355 356 357
        if (buf[i] != '\0')
            goto cleanup;

    ret = 0;

cleanup:
358
    virObjectUnref(csock);
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    return ret;
}

static int testSocketCommandFail(const void *data ATTRIBUTE_UNUSED)
{
    virNetSocketPtr csock = NULL; /* Client socket */
    char buf[100];
    int ret = -1;
    virCommandPtr cmd = virCommandNewArgList("/bin/cat", "/dev/does-not-exist", NULL);
    virCommandAddEnvPassCommon(cmd);

    if (virNetSocketNewConnectCommand(cmd, &csock) < 0)
        goto cleanup;

    virNetSocketSetBlocking(csock, true);

    if (virNetSocketRead(csock, buf, sizeof(buf)) == 0)
        goto cleanup;

    ret = 0;

cleanup:
381
    virObjectUnref(csock);
382 383 384 385 386 387 388 389 390
    return ret;
}

struct testSSHData {
    const char *nodename;
    const char *service;
    const char *binary;
    const char *username;
    bool noTTY;
391
    bool noVerify;
392
    const char *netcat;
393
    const char *keyfile;
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
    const char *path;

    const char *expectOut;
    bool failConnect;
    bool dieEarly;
};

static int testSocketSSH(const void *opaque)
{
    const struct testSSHData *data = opaque;
    virNetSocketPtr csock = NULL; /* Client socket */
    int ret = -1;
    char buf[1024];

    if (virNetSocketNewConnectSSH(data->nodename,
                                  data->service,
                                  data->binary,
                                  data->username,
                                  data->noTTY,
413
                                  data->noVerify,
414
                                  data->netcat,
415
                                  data->keyfile,
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
                                  data->path,
                                  &csock) < 0)
        goto cleanup;

    virNetSocketSetBlocking(csock, true);

    if (data->failConnect) {
        if (virNetSocketRead(csock, buf, sizeof(buf)-1) >= 0) {
            VIR_DEBUG("Expected connect failure, but got some socket data");
            goto cleanup;
        }
    } else {
        ssize_t rv;
        if ((rv = virNetSocketRead(csock, buf, sizeof(buf)-1)) < 0) {
            VIR_DEBUG("Didn't get any socket data");
            goto cleanup;
        }
        buf[rv] = '\0';

        if (!STREQ(buf, data->expectOut)) {
            virtTestDifference(stderr, data->expectOut, buf);
            goto cleanup;
        }

        if (data->dieEarly &&
            virNetSocketRead(csock, buf, sizeof(buf)-1) >= 0) {
            VIR_DEBUG("Got too much socket data");
            goto cleanup;
        }
    }

    ret = 0;

cleanup:
450
    virObjectUnref(csock);
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    return ret;
}

#endif


static int
mymain(void)
{
    int ret = 0;
#ifdef HAVE_IFADDRS_H
    bool hasIPv4, hasIPv6;
    int freePort;
#endif

    signal(SIGPIPE, SIG_IGN);

#ifdef HAVE_IFADDRS_H
    if (checkProtocols(&hasIPv4, &hasIPv6, &freePort) < 0) {
        fprintf(stderr, "Cannot identify IPv4/6 availability\n");
471
        return EXIT_FAILURE;
472 473 474 475
    }

    if (hasIPv4) {
        struct testTCPData tcpData = { "127.0.0.1", freePort, "127.0.0.1" };
476
        if (virtTestRun("Socket TCP/IPv4 Accept", testSocketTCPAccept, &tcpData) < 0)
477 478 479 480
            ret = -1;
    }
    if (hasIPv6) {
        struct testTCPData tcpData = { "::1", freePort, "::1" };
481
        if (virtTestRun("Socket TCP/IPv6 Accept", testSocketTCPAccept, &tcpData) < 0)
482 483 484 485
            ret = -1;
    }
    if (hasIPv6 && hasIPv4) {
        struct testTCPData tcpData = { NULL, freePort, "127.0.0.1" };
486
        if (virtTestRun("Socket TCP/IPv4+IPv6 Accept", testSocketTCPAccept, &tcpData) < 0)
487 488 489
            ret = -1;

        tcpData.cnode = "::1";
490
        if (virtTestRun("Socket TCP/IPv4+IPv6 Accept", testSocketTCPAccept, &tcpData) < 0)
491 492 493 494 495
            ret = -1;
    }
#endif

#ifndef WIN32
496
    if (virtTestRun("Socket UNIX Accept", testSocketUNIXAccept, NULL) < 0)
497 498
        ret = -1;

499
    if (virtTestRun("Socket UNIX Addrs", testSocketUNIXAddrs, NULL) < 0)
500 501
        ret = -1;

502
    if (virtTestRun("Socket External Command /dev/zero", testSocketCommandNormal, NULL) < 0)
503
        ret = -1;
504
    if (virtTestRun("Socket External Command /dev/does-not-exist", testSocketCommandFail, NULL) < 0)
505 506 507 508 509
        ret = -1;

    struct testSSHData sshData1 = {
        .nodename = "somehost",
        .path = "/tmp/socket",
510
        .expectOut = "somehost sh -c 'if 'nc' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
511 512 513 514
                                         "ARG=-q0;"
                                     "else "
                                         "ARG=;"
                                     "fi;"
515
                                     "'nc' $ARG -U /tmp/socket'\n",
516
    };
517
    if (virtTestRun("SSH test 1", testSocketSSH, &sshData1) < 0)
518 519 520 521 522 523 524 525
        ret = -1;

    struct testSSHData sshData2 = {
        .nodename = "somehost",
        .service = "9000",
        .username = "fred",
        .netcat = "netcat",
        .noTTY = true,
526
        .noVerify = false,
527
        .path = "/tmp/socket",
528
        .expectOut = "-p 9000 -l fred -T -o BatchMode=yes -e none somehost sh -c '"
529
                     "if 'netcat' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
530 531 532 533
                         "ARG=-q0;"
                     "else "
                         "ARG=;"
                     "fi;"
534
                     "'netcat' $ARG -U /tmp/socket'\n",
535
    };
536
    if (virtTestRun("SSH test 2", testSocketSSH, &sshData2) < 0)
537 538 539
        ret = -1;

    struct testSSHData sshData3 = {
540 541 542 543 544 545
        .nodename = "somehost",
        .service = "9000",
        .username = "fred",
        .netcat = "netcat",
        .noTTY = false,
        .noVerify = true,
546
        .path = "/tmp/socket",
547
        .expectOut = "-p 9000 -l fred -o StrictHostKeyChecking=no somehost sh -c '"
548
                     "if 'netcat' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
549 550 551 552
                         "ARG=-q0;"
                     "else "
                         "ARG=;"
                     "fi;"
553
                     "'netcat' $ARG -U /tmp/socket'\n",
554
    };
555
    if (virtTestRun("SSH test 3", testSocketSSH, &sshData3) < 0)
556 557 558
        ret = -1;

    struct testSSHData sshData4 = {
559 560 561 562
        .nodename = "nosuchhost",
        .path = "/tmp/socket",
        .failConnect = true,
    };
563
    if (virtTestRun("SSH test 4", testSocketSSH, &sshData4) < 0)
564 565 566
        ret = -1;

    struct testSSHData sshData5 = {
567 568
        .nodename = "crashyhost",
        .path = "/tmp/socket",
569
        .expectOut = "crashyhost sh -c "
570
                     "'if 'nc' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
571 572 573 574
                         "ARG=-q0;"
                     "else "
                         "ARG=;"
                     "fi;"
575
                     "'nc' $ARG -U /tmp/socket'\n",
576 577
        .dieEarly = true,
    };
578
    if (virtTestRun("SSH test 5", testSocketSSH, &sshData5) < 0)
579 580
        ret = -1;

581 582 583 584 585
    struct testSSHData sshData6 = {
        .nodename = "example.com",
        .path = "/tmp/socket",
        .keyfile = "/root/.ssh/example_key",
        .noVerify = true,
586
        .expectOut = "-i /root/.ssh/example_key -o StrictHostKeyChecking=no example.com sh -c '"
587
                     "if 'nc' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
588 589 590 591
                         "ARG=-q0;"
                     "else "
                         "ARG=;"
                     "fi;"
592
                     "'nc' $ARG -U /tmp/socket'\n",
593
    };
594
    if (virtTestRun("SSH test 6", testSocketSSH, &sshData6) < 0)
595 596
        ret = -1;

597 598 599 600 601 602 603 604 605 606 607
    struct testSSHData sshData7 = {
        .nodename = "somehost",
        .netcat = "nc -4",
        .path = "/tmp/socket",
        .expectOut = "somehost sh -c 'if ''nc -4'' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
                                         "ARG=-q0;"
                                     "else "
                                         "ARG=;"
                                     "fi;"
                                     "''nc -4'' $ARG -U /tmp/socket'\n",
    };
608
    if (virtTestRun("SSH test 7", testSocketSSH, &sshData7) < 0)
609 610
        ret = -1;

611 612
#endif

613
    return ret==0 ? EXIT_SUCCESS : EXIT_FAILURE;
614 615 616
}

VIRT_TEST_MAIN(mymain)