virnetsockettest.c 18.2 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

#include "rpc/virnetsocket.h"

#define VIR_FROM_THIS VIR_FROM_RPC

42 43
VIR_LOG_INIT("tests.netsockettest");

44 45 46 47 48 49 50 51 52 53
#if HAVE_IFADDRS_H
# define BASE_PORT 5672

static int
checkProtocols(bool *hasIPv4, bool *hasIPv6,
               int *freePort)
{
    struct sockaddr_in in4;
    struct sockaddr_in6 in6;
    int s4 = -1, s6 = -1;
54
    size_t i;
55 56 57
    int ret = -1;

    *freePort = 0;
58 59
    if (virNetSocketCheckProtocols(hasIPv4, hasIPv6) < 0)
        return -1;
60

61
    for (i = 0; i < 50; i++) {
62 63 64 65
        int only = 1;
        if ((s4 = socket(AF_INET, SOCK_STREAM, 0)) < 0)
            goto cleanup;

66 67 68
        if (*hasIPv6) {
            if ((s6 = socket(AF_INET6, SOCK_STREAM, 0)) < 0)
                goto cleanup;
69

70 71 72
            if (setsockopt(s6, IPPROTO_IPV6, IPV6_V6ONLY, &only, sizeof(only)) < 0)
                goto cleanup;
        }
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

        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;
        }
92 93 94 95 96 97 98 99 100

        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;
101 102 103 104 105 106 107
            }
        }

        *freePort = BASE_PORT + i;
        break;
    }

J
Jiri Denemark 已提交
108
    VIR_DEBUG("Choose port %d", *freePort);
109 110 111

    ret = 0;

112
 cleanup:
113 114 115 116 117
    VIR_FORCE_CLOSE(s4);
    VIR_FORCE_CLOSE(s6);
    return ret;
}

118 119 120 121 122 123 124 125 126 127 128 129 130 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
struct testClientData {
    const char *path;
    const char *cnode;
    const char *portstr;
};

static void
testSocketClient(void *opaque)
{
    struct testClientData *data = opaque;
    char c;
    virNetSocketPtr csock = NULL;

    if (data->path) {
        if (virNetSocketNewConnectUNIX(data->path, false,
                                       NULL, &csock) < 0)
            return;
    } else {
        if (virNetSocketNewConnectTCP(data->cnode, data->portstr,
                                      AF_UNSPEC,
                                      &csock) < 0)
            return;
    }

    virNetSocketSetBlocking(csock, true);

    if (virNetSocketRead(csock, &c, 1) != 1) {
        VIR_DEBUG("Cannot read from server");
        goto done;
    }
    if (virNetSocketWrite(csock, &c, 1) != 1) {
        VIR_DEBUG("Cannot write to server");
        goto done;
    }

 done:
    virObjectUnref(csock);
}


static void
testSocketIncoming(virNetSocketPtr sock,
                   int events ATTRIBUTE_UNUSED,
                   void *opaque)
{
    virNetSocketPtr *retsock = opaque;
    VIR_DEBUG("Incoming sock=%p events=%d\n", sock, events);
    *retsock = sock;
}

168

169
struct testSocketData {
170 171 172 173 174
    const char *lnode;
    int port;
    const char *cnode;
};

175 176 177

