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