github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/test/syscalls/linux/socket_inet_loopback.cc (about)

     1  // Copyright 2018 The gVisor Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  #include <arpa/inet.h>
    16  #include <netinet/in.h>
    17  #include <netinet/tcp.h>
    18  #include <poll.h>
    19  #include <string.h>
    20  #include <sys/socket.h>
    21  
    22  #include <atomic>
    23  #include <iostream>
    24  #include <memory>
    25  #include <string>
    26  #include <tuple>
    27  #include <utility>
    28  #include <vector>
    29  
    30  #include "gmock/gmock.h"
    31  #include "gtest/gtest.h"
    32  #include "absl/memory/memory.h"
    33  #include "absl/strings/str_cat.h"
    34  #include "absl/time/clock.h"
    35  #include "absl/time/time.h"
    36  #include "test/syscalls/linux/ip_socket_test_util.h"
    37  #include "test/syscalls/linux/socket_inet_loopback_test_params.h"
    38  #include "test/syscalls/linux/socket_test_util.h"
    39  #include "test/util/file_descriptor.h"
    40  #include "test/util/posix_error.h"
    41  #include "test/util/save_util.h"
    42  #include "test/util/test_util.h"
    43  #include "test/util/thread_util.h"
    44  
    45  namespace gvisor {
    46  namespace testing {
    47  
    48  namespace {
    49  
    50  using ::testing::Gt;
    51  
    52  using SocketInetLoopbackTest = ::testing::TestWithParam<SocketInetTestParam>;
    53  
    54  TEST(BadSocketPairArgs, ValidateErrForBadCallsToSocketPair) {
    55    int fd[2] = {};
    56  
    57    // Valid AF but invalid for socketpair(2) return ESOCKTNOSUPPORT.
    58    ASSERT_THAT(socketpair(AF_INET, 0, 0, fd),
    59                SyscallFailsWithErrno(ESOCKTNOSUPPORT));
    60    ASSERT_THAT(socketpair(AF_INET6, 0, 0, fd),
    61                SyscallFailsWithErrno(ESOCKTNOSUPPORT));
    62  
    63    // Invalid AF will fail.
    64    ASSERT_THAT(socketpair(AF_MAX, 0, 0, fd), SyscallFails());
    65    ASSERT_THAT(socketpair(8675309, 0, 0, fd), SyscallFails());
    66  }
    67  
    68  enum class Operation {
    69    Bind,
    70    Connect,
    71    SendTo,
    72  };
    73  
    74  std::string OperationToString(Operation operation) {
    75    switch (operation) {
    76      case Operation::Bind:
    77        return "Bind";
    78      case Operation::Connect:
    79        return "Connect";
    80      // Operation::SendTo is the default.
    81      default:
    82        return "SendTo";
    83    }
    84  }
    85  
    86  using OperationSequence = std::vector<Operation>;
    87  
    88  using DualStackSocketTest =
    89      ::testing::TestWithParam<std::tuple<TestAddress, OperationSequence>>;
    90  
    91  TEST_P(DualStackSocketTest, AddressOperations) {
    92    const FileDescriptor fd =
    93        ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET6, SOCK_DGRAM, 0));
    94  
    95    const TestAddress& addr = std::get<0>(GetParam());
    96    const OperationSequence& operations = std::get<1>(GetParam());
    97  
    98    auto addr_in = reinterpret_cast<const sockaddr*>(&addr.addr);
    99  
   100    // sockets may only be bound once. Both `connect` and `sendto` cause a socket
   101    // to be bound.
   102    bool bound = false;
   103    for (const Operation& operation : operations) {
   104      bool sockname = false;
   105      bool peername = false;
   106      switch (operation) {
   107        case Operation::Bind: {
   108          ASSERT_NO_ERRNO(SetAddrPort(
   109              addr.family(), const_cast<sockaddr_storage*>(&addr.addr), 0));
   110  
   111          int bind_ret = bind(fd.get(), addr_in, addr.addr_len);
   112  
   113          // Dual stack sockets may only be bound to AF_INET6.
   114          if (!bound && addr.family() == AF_INET6) {
   115            EXPECT_THAT(bind_ret, SyscallSucceeds());
   116            bound = true;
   117  
   118            sockname = true;
   119          } else {
   120            EXPECT_THAT(bind_ret, SyscallFailsWithErrno(EINVAL));
   121          }
   122          break;
   123        }
   124        case Operation::Connect: {
   125          ASSERT_NO_ERRNO(SetAddrPort(
   126              addr.family(), const_cast<sockaddr_storage*>(&addr.addr), 1337));
   127  
   128          EXPECT_THAT(RetryEINTR(connect)(fd.get(), addr_in, addr.addr_len),
   129                      SyscallSucceeds())
   130              << GetAddrStr(addr_in);
   131          bound = true;
   132  
   133          sockname = true;
   134          peername = true;
   135  
   136          break;
   137        }
   138        case Operation::SendTo: {
   139          const char payload[] = "hello";
   140          ASSERT_NO_ERRNO(SetAddrPort(
   141              addr.family(), const_cast<sockaddr_storage*>(&addr.addr), 1337));
   142  
   143          ssize_t sendto_ret = sendto(fd.get(), &payload, sizeof(payload), 0,
   144                                      addr_in, addr.addr_len);
   145  
   146          EXPECT_THAT(sendto_ret, SyscallSucceedsWithValue(sizeof(payload)));
   147          sockname = !bound;
   148          bound = true;
   149          break;
   150        }
   151      }
   152  
   153      if (sockname) {
   154        sockaddr_storage sock_addr;
   155        socklen_t addrlen = sizeof(sock_addr);
   156        ASSERT_THAT(getsockname(fd.get(), AsSockAddr(&sock_addr), &addrlen),
   157                    SyscallSucceeds());
   158        ASSERT_EQ(addrlen, sizeof(struct sockaddr_in6));
   159  
   160        auto sock_addr_in6 = reinterpret_cast<const sockaddr_in6*>(&sock_addr);
   161  
   162        if (operation == Operation::SendTo) {
   163          EXPECT_EQ(sock_addr_in6->sin6_family, AF_INET6);
   164          EXPECT_TRUE(IN6_IS_ADDR_UNSPECIFIED(sock_addr_in6->sin6_addr.s6_addr32))
   165              << OperationToString(operation)
   166              << " getsocknam=" << GetAddrStr(AsSockAddr(&sock_addr));
   167  
   168          EXPECT_NE(sock_addr_in6->sin6_port, 0);
   169        } else if (IN6_IS_ADDR_V4MAPPED(
   170                       reinterpret_cast<const sockaddr_in6*>(addr_in)
   171                           ->sin6_addr.s6_addr32)) {
   172          EXPECT_TRUE(IN6_IS_ADDR_V4MAPPED(sock_addr_in6->sin6_addr.s6_addr32))
   173              << OperationToString(operation)
   174              << " getsocknam=" << GetAddrStr(AsSockAddr(&sock_addr));
   175        }
   176      }
   177  
   178      if (peername) {
   179        sockaddr_storage peer_addr;
   180        socklen_t addrlen = sizeof(peer_addr);
   181        ASSERT_THAT(getpeername(fd.get(), AsSockAddr(&peer_addr), &addrlen),
   182                    SyscallSucceeds());
   183        ASSERT_EQ(addrlen, sizeof(struct sockaddr_in6));
   184  
   185        if (addr.family() == AF_INET ||
   186            IN6_IS_ADDR_V4MAPPED(reinterpret_cast<const sockaddr_in6*>(addr_in)
   187                                     ->sin6_addr.s6_addr32)) {
   188          EXPECT_TRUE(IN6_IS_ADDR_V4MAPPED(
   189              reinterpret_cast<const sockaddr_in6*>(&peer_addr)
   190                  ->sin6_addr.s6_addr32))
   191              << OperationToString(operation)
   192              << " getpeername=" << GetAddrStr(AsSockAddr(&peer_addr));
   193        }
   194      }
   195    }
   196  }
   197  
   198  // TODO(gvisor.dev/issue/1556): uncomment V4MappedAny.
   199  INSTANTIATE_TEST_SUITE_P(
   200      All, DualStackSocketTest,
   201      ::testing::Combine(
   202          ::testing::Values(V4Any(), V4Loopback(), /*V4MappedAny(),*/
   203                            V4MappedLoopback(), V6Any(), V6Loopback()),
   204          ::testing::ValuesIn<OperationSequence>(
   205              {{Operation::Bind, Operation::Connect, Operation::SendTo},
   206               {Operation::Bind, Operation::SendTo, Operation::Connect},
   207               {Operation::Connect, Operation::Bind, Operation::SendTo},
   208               {Operation::Connect, Operation::SendTo, Operation::Bind},
   209               {Operation::SendTo, Operation::Bind, Operation::Connect},
   210               {Operation::SendTo, Operation::Connect, Operation::Bind}})),
   211      [](::testing::TestParamInfo<
   212          std::tuple<TestAddress, OperationSequence>> const& info) {
   213        const TestAddress& addr = std::get<0>(info.param);
   214        const OperationSequence& operations = std::get<1>(info.param);
   215        std::string s = addr.description;
   216        for (const Operation& operation : operations) {
   217          absl::StrAppend(&s, OperationToString(operation));
   218        }
   219        return s;
   220      });
   221  
   222  void tcpSimpleConnectTest(TestAddress const& listener,
   223                            TestAddress const& connector, bool unbound) {
   224    // Create the listening socket.
   225    const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
   226        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
   227    sockaddr_storage listen_addr = listener.addr;
   228    if (!unbound) {
   229      ASSERT_THAT(
   230          bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
   231          SyscallSucceeds());
   232    }
   233    ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
   234  
   235    // Get the port bound by the listening socket.
   236    socklen_t addrlen = listener.addr_len;
   237    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
   238                SyscallSucceeds());
   239    uint16_t const port =
   240        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
   241  
   242    // Connect to the listening socket.
   243    const FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
   244        Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
   245    sockaddr_storage conn_addr = connector.addr;
   246    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
   247    ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
   248                                    connector.addr_len),
   249                SyscallSucceeds());
   250  
   251    // Accept the connection.
   252    //
   253    // We have to assign a name to the accepted socket, as unamed temporary
   254    // objects are destructed upon full evaluation of the expression it is in,
   255    // potentially causing the connecting socket to fail to shutdown properly.
   256    auto accepted =
   257        ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
   258  
   259    ASSERT_THAT(shutdown(listen_fd.get(), SHUT_RDWR), SyscallSucceeds());
   260  
   261    ASSERT_THAT(shutdown(conn_fd.get(), SHUT_RDWR), SyscallSucceeds());
   262  }
   263  
   264  TEST_P(SocketInetLoopbackTest, TCP) {
   265    SocketInetTestParam const& param = GetParam();
   266    TestAddress const& listener = param.listener;
   267    TestAddress const& connector = param.connector;
   268  
   269    tcpSimpleConnectTest(listener, connector, true);
   270  }
   271  
   272  TEST_P(SocketInetLoopbackTest, TCPListenUnbound) {
   273    SocketInetTestParam const& param = GetParam();
   274  
   275    TestAddress const& listener = param.listener;
   276    TestAddress const& connector = param.connector;
   277  
   278    tcpSimpleConnectTest(listener, connector, false);
   279  }
   280  
   281  TEST_P(SocketInetLoopbackTest, TCPListenShutdownListen) {
   282    SocketInetTestParam const& param = GetParam();
   283  
   284    const TestAddress& listener = param.listener;
   285    const TestAddress& connector = param.connector;
   286  
   287    constexpr int kBacklog = 5;
   288  
   289    // Create the listening socket.
   290    FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
   291        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
   292    sockaddr_storage listen_addr = listener.addr;
   293    ASSERT_THAT(
   294        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
   295        SyscallSucceeds());
   296  
   297    ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());
   298    ASSERT_THAT(shutdown(listen_fd.get(), SHUT_RD), SyscallSucceeds());
   299    ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());
   300  
   301    // Get the port bound by the listening socket.
   302    socklen_t addrlen = listener.addr_len;
   303    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
   304                SyscallSucceeds());
   305    const uint16_t port =
   306        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
   307  
   308    sockaddr_storage conn_addr = connector.addr;
   309    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
   310  
   311    // TODO(b/157236388): Remove Disable save after bug is fixed. S/R test can
   312    // fail because the last socket may not be delivered to the accept queue
   313    // by the time connect returns.
   314    DisableSave ds;
   315    for (int i = 0; i < kBacklog; i++) {
   316      auto client = ASSERT_NO_ERRNO_AND_VALUE(
   317          Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
   318      ASSERT_THAT(RetryEINTR(connect)(client.get(), AsSockAddr(&conn_addr),
   319                                      connector.addr_len),
   320                  SyscallSucceeds());
   321    }
   322    for (int i = 0; i < kBacklog; i++) {
   323      ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr), SyscallSucceeds());
   324    }
   325  }
   326  
   327  TEST_P(SocketInetLoopbackTest, TCPListenShutdown) {
   328    SocketInetTestParam const& param = GetParam();
   329  
   330    TestAddress const& listener = param.listener;
   331    TestAddress const& connector = param.connector;
   332  
   333    constexpr int kBacklog = 2;
   334    // See the comment in TCPBacklog for why this isn't kBacklog + 1.
   335    constexpr int kFDs = kBacklog;
   336  
   337    // Create the listening socket.
   338    FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
   339        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
   340    sockaddr_storage listen_addr = listener.addr;
   341    ASSERT_THAT(
   342        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
   343        SyscallSucceeds());
   344    ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());
   345  
   346    // Get the port bound by the listening socket.
   347    socklen_t addrlen = listener.addr_len;
   348    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
   349                SyscallSucceeds());
   350    uint16_t const port =
   351        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
   352  
   353    sockaddr_storage conn_addr = connector.addr;
   354    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
   355  
   356    // Shutdown the write of the listener, expect to not have any effect.
   357    ASSERT_THAT(shutdown(listen_fd.get(), SHUT_WR), SyscallSucceeds());
   358  
   359    for (int i = 0; i < kFDs; i++) {
   360      auto client = ASSERT_NO_ERRNO_AND_VALUE(
   361          Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
   362      ASSERT_THAT(RetryEINTR(connect)(client.get(), AsSockAddr(&conn_addr),
   363                                      connector.addr_len),
   364                  SyscallSucceeds());
   365      ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr), SyscallSucceeds());
   366    }
   367  
   368    // Shutdown the read of the listener, expect to fail subsequent
   369    // server accepts, binds and client connects.
   370    ASSERT_THAT(shutdown(listen_fd.get(), SHUT_RD), SyscallSucceeds());
   371  
   372    ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr),
   373                SyscallFailsWithErrno(EINVAL));
   374  
   375    // Check that shutdown did not release the port.
   376    FileDescriptor new_listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
   377        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
   378    ASSERT_THAT(
   379        bind(new_listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
   380        SyscallFailsWithErrno(EADDRINUSE));
   381  
   382    // Check that subsequent connection attempts receive a RST.
   383    auto client = ASSERT_NO_ERRNO_AND_VALUE(
   384        Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
   385  
   386    for (int i = 0; i < kFDs; i++) {
   387      auto client = ASSERT_NO_ERRNO_AND_VALUE(
   388          Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
   389      ASSERT_THAT(RetryEINTR(connect)(client.get(), AsSockAddr(&conn_addr),
   390                                      connector.addr_len),
   391                  SyscallFailsWithErrno(ECONNREFUSED));
   392    }
   393  }
   394  
   395  TEST_P(SocketInetLoopbackTest, TCPListenClose) {
   396    SocketInetTestParam const& param = GetParam();
   397  
   398    TestAddress const& listener = param.listener;
   399    TestAddress const& connector = param.connector;
   400  
   401    constexpr int kAcceptCount = 2;
   402    constexpr int kBacklog = kAcceptCount + 2;
   403    constexpr int kFDs = kBacklog * 3;
   404  
   405    // Create the listening socket.
   406    FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
   407        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
   408    sockaddr_storage listen_addr = listener.addr;
   409    ASSERT_THAT(
   410        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
   411        SyscallSucceeds());
   412    ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());
   413  
   414    // Get the port bound by the listening socket.
   415    socklen_t addrlen = listener.addr_len;
   416    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
   417                SyscallSucceeds());
   418    uint16_t const port =
   419        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
   420  
   421    // Connect repeatedly, keeping each connection open. After kBacklog
   422    // connections, we'll start getting EINPROGRESS.
   423    sockaddr_storage conn_addr = connector.addr;
   424    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
   425    std::vector<FileDescriptor> clients;
   426    for (int i = 0; i < kFDs; i++) {
   427      auto client = ASSERT_NO_ERRNO_AND_VALUE(
   428          Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
   429      int ret = connect(client.get(), AsSockAddr(&conn_addr), connector.addr_len);
   430      if (ret != 0) {
   431        EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));
   432      }
   433      clients.push_back(std::move(client));
   434    }
   435    for (int i = 0; i < kAcceptCount; i++) {
   436      auto accepted =
   437          ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
   438    }
   439  }
   440  
   441  // Test the protocol state information returned by TCPINFO.
   442  TEST_P(SocketInetLoopbackTest, TCPInfoState) {
   443    SocketInetTestParam const& param = GetParam();
   444    TestAddress const& listener = param.listener;
   445    TestAddress const& connector = param.connector;
   446  
   447    // Create the listening socket.
   448    FileDescriptor const listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
   449        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
   450  
   451    auto state = [](int fd) -> int {
   452      struct tcp_info opt = {};
   453      socklen_t optLen = sizeof(opt);
   454      EXPECT_THAT(getsockopt(fd, SOL_TCP, TCP_INFO, &opt, &optLen),
   455                  SyscallSucceeds());
   456      return opt.tcpi_state;
   457    };
   458    ASSERT_EQ(state(listen_fd.get()), TCP_CLOSE);
   459  
   460    sockaddr_storage listen_addr = listener.addr;
   461    ASSERT_THAT(
   462        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
   463        SyscallSucceeds());
   464    ASSERT_EQ(state(listen_fd.get()), TCP_CLOSE);
   465  
   466    ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
   467    ASSERT_EQ(state(listen_fd.get()), TCP_LISTEN);
   468  
   469    // Get the port bound by the listening socket.
   470    socklen_t addrlen = listener.addr_len;
   471    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
   472                SyscallSucceeds());
   473    uint16_t const port =
   474        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
   475  
   476    // Connect to the listening socket.
   477    FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
   478        Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
   479    sockaddr_storage conn_addr = connector.addr;
   480    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
   481    ASSERT_EQ(state(conn_fd.get()), TCP_CLOSE);
   482    ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
   483                                    connector.addr_len),
   484                SyscallSucceeds());
   485    ASSERT_EQ(state(conn_fd.get()), TCP_ESTABLISHED);
   486  
   487    auto accepted =
   488        ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
   489    ASSERT_EQ(state(accepted.get()), TCP_ESTABLISHED);
   490  
   491    ASSERT_THAT(close(accepted.release()), SyscallSucceeds());
   492  
   493    struct pollfd pfd = {
   494        .fd = conn_fd.get(),
   495        .events = POLLIN | POLLRDHUP,
   496    };
   497    constexpr int kTimeout = 10000;
   498    int n = poll(&pfd, 1, kTimeout);
   499    ASSERT_GE(n, 0) << strerror(errno);
   500    ASSERT_EQ(n, 1);
   501    if (IsRunningOnGvisor() && GvisorPlatform() != Platform::kFuchsia) {
   502      // TODO(gvisor.dev/issue/6015): Notify POLLRDHUP on incoming FIN.
   503      ASSERT_EQ(pfd.revents, POLLIN);
   504    } else {
   505      ASSERT_EQ(pfd.revents, POLLIN | POLLRDHUP);
   506    }
   507  
   508    ASSERT_THAT(state(conn_fd.get()), TCP_CLOSE_WAIT);
   509    ASSERT_THAT(close(conn_fd.release()), SyscallSucceeds());
   510  }
   511  
   512  void TestHangupDuringConnect(const SocketInetTestParam& param,
   513                               void (*hangup)(FileDescriptor&)) {
   514    TestAddress const& listener = param.listener;
   515    TestAddress const& connector = param.connector;
   516  
   517    for (int i = 0; i < 100; i++) {
   518      // Create the listening socket.
   519      FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
   520          Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
   521      sockaddr_storage listen_addr = listener.addr;
   522      ASSERT_THAT(bind(listen_fd.get(), reinterpret_cast<sockaddr*>(&listen_addr),
   523                       listener.addr_len),
   524                  SyscallSucceeds());
   525      ASSERT_THAT(listen(listen_fd.get(), 0), SyscallSucceeds());
   526  
   527      // Get the port bound by the listening socket.
   528      socklen_t addrlen = listener.addr_len;
   529      ASSERT_THAT(
   530          getsockname(listen_fd.get(), reinterpret_cast<sockaddr*>(&listen_addr),
   531                      &addrlen),
   532          SyscallSucceeds());
   533      uint16_t const port =
   534          ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
   535  
   536      sockaddr_storage conn_addr = connector.addr;
   537      ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
   538  
   539      // Connect asynchronously and immediately hang up the listener.
   540      FileDescriptor client = ASSERT_NO_ERRNO_AND_VALUE(
   541          Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
   542      int ret = connect(client.get(), reinterpret_cast<sockaddr*>(&conn_addr),
   543                        connector.addr_len);
   544      if (ret != 0) {
   545        EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));
   546      }
   547  
   548      hangup(listen_fd);
   549  
   550      // Wait for the connection to close.
   551      struct pollfd pfd = {
   552          .fd = client.get(),
   553      };
   554      constexpr int kTimeout = 10000;
   555      int n = poll(&pfd, 1, kTimeout);
   556      ASSERT_GE(n, 0) << strerror(errno);
   557      ASSERT_EQ(n, 1);
   558      ASSERT_EQ(pfd.revents, POLLHUP | POLLERR);
   559      ASSERT_EQ(close(client.release()), 0) << strerror(errno);
   560    }
   561  }
   562  
   563  TEST_P(SocketInetLoopbackTest, TCPListenCloseDuringConnect) {
   564    TestHangupDuringConnect(GetParam(), [](FileDescriptor& f) {
   565      ASSERT_THAT(close(f.release()), SyscallSucceeds());
   566    });
   567  }
   568  
   569  TEST_P(SocketInetLoopbackTest, TCPListenShutdownDuringConnect) {
   570    TestHangupDuringConnect(GetParam(), [](FileDescriptor& f) {
   571      ASSERT_THAT(shutdown(f.get(), SHUT_RD), SyscallSucceeds());
   572    });
   573  }
   574  
   575  void TestListenHangupConnectingRead(const SocketInetTestParam& param,
   576                                      void (*hangup)(FileDescriptor&)) {
   577    constexpr int kTimeout = 10000;
   578  
   579    TestAddress const& listener = param.listener;
   580    TestAddress const& connector = param.connector;
   581  
   582    // Create the listening socket.
   583    FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
   584        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
   585    sockaddr_storage listen_addr = listener.addr;
   586    ASSERT_THAT(
   587        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
   588        SyscallSucceeds());
   589    // This test is only interested in deterministically getting a socket in
   590    // connecting state. For that, we use a listen backlog of zero which would
   591    // mean there is exactly one connection that gets established and is enqueued
   592    // to the accept queue. We poll on the listener to ensure that is enqueued.
   593    // After that the subsequent client connect will stay in connecting state as
   594    // the accept queue is full.
   595    constexpr int kBacklog = 0;
   596    ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());
   597  
   598    // Get the port bound by the listening socket.
   599    socklen_t addrlen = listener.addr_len;
   600    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
   601                SyscallSucceeds());
   602    uint16_t const port =
   603        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
   604  
   605    sockaddr_storage conn_addr = connector.addr;
   606    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
   607    FileDescriptor established_client = ASSERT_NO_ERRNO_AND_VALUE(
   608        Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
   609    int ret = connect(established_client.get(), AsSockAddr(&conn_addr),
   610                      connector.addr_len);
   611    if (ret != 0) {
   612      EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));
   613    }
   614  
   615    // On some kernels a backlog of 0 means no backlog, while on others it means a
   616    // backlog of 1. See commit c609e6aae4efcf383fe86b195d1b060befcb3666 for more
   617    // explanation.
   618    //
   619    // If we timeout connecting to loopback, we're on a kernel with no backlog.
   620    pollfd pfd = {
   621        .fd = established_client.get(),
   622        .events = POLLIN | POLLOUT,
   623    };
   624    if (!poll(&pfd, 1, kTimeout)) {
   625      // We're on one of those kernels. It should be impossible to establish the
   626      // connection, so connect will always return EALREADY.
   627      EXPECT_THAT(connect(established_client.get(), AsSockAddr(&conn_addr),
   628                          connector.addr_len),
   629                  SyscallFailsWithErrno(EALREADY));
   630      return;
   631    }
   632  
   633    // Ensure that the accept queue has the completed connection.
   634    pfd = {
   635        .fd = listen_fd.get(),
   636        .events = POLLIN,
   637    };
   638    ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));
   639    ASSERT_EQ(pfd.revents, POLLIN);
   640  
   641    FileDescriptor connecting_client = ASSERT_NO_ERRNO_AND_VALUE(
   642        Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
   643    // Keep the last client in connecting state.
   644    ret = connect(connecting_client.get(), AsSockAddr(&conn_addr),
   645                  connector.addr_len);
   646    if (ret != 0) {
   647      EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));
   648    }
   649  
   650    hangup(listen_fd);
   651  
   652    std::array<std::pair<int, int>, 2> sockets = {
   653        std::make_pair(established_client.get(), ECONNRESET),
   654        std::make_pair(connecting_client.get(), ECONNREFUSED),
   655    };
   656    for (size_t i = 0; i < sockets.size(); i++) {
   657      SCOPED_TRACE(absl::StrCat("i=", i));
   658      auto [fd, expected_errno] = sockets[i];
   659      pollfd pfd = {
   660          .fd = fd,
   661      };
   662      // When the listening socket is closed, the peer would reset the connection.
   663      EXPECT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));
   664      EXPECT_EQ(pfd.revents, POLLHUP | POLLERR);
   665      char c;
   666      EXPECT_THAT(read(fd, &c, sizeof(c)), SyscallFailsWithErrno(expected_errno));
   667    }
   668  }
   669  
   670  TEST_P(SocketInetLoopbackTest, TCPListenCloseConnectingRead) {
   671    TestListenHangupConnectingRead(GetParam(), [](FileDescriptor& f) {
   672      ASSERT_THAT(close(f.release()), SyscallSucceeds());
   673    });
   674  }
   675  
   676  TEST_P(SocketInetLoopbackTest, TCPListenShutdownConnectingRead) {
   677    TestListenHangupConnectingRead(GetParam(), [](FileDescriptor& f) {
   678      ASSERT_THAT(shutdown(f.get(), SHUT_RD), SyscallSucceeds());
   679    });
   680  }
   681  
   682  // Test close of a non-blocking connecting socket.
   683  TEST_P(SocketInetLoopbackTest, TCPNonBlockingConnectClose) {
   684    SocketInetTestParam const& param = GetParam();
   685    TestAddress const& listener = param.listener;
   686    TestAddress const& connector = param.connector;
   687  
   688    // Create the listening socket.
   689    FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
   690        Socket(listener.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
   691    sockaddr_storage listen_addr = listener.addr;
   692    ASSERT_THAT(
   693        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
   694        SyscallSucceeds());
   695    ASSERT_THAT(listen(listen_fd.get(), 0), SyscallSucceeds());
   696  
   697    // Get the port bound by the listening socket.
   698    socklen_t addrlen = listener.addr_len;
   699    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
   700                SyscallSucceeds());
   701    ASSERT_EQ(addrlen, listener.addr_len);
   702    uint16_t const port =
   703        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
   704  
   705    sockaddr_storage conn_addr = connector.addr;
   706    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
   707  
   708    // Try many iterations to catch a race with socket close and handshake
   709    // completion.
   710    for (int i = 0; i < 100; ++i) {
   711      FileDescriptor client = ASSERT_NO_ERRNO_AND_VALUE(
   712          Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
   713      ASSERT_THAT(
   714          connect(client.get(), AsSockAddr(&conn_addr), connector.addr_len),
   715          SyscallFailsWithErrno(EINPROGRESS));
   716      ASSERT_THAT(close(client.release()), SyscallSucceeds());
   717  
   718      // Accept any connections and check if they were closed from the peer. Not
   719      // all client connects would result in an acceptable connection as the
   720      // client handshake might never complete if the socket close was processed
   721      // sooner than the non-blocking connect OR the accept queue is full. We are
   722      // only interested in the case where we do have an acceptable completed
   723      // connection. The accept is non-blocking here, which means that at the time
   724      // of listener close (after the loop ends), we could still have a completed
   725      // connection (from connect of any previous iteration) in the accept queue.
   726      // The listener close would clean up the accept queue.
   727      int accepted_fd;
   728      ASSERT_THAT(accepted_fd = accept(listen_fd.get(), nullptr, nullptr),
   729                  AnyOf(SyscallSucceeds(), SyscallFailsWithErrno(EWOULDBLOCK)));
   730      if (accepted_fd < 0) {
   731        continue;
   732      }
   733      FileDescriptor accepted(accepted_fd);
   734      struct pollfd pfd = {
   735          .fd = accepted.get(),
   736          .events = POLLIN | POLLRDHUP,
   737      };
   738      // Use a large timeout to accomodate for retransmitted FINs.
   739      constexpr int kTimeout = 30000;
   740      int n = poll(&pfd, 1, kTimeout);
   741      ASSERT_GE(n, 0) << strerror(errno);
   742      ASSERT_EQ(n, 1);
   743  
   744      if (IsRunningOnGvisor() && GvisorPlatform() != Platform::kFuchsia) {
   745        // TODO(gvisor.dev/issue/6015): Notify POLLRDHUP on incoming FIN.
   746        ASSERT_EQ(pfd.revents, POLLIN);
   747      } else {
   748        ASSERT_EQ(pfd.revents, POLLIN | POLLRDHUP);
   749      }
   750      ASSERT_THAT(close(accepted.release()), SyscallSucceeds());
   751    }
   752  }
   753  
   754  // TODO(b/157236388): Remove  once bug is fixed. Test fails w/
   755  // random save as established connections which can't be delivered to the accept
   756  // queue because the queue is full are not correctly delivered after restore
   757  // causing the last accept to timeout on the restore.
   758  TEST_P(SocketInetLoopbackTest, TCPAcceptBacklogSizes) {
   759    SocketInetTestParam const& param = GetParam();
   760  
   761    TestAddress const& listener = param.listener;
   762    TestAddress const& connector = param.connector;
   763  
   764    // Create the listening socket.
   765    const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
   766        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
   767    sockaddr_storage listen_addr = listener.addr;
   768    ASSERT_THAT(
   769        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
   770        SyscallSucceeds());
   771    // Get the port bound by the listening socket.
   772    socklen_t addrlen = listener.addr_len;
   773    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
   774                SyscallSucceeds());
   775    uint16_t const port =
   776        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
   777    std::array<int, 3> backlogs = {-1, 0, 1};
   778    for (auto& backlog : backlogs) {
   779      ASSERT_THAT(listen(listen_fd.get(), backlog), SyscallSucceeds());
   780  
   781      int expected_accepts;
   782      if (backlog < 0) {
   783        expected_accepts = 1024;
   784      } else {
   785        // See the comment in TCPBacklog for why this isn't backlog + 1.
   786        expected_accepts = backlog;
   787      }
   788      for (int i = 0; i < expected_accepts; i++) {
   789        SCOPED_TRACE(absl::StrCat("i=", i));
   790        // Connect to the listening socket.
   791        const FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
   792            Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
   793        sockaddr_storage conn_addr = connector.addr;
   794        ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
   795        ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
   796                                        connector.addr_len),
   797                    SyscallSucceeds());
   798        const FileDescriptor accepted =
   799            ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
   800      }
   801    }
   802  }
   803  
   804  // TODO(b/157236388): Remove  once bug is fixed. Test fails w/
   805  // random save as established connections which can't be delivered to the accept
   806  // queue because the queue is full are not correctly delivered after restore
   807  // causing the last accept to timeout on the restore.
   808  TEST_P(SocketInetLoopbackTest, TCPBacklog) {
   809    SocketInetTestParam const& param = GetParam();
   810  
   811    TestAddress const& listener = param.listener;
   812    TestAddress const& connector = param.connector;
   813  
   814    // Create the listening socket.
   815    const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
   816        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
   817    sockaddr_storage listen_addr = listener.addr;
   818    ASSERT_THAT(
   819        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
   820        SyscallSucceeds());
   821    constexpr int kBacklogSize = 2;
   822    ASSERT_THAT(listen(listen_fd.get(), kBacklogSize), SyscallSucceeds());
   823  
   824    // Get the port bound by the listening socket.
   825    socklen_t addrlen = listener.addr_len;
   826    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
   827                SyscallSucceeds());
   828    uint16_t const port =
   829        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
   830    int i = 0;
   831    while (1) {
   832      SCOPED_TRACE(absl::StrCat("i=", i));
   833      int ret;
   834  
   835      // Connect to the listening socket.
   836      const FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
   837          Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
   838      sockaddr_storage conn_addr = connector.addr;
   839      ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
   840      ret = connect(conn_fd.get(), AsSockAddr(&conn_addr), connector.addr_len);
   841      if (ret != 0) {
   842        EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));
   843        pollfd pfd = {
   844            .fd = conn_fd.get(),
   845            .events = POLLOUT,
   846        };
   847        ret = poll(&pfd, 1, 3000);
   848        if (ret == 0) break;
   849        EXPECT_THAT(ret, SyscallSucceedsWithValue(1));
   850      }
   851      EXPECT_THAT(RetryEINTR(send)(conn_fd.get(), &i, sizeof(i), 0),
   852                  SyscallSucceedsWithValue(sizeof(i)));
   853      ASSERT_THAT(shutdown(conn_fd.get(), SHUT_RDWR), SyscallSucceeds());
   854      i++;
   855    }
   856  
   857    int client_conns = i;
   858    int accepted_conns = 0;
   859    for (; i != 0; i--) {
   860      SCOPED_TRACE(absl::StrCat("i=", i));
   861      pollfd pfd = {
   862          .fd = listen_fd.get(),
   863          .events = POLLIN,
   864      };
   865      // Look for incoming connections to accept. The last connect request could
   866      // be established from the client side, but the ACK of the handshake could
   867      // be dropped by the listener if the accept queue was filled up by the
   868      // previous connect.
   869      int ret;
   870      ASSERT_THAT(ret = poll(&pfd, 1, 3000), SyscallSucceeds());
   871      if (ret == 0) break;
   872      if (pfd.revents == POLLIN) {
   873        // Accept the connection.
   874        //
   875        // We have to assign a name to the accepted socket, as unamed temporary
   876        // objects are destructed upon full evaluation of the expression it is in,
   877        // potentially causing the connecting socket to fail to shutdown properly.
   878        auto accepted =
   879            ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
   880        accepted_conns++;
   881      }
   882    }
   883    // We should accept at least listen backlog + 1 connections. As the stack is
   884    // enqueuing established connections to the accept queue, newer SYNs could
   885    // still be replied to causing those client connections would be accepted as
   886    // we start dequeuing the queue.
   887    //
   888    // On some kernels this can value can be off by one, so we don't add 1 to
   889    // kBacklogSize. See commit c609e6aae4efcf383fe86b195d1b060befcb3666 for more
   890    // explanation.
   891    ASSERT_GE(accepted_conns, kBacklogSize);
   892    ASSERT_GE(client_conns, accepted_conns);
   893  }
   894  
   895  // TODO(b/157236388): Remove  once bug is fixed. Test fails w/
   896  // random save as established connections which can't be delivered to the accept
   897  // queue because the queue is full are not correctly delivered after restore
   898  // causing the last accept to timeout on the restore.
   899  TEST_P(SocketInetLoopbackTest, TCPBacklogAcceptAll) {
   900    SocketInetTestParam const& param = GetParam();
   901    TestAddress const& listener = param.listener;
   902    TestAddress const& connector = param.connector;
   903  
   904    // Create the listening socket.
   905    FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
   906        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
   907    sockaddr_storage listen_addr = listener.addr;
   908    ASSERT_THAT(
   909        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
   910        SyscallSucceeds());
   911    constexpr int kBacklog = 1;
   912    ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());
   913  
   914    // Get the port bound by the listening socket.
   915    socklen_t addrlen = listener.addr_len;
   916    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
   917                SyscallSucceeds());
   918    uint16_t const port =
   919        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
   920  
   921    sockaddr_storage conn_addr = connector.addr;
   922    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
   923  
   924    // Fill up the accept queue and trigger more client connections which would be
   925    // waiting to be accepted.
   926    //
   927    // See the comment in TCPBacklog for why this isn't backlog + 1.
   928    std::array<FileDescriptor, kBacklog> established_clients;
   929    for (auto& fd : established_clients) {
   930      fd = ASSERT_NO_ERRNO_AND_VALUE(
   931          Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
   932      ASSERT_THAT(connect(fd.get(), AsSockAddr(&conn_addr), connector.addr_len),
   933                  SyscallSucceeds());
   934    }
   935    std::array<FileDescriptor, kBacklog> waiting_clients;
   936    for (auto& fd : waiting_clients) {
   937      fd = ASSERT_NO_ERRNO_AND_VALUE(
   938          Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
   939      int ret = connect(fd.get(), AsSockAddr(&conn_addr), connector.addr_len);
   940      if (ret != 0) {
   941        EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));
   942      }
   943    }
   944  
   945    auto accept_connection = [&]() {
   946      constexpr int kTimeout = 10000;
   947      pollfd pfd = {
   948          .fd = listen_fd.get(),
   949          .events = POLLIN,
   950      };
   951      ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));
   952      ASSERT_EQ(pfd.revents, POLLIN);
   953      // Accept the connection.
   954      //
   955      // We have to assign a name to the accepted socket, as unamed temporary
   956      // objects are destructed upon full evaluation of the expression it is in,
   957      // potentially causing the connecting socket to fail to shutdown properly.
   958      auto accepted =
   959          ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
   960    };
   961  
   962    // Ensure that we accept all client connections. The waiting connections would
   963    // get enqueued as we drain the accept queue.
   964    for (int i = 0; i < std::size(established_clients); i++) {
   965      SCOPED_TRACE(absl::StrCat("established clients i=", i));
   966      accept_connection();
   967    }
   968  
   969    // The waiting client connections could be in one of these 2 states:
   970    // (1) SYN_SENT: if the SYN was dropped because accept queue was full
   971    // (2) ESTABLISHED: if the listener sent back a SYNACK, but may have dropped
   972    // the ACK from the client if the accept queue was full (send out a data to
   973    // re-send that ACK, to address that case).
   974    for (int i = 0; i < std::size(waiting_clients); i++) {
   975      SCOPED_TRACE(absl::StrCat("waiting clients i=", i));
   976      constexpr int kTimeout = 10000;
   977      pollfd pfd = {
   978          .fd = waiting_clients[i].get(),
   979          .events = POLLOUT,
   980      };
   981      EXPECT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));
   982      EXPECT_EQ(pfd.revents, POLLOUT);
   983      char c;
   984      EXPECT_THAT(RetryEINTR(send)(waiting_clients[i].get(), &c, sizeof(c), 0),
   985                  SyscallSucceedsWithValue(sizeof(c)));
   986      accept_connection();
   987    }
   988  }
   989  
   990  // TCPResetAfterClose creates a pair of connected sockets then closes
   991  // one end to trigger FIN_WAIT2 state for the closed endpoint verifies
   992  // that we generate RSTs for any new data after the socket is fully
   993  // closed.
   994  TEST_P(SocketInetLoopbackTest, TCPResetAfterClose) {
   995    SocketInetTestParam const& param = GetParam();
   996    TestAddress const& listener = param.listener;
   997    TestAddress const& connector = param.connector;
   998  
   999    // Create the listening socket.
  1000    const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
  1001        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
  1002    sockaddr_storage listen_addr = listener.addr;
  1003    ASSERT_THAT(
  1004        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
  1005        SyscallSucceeds());
  1006    ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
  1007  
  1008    // Get the port bound by the listening socket.
  1009    socklen_t addrlen = listener.addr_len;
  1010    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
  1011                SyscallSucceeds());
  1012  
  1013    uint16_t const port =
  1014        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
  1015  
  1016    // Connect to the listening socket.
  1017    FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
  1018        Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
  1019  
  1020    sockaddr_storage conn_addr = connector.addr;
  1021    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
  1022    ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
  1023                                    connector.addr_len),
  1024                SyscallSucceeds());
  1025  
  1026    // Accept the connection.
  1027    auto accepted =
  1028        ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
  1029  
  1030    // close the connecting FD to trigger FIN_WAIT2  on the connected fd.
  1031    conn_fd.reset();
  1032  
  1033    int data = 1234;
  1034  
  1035    // Now send data which should trigger a RST as the other end should
  1036    // have timed out and closed the socket.
  1037    EXPECT_THAT(RetryEINTR(send)(accepted.get(), &data, sizeof(data), 0),
  1038                SyscallSucceeds());
  1039    // Sleep for a shortwhile to get a RST back.
  1040    absl::SleepFor(absl::Seconds(1));
  1041  
  1042    // Try writing again and we should get an EPIPE back.
  1043    EXPECT_THAT(RetryEINTR(send)(accepted.get(), &data, sizeof(data), 0),
  1044                SyscallFailsWithErrno(EPIPE));
  1045  
  1046    // Trying to read should return zero as the other end did send
  1047    // us a FIN. We do it twice to verify that the RST does not cause an
  1048    // ECONNRESET on the read after EOF has been read by applicaiton.
  1049    EXPECT_THAT(RetryEINTR(recv)(accepted.get(), &data, sizeof(data), 0),
  1050                SyscallSucceedsWithValue(0));
  1051    EXPECT_THAT(RetryEINTR(recv)(accepted.get(), &data, sizeof(data), 0),
  1052                SyscallSucceedsWithValue(0));
  1053  }
  1054  
  1055  TEST_P(SocketInetLoopbackTest, AcceptedInheritsTCPUserTimeout) {
  1056    SocketInetTestParam const& param = GetParam();
  1057    TestAddress const& listener = param.listener;
  1058    TestAddress const& connector = param.connector;
  1059  
  1060    // Create the listening socket.
  1061    const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
  1062        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
  1063    sockaddr_storage listen_addr = listener.addr;
  1064    ASSERT_THAT(
  1065        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
  1066        SyscallSucceeds());
  1067    ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
  1068  
  1069    // Get the port bound by the listening socket.
  1070    socklen_t addrlen = listener.addr_len;
  1071    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
  1072                SyscallSucceeds());
  1073  
  1074    const uint16_t port =
  1075        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
  1076  
  1077    // Set the userTimeout on the listening socket.
  1078    constexpr int kUserTimeout = 10;
  1079    ASSERT_THAT(setsockopt(listen_fd.get(), IPPROTO_TCP, TCP_USER_TIMEOUT,
  1080                           &kUserTimeout, sizeof(kUserTimeout)),
  1081                SyscallSucceeds());
  1082  
  1083    // Connect to the listening socket.
  1084    FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
  1085        Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
  1086  
  1087    sockaddr_storage conn_addr = connector.addr;
  1088    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
  1089    ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
  1090                                    connector.addr_len),
  1091                SyscallSucceeds());
  1092  
  1093    // Accept the connection.
  1094    auto accepted =
  1095        ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
  1096    // Verify that the accepted socket inherited the user timeout set on
  1097    // listening socket.
  1098    int get = -1;
  1099    socklen_t get_len = sizeof(get);
  1100    ASSERT_THAT(
  1101        getsockopt(accepted.get(), IPPROTO_TCP, TCP_USER_TIMEOUT, &get, &get_len),
  1102        SyscallSucceeds());
  1103    EXPECT_EQ(get_len, sizeof(get));
  1104    EXPECT_EQ(get, kUserTimeout);
  1105  }
  1106  
  1107  TEST_P(SocketInetLoopbackTest, TCPAcceptAfterReset) {
  1108    SocketInetTestParam const& param = GetParam();
  1109    TestAddress const& listener = param.listener;
  1110    TestAddress const& connector = param.connector;
  1111  
  1112    // Create the listening socket.
  1113    const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
  1114        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
  1115    sockaddr_storage listen_addr = listener.addr;
  1116    ASSERT_THAT(
  1117        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
  1118        SyscallSucceeds());
  1119    ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
  1120  
  1121    // Get the port bound by the listening socket.
  1122    {
  1123      socklen_t addrlen = listener.addr_len;
  1124      ASSERT_THAT(
  1125          getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
  1126          SyscallSucceeds());
  1127    }
  1128  
  1129    const uint16_t port =
  1130        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
  1131  
  1132    // Connect to the listening socket.
  1133    FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
  1134        Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
  1135  
  1136    sockaddr_storage conn_addr = connector.addr;
  1137    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
  1138  
  1139    // TODO(b/157236388): Reenable Cooperative S/R once bug is fixed.
  1140    DisableSave ds;
  1141    ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
  1142                                    connector.addr_len),
  1143                SyscallSucceeds());
  1144  
  1145    // Trigger a RST by turning linger off and closing the socket.
  1146    struct linger opt = {
  1147        .l_onoff = 1,
  1148        .l_linger = 0,
  1149    };
  1150    ASSERT_THAT(
  1151        setsockopt(conn_fd.get(), SOL_SOCKET, SO_LINGER, &opt, sizeof(opt)),
  1152        SyscallSucceeds());
  1153    ASSERT_THAT(close(conn_fd.release()), SyscallSucceeds());
  1154  
  1155    if (IsRunningOnGvisor()) {
  1156      // Gvisor packet procssing is asynchronous and can take a bit of time in
  1157      // some cases so we give it a bit of time to process the RST packet before
  1158      // calling accept.
  1159      //
  1160      // There is nothing to poll() on so we have no choice but to use a sleep
  1161      // here.
  1162      absl::SleepFor(absl::Milliseconds(100));
  1163    }
  1164  
  1165    sockaddr_storage accept_addr;
  1166    socklen_t addrlen = sizeof(accept_addr);
  1167  
  1168    auto accept_fd = ASSERT_NO_ERRNO_AND_VALUE(
  1169        Accept(listen_fd.get(), AsSockAddr(&accept_addr), &addrlen));
  1170    ASSERT_EQ(addrlen, listener.addr_len);
  1171  
  1172    // Wait for accept_fd to process the RST.
  1173    constexpr int kTimeout = 10000;
  1174    pollfd pfd = {
  1175        .fd = accept_fd.get(),
  1176        .events = POLLIN,
  1177    };
  1178    ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));
  1179    ASSERT_EQ(pfd.revents, POLLIN | POLLHUP | POLLERR);
  1180  
  1181    {
  1182      int err;
  1183      socklen_t optlen = sizeof(err);
  1184      ASSERT_THAT(
  1185          getsockopt(accept_fd.get(), SOL_SOCKET, SO_ERROR, &err, &optlen),
  1186          SyscallSucceeds());
  1187      // This should return ECONNRESET as the socket just received a RST packet
  1188      // from the peer.
  1189      ASSERT_EQ(optlen, sizeof(err));
  1190      ASSERT_EQ(err, ECONNRESET);
  1191    }
  1192    {
  1193      int err;
  1194      socklen_t optlen = sizeof(err);
  1195      ASSERT_THAT(
  1196          getsockopt(accept_fd.get(), SOL_SOCKET, SO_ERROR, &err, &optlen),
  1197          SyscallSucceeds());
  1198      // This should return no error as the previous getsockopt call would have
  1199      // cleared the socket error.
  1200      ASSERT_EQ(optlen, sizeof(err));
  1201      ASSERT_EQ(err, 0);
  1202    }
  1203    {
  1204      sockaddr_storage peer_addr;
  1205      socklen_t addrlen = sizeof(peer_addr);
  1206      // The socket is not connected anymore and should return ENOTCONN.
  1207      ASSERT_THAT(getpeername(accept_fd.get(), AsSockAddr(&peer_addr), &addrlen),
  1208                  SyscallFailsWithErrno(ENOTCONN));
  1209    }
  1210  }
  1211  
  1212  // TODO(gvisor.dev/issue/1688): Partially completed passive endpoints are not
  1213  // saved. Enable S/R once issue is fixed.
  1214  TEST_P(SocketInetLoopbackTest, TCPDeferAccept) {
  1215    // TODO(gvisor.dev/issue/1688): Partially completed passive endpoints are not
  1216    // saved. Enable S/R issue is fixed.
  1217    DisableSave ds;
  1218  
  1219    SocketInetTestParam const& param = GetParam();
  1220    TestAddress const& listener = param.listener;
  1221    TestAddress const& connector = param.connector;
  1222  
  1223    // Create the listening socket.
  1224    const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
  1225        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
  1226    sockaddr_storage listen_addr = listener.addr;
  1227    ASSERT_THAT(
  1228        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
  1229        SyscallSucceeds());
  1230    ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
  1231  
  1232    // Get the port bound by the listening socket.
  1233    socklen_t addrlen = listener.addr_len;
  1234    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
  1235                SyscallSucceeds());
  1236  
  1237    const uint16_t port =
  1238        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
  1239  
  1240    // Set the TCP_DEFER_ACCEPT on the listening socket.
  1241    constexpr int kTCPDeferAccept = 3;
  1242    ASSERT_THAT(setsockopt(listen_fd.get(), IPPROTO_TCP, TCP_DEFER_ACCEPT,
  1243                           &kTCPDeferAccept, sizeof(kTCPDeferAccept)),
  1244                SyscallSucceeds());
  1245  
  1246    // Connect to the listening socket.
  1247    FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
  1248        Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
  1249  
  1250    sockaddr_storage conn_addr = connector.addr;
  1251    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
  1252    ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
  1253                                    connector.addr_len),
  1254                SyscallSucceeds());
  1255  
  1256    // Set the listening socket to nonblock so that we can verify that there is no
  1257    // connection in queue despite the connect above succeeding since the peer has
  1258    // sent no data and TCP_DEFER_ACCEPT is set on the listening socket. Set the
  1259    // FD to O_NONBLOCK.
  1260    int opts;
  1261    ASSERT_THAT(opts = fcntl(listen_fd.get(), F_GETFL), SyscallSucceeds());
  1262    opts |= O_NONBLOCK;
  1263    ASSERT_THAT(fcntl(listen_fd.get(), F_SETFL, opts), SyscallSucceeds());
  1264  
  1265    ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr),
  1266                SyscallFailsWithErrno(EWOULDBLOCK));
  1267  
  1268    // Set FD back to blocking.
  1269    opts &= ~O_NONBLOCK;
  1270    ASSERT_THAT(fcntl(listen_fd.get(), F_SETFL, opts), SyscallSucceeds());
  1271  
  1272    // Now write some data to the socket.
  1273    int data = 0;
  1274    ASSERT_THAT(RetryEINTR(write)(conn_fd.get(), &data, sizeof(data)),
  1275                SyscallSucceedsWithValue(sizeof(data)));
  1276  
  1277    // This should now cause the connection to complete and be delivered to the
  1278    // accept socket.
  1279  
  1280    // Accept the connection.
  1281    auto accepted =
  1282        ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
  1283  
  1284    // Verify that the accepted socket returns the data written.
  1285    int get = -1;
  1286    ASSERT_THAT(RetryEINTR(recv)(accepted.get(), &get, sizeof(get), 0),
  1287                SyscallSucceedsWithValue(sizeof(get)));
  1288  
  1289    EXPECT_EQ(get, data);
  1290  }
  1291  
  1292  // TODO(gvisor.dev/issue/1688): Partially completed passive endpoints are not
  1293  // saved. Enable S/R once issue is fixed.
  1294  TEST_P(SocketInetLoopbackTest, TCPDeferAcceptTimeout) {
  1295    // TODO(gvisor.dev/issue/1688): Partially completed passive endpoints are not
  1296    // saved. Enable S/R once issue is fixed.
  1297    DisableSave ds;
  1298  
  1299    SocketInetTestParam const& param = GetParam();
  1300    TestAddress const& listener = param.listener;
  1301    TestAddress const& connector = param.connector;
  1302  
  1303    // Create the listening socket.
  1304    const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
  1305        Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
  1306    sockaddr_storage listen_addr = listener.addr;
  1307    ASSERT_THAT(
  1308        bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
  1309        SyscallSucceeds());
  1310    ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
  1311  
  1312    // Get the port bound by the listening socket.
  1313    socklen_t addrlen = listener.addr_len;
  1314    ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
  1315                SyscallSucceeds());
  1316  
  1317    const uint16_t port =
  1318        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
  1319  
  1320    // Set the TCP_DEFER_ACCEPT on the listening socket.
  1321    constexpr int kTCPDeferAccept = 3;
  1322    ASSERT_THAT(setsockopt(listen_fd.get(), IPPROTO_TCP, TCP_DEFER_ACCEPT,
  1323                           &kTCPDeferAccept, sizeof(kTCPDeferAccept)),
  1324                SyscallSucceeds());
  1325  
  1326    // Connect to the listening socket.
  1327    FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
  1328        Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
  1329  
  1330    sockaddr_storage conn_addr = connector.addr;
  1331    ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
  1332    ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
  1333                                    connector.addr_len),
  1334                SyscallSucceeds());
  1335  
  1336    // Set the listening socket to nonblock so that we can verify that there is no
  1337    // connection in queue despite the connect above succeeding since the peer has
  1338    // sent no data and TCP_DEFER_ACCEPT is set on the listening socket. Set the
  1339    // FD to O_NONBLOCK.
  1340    int opts;
  1341    ASSERT_THAT(opts = fcntl(listen_fd.get(), F_GETFL), SyscallSucceeds());
  1342    opts |= O_NONBLOCK;
  1343    ASSERT_THAT(fcntl(listen_fd.get(), F_SETFL, opts), SyscallSucceeds());
  1344  
  1345    // Verify that there is no acceptable connection before TCP_DEFER_ACCEPT
  1346    // timeout is hit.
  1347    absl::SleepFor(absl::Seconds(kTCPDeferAccept - 1));
  1348    ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr),
  1349                SyscallFailsWithErrno(EWOULDBLOCK));
  1350  
  1351    // Set FD back to blocking.
  1352    opts &= ~O_NONBLOCK;
  1353    ASSERT_THAT(fcntl(listen_fd.get(), F_SETFL, opts), SyscallSucceeds());
  1354  
  1355    // Now sleep for a little over the TCP_DEFER_ACCEPT duration. When the timeout
  1356    // is hit a SYN-ACK should be retransmitted by the listener as a last ditch
  1357    // attempt to complete the connection with or without data.
  1358    absl::SleepFor(absl::Seconds(2));
  1359  
  1360    // Verify that we have a connection that can be accepted even though no
  1361    // data was written.
  1362    auto accepted =
  1363        ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
  1364  }
  1365  
  1366  INSTANTIATE_TEST_SUITE_P(All, SocketInetLoopbackTest,
  1367                           SocketInetLoopbackTestValues(),
  1368                           DescribeSocketInetTestParam);
  1369  
  1370  using SocketInetReusePortTest = ::testing::TestWithParam<SocketInetTestParam>;
  1371  
  1372  // TODO(gvisor.dev/issue/940): Remove  when portHint/stack.Seed is
  1373  // saved/restored.
  1374  TEST_P(SocketInetReusePortTest, TcpPortReuseMultiThread) {
  1375    SocketInetTestParam const& param = GetParam();
  1376  
  1377    TestAddress const& listener = param.listener;
  1378    TestAddress const& connector = param.connector;
  1379    sockaddr_storage listen_addr = listener.addr;
  1380    sockaddr_storage conn_addr = connector.addr;
  1381    constexpr int kThreadCount = 3;
  1382    constexpr int kConnectAttempts = 10000;
  1383  
  1384    // Create the listening socket.
  1385    FileDescriptor listener_fds[kThreadCount];
  1386    for (int i = 0; i < kThreadCount; i++) {
  1387      listener_fds[i] = ASSERT_NO_ERRNO_AND_VALUE(
  1388          Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
  1389      int fd = listener_fds[i].get();
  1390  
  1391      ASSERT_THAT(setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1392                             sizeof(kSockOptOn)),
  1393                  SyscallSucceeds());
  1394      ASSERT_THAT(bind(fd, AsSockAddr(&listen_addr), listener.addr_len),
  1395                  SyscallSucceeds());
  1396      ASSERT_THAT(listen(fd, 40), SyscallSucceeds());
  1397  
  1398      // On the first bind we need to determine which port was bound.
  1399      if (i != 0) {
  1400        continue;
  1401      }
  1402  
  1403      // Get the port bound by the listening socket.
  1404      socklen_t addrlen = listener.addr_len;
  1405      ASSERT_THAT(
  1406          getsockname(listener_fds[0].get(), AsSockAddr(&listen_addr), &addrlen),
  1407          SyscallSucceeds());
  1408      uint16_t const port =
  1409          ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
  1410      ASSERT_NO_ERRNO(SetAddrPort(listener.family(), &listen_addr, port));
  1411      ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
  1412    }
  1413  
  1414    std::atomic<int> connects_received = ATOMIC_VAR_INIT(0);
  1415    std::unique_ptr<ScopedThread> listen_thread[kThreadCount];
  1416    int accept_counts[kThreadCount] = {};
  1417    // TODO(avagin): figure how to not disable S/R for the whole test.
  1418    // We need to take into account that this test executes a lot of system
  1419    // calls from many threads.
  1420    DisableSave ds;
  1421  
  1422    for (int i = 0; i < kThreadCount; i++) {
  1423      listen_thread[i] = absl::make_unique<ScopedThread>(
  1424          [&listener_fds, &accept_counts, i, &connects_received]() {
  1425            do {
  1426              auto fd = Accept(listener_fds[i].get(), nullptr, nullptr);
  1427              if (!fd.ok()) {
  1428                if (connects_received >= kConnectAttempts) {
  1429                  // Another thread have shutdown our read side causing the
  1430                  // accept to fail.
  1431                  ASSERT_EQ(errno, EINVAL);
  1432                  break;
  1433                }
  1434                ASSERT_NO_ERRNO(fd);
  1435                break;
  1436              }
  1437              // Receive some data from a socket to be sure that the connect()
  1438              // system call has been completed on another side.
  1439              // Do a short read and then close the socket to trigger a RST. This
  1440              // ensures that both ends of the connection are cleaned up and no
  1441              // goroutines hang around in TIME-WAIT. We do this so that this test
  1442              // does not timeout under gotsan runs where lots of goroutines can
  1443              // cause the test to use absurd amounts of memory.
  1444              //
  1445              // See: https://tools.ietf.org/html/rfc2525#page-50 section 2.17
  1446              uint16_t data;
  1447              EXPECT_THAT(
  1448                  RetryEINTR(recv)(fd.ValueOrDie().get(), &data, sizeof(data), 0),
  1449                  SyscallSucceedsWithValue(sizeof(data)));
  1450              accept_counts[i]++;
  1451            } while (++connects_received < kConnectAttempts);
  1452  
  1453            // Shutdown all sockets to wake up other threads.
  1454            for (int j = 0; j < kThreadCount; j++) {
  1455              shutdown(listener_fds[j].get(), SHUT_RDWR);
  1456            }
  1457          });
  1458    }
  1459  
  1460    ScopedThread connecting_thread([&connector, &conn_addr]() {
  1461      for (int32_t i = 0; i < kConnectAttempts; i++) {
  1462        const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(
  1463            Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
  1464        ASSERT_THAT(RetryEINTR(connect)(fd.get(), AsSockAddr(&conn_addr),
  1465                                        connector.addr_len),
  1466                    SyscallSucceeds());
  1467  
  1468        EXPECT_THAT(RetryEINTR(send)(fd.get(), &i, sizeof(i), 0),
  1469                    SyscallSucceedsWithValue(sizeof(i)));
  1470      }
  1471    });
  1472  
  1473    // Join threads to be sure that all connections have been counted
  1474    connecting_thread.Join();
  1475    for (int i = 0; i < kThreadCount; i++) {
  1476      listen_thread[i]->Join();
  1477    }
  1478    // Check that connections are distributed fairly between listening sockets
  1479    for (int i = 0; i < kThreadCount; i++)
  1480      EXPECT_THAT(accept_counts[i],
  1481                  EquivalentWithin((kConnectAttempts / kThreadCount), 0.10));
  1482  }
  1483  
  1484  TEST_P(SocketInetReusePortTest, UdpPortReuseMultiThread) {
  1485    SocketInetTestParam const& param = GetParam();
  1486  
  1487    TestAddress const& listener = param.listener;
  1488    TestAddress const& connector = param.connector;
  1489    sockaddr_storage listen_addr = listener.addr;
  1490    sockaddr_storage conn_addr = connector.addr;
  1491    constexpr int kThreadCount = 3;
  1492  
  1493    // Create the listening socket.
  1494    FileDescriptor listener_fds[kThreadCount];
  1495    for (int i = 0; i < kThreadCount; i++) {
  1496      listener_fds[i] =
  1497          ASSERT_NO_ERRNO_AND_VALUE(Socket(listener.family(), SOCK_DGRAM, 0));
  1498      int fd = listener_fds[i].get();
  1499  
  1500      ASSERT_THAT(setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1501                             sizeof(kSockOptOn)),
  1502                  SyscallSucceeds());
  1503      ASSERT_THAT(bind(fd, AsSockAddr(&listen_addr), listener.addr_len),
  1504                  SyscallSucceeds());
  1505  
  1506      // On the first bind we need to determine which port was bound.
  1507      if (i != 0) {
  1508        continue;
  1509      }
  1510  
  1511      // Get the port bound by the listening socket.
  1512      socklen_t addrlen = listener.addr_len;
  1513      ASSERT_THAT(
  1514          getsockname(listener_fds[0].get(), AsSockAddr(&listen_addr), &addrlen),
  1515          SyscallSucceeds());
  1516      uint16_t const port =
  1517          ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
  1518      ASSERT_NO_ERRNO(SetAddrPort(listener.family(), &listen_addr, port));
  1519      ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
  1520    }
  1521  
  1522    constexpr int kConnectAttempts = 10000;
  1523    std::atomic<int> packets_received = ATOMIC_VAR_INIT(0);
  1524    std::unique_ptr<ScopedThread> receiver_thread[kThreadCount];
  1525    int packets_per_socket[kThreadCount] = {};
  1526    // TODO(avagin): figure how to not disable S/R for the whole test.
  1527    DisableSave ds;  // Too expensive.
  1528  
  1529    for (int i = 0; i < kThreadCount; i++) {
  1530      receiver_thread[i] = absl::make_unique<ScopedThread>(
  1531          [&listener_fds, &packets_per_socket, i, &packets_received]() {
  1532            do {
  1533              struct sockaddr_storage addr = {};
  1534              socklen_t addrlen = sizeof(addr);
  1535              int data;
  1536  
  1537              auto ret =
  1538                  RetryEINTR(recvfrom)(listener_fds[i].get(), &data, sizeof(data),
  1539                                       0, AsSockAddr(&addr), &addrlen);
  1540  
  1541              if (packets_received < kConnectAttempts) {
  1542                ASSERT_THAT(ret, SyscallSucceedsWithValue(sizeof(data)));
  1543              }
  1544  
  1545              if (ret != sizeof(data)) {
  1546                // Another thread may have shutdown our read side causing the
  1547                // recvfrom to fail.
  1548                break;
  1549              }
  1550  
  1551              packets_received++;
  1552              packets_per_socket[i]++;
  1553  
  1554              // A response is required to synchronize with the main thread,
  1555              // otherwise the main thread can send more than can fit into receive
  1556              // queues.
  1557              EXPECT_THAT(
  1558                  RetryEINTR(sendto)(listener_fds[i].get(), &data, sizeof(data),
  1559                                     0, AsSockAddr(&addr), addrlen),
  1560                  SyscallSucceedsWithValue(sizeof(data)));
  1561            } while (packets_received < kConnectAttempts);
  1562  
  1563            // Shutdown all sockets to wake up other threads.
  1564            for (int j = 0; j < kThreadCount; j++)
  1565              shutdown(listener_fds[j].get(), SHUT_RDWR);
  1566          });
  1567    }
  1568  
  1569    ScopedThread main_thread([&connector, &conn_addr]() {
  1570      for (int i = 0; i < kConnectAttempts; i++) {
  1571        const FileDescriptor fd =
  1572            ASSERT_NO_ERRNO_AND_VALUE(Socket(connector.family(), SOCK_DGRAM, 0));
  1573        EXPECT_THAT(
  1574            RetryEINTR(sendto)(fd.get(), &i, sizeof(i), 0, AsSockAddr(&conn_addr),
  1575                               connector.addr_len),
  1576            SyscallSucceedsWithValue(sizeof(i)));
  1577        int data;
  1578        EXPECT_THAT(RetryEINTR(recv)(fd.get(), &data, sizeof(data), 0),
  1579                    SyscallSucceedsWithValue(sizeof(data)));
  1580      }
  1581    });
  1582  
  1583    main_thread.Join();
  1584  
  1585    // Join threads to be sure that all connections have been counted
  1586    for (int i = 0; i < kThreadCount; i++) {
  1587      receiver_thread[i]->Join();
  1588    }
  1589    // Check that packets are distributed fairly between listening sockets.
  1590    for (int i = 0; i < kThreadCount; i++)
  1591      EXPECT_THAT(packets_per_socket[i],
  1592                  EquivalentWithin((kConnectAttempts / kThreadCount), 0.10));
  1593  }
  1594  
  1595  TEST_P(SocketInetReusePortTest, UdpPortReuseMultiThreadShort) {
  1596    SocketInetTestParam const& param = GetParam();
  1597  
  1598    TestAddress const& listener = param.listener;
  1599    TestAddress const& connector = param.connector;
  1600    sockaddr_storage listen_addr = listener.addr;
  1601    sockaddr_storage conn_addr = connector.addr;
  1602    constexpr int kThreadCount = 3;
  1603  
  1604    // TODO(b/141211329): endpointsByNic.seed has to be saved/restored.
  1605    const DisableSave ds141211329;
  1606  
  1607    // Create listening sockets.
  1608    FileDescriptor listener_fds[kThreadCount];
  1609    for (int i = 0; i < kThreadCount; i++) {
  1610      listener_fds[i] =
  1611          ASSERT_NO_ERRNO_AND_VALUE(Socket(listener.family(), SOCK_DGRAM, 0));
  1612      int fd = listener_fds[i].get();
  1613  
  1614      ASSERT_THAT(setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1615                             sizeof(kSockOptOn)),
  1616                  SyscallSucceeds());
  1617      ASSERT_THAT(bind(fd, AsSockAddr(&listen_addr), listener.addr_len),
  1618                  SyscallSucceeds());
  1619  
  1620      // On the first bind we need to determine which port was bound.
  1621      if (i != 0) {
  1622        continue;
  1623      }
  1624  
  1625      // Get the port bound by the listening socket.
  1626      socklen_t addrlen = listener.addr_len;
  1627      ASSERT_THAT(
  1628          getsockname(listener_fds[0].get(), AsSockAddr(&listen_addr), &addrlen),
  1629          SyscallSucceeds());
  1630      uint16_t const port =
  1631          ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
  1632      ASSERT_NO_ERRNO(SetAddrPort(listener.family(), &listen_addr, port));
  1633      ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
  1634    }
  1635  
  1636    constexpr int kConnectAttempts = 10;
  1637    FileDescriptor client_fds[kConnectAttempts];
  1638  
  1639    // Do the first run without save/restore.
  1640    DisableSave ds;
  1641    for (int i = 0; i < kConnectAttempts; i++) {
  1642      client_fds[i] =
  1643          ASSERT_NO_ERRNO_AND_VALUE(Socket(connector.family(), SOCK_DGRAM, 0));
  1644      EXPECT_THAT(RetryEINTR(sendto)(client_fds[i].get(), &i, sizeof(i), 0,
  1645                                     AsSockAddr(&conn_addr), connector.addr_len),
  1646                  SyscallSucceedsWithValue(sizeof(i)));
  1647    }
  1648    ds.reset();
  1649  
  1650    // Check that a mapping of client and server sockets has
  1651    // not been change after save/restore.
  1652    for (int i = 0; i < kConnectAttempts; i++) {
  1653      EXPECT_THAT(RetryEINTR(sendto)(client_fds[i].get(), &i, sizeof(i), 0,
  1654                                     AsSockAddr(&conn_addr), connector.addr_len),
  1655                  SyscallSucceedsWithValue(sizeof(i)));
  1656    }
  1657  
  1658    pollfd pollfds[kThreadCount];
  1659    for (int i = 0; i < kThreadCount; i++) {
  1660      pollfds[i].fd = listener_fds[i].get();
  1661      pollfds[i].events = POLLIN;
  1662    }
  1663  
  1664    std::map<uint16_t, int> portToFD;
  1665  
  1666    int received = 0;
  1667    while (received < kConnectAttempts * 2) {
  1668      ASSERT_THAT(poll(pollfds, kThreadCount, -1),
  1669                  SyscallSucceedsWithValue(Gt(0)));
  1670  
  1671      for (int i = 0; i < kThreadCount; i++) {
  1672        if ((pollfds[i].revents & POLLIN) == 0) {
  1673          continue;
  1674        }
  1675  
  1676        received++;
  1677  
  1678        const int fd = pollfds[i].fd;
  1679        struct sockaddr_storage addr = {};
  1680        socklen_t addrlen = sizeof(addr);
  1681        int data;
  1682        EXPECT_THAT(RetryEINTR(recvfrom)(fd, &data, sizeof(data), 0,
  1683                                         AsSockAddr(&addr), &addrlen),
  1684                    SyscallSucceedsWithValue(sizeof(data)));
  1685        uint16_t const port =
  1686            ASSERT_NO_ERRNO_AND_VALUE(AddrPort(connector.family(), addr));
  1687        auto prev_port = portToFD.find(port);
  1688        // Check that all packets from one client have been delivered to the
  1689        // same server socket.
  1690        if (prev_port == portToFD.end()) {
  1691          portToFD[port] = fd;
  1692        } else {
  1693          EXPECT_EQ(portToFD[port], fd);
  1694        }
  1695      }
  1696    }
  1697  }
  1698  
  1699  INSTANTIATE_TEST_SUITE_P(
  1700      All, SocketInetReusePortTest,
  1701      ::testing::Values(
  1702          // Listeners bound to IPv4 addresses refuse connections using IPv6
  1703          // addresses.
  1704          SocketInetTestParam{V4Any(), V4Loopback()},
  1705          SocketInetTestParam{V4Loopback(), V4MappedLoopback()},
  1706  
  1707          // Listeners bound to IN6ADDR_ANY accept all connections.
  1708          SocketInetTestParam{V6Any(), V4Loopback()},
  1709          SocketInetTestParam{V6Any(), V6Loopback()},
  1710  
  1711          // Listeners bound to IN6ADDR_LOOPBACK refuse connections using IPv4
  1712          // addresses.
  1713          SocketInetTestParam{V6Loopback(), V6Loopback()}),
  1714      DescribeSocketInetTestParam);
  1715  
  1716  using SocketMultiProtocolInetLoopbackTest =
  1717      ::testing::TestWithParam<ProtocolTestParam>;
  1718  
  1719  TEST_P(SocketMultiProtocolInetLoopbackTest, V4MappedLoopbackOnlyReservesV4) {
  1720    ProtocolTestParam const& param = GetParam();
  1721  
  1722    for (int i = 0; true; i++) {
  1723      // Bind the v4 loopback on a dual stack socket.
  1724      TestAddress const& test_addr_dual = V4MappedLoopback();
  1725      sockaddr_storage addr_dual = test_addr_dual.addr;
  1726      const FileDescriptor fd_dual = ASSERT_NO_ERRNO_AND_VALUE(
  1727          Socket(test_addr_dual.family(), param.type, 0));
  1728      ASSERT_THAT(
  1729          bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
  1730          SyscallSucceeds());
  1731  
  1732      // Get the port that we bound.
  1733      socklen_t addrlen = test_addr_dual.addr_len;
  1734      ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
  1735                  SyscallSucceeds());
  1736      uint16_t const port =
  1737          ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
  1738  
  1739      // Verify that we can still bind the v6 loopback on the same port.
  1740      TestAddress const& test_addr_v6 = V6Loopback();
  1741      sockaddr_storage addr_v6 = test_addr_v6.addr;
  1742      ASSERT_NO_ERRNO(SetAddrPort(test_addr_v6.family(), &addr_v6, port));
  1743      const FileDescriptor fd_v6 =
  1744          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v6.family(), param.type, 0));
  1745      int ret = bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len);
  1746      if (ret == -1 && errno == EADDRINUSE) {
  1747        // Port may have been in use.
  1748        ASSERT_LT(i, 100);  // Give up after 100 tries.
  1749        continue;
  1750      }
  1751      ASSERT_THAT(ret, SyscallSucceeds());
  1752  
  1753      // Verify that binding the v4 loopback with the same port on a v4 socket
  1754      // fails.
  1755      TestAddress const& test_addr_v4 = V4Loopback();
  1756      sockaddr_storage addr_v4 = test_addr_v4.addr;
  1757      ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4.family(), &addr_v4, port));
  1758      const FileDescriptor fd_v4 =
  1759          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v4.family(), param.type, 0));
  1760      ASSERT_THAT(bind(fd_v4.get(), AsSockAddr(&addr_v4), test_addr_v4.addr_len),
  1761                  SyscallFailsWithErrno(EADDRINUSE));
  1762  
  1763      // No need to try again.
  1764      break;
  1765    }
  1766  }
  1767  
  1768  TEST_P(SocketMultiProtocolInetLoopbackTest, V4MappedAnyOnlyReservesV4) {
  1769    ProtocolTestParam const& param = GetParam();
  1770  
  1771    for (int i = 0; true; i++) {
  1772      // Bind the v4 any on a dual stack socket.
  1773      TestAddress const& test_addr_dual = V4MappedAny();
  1774      sockaddr_storage addr_dual = test_addr_dual.addr;
  1775      const FileDescriptor fd_dual = ASSERT_NO_ERRNO_AND_VALUE(
  1776          Socket(test_addr_dual.family(), param.type, 0));
  1777      ASSERT_THAT(
  1778          bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
  1779          SyscallSucceeds());
  1780  
  1781      // Get the port that we bound.
  1782      socklen_t addrlen = test_addr_dual.addr_len;
  1783      ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
  1784                  SyscallSucceeds());
  1785      uint16_t const port =
  1786          ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
  1787  
  1788      // Verify that we can still bind the v6 loopback on the same port.
  1789      TestAddress const& test_addr_v6 = V6Loopback();
  1790      sockaddr_storage addr_v6 = test_addr_v6.addr;
  1791      ASSERT_NO_ERRNO(SetAddrPort(test_addr_v6.family(), &addr_v6, port));
  1792      const FileDescriptor fd_v6 =
  1793          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v6.family(), param.type, 0));
  1794      int ret = bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len);
  1795      if (ret == -1 && errno == EADDRINUSE) {
  1796        // Port may have been in use.
  1797        ASSERT_LT(i, 100);  // Give up after 100 tries.
  1798        continue;
  1799      }
  1800      ASSERT_THAT(ret, SyscallSucceeds());
  1801  
  1802      // Verify that binding the v4 loopback with the same port on a v4 socket
  1803      // fails.
  1804      TestAddress const& test_addr_v4 = V4Loopback();
  1805      sockaddr_storage addr_v4 = test_addr_v4.addr;
  1806      ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4.family(), &addr_v4, port));
  1807      const FileDescriptor fd_v4 =
  1808          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v4.family(), param.type, 0));
  1809      ASSERT_THAT(bind(fd_v4.get(), AsSockAddr(&addr_v4), test_addr_v4.addr_len),
  1810                  SyscallFailsWithErrno(EADDRINUSE));
  1811  
  1812      // No need to try again.
  1813      break;
  1814    }
  1815  }
  1816  
  1817  TEST_P(SocketMultiProtocolInetLoopbackTest, DualStackV6AnyReservesEverything) {
  1818    ProtocolTestParam const& param = GetParam();
  1819  
  1820    // Bind the v6 any on a dual stack socket.
  1821    TestAddress const& test_addr_dual = V6Any();
  1822    sockaddr_storage addr_dual = test_addr_dual.addr;
  1823    const FileDescriptor fd_dual =
  1824        ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_dual.family(), param.type, 0));
  1825    ASSERT_THAT(
  1826        bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
  1827        SyscallSucceeds());
  1828  
  1829    // Get the port that we bound.
  1830    socklen_t addrlen = test_addr_dual.addr_len;
  1831    ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
  1832                SyscallSucceeds());
  1833    uint16_t const port =
  1834        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
  1835  
  1836    // Verify that binding the v6 loopback with the same port fails.
  1837    TestAddress const& test_addr_v6 = V6Loopback();
  1838    sockaddr_storage addr_v6 = test_addr_v6.addr;
  1839    ASSERT_NO_ERRNO(SetAddrPort(test_addr_v6.family(), &addr_v6, port));
  1840    const FileDescriptor fd_v6 =
  1841        ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v6.family(), param.type, 0));
  1842    ASSERT_THAT(bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len),
  1843                SyscallFailsWithErrno(EADDRINUSE));
  1844  
  1845    // Verify that binding the v4 loopback on the same port with a v6 socket
  1846    // fails.
  1847    TestAddress const& test_addr_v4_mapped = V4MappedLoopback();
  1848    sockaddr_storage addr_v4_mapped = test_addr_v4_mapped.addr;
  1849    ASSERT_NO_ERRNO(
  1850        SetAddrPort(test_addr_v4_mapped.family(), &addr_v4_mapped, port));
  1851    const FileDescriptor fd_v4_mapped = ASSERT_NO_ERRNO_AND_VALUE(
  1852        Socket(test_addr_v4_mapped.family(), param.type, 0));
  1853    ASSERT_THAT(bind(fd_v4_mapped.get(), AsSockAddr(&addr_v4_mapped),
  1854                     test_addr_v4_mapped.addr_len),
  1855                SyscallFailsWithErrno(EADDRINUSE));
  1856  
  1857    // Verify that binding the v4 loopback on the same port with a v4 socket
  1858    // fails.
  1859    TestAddress const& test_addr_v4 = V4Loopback();
  1860    sockaddr_storage addr_v4 = test_addr_v4.addr;
  1861    ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4.family(), &addr_v4, port));
  1862    const FileDescriptor fd_v4 =
  1863        ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v4.family(), param.type, 0));
  1864    ASSERT_THAT(bind(fd_v4.get(), AsSockAddr(&addr_v4), test_addr_v4.addr_len),
  1865                SyscallFailsWithErrno(EADDRINUSE));
  1866  
  1867    // Verify that binding the v4 any on the same port with a v4 socket
  1868    // fails.
  1869    TestAddress const& test_addr_v4_any = V4Any();
  1870    sockaddr_storage addr_v4_any = test_addr_v4_any.addr;
  1871    ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4_any.family(), &addr_v4_any, port));
  1872    const FileDescriptor fd_v4_any = ASSERT_NO_ERRNO_AND_VALUE(
  1873        Socket(test_addr_v4_any.family(), param.type, 0));
  1874    ASSERT_THAT(bind(fd_v4_any.get(), AsSockAddr(&addr_v4_any),
  1875                     test_addr_v4_any.addr_len),
  1876                SyscallFailsWithErrno(EADDRINUSE));
  1877  }
  1878  
  1879  TEST_P(SocketMultiProtocolInetLoopbackTest,
  1880         DualStackV6AnyReuseAddrDoesNotReserveV4Any) {
  1881    ProtocolTestParam const& param = GetParam();
  1882  
  1883    // Bind the v6 any on a dual stack socket.
  1884    TestAddress const& test_addr_dual = V6Any();
  1885    sockaddr_storage addr_dual = test_addr_dual.addr;
  1886    const FileDescriptor fd_dual =
  1887        ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_dual.family(), param.type, 0));
  1888    ASSERT_THAT(setsockopt(fd_dual.get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1889                           sizeof(kSockOptOn)),
  1890                SyscallSucceeds());
  1891    ASSERT_THAT(
  1892        bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
  1893        SyscallSucceeds());
  1894  
  1895    // Get the port that we bound.
  1896    socklen_t addrlen = test_addr_dual.addr_len;
  1897    ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
  1898                SyscallSucceeds());
  1899    uint16_t const port =
  1900        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
  1901  
  1902    // Verify that binding the v4 any on the same port with a v4 socket succeeds.
  1903    TestAddress const& test_addr_v4_any = V4Any();
  1904    sockaddr_storage addr_v4_any = test_addr_v4_any.addr;
  1905    ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4_any.family(), &addr_v4_any, port));
  1906    const FileDescriptor fd_v4_any = ASSERT_NO_ERRNO_AND_VALUE(
  1907        Socket(test_addr_v4_any.family(), param.type, 0));
  1908    ASSERT_THAT(setsockopt(fd_v4_any.get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1909                           sizeof(kSockOptOn)),
  1910                SyscallSucceeds());
  1911    ASSERT_THAT(bind(fd_v4_any.get(), AsSockAddr(&addr_v4_any),
  1912                     test_addr_v4_any.addr_len),
  1913                SyscallSucceeds());
  1914  }
  1915  
  1916  TEST_P(SocketMultiProtocolInetLoopbackTest,
  1917         DualStackV6AnyReuseAddrListenReservesV4Any) {
  1918    ProtocolTestParam const& param = GetParam();
  1919  
  1920    // Only TCP sockets are supported.
  1921    SKIP_IF((param.type & SOCK_STREAM) == 0);
  1922  
  1923    // Bind the v6 any on a dual stack socket.
  1924    TestAddress const& test_addr_dual = V6Any();
  1925    sockaddr_storage addr_dual = test_addr_dual.addr;
  1926    const FileDescriptor fd_dual =
  1927        ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_dual.family(), param.type, 0));
  1928    ASSERT_THAT(setsockopt(fd_dual.get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1929                           sizeof(kSockOptOn)),
  1930                SyscallSucceeds());
  1931    ASSERT_THAT(
  1932        bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
  1933        SyscallSucceeds());
  1934  
  1935    ASSERT_THAT(listen(fd_dual.get(), 5), SyscallSucceeds());
  1936  
  1937    // Get the port that we bound.
  1938    socklen_t addrlen = test_addr_dual.addr_len;
  1939    ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
  1940                SyscallSucceeds());
  1941    uint16_t const port =
  1942        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
  1943  
  1944    // Verify that binding the v4 any on the same port with a v4 socket succeeds.
  1945    TestAddress const& test_addr_v4_any = V4Any();
  1946    sockaddr_storage addr_v4_any = test_addr_v4_any.addr;
  1947    ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4_any.family(), &addr_v4_any, port));
  1948    const FileDescriptor fd_v4_any = ASSERT_NO_ERRNO_AND_VALUE(
  1949        Socket(test_addr_v4_any.family(), param.type, 0));
  1950    ASSERT_THAT(setsockopt(fd_v4_any.get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1951                           sizeof(kSockOptOn)),
  1952                SyscallSucceeds());
  1953  
  1954    ASSERT_THAT(bind(fd_v4_any.get(), AsSockAddr(&addr_v4_any),
  1955                     test_addr_v4_any.addr_len),
  1956                SyscallFailsWithErrno(EADDRINUSE));
  1957  }
  1958  
  1959  TEST_P(SocketMultiProtocolInetLoopbackTest,
  1960         DualStackV6AnyWithListenReservesEverything) {
  1961    ProtocolTestParam const& param = GetParam();
  1962  
  1963    // Only TCP sockets are supported.
  1964    SKIP_IF((param.type & SOCK_STREAM) == 0);
  1965  
  1966    // Bind the v6 any on a dual stack socket.
  1967    TestAddress const& test_addr_dual = V6Any();
  1968    sockaddr_storage addr_dual = test_addr_dual.addr;
  1969    const FileDescriptor fd_dual =
  1970        ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_dual.family(), param.type, 0));
  1971    ASSERT_THAT(
  1972        bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
  1973        SyscallSucceeds());
  1974  
  1975    ASSERT_THAT(listen(fd_dual.get(), 5), SyscallSucceeds());
  1976  
  1977    // Get the port that we bound.
  1978    socklen_t addrlen = test_addr_dual.addr_len;
  1979    ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
  1980                SyscallSucceeds());
  1981    uint16_t const port =
  1982        ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
  1983  
  1984    // Verify that binding the v6 loopback with the same port fails.
  1985    TestAddress const& test_addr_v6 = V6Loopback();
  1986    sockaddr_storage addr_v6 = test_addr_v6.addr;
  1987    ASSERT_NO_ERRNO(SetAddrPort(test_addr_v6.family(), &addr_v6, port));
  1988    const FileDescriptor fd_v6 =
  1989        ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v6.family(), param.type, 0));
  1990    ASSERT_THAT(bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len),
  1991                SyscallFailsWithErrno(EADDRINUSE));
  1992  
  1993    // Verify that binding the v4 loopback on the same port with a v6 socket
  1994    // fails.
  1995    TestAddress const& test_addr_v4_mapped = V4MappedLoopback();
  1996    sockaddr_storage addr_v4_mapped = test_addr_v4_mapped.addr;
  1997    ASSERT_NO_ERRNO(
  1998        SetAddrPort(test_addr_v4_mapped.family(), &addr_v4_mapped, port));
  1999    const FileDescriptor fd_v4_mapped = ASSERT_NO_ERRNO_AND_VALUE(
  2000        Socket(test_addr_v4_mapped.family(), param.type, 0));
  2001    ASSERT_THAT(bind(fd_v4_mapped.get(), AsSockAddr(&addr_v4_mapped),
  2002                     test_addr_v4_mapped.addr_len),
  2003                SyscallFailsWithErrno(EADDRINUSE));
  2004  
  2005    // Verify that binding the v4 loopback on the same port with a v4 socket
  2006    // fails.
  2007    TestAddress const& test_addr_v4 = V4Loopback();
  2008    sockaddr_storage addr_v4 = test_addr_v4.addr;
  2009    ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4.family(), &addr_v4, port));
  2010    const FileDescriptor fd_v4 =
  2011        ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v4.family(), param.type, 0));
  2012    ASSERT_THAT(bind(fd_v4.get(), AsSockAddr(&addr_v4), test_addr_v4.addr_len),
  2013                SyscallFailsWithErrno(EADDRINUSE));
  2014  
  2015    // Verify that binding the v4 any on the same port with a v4 socket
  2016    // fails.
  2017    TestAddress const& test_addr_v4_any = V4Any();
  2018    sockaddr_storage addr_v4_any = test_addr_v4_any.addr;
  2019    ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4_any.family(), &addr_v4_any, port));
  2020    const FileDescriptor fd_v4_any = ASSERT_NO_ERRNO_AND_VALUE(
  2021        Socket(test_addr_v4_any.family(), param.type, 0));
  2022    ASSERT_THAT(bind(fd_v4_any.get(), AsSockAddr(&addr_v4_any),
  2023                     test_addr_v4_any.addr_len),
  2024                SyscallFailsWithErrno(EADDRINUSE));
  2025  }
  2026  
  2027  TEST_P(SocketMultiProtocolInetLoopbackTest, V6OnlyV6AnyReservesV6) {
  2028    ProtocolTestParam const& param = GetParam();
  2029  
  2030    for (int i = 0; true; i++) {
  2031      // Bind the v6 any on a v6-only socket.
  2032      TestAddress const& test_addr_dual = V6Any();
  2033      sockaddr_storage addr_dual = test_addr_dual.addr;
  2034      const FileDescriptor fd_dual = ASSERT_NO_ERRNO_AND_VALUE(
  2035          Socket(test_addr_dual.family(), param.type, 0));
  2036      EXPECT_THAT(setsockopt(fd_dual.get(), IPPROTO_IPV6, IPV6_V6ONLY,
  2037                             &kSockOptOn, sizeof(kSockOptOn)),
  2038                  SyscallSucceeds());
  2039      ASSERT_THAT(
  2040          bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
  2041          SyscallSucceeds());
  2042  
  2043      // Get the port that we bound.
  2044      socklen_t addrlen = test_addr_dual.addr_len;
  2045      ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
  2046                  SyscallSucceeds());
  2047      uint16_t const port =
  2048          ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
  2049  
  2050      // Verify that binding the v6 loopback with the same port fails.
  2051      TestAddress const& test_addr_v6 = V6Loopback();
  2052      sockaddr_storage addr_v6 = test_addr_v6.addr;
  2053      ASSERT_NO_ERRNO(SetAddrPort(test_addr_v6.family(), &addr_v6, port));
  2054      const FileDescriptor fd_v6 =
  2055          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v6.family(), param.type, 0));
  2056      ASSERT_THAT(bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len),
  2057                  SyscallFailsWithErrno(EADDRINUSE));
  2058  
  2059      // Verify that we can still bind the v4 loopback on the same port.
  2060      TestAddress const& test_addr_v4_mapped = V4MappedLoopback();
  2061      sockaddr_storage addr_v4_mapped = test_addr_v4_mapped.addr;
  2062      ASSERT_NO_ERRNO(
  2063          SetAddrPort(test_addr_v4_mapped.family(), &addr_v4_mapped, port));
  2064      const FileDescriptor fd_v4_mapped = ASSERT_NO_ERRNO_AND_VALUE(
  2065          Socket(test_addr_v4_mapped.family(), param.type, 0));
  2066      int ret = bind(fd_v4_mapped.get(), AsSockAddr(&addr_v4_mapped),
  2067                     test_addr_v4_mapped.addr_len);
  2068      if (ret == -1 && errno == EADDRINUSE) {
  2069        // Port may have been in use.
  2070        ASSERT_LT(i, 100);  // Give up after 100 tries.
  2071        continue;
  2072      }
  2073      ASSERT_THAT(ret, SyscallSucceeds());
  2074  
  2075      // No need to try again.
  2076      break;
  2077    }
  2078  }
  2079  
  2080  TEST_P(SocketMultiProtocolInetLoopbackTest, V6EphemeralPortReserved) {
  2081    ProtocolTestParam const& param = GetParam();
  2082  
  2083    for (int i = 0; true; i++) {
  2084      // Bind the v6 loopback on a dual stack socket.
  2085      TestAddress const& test_addr = V6Loopback();
  2086      sockaddr_storage bound_addr = test_addr.addr;
  2087      const FileDescriptor bound_fd =
  2088          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2089      ASSERT_THAT(
  2090          bind(bound_fd.get(), AsSockAddr(&bound_addr), test_addr.addr_len),
  2091          SyscallSucceeds());
  2092  
  2093      // Listen iff TCP.
  2094      if (param.type == SOCK_STREAM) {
  2095        ASSERT_THAT(listen(bound_fd.get(), SOMAXCONN), SyscallSucceeds());
  2096      }
  2097  
  2098      // Get the port that we bound.
  2099      socklen_t bound_addr_len = test_addr.addr_len;
  2100      ASSERT_THAT(
  2101          getsockname(bound_fd.get(), AsSockAddr(&bound_addr), &bound_addr_len),
  2102          SyscallSucceeds());
  2103  
  2104      // Connect to bind an ephemeral port.
  2105      const FileDescriptor connected_fd =
  2106          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2107      ASSERT_THAT(RetryEINTR(connect)(connected_fd.get(), AsSockAddr(&bound_addr),
  2108                                      bound_addr_len),
  2109                  SyscallSucceeds());
  2110  
  2111      // Get the ephemeral port.
  2112      sockaddr_storage connected_addr = {};
  2113      socklen_t connected_addr_len = sizeof(connected_addr);
  2114      ASSERT_THAT(getsockname(connected_fd.get(), AsSockAddr(&connected_addr),
  2115                              &connected_addr_len),
  2116                  SyscallSucceeds());
  2117      uint16_t const ephemeral_port =
  2118          ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr.family(), connected_addr));
  2119  
  2120      // Verify that we actually got an ephemeral port.
  2121      ASSERT_NE(ephemeral_port, 0);
  2122  
  2123      // Verify that the ephemeral port is reserved.
  2124      const FileDescriptor checking_fd =
  2125          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2126      EXPECT_THAT(bind(checking_fd.get(), AsSockAddr(&connected_addr),
  2127                       connected_addr_len),
  2128                  SyscallFailsWithErrno(EADDRINUSE));
  2129  
  2130      // Verify that binding the v6 loopback with the same port fails.
  2131      TestAddress const& test_addr_v6 = V6Loopback();
  2132      sockaddr_storage addr_v6 = test_addr_v6.addr;
  2133      ASSERT_NO_ERRNO(
  2134          SetAddrPort(test_addr_v6.family(), &addr_v6, ephemeral_port));
  2135      const FileDescriptor fd_v6 =
  2136          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v6.family(), param.type, 0));
  2137      ASSERT_THAT(bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len),
  2138                  SyscallFailsWithErrno(EADDRINUSE));
  2139  
  2140      // Verify that we can still bind the v4 loopback on the same port.
  2141      TestAddress const& test_addr_v4_mapped = V4MappedLoopback();
  2142      sockaddr_storage addr_v4_mapped = test_addr_v4_mapped.addr;
  2143      ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4_mapped.family(), &addr_v4_mapped,
  2144                                  ephemeral_port));
  2145      const FileDescriptor fd_v4_mapped = ASSERT_NO_ERRNO_AND_VALUE(
  2146          Socket(test_addr_v4_mapped.family(), param.type, 0));
  2147      int ret = bind(fd_v4_mapped.get(), AsSockAddr(&addr_v4_mapped),
  2148                     test_addr_v4_mapped.addr_len);
  2149      if (ret == -1 && errno == EADDRINUSE) {
  2150        // Port may have been in use.
  2151        ASSERT_LT(i, 100);  // Give up after 100 tries.
  2152        continue;
  2153      }
  2154      EXPECT_THAT(ret, SyscallSucceeds());
  2155  
  2156      // No need to try again.
  2157      break;
  2158    }
  2159  }
  2160  
  2161  TEST_P(SocketMultiProtocolInetLoopbackTest, V4MappedEphemeralPortReserved) {
  2162    ProtocolTestParam const& param = GetParam();
  2163  
  2164    for (int i = 0; true; i++) {
  2165      // Bind the v4 loopback on a dual stack socket.
  2166      TestAddress const& test_addr = V4MappedLoopback();
  2167      sockaddr_storage bound_addr = test_addr.addr;
  2168      const FileDescriptor bound_fd =
  2169          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2170      ASSERT_THAT(
  2171          bind(bound_fd.get(), AsSockAddr(&bound_addr), test_addr.addr_len),
  2172          SyscallSucceeds());
  2173  
  2174      // Listen iff TCP.
  2175      if (param.type == SOCK_STREAM) {
  2176        ASSERT_THAT(listen(bound_fd.get(), SOMAXCONN), SyscallSucceeds());
  2177      }
  2178  
  2179      // Get the port that we bound.
  2180      socklen_t bound_addr_len = test_addr.addr_len;
  2181      ASSERT_THAT(
  2182          getsockname(bound_fd.get(), AsSockAddr(&bound_addr), &bound_addr_len),
  2183          SyscallSucceeds());
  2184  
  2185      // Connect to bind an ephemeral port.
  2186      const FileDescriptor connected_fd =
  2187          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2188      ASSERT_THAT(RetryEINTR(connect)(connected_fd.get(), AsSockAddr(&bound_addr),
  2189                                      bound_addr_len),
  2190                  SyscallSucceeds());
  2191  
  2192      // Get the ephemeral port.
  2193      sockaddr_storage connected_addr = {};
  2194      socklen_t connected_addr_len = sizeof(connected_addr);
  2195      ASSERT_THAT(getsockname(connected_fd.get(), AsSockAddr(&connected_addr),
  2196                              &connected_addr_len),
  2197                  SyscallSucceeds());
  2198      uint16_t const ephemeral_port =
  2199          ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr.family(), connected_addr));
  2200  
  2201      // Verify that we actually got an ephemeral port.
  2202      ASSERT_NE(ephemeral_port, 0);
  2203  
  2204      // Verify that the ephemeral port is reserved.
  2205      const FileDescriptor checking_fd =
  2206          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2207      EXPECT_THAT(bind(checking_fd.get(), AsSockAddr(&connected_addr),
  2208                       connected_addr_len),
  2209                  SyscallFailsWithErrno(EADDRINUSE));
  2210  
  2211      // Verify that binding the v4 loopback on the same port with a v4 socket
  2212      // fails.
  2213      TestAddress const& test_addr_v4 = V4Loopback();
  2214      sockaddr_storage addr_v4 = test_addr_v4.addr;
  2215      ASSERT_NO_ERRNO(
  2216          SetAddrPort(test_addr_v4.family(), &addr_v4, ephemeral_port));
  2217      const FileDescriptor fd_v4 =
  2218          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v4.family(), param.type, 0));
  2219      EXPECT_THAT(bind(fd_v4.get(), AsSockAddr(&addr_v4), test_addr_v4.addr_len),
  2220                  SyscallFailsWithErrno(EADDRINUSE));
  2221  
  2222      // Verify that binding the v6 any on the same port with a dual-stack socket
  2223      // fails.
  2224      TestAddress const& test_addr_v6_any = V6Any();
  2225      sockaddr_storage addr_v6_any = test_addr_v6_any.addr;
  2226      ASSERT_NO_ERRNO(
  2227          SetAddrPort(test_addr_v6_any.family(), &addr_v6_any, ephemeral_port));
  2228      const FileDescriptor fd_v6_any = ASSERT_NO_ERRNO_AND_VALUE(
  2229          Socket(test_addr_v6_any.family(), param.type, 0));
  2230      ASSERT_THAT(bind(fd_v6_any.get(), AsSockAddr(&addr_v6_any),
  2231                       test_addr_v6_any.addr_len),
  2232                  SyscallFailsWithErrno(EADDRINUSE));
  2233  
  2234      // For some reason, binding the TCP v6-only any is flaky on Linux. Maybe we
  2235      // tend to run out of ephemeral ports? Regardless, binding the v6 loopback
  2236      // seems pretty reliable. Only try to bind the v6-only any on UDP and
  2237      // gVisor.
  2238  
  2239      int ret = -1;
  2240  
  2241      if (!IsRunningOnGvisor() && param.type == SOCK_STREAM) {
  2242        // Verify that we can still bind the v6 loopback on the same port.
  2243        TestAddress const& test_addr_v6 = V6Loopback();
  2244        sockaddr_storage addr_v6 = test_addr_v6.addr;
  2245        ASSERT_NO_ERRNO(
  2246            SetAddrPort(test_addr_v6.family(), &addr_v6, ephemeral_port));
  2247        const FileDescriptor fd_v6 = ASSERT_NO_ERRNO_AND_VALUE(
  2248            Socket(test_addr_v6.family(), param.type, 0));
  2249        ret = bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len);
  2250      } else {
  2251        // Verify that we can still bind the v6 any on the same port with a
  2252        // v6-only socket.
  2253        const FileDescriptor fd_v6_only_any = ASSERT_NO_ERRNO_AND_VALUE(
  2254            Socket(test_addr_v6_any.family(), param.type, 0));
  2255        EXPECT_THAT(setsockopt(fd_v6_only_any.get(), IPPROTO_IPV6, IPV6_V6ONLY,
  2256                               &kSockOptOn, sizeof(kSockOptOn)),
  2257                    SyscallSucceeds());
  2258        ret = bind(fd_v6_only_any.get(), AsSockAddr(&addr_v6_any),
  2259                   test_addr_v6_any.addr_len);
  2260      }
  2261  
  2262      if (ret == -1 && errno == EADDRINUSE) {
  2263        // Port may have been in use.
  2264        ASSERT_LT(i, 100);  // Give up after 100 tries.
  2265        continue;
  2266      }
  2267      EXPECT_THAT(ret, SyscallSucceeds());
  2268  
  2269      // No need to try again.
  2270      break;
  2271    }
  2272  }
  2273  
  2274  TEST_P(SocketMultiProtocolInetLoopbackTest, V4EphemeralPortReserved) {
  2275    ProtocolTestParam const& param = GetParam();
  2276  
  2277    for (int i = 0; true; i++) {
  2278      // Bind the v4 loopback on a v4 socket.
  2279      TestAddress const& test_addr = V4Loopback();
  2280      sockaddr_storage bound_addr = test_addr.addr;
  2281      const FileDescriptor bound_fd =
  2282          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2283      ASSERT_THAT(
  2284          bind(bound_fd.get(), AsSockAddr(&bound_addr), test_addr.addr_len),
  2285          SyscallSucceeds());
  2286  
  2287      // Listen iff TCP.
  2288      if (param.type == SOCK_STREAM) {
  2289        ASSERT_THAT(listen(bound_fd.get(), SOMAXCONN), SyscallSucceeds());
  2290      }
  2291  
  2292      // Get the port that we bound.
  2293      socklen_t bound_addr_len = test_addr.addr_len;
  2294      ASSERT_THAT(
  2295          getsockname(bound_fd.get(), AsSockAddr(&bound_addr), &bound_addr_len),
  2296          SyscallSucceeds());
  2297  
  2298      // Connect to bind an ephemeral port.
  2299      const FileDescriptor connected_fd =
  2300          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2301      ASSERT_THAT(RetryEINTR(connect)(connected_fd.get(), AsSockAddr(&bound_addr),
  2302                                      bound_addr_len),
  2303                  SyscallSucceeds());
  2304  
  2305      // Get the ephemeral port.
  2306      sockaddr_storage connected_addr = {};
  2307      socklen_t connected_addr_len = sizeof(connected_addr);
  2308      ASSERT_THAT(getsockname(connected_fd.get(), AsSockAddr(&connected_addr),
  2309                              &connected_addr_len),
  2310                  SyscallSucceeds());
  2311      uint16_t const ephemeral_port =
  2312          ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr.family(), connected_addr));
  2313  
  2314      // Verify that we actually got an ephemeral port.
  2315      ASSERT_NE(ephemeral_port, 0);
  2316  
  2317      // Verify that the ephemeral port is reserved.
  2318      const FileDescriptor checking_fd =
  2319          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2320      EXPECT_THAT(bind(checking_fd.get(), AsSockAddr(&connected_addr),
  2321                       connected_addr_len),
  2322                  SyscallFailsWithErrno(EADDRINUSE));
  2323  
  2324      // Verify that binding the v4 loopback on the same port with a v6 socket
  2325      // fails.
  2326      TestAddress const& test_addr_v4_mapped = V4MappedLoopback();
  2327      sockaddr_storage addr_v4_mapped = test_addr_v4_mapped.addr;
  2328      ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4_mapped.family(), &addr_v4_mapped,
  2329                                  ephemeral_port));
  2330      const FileDescriptor fd_v4_mapped = ASSERT_NO_ERRNO_AND_VALUE(
  2331          Socket(test_addr_v4_mapped.family(), param.type, 0));
  2332      EXPECT_THAT(bind(fd_v4_mapped.get(), AsSockAddr(&addr_v4_mapped),
  2333                       test_addr_v4_mapped.addr_len),
  2334                  SyscallFailsWithErrno(EADDRINUSE));
  2335  
  2336      // Verify that binding the v6 any on the same port with a dual-stack socket
  2337      // fails.
  2338      TestAddress const& test_addr_v6_any = V6Any();
  2339      sockaddr_storage addr_v6_any = test_addr_v6_any.addr;
  2340      ASSERT_NO_ERRNO(
  2341          SetAddrPort(test_addr_v6_any.family(), &addr_v6_any, ephemeral_port));
  2342      const FileDescriptor fd_v6_any = ASSERT_NO_ERRNO_AND_VALUE(
  2343          Socket(test_addr_v6_any.family(), param.type, 0));
  2344      ASSERT_THAT(bind(fd_v6_any.get(), AsSockAddr(&addr_v6_any),
  2345                       test_addr_v6_any.addr_len),
  2346                  SyscallFailsWithErrno(EADDRINUSE));
  2347  
  2348      // For some reason, binding the TCP v6-only any is flaky on Linux. Maybe we
  2349      // tend to run out of ephemeral ports? Regardless, binding the v6 loopback
  2350      // seems pretty reliable. Only try to bind the v6-only any on UDP and
  2351      // gVisor.
  2352  
  2353      int ret = -1;
  2354  
  2355      if (!IsRunningOnGvisor() && param.type == SOCK_STREAM) {
  2356        // Verify that we can still bind the v6 loopback on the same port.
  2357        TestAddress const& test_addr_v6 = V6Loopback();
  2358        sockaddr_storage addr_v6 = test_addr_v6.addr;
  2359        ASSERT_NO_ERRNO(
  2360            SetAddrPort(test_addr_v6.family(), &addr_v6, ephemeral_port));
  2361        const FileDescriptor fd_v6 = ASSERT_NO_ERRNO_AND_VALUE(
  2362            Socket(test_addr_v6.family(), param.type, 0));
  2363        ret = bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len);
  2364      } else {
  2365        // Verify that we can still bind the v6 any on the same port with a
  2366        // v6-only socket.
  2367        const FileDescriptor fd_v6_only_any = ASSERT_NO_ERRNO_AND_VALUE(
  2368            Socket(test_addr_v6_any.family(), param.type, 0));
  2369        EXPECT_THAT(setsockopt(fd_v6_only_any.get(), IPPROTO_IPV6, IPV6_V6ONLY,
  2370                               &kSockOptOn, sizeof(kSockOptOn)),
  2371                    SyscallSucceeds());
  2372        ret = bind(fd_v6_only_any.get(), AsSockAddr(&addr_v6_any),
  2373                   test_addr_v6_any.addr_len);
  2374      }
  2375  
  2376      if (ret == -1 && errno == EADDRINUSE) {
  2377        // Port may have been in use.
  2378        ASSERT_LT(i, 100);  // Give up after 100 tries.
  2379        continue;
  2380      }
  2381      EXPECT_THAT(ret, SyscallSucceeds());
  2382  
  2383      // No need to try again.
  2384      break;
  2385    }
  2386  }
  2387  
  2388  TEST_P(SocketMultiProtocolInetLoopbackTest,
  2389         MultipleBindsAllowedNoListeningReuseAddr) {
  2390    ProtocolTestParam const& param = GetParam();
  2391    // UDP sockets are allowed to bind/listen on the port w/ SO_REUSEADDR, for TCP
  2392    // this is only permitted if there is no other listening socket.
  2393    SKIP_IF(param.type != SOCK_STREAM);
  2394    // Bind the v4 loopback on a v4 socket.
  2395    const TestAddress& test_addr = V4Loopback();
  2396    sockaddr_storage bound_addr = test_addr.addr;
  2397    FileDescriptor bound_fd =
  2398        ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2399  
  2400    ASSERT_THAT(setsockopt(bound_fd.get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  2401                           sizeof(kSockOptOn)),
  2402                SyscallSucceeds());
  2403    ASSERT_THAT(bind(bound_fd.get(), AsSockAddr(&bound_addr), test_addr.addr_len),
  2404                SyscallSucceeds());
  2405    // Get the port that we bound.
  2406    socklen_t bound_addr_len = test_addr.addr_len;
  2407    ASSERT_THAT(
  2408        getsockname(bound_fd.get(), AsSockAddr(&bound_addr), &bound_addr_len),
  2409        SyscallSucceeds());
  2410  
  2411    // Now create a socket and bind it to the same port, this should
  2412    // succeed since there is no listening socket for the same port.
  2413    FileDescriptor second_fd =
  2414        ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2415  
  2416    ASSERT_THAT(setsockopt(second_fd.get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  2417                           sizeof(kSockOptOn)),
  2418                SyscallSucceeds());
  2419    ASSERT_THAT(
  2420        bind(second_fd.get(), AsSockAddr(&bound_addr), test_addr.addr_len),
  2421        SyscallSucceeds());
  2422  }
  2423  
  2424  TEST_P(SocketMultiProtocolInetLoopbackTest, PortReuseTwoSockets) {
  2425    ProtocolTestParam const& param = GetParam();
  2426    TestAddress const& test_addr = V4Loopback();
  2427    sockaddr_storage addr = test_addr.addr;
  2428  
  2429    for (int i = 0; i < 2; i++) {
  2430      const int portreuse1 = i % 2;
  2431      auto s1 =
  2432          ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2433      int fd1 = s1.get();
  2434      socklen_t addrlen = test_addr.addr_len;
  2435  
  2436      EXPECT_THAT(
  2437          setsockopt(fd1, SOL_SOCKET, SO_REUSEPORT, &portreuse1, sizeof(int)),
  2438          SyscallSucceeds());
  2439  
  2440      ASSERT_THAT(bind(fd1, AsSockAddr(&addr), addrlen), SyscallSucceeds());
  2441  
  2442      ASSERT_THAT(getsockname(fd1, AsSockAddr(&addr), &addrlen),
  2443                  SyscallSucceeds());
  2444      if (param.type == SOCK_STREAM) {
  2445        ASSERT_THAT(listen(fd1, 1), SyscallSucceeds());
  2446      }
  2447  
  2448      // j is less than 4 to check that the port reuse logic works correctly after
  2449      // closing bound sockets.
  2450      for (int j = 0; j < 4; j++) {
  2451        const int portreuse2 = j % 2;
  2452        auto s2 =
  2453            ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2454        int fd2 = s2.get();
  2455  
  2456        EXPECT_THAT(
  2457            setsockopt(fd2, SOL_SOCKET, SO_REUSEPORT, &portreuse2, sizeof(int)),
  2458            SyscallSucceeds());
  2459  
  2460        std::cout << portreuse1 << " " << portreuse2 << std::endl;
  2461        int ret = bind(fd2, AsSockAddr(&addr), addrlen);
  2462  
  2463        // Verify that two sockets can be bound to the same port only if
  2464        // SO_REUSEPORT is set for both of them.
  2465        if (!portreuse1 || !portreuse2) {
  2466          ASSERT_THAT(ret, SyscallFailsWithErrno(EADDRINUSE));
  2467        } else {
  2468          ASSERT_THAT(ret, SyscallSucceeds());
  2469        }
  2470      }
  2471    }
  2472  }
  2473  
  2474  // Check that when a socket was bound to an address with REUSEPORT and then
  2475  // closed, we can bind a different socket to the same address without needing
  2476  // REUSEPORT.
  2477  TEST_P(SocketMultiProtocolInetLoopbackTest, NoReusePortFollowingReusePort) {
  2478    ProtocolTestParam const& param = GetParam();
  2479    TestAddress const& test_addr = V4Loopback();
  2480    sockaddr_storage addr = test_addr.addr;
  2481  
  2482    auto s = ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2483    int fd = s.get();
  2484    socklen_t addrlen = test_addr.addr_len;
  2485    int portreuse = 1;
  2486    ASSERT_THAT(
  2487        setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &portreuse, sizeof(portreuse)),
  2488        SyscallSucceeds());
  2489    ASSERT_THAT(bind(fd, AsSockAddr(&addr), addrlen), SyscallSucceeds());
  2490    ASSERT_THAT(getsockname(fd, AsSockAddr(&addr), &addrlen), SyscallSucceeds());
  2491    ASSERT_EQ(addrlen, test_addr.addr_len);
  2492  
  2493    s.reset();
  2494  
  2495    // Open a new socket and bind to the same address, but w/o REUSEPORT.
  2496    s = ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
  2497    fd = s.get();
  2498    portreuse = 0;
  2499    ASSERT_THAT(
  2500        setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &portreuse, sizeof(portreuse)),
  2501        SyscallSucceeds());
  2502    ASSERT_THAT(bind(fd, AsSockAddr(&addr), addrlen), SyscallSucceeds());
  2503  }
  2504  
  2505  INSTANTIATE_TEST_SUITE_P(AllFamilies, SocketMultiProtocolInetLoopbackTest,
  2506                           ProtocolTestValues(), DescribeProtocolTestParam);
  2507  
  2508  }  // namespace
  2509  
  2510  // Check that loopback receives connections from any address in the range:
  2511  // 127.0.0.1 to 127.254.255.255. This behavior is exclusive to IPv4.
  2512  TEST_F(SocketInetLoopbackTest, LoopbackAddressRangeConnect) {
  2513    TestAddress const& listener = V4Any();
  2514  
  2515    in_addr_t addresses[] = {
  2516        INADDR_LOOPBACK,
  2517        INADDR_LOOPBACK + 1,    // 127.0.0.2
  2518        (in_addr_t)0x7f000101,  // 127.0.1.1
  2519        (in_addr_t)0x7f010101,  // 127.1.1.1
  2520        (in_addr_t)0x7ffeffff,  // 127.254.255.255
  2521    };
  2522    for (const auto& address : addresses) {
  2523      TestAddress connector("V4Loopback");
  2524      connector.addr.ss_family = AF_INET;
  2525      connector.addr_len = sizeof(sockaddr_in);
  2526      reinterpret_cast<sockaddr_in*>(&connector.addr)->sin_addr.s_addr =
  2527          htonl(address);
  2528  
  2529      tcpSimpleConnectTest(listener, connector, true);
  2530    }
  2531  }
  2532  
  2533  }  // namespace testing
  2534  }  // namespace gvisor