static int
testSocketAccept(const void *opaque)
178 179 180 181
{
    virNetSocketPtr *lsock = NULL; /* Listen socket */
    size_t nlsock = 0, i;
    virNetSocketPtr ssock = NULL; /* Server socket */
182
    virNetSocketPtr rsock = NULL; /* Incoming client socket */
183
    const struct testSocketData *data = opaque;
184 185
    int ret = -1;
    char portstr[100];
186 187 188
    char *tmpdir = NULL;
    char *path = NULL;
    char template[] = "/tmp/libvirt_XXXXXX";
189 190 191 192 193
    virThread th;
    struct testClientData cdata = { 0 };
    bool goodsock = false;
    char a = 'a';
    char b = '\0';
194

195 196 197 198 199 200 201 202 203
    if (!data) {
        virNetSocketPtr usock;
        tmpdir = mkdtemp(template);
        if (tmpdir == NULL) {
            VIR_WARN("Failed to create temporary directory");
            goto cleanup;
        }
        if (virAsprintf(&path, "%s/test.sock", tmpdir) < 0)
            goto cleanup;
204

205 206 207 208 209 210 211 212 213 214
        if (virNetSocketNewListenUNIX(path, 0700, -1, getegid(), &usock) < 0)
            goto cleanup;

        if (VIR_ALLOC_N(lsock, 1) < 0) {
            virObjectUnref(usock);
            goto cleanup;
        }

        lsock[0] = usock;
        nlsock = 1;
215 216

        cdata.path = path;
217 218 219 220 221 222
    } else {
        snprintf(portstr, sizeof(portstr), "%d", data->port);
        if (virNetSocketNewListenTCP(data->lnode, portstr,
                                     AF_UNSPEC,
                                     &lsock, &nlsock) < 0)
            goto cleanup;
223 224 225

        cdata.cnode = data->cnode;
        cdata.portstr = portstr;
226
    }
227

228
    for (i = 0; i < nlsock; i++) {
229
        if (virNetSocketListen(lsock[i], 0) < 0)
230 231
            goto cleanup;

232 233 234 235 236
        if (virNetSocketAddIOCallback(lsock[i],
                                      VIR_EVENT_HANDLE_READABLE,
                                      testSocketIncoming,
                                      &rsock,
                                      NULL) < 0) {
237
            goto cleanup;
238
        }
239
    }
240

241 242 243 244 245
    if (virThreadCreate(&th, true,
                        testSocketClient,
                        &cdata) < 0)
        goto cleanup;

246 247 248 249
    while (rsock == NULL) {
        if (virEventRunDefaultImpl() < 0)
            break;
    }
250

251
    for (i = 0; i < nlsock; i++) {
252 253 254
        if (lsock[i] == rsock) {
            goodsock = true;
            break;
255 256 257
        }
    }

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    if (!goodsock) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       "Unexpected server socket seen");
        goto join;
    }

    if (virNetSocketAccept(rsock, &ssock) < 0)
        goto join;

    if (!ssock) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       "Client went away unexpectedly");
        goto join;
    }

    virNetSocketSetBlocking(ssock, true);

    if (virNetSocketWrite(ssock, &a, 1) < 0 ||
        virNetSocketRead(ssock, &b, 1) < 0) {
        goto join;
    }

    if (a != b) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "Bad data received '%x' != '%x'", a, b);
        goto join;
    }

    virObjectUnref(ssock);
    ssock = NULL;

289 290
    ret = 0;

291 292 293
 join:
    virThreadJoin(&th);

294
 cleanup:
295
    virObjectUnref(ssock);
296 297 298
    for (i = 0; i < nlsock; i++) {
        virNetSocketRemoveIOCallback(lsock[i]);
        virNetSocketClose(lsock[i]);
299
        virObjectUnref(lsock[i]);
300
    }
301 302
    VIR_FREE(lsock);
    VIR_FREE(path);
303 304
    if (tmpdir)
        rmdir(tmpdir);
305 306
    return ret;
}
307
#endif
308 309


310
#ifndef WIN32
311 312 313 314 315 316 317
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;

318
    char *path = NULL;
319 320 321 322 323
    char *tmpdir;
    char template[] = "/tmp/libvirt_XXXXXX";

    tmpdir = mkdtemp(template);
    if (tmpdir == NULL) {
324
        VIR_WARN("Failed to create temporary directory");
325 326
        goto cleanup;
    }
327
    if (virAsprintf(&path, "%s/test.sock", tmpdir) < 0)
328
        goto cleanup;
329

330
    if (virNetSocketNewListenUNIX(path, 0700, -1, getegid(), &lsock) < 0)
331 332
        goto cleanup;

333
    if (STRNEQ(virNetSocketLocalAddrStringSASL(lsock), "127.0.0.1;0")) {
334 335 336 337
        VIR_DEBUG("Unexpected local address");
        goto cleanup;
    }

338
    if (virNetSocketRemoteAddrStringSASL(lsock) != NULL) {
339 340 341 342
        VIR_DEBUG("Unexpected remote address");
        goto cleanup;
    }

343
    if (virNetSocketListen(lsock, 0) < 0)
344 345 346 347 348
        goto cleanup;

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

349
    if (STRNEQ(virNetSocketLocalAddrStringSASL(csock), "127.0.0.1;0")) {
350 351 352 353
        VIR_DEBUG("Unexpected local address");
        goto cleanup;
    }

354
    if (STRNEQ(virNetSocketRemoteAddrStringSASL(csock), "127.0.0.1;0")) {
355
        VIR_DEBUG("Unexpected remote address");
356 357 358
        goto cleanup;
    }

359 360 361 362 363
    if (STRNEQ(virNetSocketRemoteAddrStringURI(csock), "127.0.0.1:0")) {
        VIR_DEBUG("Unexpected remote address");
        goto cleanup;
    }

364 365 366 367 368 369 370

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


371
    if (STRNEQ(virNetSocketLocalAddrStringSASL(ssock), "127.0.0.1;0")) {
372 373 374 375
        VIR_DEBUG("Unexpected local address");
        goto cleanup;
    }

376
    if (STRNEQ(virNetSocketRemoteAddrStringSASL(ssock), "127.0.0.1;0")) {
377
        VIR_DEBUG("Unexpected remote address");
378 379 380
        goto cleanup;
    }

381 382 383 384 385
    if (STRNEQ(virNetSocketRemoteAddrStringURI(ssock), "127.0.0.1:0")) {
        VIR_DEBUG("Unexpected remote address");
        goto cleanup;
    }

386 387 388

    ret = 0;

389
 cleanup:
390
    VIR_FREE(path);
391 392 393
    virObjectUnref(lsock);
    virObjectUnref(ssock);
    virObjectUnref(csock);
394 395
    if (tmpdir)
        rmdir(tmpdir);
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
    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;

416
    for (i = 0; i < sizeof(buf); i++)
417 418 419 420 421
        if (buf[i] != '\0')
            goto cleanup;

    ret = 0;

422
 cleanup:
423
    virObjectUnref(csock);
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
    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;

445
 cleanup:
446
    virObjectUnref(csock);
447 448 449 450 451 452 453 454 455
    return ret;
}

struct testSSHData {
    const char *nodename;
    const char *service;
    const char *binary;
    const char *username;
    bool noTTY;
456
    bool noVerify;
457
    const char *netcat;
458
    const char *keyfile;
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
    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,
478
                                  data->noVerify,
479
                                  data->netcat,
480
                                  data->keyfile,
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
                                  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';

500
        if (STRNEQ(buf, data->expectOut)) {
501
            virTestDifference(stderr, data->expectOut, buf);
502 503 504 505 506 507 508 509 510 511 512 513
            goto cleanup;
        }

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

    ret = 0;

514
 cleanup:
515
    virObjectUnref(csock);
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
    return ret;
}

#endif


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

    signal(SIGPIPE, SIG_IGN);

533 534
    virEventRegisterDefaultImpl();

535 536 537
#ifdef HAVE_IFADDRS_H
    if (checkProtocols(&hasIPv4, &hasIPv6, &freePort) < 0) {
        fprintf(stderr, "Cannot identify IPv4/6 availability\n");
538
        return EXIT_FAILURE;
539 540 541
    }

    if (hasIPv4) {
542 543
        struct testSocketData tcpData = { "127.0.0.1", freePort, "127.0.0.1" };
        if (virTestRun("Socket TCP/IPv4 Accept", testSocketAccept, &tcpData) < 0)
544 545 546
            ret = -1;
    }
    if (hasIPv6) {
547 548
        struct testSocketData tcpData = { "::1", freePort, "::1" };
        if (virTestRun("Socket TCP/IPv6 Accept", testSocketAccept, &tcpData) < 0)
549 550 551
            ret = -1;
    }
    if (hasIPv6 && hasIPv4) {
552 553
        struct testSocketData tcpData = { NULL, freePort, "127.0.0.1" };
        if (virTestRun("Socket TCP/IPv4+IPv6 Accept", testSocketAccept, &tcpData) < 0)
554 555 556
            ret = -1;

        tcpData.cnode = "::1";
557
        if (virTestRun("Socket TCP/IPv4+IPv6 Accept", testSocketAccept, &tcpData) < 0)
558 559 560 561 562
            ret = -1;
    }
#endif

#ifndef WIN32
563
    if (virTestRun("Socket UNIX Accept", testSocketAccept, NULL) < 0)
564 565
        ret = -1;

566
    if (virTestRun("Socket UNIX Addrs", testSocketUNIXAddrs, NULL) < 0)
567 568
        ret = -1;

569
    if (virTestRun("Socket External Command /dev/zero", testSocketCommandNormal, NULL) < 0)
570
        ret = -1;
571
    if (virTestRun("Socket External Command /dev/does-not-exist", testSocketCommandFail, NULL) < 0)
572 573 574 575 576
        ret = -1;

    struct testSSHData sshData1 = {
        .nodename = "somehost",
        .path = "/tmp/socket",
577
        .expectOut = "-- somehost sh -c 'if 'nc' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
578 579 580 581
                                         "ARG=-q0;"
                                     "else "
                                         "ARG=;"
                                     "fi;"
582
                                     "'nc' $ARG -U /tmp/socket'\n",
583
    };
584
    if (virTestRun("SSH test 1", testSocketSSH, &sshData1) < 0)
585 586 587 588 589 590 591 592
        ret = -1;

    struct testSSHData sshData2 = {
        .nodename = "somehost",
        .service = "9000",
        .username = "fred",
        .netcat = "netcat",
        .noTTY = true,
593
        .noVerify = false,
594
        .path = "/tmp/socket",
595
        .expectOut = "-p 9000 -l fred -T -o BatchMode=yes -e none -- somehost sh -c '"
596
                     "if 'netcat' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
597 598 599 600
                         "ARG=-q0;"
                     "else "
                         "ARG=;"
                     "fi;"
601
                     "'netcat' $ARG -U /tmp/socket'\n",
602
    };
603
    if (virTestRun("SSH test 2", testSocketSSH, &sshData2) < 0)
604 605 606
        ret = -1;

    struct testSSHData sshData3 = {
607 608 609 610 611 612
        .nodename = "somehost",
        .service = "9000",
        .username = "fred",
        .netcat = "netcat",
        .noTTY = false,
        .noVerify = true,
613
        .path = "/tmp/socket",
614
        .expectOut = "-p 9000 -l fred -o StrictHostKeyChecking=no -- somehost sh -c '"
615
                     "if 'netcat' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
616 617 618 619
                         "ARG=-q0;"
                     "else "
                         "ARG=;"
                     "fi;"
620
                     "'netcat' $ARG -U /tmp/socket'\n",
621
    };
622
    if (virTestRun("SSH test 3", testSocketSSH, &sshData3) < 0)
623 624 625
        ret = -1;

    struct testSSHData sshData4 = {
626 627 628 629
        .nodename = "nosuchhost",
        .path = "/tmp/socket",
        .failConnect = true,
    };
630
    if (virTestRun("SSH test 4", testSocketSSH, &sshData4) < 0)
631 632 633
        ret = -1;

    struct testSSHData sshData5 = {
634 635
        .nodename = "crashyhost",
        .path = "/tmp/socket",
636
        .expectOut = "-- crashyhost sh -c "
637
                     "'if 'nc' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
638 639 640 641
                         "ARG=-q0;"
                     "else "
                         "ARG=;"
                     "fi;"
642
                     "'nc' $ARG -U /tmp/socket'\n",
643 644
        .dieEarly = true,
    };
645
    if (virTestRun("SSH test 5", testSocketSSH, &sshData5) < 0)
646 647
        ret = -1;

648 649 650 651 652
    struct testSSHData sshData6 = {
        .nodename = "example.com",
        .path = "/tmp/socket",
        .keyfile = "/root/.ssh/example_key",
        .noVerify = true,
653
        .expectOut = "-i /root/.ssh/example_key -o StrictHostKeyChecking=no -- example.com sh -c '"
654
                     "if 'nc' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
655 656 657 658
                         "ARG=-q0;"
                     "else "
                         "ARG=;"
                     "fi;"
659
                     "'nc' $ARG -U /tmp/socket'\n",
660
    };
661
    if (virTestRun("SSH test 6", testSocketSSH, &sshData6) < 0)
662 663
        ret = -1;

664 665 666 667
    struct testSSHData sshData7 = {
        .nodename = "somehost",
        .netcat = "nc -4",
        .path = "/tmp/socket",
668
        .expectOut = "-- somehost sh -c 'if ''nc -4'' -q 2>&1 | grep \"requires an argument\" >/dev/null 2>&1; then "
669 670 671 672 673 674
                                         "ARG=-q0;"
                                     "else "
                                         "ARG=;"
                                     "fi;"
                                     "''nc -4'' $ARG -U /tmp/socket'\n",
    };
675
    if (virTestRun("SSH test 7", testSocketSSH, &sshData7) < 0)
676 677
        ret = -1;

678 679
#endif

680
    return ret == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
681 682
}

683
VIR_TEST_MAIN(mymain)