gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/test/syscalls/linux/udp_socket.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 <fcntl.h>
    17  #include <netinet/icmp6.h>
    18  #include <netinet/ip_icmp.h>
    19  
    20  #include <cerrno>
    21  #include <ctime>
    22  #include <utility>
    23  #include <vector>
    24  
    25  #ifdef __linux__
    26  #include <linux/errqueue.h>
    27  #include <linux/filter.h>
    28  #endif  // __linux__
    29  #include <netinet/in.h>
    30  #include <poll.h>
    31  #include <sys/ioctl.h>
    32  #include <sys/socket.h>
    33  #include <sys/types.h>
    34  
    35  #include "absl/strings/str_format.h"
    36  #ifndef SIOCGSTAMP
    37  #include <linux/sockios.h>
    38  #endif
    39  
    40  #include "gtest/gtest.h"
    41  #include "absl/base/macros.h"
    42  #include "absl/time/clock.h"
    43  #include "absl/time/time.h"
    44  #include "test/syscalls/linux/ip_socket_test_util.h"
    45  #include "test/syscalls/linux/unix_domain_socket_test_util.h"
    46  #include "test/util/file_descriptor.h"
    47  #include "test/util/posix_error.h"
    48  #include "test/util/socket_util.h"
    49  #include "test/util/test_util.h"
    50  #include "test/util/thread_util.h"
    51  
    52  namespace gvisor {
    53  namespace testing {
    54  
    55  namespace {
    56  
    57  int IcmpTimeoutMillis() {
    58    // Fuchsia's CI infra is susceptible to timing jumps. Set a negative timeout
    59    // so that poll will block indefinitely, which effectively delegates the
    60    // timeout to infra.
    61    return GvisorPlatform() == Platform::kFuchsia ? -1 : 1000;
    62  }
    63  
    64  // Fixture for tests parameterized by the address family to use (AF_INET and
    65  // AF_INET6) when creating sockets.
    66  class UdpSocketTest : public ::testing::TestWithParam<int> {
    67   protected:
    68    // Creates two sockets that will be used by test cases.
    69    void SetUp() override;
    70  
    71    // Binds the socket bind_ to the loopback and updates bind_addr_.
    72    PosixError BindLoopback();
    73  
    74    // Binds the socket bind_ to Any and updates bind_addr_.
    75    PosixError BindAny();
    76  
    77    // Binds given socket to address addr and updates.
    78    PosixError BindSocket(int socket, struct sockaddr* addr);
    79  
    80    // Return initialized Any address to port 0.
    81    struct sockaddr_storage InetAnyAddr();
    82  
    83    // Return initialized Loopback address to port 0.
    84    struct sockaddr_storage InetLoopbackAddr();
    85  
    86    // Disconnects socket sockfd.
    87    void Disconnect(int sockfd);
    88  
    89    // Socket used by Bind methods
    90    FileDescriptor bind_;
    91  
    92    // Second socket used for tests.
    93    FileDescriptor sock_;
    94  
    95    // Address for bind_ socket.
    96    struct sockaddr* bind_addr_;
    97  
    98    // Initialized to the length based on GetParam().
    99    socklen_t addrlen_;
   100  
   101    // Storage for bind_addr_.
   102    struct sockaddr_storage bind_addr_storage_;
   103  
   104   private:
   105    // Helper to initialize addrlen_ for the test case.
   106    socklen_t GetAddrLength();
   107  };
   108  
   109  // Blocks until POLLIN is signaled on fd.
   110  void BlockUntilPollin(int fd) {
   111    constexpr int kInfiniteTimeout = -1;
   112    pollfd pfd = {
   113        .fd = fd,
   114        .events = POLLIN,
   115    };
   116    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, kInfiniteTimeout),
   117                SyscallSucceedsWithValue(1));
   118    ASSERT_EQ(pfd.revents, POLLIN);
   119  }
   120  
   121  // Gets a pointer to the port component of the given address.
   122  uint16_t* Port(struct sockaddr_storage* addr) {
   123    switch (addr->ss_family) {
   124      case AF_INET: {
   125        auto sin = reinterpret_cast<struct sockaddr_in*>(addr);
   126        return &sin->sin_port;
   127      }
   128      case AF_INET6: {
   129        auto sin6 = reinterpret_cast<struct sockaddr_in6*>(addr);
   130        return &sin6->sin6_port;
   131      }
   132    }
   133  
   134    return nullptr;
   135  }
   136  
   137  // Sets addr port to "port".
   138  void SetPort(struct sockaddr_storage* addr, uint16_t port) {
   139    switch (addr->ss_family) {
   140      case AF_INET: {
   141        auto sin = reinterpret_cast<struct sockaddr_in*>(addr);
   142        sin->sin_port = port;
   143        break;
   144      }
   145      case AF_INET6: {
   146        auto sin6 = reinterpret_cast<struct sockaddr_in6*>(addr);
   147        sin6->sin6_port = port;
   148        break;
   149      }
   150    }
   151  }
   152  
   153  void UdpSocketTest::SetUp() {
   154    addrlen_ = GetAddrLength();
   155  
   156    bind_ =
   157        ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_DGRAM, IPPROTO_UDP));
   158    memset(&bind_addr_storage_, 0, sizeof(bind_addr_storage_));
   159    bind_addr_ = AsSockAddr(&bind_addr_storage_);
   160  
   161    sock_ =
   162        ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_DGRAM, IPPROTO_UDP));
   163  }
   164  
   165  PosixError UdpSocketTest::BindLoopback() {
   166    bind_addr_storage_ = InetLoopbackAddr();
   167    struct sockaddr* bind_addr_ = AsSockAddr(&bind_addr_storage_);
   168    return BindSocket(bind_.get(), bind_addr_);
   169  }
   170  
   171  PosixError UdpSocketTest::BindAny() {
   172    bind_addr_storage_ = InetAnyAddr();
   173    struct sockaddr* bind_addr_ = AsSockAddr(&bind_addr_storage_);
   174    return BindSocket(bind_.get(), bind_addr_);
   175  }
   176  
   177  PosixError UdpSocketTest::BindSocket(int socket, struct sockaddr* addr) {
   178    socklen_t len = sizeof(bind_addr_storage_);
   179  
   180    // Bind, then check that we get the right address.
   181    RETURN_ERROR_IF_SYSCALL_FAIL(bind(socket, addr, addrlen_));
   182  
   183    RETURN_ERROR_IF_SYSCALL_FAIL(getsockname(socket, addr, &len));
   184  
   185    if (addrlen_ != len) {
   186      return PosixError(
   187          EINVAL,
   188          absl::StrFormat("getsockname len: %u expected: %u", len, addrlen_));
   189    }
   190    return PosixError(0);
   191  }
   192  
   193  socklen_t UdpSocketTest::GetAddrLength() {
   194    struct sockaddr_storage addr;
   195    if (GetParam() == AF_INET) {
   196      auto sin = reinterpret_cast<struct sockaddr_in*>(&addr);
   197      return sizeof(*sin);
   198    }
   199  
   200    auto sin6 = reinterpret_cast<struct sockaddr_in6*>(&addr);
   201    return sizeof(*sin6);
   202  }
   203  
   204  sockaddr_storage UdpSocketTest::InetAnyAddr() {
   205    struct sockaddr_storage addr;
   206    memset(&addr, 0, sizeof(addr));
   207    AsSockAddr(&addr)->sa_family = GetParam();
   208  
   209    if (GetParam() == AF_INET) {
   210      auto sin = reinterpret_cast<struct sockaddr_in*>(&addr);
   211      sin->sin_addr.s_addr = htonl(INADDR_ANY);
   212      sin->sin_port = htons(0);
   213      return addr;
   214    }
   215  
   216    auto sin6 = reinterpret_cast<struct sockaddr_in6*>(&addr);
   217    sin6->sin6_addr = IN6ADDR_ANY_INIT;
   218    sin6->sin6_port = htons(0);
   219    return addr;
   220  }
   221  
   222  sockaddr_storage UdpSocketTest::InetLoopbackAddr() {
   223    return gvisor::testing::InetLoopbackAddr(GetParam());
   224  }
   225  
   226  void UdpSocketTest::Disconnect(int sockfd) {
   227    sockaddr_storage addr_storage = InetAnyAddr();
   228    sockaddr* addr = AsSockAddr(&addr_storage);
   229    socklen_t addrlen = sizeof(addr_storage);
   230  
   231    addr->sa_family = AF_UNSPEC;
   232    ASSERT_THAT(connect(sockfd, addr, addrlen), SyscallSucceeds());
   233  
   234    // Check that after disconnect the socket is bound to the ANY address.
   235    EXPECT_THAT(getsockname(sockfd, addr, &addrlen), SyscallSucceeds());
   236    if (GetParam() == AF_INET) {
   237      auto addr_out = reinterpret_cast<struct sockaddr_in*>(addr);
   238      EXPECT_EQ(addrlen, sizeof(*addr_out));
   239      EXPECT_EQ(addr_out->sin_addr.s_addr, htonl(INADDR_ANY));
   240    } else {
   241      auto addr_out = reinterpret_cast<struct sockaddr_in6*>(addr);
   242      EXPECT_EQ(addrlen, sizeof(*addr_out));
   243      struct in6_addr loopback = IN6ADDR_ANY_INIT;
   244  
   245      EXPECT_EQ(memcmp(&addr_out->sin6_addr, &loopback, sizeof(in6_addr)), 0);
   246    }
   247  }
   248  
   249  TEST_P(UdpSocketTest, Creation) {
   250    FileDescriptor sock =
   251        ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_DGRAM, IPPROTO_UDP));
   252    EXPECT_THAT(close(sock.release()), SyscallSucceeds());
   253  
   254    sock = ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_DGRAM, 0));
   255    EXPECT_THAT(close(sock.release()), SyscallSucceeds());
   256  
   257    ASSERT_THAT(socket(GetParam(), SOCK_STREAM, IPPROTO_UDP), SyscallFails());
   258  }
   259  
   260  TEST_P(UdpSocketTest, Getsockname) {
   261    // Check that we're not bound.
   262    struct sockaddr_storage addr;
   263    socklen_t addrlen = sizeof(addr);
   264    EXPECT_THAT(getsockname(bind_.get(), AsSockAddr(&addr), &addrlen),
   265                SyscallSucceeds());
   266    EXPECT_EQ(addrlen, addrlen_);
   267    struct sockaddr_storage any = InetAnyAddr();
   268    EXPECT_EQ(memcmp(&addr, AsSockAddr(&any), addrlen_), 0);
   269  
   270    ASSERT_NO_ERRNO(BindLoopback());
   271  
   272    EXPECT_THAT(getsockname(bind_.get(), AsSockAddr(&addr), &addrlen),
   273                SyscallSucceeds());
   274  
   275    EXPECT_EQ(addrlen, addrlen_);
   276    EXPECT_EQ(memcmp(&addr, bind_addr_, addrlen_), 0);
   277  }
   278  
   279  TEST_P(UdpSocketTest, Getpeername) {
   280    ASSERT_NO_ERRNO(BindLoopback());
   281  
   282    // Check that we're not connected.
   283    struct sockaddr_storage addr;
   284    socklen_t addrlen = sizeof(addr);
   285    EXPECT_THAT(getpeername(sock_.get(), AsSockAddr(&addr), &addrlen),
   286                SyscallFailsWithErrno(ENOTCONN));
   287  
   288    // Connect, then check that we get the right address.
   289    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   290  
   291    addrlen = sizeof(addr);
   292    EXPECT_THAT(getpeername(sock_.get(), AsSockAddr(&addr), &addrlen),
   293                SyscallSucceeds());
   294    EXPECT_EQ(addrlen, addrlen_);
   295    EXPECT_EQ(memcmp(&addr, bind_addr_, addrlen_), 0);
   296  }
   297  
   298  TEST_P(UdpSocketTest, SendNotConnected) {
   299    ASSERT_NO_ERRNO(BindLoopback());
   300  
   301    // Do send & write, they must fail.
   302    char buf[512];
   303    EXPECT_THAT(send(sock_.get(), buf, sizeof(buf), 0),
   304                SyscallFailsWithErrno(EDESTADDRREQ));
   305  
   306    EXPECT_THAT(write(sock_.get(), buf, sizeof(buf)),
   307                SyscallFailsWithErrno(EDESTADDRREQ));
   308  
   309    // Use sendto.
   310    ASSERT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0, bind_addr_, addrlen_),
   311                SyscallSucceedsWithValue(sizeof(buf)));
   312  
   313    // Check that we're bound now.
   314    struct sockaddr_storage addr;
   315    socklen_t addrlen = sizeof(addr);
   316    EXPECT_THAT(getsockname(sock_.get(), AsSockAddr(&addr), &addrlen),
   317                SyscallSucceeds());
   318    EXPECT_EQ(addrlen, addrlen_);
   319    EXPECT_NE(*Port(&addr), 0);
   320  }
   321  
   322  TEST_P(UdpSocketTest, ConnectBinds) {
   323    ASSERT_NO_ERRNO(BindLoopback());
   324  
   325    // Connect the socket.
   326    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   327  
   328    // Check that we're bound now.
   329    struct sockaddr_storage addr;
   330    socklen_t addrlen = sizeof(addr);
   331    EXPECT_THAT(getsockname(sock_.get(), AsSockAddr(&addr), &addrlen),
   332                SyscallSucceeds());
   333    EXPECT_EQ(addrlen, addrlen_);
   334    EXPECT_NE(*Port(&addr), 0);
   335  }
   336  
   337  TEST_P(UdpSocketTest, ReceiveNotBound) {
   338    char buf[512];
   339    EXPECT_THAT(recv(sock_.get(), buf, sizeof(buf), MSG_DONTWAIT),
   340                SyscallFailsWithErrno(EWOULDBLOCK));
   341  }
   342  
   343  TEST_P(UdpSocketTest, Bind) {
   344    ASSERT_NO_ERRNO(BindLoopback());
   345  
   346    // Try to bind again.
   347    EXPECT_THAT(bind(bind_.get(), bind_addr_, addrlen_),
   348                SyscallFailsWithErrno(EINVAL));
   349  
   350    // Check that we're still bound to the original address.
   351    struct sockaddr_storage addr;
   352    socklen_t addrlen = sizeof(addr);
   353    EXPECT_THAT(getsockname(bind_.get(), AsSockAddr(&addr), &addrlen),
   354                SyscallSucceeds());
   355    EXPECT_EQ(addrlen, addrlen_);
   356    EXPECT_EQ(memcmp(&addr, bind_addr_, addrlen_), 0);
   357  }
   358  
   359  TEST_P(UdpSocketTest, BindInUse) {
   360    ASSERT_NO_ERRNO(BindLoopback());
   361  
   362    // Try to bind again.
   363    EXPECT_THAT(bind(sock_.get(), bind_addr_, addrlen_),
   364                SyscallFailsWithErrno(EADDRINUSE));
   365  }
   366  
   367  TEST_P(UdpSocketTest, ConnectWriteToInvalidPort) {
   368    // Discover a free unused port by creating a new UDP socket, binding it
   369    // recording the just bound port and closing it. This is not guaranteed as it
   370    // can still race with other port UDP sockets trying to bind a port at the
   371    // same time.
   372    struct sockaddr_storage addr_storage = InetLoopbackAddr();
   373    socklen_t addrlen = sizeof(addr_storage);
   374    struct sockaddr* addr = AsSockAddr(&addr_storage);
   375    FileDescriptor s =
   376        ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_DGRAM, IPPROTO_UDP));
   377    ASSERT_THAT(bind(s.get(), addr, addrlen), SyscallSucceeds());
   378    ASSERT_THAT(getsockname(s.get(), addr, &addrlen), SyscallSucceeds());
   379    EXPECT_EQ(addrlen, addrlen_);
   380    EXPECT_NE(*Port(&addr_storage), 0);
   381    // Connect to the same address. This won't send data yet but will ensure that
   382    // the local port chosen for the connecting socket is different from the
   383    // remote port, since it is still in use.
   384    ASSERT_THAT(connect(sock_.get(), addr, addrlen_), SyscallSucceeds());
   385  
   386    // Now free the destination port and then send a packet to it. This should
   387    // generate an ECONNREFUSED error.
   388    ASSERT_THAT(close(s.release()), SyscallSucceeds());
   389    char buf[512];
   390    RandomizeBuffer(buf, sizeof(buf));
   391    // Send from sock_ to an unbound port.
   392    ASSERT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0, addr, addrlen_),
   393                SyscallSucceedsWithValue(sizeof(buf)));
   394  
   395    // Poll to make sure we get the ICMP error back.
   396    struct pollfd pfd = {sock_.get(), POLLERR, 0};
   397    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, IcmpTimeoutMillis()),
   398                SyscallSucceedsWithValue(1));
   399  
   400    // Now verify that we got an ICMP error back of ECONNREFUSED.
   401    int err;
   402    socklen_t optlen = sizeof(err);
   403    ASSERT_THAT(getsockopt(sock_.get(), SOL_SOCKET, SO_ERROR, &err, &optlen),
   404                SyscallSucceeds());
   405    ASSERT_EQ(err, ECONNREFUSED);
   406    ASSERT_EQ(optlen, sizeof(err));
   407  }
   408  
   409  TEST_P(UdpSocketTest, ConnectSimultaneousWriteToInvalidPort) {
   410    // Discover a free unused port by creating a new UDP socket, binding it
   411    // recording the just bound port and closing it. This is not guaranteed as it
   412    // can still race with other port UDP sockets trying to bind a port at the
   413    // same time.
   414    struct sockaddr_storage addr_storage = InetLoopbackAddr();
   415    socklen_t addrlen = sizeof(addr_storage);
   416    struct sockaddr* addr = AsSockAddr(&addr_storage);
   417    FileDescriptor s =
   418        ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_DGRAM, IPPROTO_UDP));
   419    ASSERT_THAT(bind(s.get(), addr, addrlen), SyscallSucceeds());
   420    ASSERT_THAT(getsockname(s.get(), addr, &addrlen), SyscallSucceeds());
   421    EXPECT_EQ(addrlen, addrlen_);
   422    EXPECT_NE(*Port(&addr_storage), 0);
   423    ASSERT_THAT(close(s.release()), SyscallSucceeds());
   424  
   425    // Now connect to the port that we just released.
   426    ScopedThread t([&] {
   427      ASSERT_THAT(connect(sock_.get(), addr, addrlen_), SyscallSucceeds());
   428    });
   429  
   430    char buf[512];
   431    RandomizeBuffer(buf, sizeof(buf));
   432    // Send from sock_ to an unbound port.
   433    ASSERT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0, addr, addrlen_),
   434                SyscallSucceedsWithValue(sizeof(buf)));
   435    t.Join();
   436  }
   437  
   438  TEST_P(UdpSocketTest, ReceiveAfterConnect) {
   439    ASSERT_NO_ERRNO(BindLoopback());
   440    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   441  
   442    // Send from sock_ to bind_
   443    char buf[512];
   444    RandomizeBuffer(buf, sizeof(buf));
   445    ASSERT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0, bind_addr_, addrlen_),
   446                SyscallSucceedsWithValue(sizeof(buf)));
   447  
   448    // Receive the data.
   449    char received[sizeof(buf)];
   450    EXPECT_THAT(recv(bind_.get(), received, sizeof(received), 0),
   451                SyscallSucceedsWithValue(sizeof(received)));
   452    EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);
   453  }
   454  
   455  TEST_P(UdpSocketTest, ReceiveAfterDisconnect) {
   456    ASSERT_NO_ERRNO(BindLoopback());
   457  
   458    for (int i = 0; i < 2; i++) {
   459      // Connet sock_ to bound address.
   460      ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   461  
   462      struct sockaddr_storage addr;
   463      socklen_t addrlen = sizeof(addr);
   464      EXPECT_THAT(getsockname(sock_.get(), AsSockAddr(&addr), &addrlen),
   465                  SyscallSucceeds());
   466      EXPECT_EQ(addrlen, addrlen_);
   467  
   468      // Send from sock to bind_.
   469      char buf[512];
   470      RandomizeBuffer(buf, sizeof(buf));
   471  
   472      ASSERT_THAT(
   473          sendto(bind_.get(), buf, sizeof(buf), 0, AsSockAddr(&addr), addrlen),
   474          SyscallSucceedsWithValue(sizeof(buf)));
   475  
   476      // Receive the data.
   477      char received[sizeof(buf)];
   478      EXPECT_THAT(recv(sock_.get(), received, sizeof(received), 0),
   479                  SyscallSucceedsWithValue(sizeof(received)));
   480      EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);
   481  
   482      // Disconnect sock_.
   483      struct sockaddr unspec = {};
   484      unspec.sa_family = AF_UNSPEC;
   485      ASSERT_THAT(connect(sock_.get(), &unspec, sizeof(unspec.sa_family)),
   486                  SyscallSucceeds());
   487    }
   488  }
   489  
   490  TEST_P(UdpSocketTest, Connect) {
   491    ASSERT_NO_ERRNO(BindLoopback());
   492    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   493  
   494    // Check that we're connected to the right peer.
   495    struct sockaddr_storage peer;
   496    socklen_t peerlen = sizeof(peer);
   497    EXPECT_THAT(getpeername(sock_.get(), AsSockAddr(&peer), &peerlen),
   498                SyscallSucceeds());
   499    EXPECT_EQ(peerlen, addrlen_);
   500    EXPECT_EQ(memcmp(&peer, bind_addr_, addrlen_), 0);
   501  
   502    // Try to bind after connect.
   503    struct sockaddr_storage any = InetAnyAddr();
   504    EXPECT_THAT(bind(sock_.get(), AsSockAddr(&any), addrlen_),
   505                SyscallFailsWithErrno(EINVAL));
   506  
   507    struct sockaddr_storage bind2_storage = InetLoopbackAddr();
   508    struct sockaddr* bind2_addr = AsSockAddr(&bind2_storage);
   509    FileDescriptor bind2 =
   510        ASSERT_NO_ERRNO_AND_VALUE(Socket(GetParam(), SOCK_DGRAM, IPPROTO_UDP));
   511    ASSERT_NO_ERRNO(BindSocket(bind2.get(), bind2_addr));
   512  
   513    // Try to connect again.
   514    EXPECT_THAT(connect(sock_.get(), bind2_addr, addrlen_), SyscallSucceeds());
   515  
   516    // Check that peer name changed.
   517    peerlen = sizeof(peer);
   518    EXPECT_THAT(getpeername(sock_.get(), AsSockAddr(&peer), &peerlen),
   519                SyscallSucceeds());
   520    EXPECT_EQ(peerlen, addrlen_);
   521    EXPECT_EQ(memcmp(&peer, bind2_addr, addrlen_), 0);
   522  }
   523  
   524  TEST_P(UdpSocketTest, ConnectAnyZero) {
   525    // TODO(138658473): Enable when we can connect to port 0 with gVisor.
   526    SKIP_IF(IsRunningOnGvisor());
   527  
   528    struct sockaddr_storage any = InetAnyAddr();
   529    EXPECT_THAT(connect(sock_.get(), AsSockAddr(&any), addrlen_),
   530                SyscallSucceeds());
   531  
   532    struct sockaddr_storage addr;
   533    socklen_t addrlen = sizeof(addr);
   534    EXPECT_THAT(getpeername(sock_.get(), AsSockAddr(&addr), &addrlen),
   535                SyscallFailsWithErrno(ENOTCONN));
   536  }
   537  
   538  TEST_P(UdpSocketTest, ConnectAnyWithPort) {
   539    ASSERT_NO_ERRNO(BindAny());
   540    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   541  
   542    struct sockaddr_storage addr;
   543    socklen_t addrlen = sizeof(addr);
   544    EXPECT_THAT(getpeername(sock_.get(), AsSockAddr(&addr), &addrlen),
   545                SyscallSucceeds());
   546  }
   547  
   548  TEST_P(UdpSocketTest, DisconnectAfterConnectAny) {
   549    // TODO(138658473): Enable when we can connect to port 0 with gVisor.
   550    SKIP_IF(IsRunningOnGvisor());
   551    struct sockaddr_storage any = InetAnyAddr();
   552    EXPECT_THAT(connect(sock_.get(), AsSockAddr(&any), addrlen_),
   553                SyscallSucceeds());
   554  
   555    struct sockaddr_storage addr;
   556    socklen_t addrlen = sizeof(addr);
   557    EXPECT_THAT(getpeername(sock_.get(), AsSockAddr(&addr), &addrlen),
   558                SyscallFailsWithErrno(ENOTCONN));
   559  
   560    Disconnect(sock_.get());
   561  }
   562  
   563  TEST_P(UdpSocketTest, DisconnectAfterConnectAnyWithPort) {
   564    ASSERT_NO_ERRNO(BindAny());
   565    EXPECT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   566  
   567    struct sockaddr_storage addr;
   568    socklen_t addrlen = sizeof(addr);
   569    ASSERT_THAT(getpeername(sock_.get(), AsSockAddr(&addr), &addrlen),
   570                SyscallSucceeds());
   571  
   572    EXPECT_EQ(addrlen, addrlen_);
   573    EXPECT_EQ(*Port(&bind_addr_storage_), *Port(&addr));
   574  
   575    Disconnect(sock_.get());
   576  }
   577  
   578  TEST_P(UdpSocketTest, DisconnectAfterBind) {
   579    ASSERT_NO_ERRNO(BindLoopback());
   580  
   581    // Bind to the next port above bind_.
   582    struct sockaddr_storage addr_storage = InetLoopbackAddr();
   583    struct sockaddr* addr = AsSockAddr(&addr_storage);
   584    SetPort(&addr_storage, *Port(&bind_addr_storage_) - 1);
   585    ASSERT_NO_ERRNO(BindSocket(sock_.get(), addr));
   586  
   587    // Connect the socket.
   588    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   589  
   590    struct sockaddr_storage unspec = {};
   591    unspec.ss_family = AF_UNSPEC;
   592    EXPECT_THAT(
   593        connect(sock_.get(), AsSockAddr(&unspec), sizeof(unspec.ss_family)),
   594        SyscallSucceeds());
   595  
   596    // Check that we're still bound.
   597    socklen_t addrlen = sizeof(unspec);
   598    EXPECT_THAT(getsockname(sock_.get(), AsSockAddr(&unspec), &addrlen),
   599                SyscallSucceeds());
   600  
   601    EXPECT_EQ(addrlen, addrlen_);
   602    EXPECT_EQ(memcmp(addr, &unspec, addrlen_), 0);
   603  
   604    addrlen = sizeof(addr);
   605    EXPECT_THAT(getpeername(sock_.get(), addr, &addrlen),
   606                SyscallFailsWithErrno(ENOTCONN));
   607  }
   608  
   609  void ConnectThenDisconnect(const FileDescriptor& sock,
   610                             const sockaddr* bind_addr,
   611                             const socklen_t expected_addrlen) {
   612    // Connect the bound socket.
   613    ASSERT_THAT(connect(sock.get(), bind_addr, expected_addrlen),
   614                SyscallSucceeds());
   615  
   616    // Disconnect.
   617    {
   618      sockaddr_storage unspec = {.ss_family = AF_UNSPEC};
   619      ASSERT_THAT(connect(sock.get(), AsSockAddr(&unspec), sizeof(unspec)),
   620                  SyscallSucceeds());
   621    }
   622    {
   623      // Check that we're not in a bound state.
   624      sockaddr_storage addr;
   625      socklen_t addrlen = sizeof(addr);
   626      ASSERT_THAT(getsockname(sock.get(), AsSockAddr(&addr), &addrlen),
   627                  SyscallSucceeds());
   628      ASSERT_EQ(addrlen, expected_addrlen);
   629      // Everything should be the zero value except the address family.
   630      sockaddr_storage expected = {
   631          .ss_family = bind_addr->sa_family,
   632      };
   633      EXPECT_EQ(memcmp(&expected, &addr, expected_addrlen), 0);
   634    }
   635  
   636    {
   637      // We are not connected so we have no peer.
   638      sockaddr_storage addr;
   639      socklen_t addrlen = sizeof(addr);
   640      EXPECT_THAT(getpeername(sock.get(), AsSockAddr(&addr), &addrlen),
   641                  SyscallFailsWithErrno(ENOTCONN));
   642    }
   643  }
   644  
   645  TEST_P(UdpSocketTest, DisconnectAfterBindToUnspecAndConnect) {
   646    ASSERT_NO_ERRNO(BindLoopback());
   647  
   648    sockaddr_storage unspec = {.ss_family = AF_UNSPEC};
   649    int bind_res = bind(sock_.get(), AsSockAddr(&unspec), sizeof(unspec));
   650    if ((!IsRunningOnGvisor() || IsRunningWithHostinet()) &&
   651        GetParam() == AF_INET) {
   652      // Linux allows this for undocumented compatibility reasons:
   653      // https://github.com/torvalds/linux/commit/29c486df6a208432b370bd4be99ae1369ede28d8.
   654      //
   655      // TODO(https://gvisor.dev/issue/6575): Match Linux's behaviour.
   656      ASSERT_THAT(bind_res, SyscallSucceeds());
   657    } else {
   658      ASSERT_THAT(bind_res, SyscallFailsWithErrno(EAFNOSUPPORT));
   659    }
   660  
   661    ASSERT_NO_FATAL_FAILURE(ConnectThenDisconnect(sock_, bind_addr_, addrlen_));
   662  }
   663  
   664  TEST_P(UdpSocketTest, DisconnectAfterConnectWithoutBind) {
   665    ASSERT_NO_ERRNO(BindLoopback());
   666  
   667    ASSERT_NO_FATAL_FAILURE(ConnectThenDisconnect(sock_, bind_addr_, addrlen_));
   668  }
   669  
   670  TEST_P(UdpSocketTest, BindToAnyConnnectToLocalhost) {
   671    ASSERT_NO_ERRNO(BindAny());
   672  
   673    struct sockaddr_storage addr_storage = InetLoopbackAddr();
   674    struct sockaddr* addr = AsSockAddr(&addr_storage);
   675    SetPort(&addr_storage, *Port(&bind_addr_storage_) - 1);
   676    socklen_t addrlen = sizeof(addr);
   677  
   678    // Connect the socket.
   679    ASSERT_THAT(connect(bind_.get(), addr, addrlen_), SyscallSucceeds());
   680  
   681    EXPECT_THAT(getsockname(bind_.get(), addr, &addrlen), SyscallSucceeds());
   682  
   683    // If the socket is bound to ANY and connected to a loopback address,
   684    // getsockname() has to return the loopback address.
   685    if (GetParam() == AF_INET) {
   686      auto addr_out = reinterpret_cast<struct sockaddr_in*>(addr);
   687      EXPECT_EQ(addrlen, sizeof(*addr_out));
   688      EXPECT_EQ(addr_out->sin_addr.s_addr, htonl(INADDR_LOOPBACK));
   689    } else {
   690      auto addr_out = reinterpret_cast<struct sockaddr_in6*>(addr);
   691      struct in6_addr loopback = IN6ADDR_LOOPBACK_INIT;
   692      EXPECT_EQ(addrlen, sizeof(*addr_out));
   693      EXPECT_EQ(memcmp(&addr_out->sin6_addr, &loopback, sizeof(in6_addr)), 0);
   694    }
   695  }
   696  
   697  TEST_P(UdpSocketTest, DisconnectAfterBindToAny) {
   698    ASSERT_NO_ERRNO(BindLoopback());
   699  
   700    struct sockaddr_storage any_storage = InetAnyAddr();
   701    struct sockaddr* any = AsSockAddr(&any_storage);
   702    SetPort(&any_storage, *Port(&bind_addr_storage_) - 1);
   703  
   704    ASSERT_NO_ERRNO(BindSocket(sock_.get(), any));
   705  
   706    // Connect the socket.
   707    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   708  
   709    Disconnect(sock_.get());
   710  
   711    // Check that we're still bound.
   712    struct sockaddr_storage addr;
   713    socklen_t addrlen = sizeof(addr);
   714    EXPECT_THAT(getsockname(sock_.get(), AsSockAddr(&addr), &addrlen),
   715                SyscallSucceeds());
   716  
   717    EXPECT_EQ(addrlen, addrlen_);
   718    EXPECT_EQ(memcmp(&addr, any, addrlen), 0);
   719  
   720    addrlen = sizeof(addr);
   721    EXPECT_THAT(getpeername(sock_.get(), AsSockAddr(&addr), &addrlen),
   722                SyscallFailsWithErrno(ENOTCONN));
   723  }
   724  
   725  TEST_P(UdpSocketTest, Disconnect) {
   726    ASSERT_NO_ERRNO(BindLoopback());
   727  
   728    struct sockaddr_storage any_storage = InetAnyAddr();
   729    struct sockaddr* any = AsSockAddr(&any_storage);
   730    SetPort(&any_storage, *Port(&bind_addr_storage_) - 1);
   731    ASSERT_NO_ERRNO(BindSocket(sock_.get(), any));
   732  
   733    for (int i = 0; i < 2; i++) {
   734      // Try to connect again.
   735      EXPECT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   736  
   737      // Check that we're connected to the right peer.
   738      struct sockaddr_storage peer;
   739      socklen_t peerlen = sizeof(peer);
   740      EXPECT_THAT(getpeername(sock_.get(), AsSockAddr(&peer), &peerlen),
   741                  SyscallSucceeds());
   742      EXPECT_EQ(peerlen, addrlen_);
   743      EXPECT_EQ(memcmp(&peer, bind_addr_, addrlen_), 0);
   744  
   745      // Try to disconnect.
   746      struct sockaddr_storage addr = {};
   747      addr.ss_family = AF_UNSPEC;
   748      EXPECT_THAT(connect(sock_.get(), AsSockAddr(&addr), sizeof(addr.ss_family)),
   749                  SyscallSucceeds());
   750  
   751      peerlen = sizeof(peer);
   752      EXPECT_THAT(getpeername(sock_.get(), AsSockAddr(&peer), &peerlen),
   753                  SyscallFailsWithErrno(ENOTCONN));
   754  
   755      // Check that we're still bound.
   756      socklen_t addrlen = sizeof(addr);
   757      EXPECT_THAT(getsockname(sock_.get(), AsSockAddr(&addr), &addrlen),
   758                  SyscallSucceeds());
   759      EXPECT_EQ(addrlen, addrlen_);
   760      EXPECT_EQ(*Port(&addr), *Port(&any_storage));
   761    }
   762  }
   763  
   764  TEST_P(UdpSocketTest, ConnectBadAddress) {
   765    struct sockaddr addr = {};
   766    addr.sa_family = GetParam();
   767    ASSERT_THAT(connect(sock_.get(), &addr, sizeof(addr.sa_family)),
   768                SyscallFailsWithErrno(EINVAL));
   769  }
   770  
   771  TEST_P(UdpSocketTest, SendToAddressOtherThanConnected) {
   772    ASSERT_NO_ERRNO(BindLoopback());
   773  
   774    struct sockaddr_storage addr_storage = InetAnyAddr();
   775    struct sockaddr* addr = AsSockAddr(&addr_storage);
   776    SetPort(&addr_storage, *Port(&bind_addr_storage_) - 1);
   777  
   778    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   779  
   780    // Send to a different destination than we're connected to.
   781    char buf[512];
   782    EXPECT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0, addr, addrlen_),
   783                SyscallSucceedsWithValue(sizeof(buf)));
   784  }
   785  
   786  TEST_P(UdpSocketTest, ConnectAndSendNoReceiver) {
   787    ASSERT_NO_ERRNO(BindLoopback());
   788    // Connect to loopback:bind_addr_ which should *hopefully* not be bound by an
   789    // UDP socket. There is no easy way to ensure that the UDP port is not bound
   790    // by another conncurrently running test. *This is potentially flaky*.
   791    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   792  
   793    // Close the socket after connecting to the bound address to make sure `sock_`
   794    // doesn't get auto-bound to the same port.
   795    ASSERT_THAT(close(bind_.release()), SyscallSucceeds());
   796  
   797    char buf[512];
   798    EXPECT_THAT(send(sock_.get(), buf, sizeof(buf), 0),
   799                SyscallSucceedsWithValue(sizeof(buf)));
   800  
   801    // Poll to make sure we get the ICMP error back before issuing more writes.
   802    struct pollfd pfd = {sock_.get(), POLLERR, 0};
   803    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, IcmpTimeoutMillis()),
   804                SyscallSucceedsWithValue(1));
   805  
   806    // Next write should fail with ECONNREFUSED due to the ICMP error generated in
   807    // response to the previous write.
   808    ASSERT_THAT(send(sock_.get(), buf, sizeof(buf), 0),
   809                SyscallFailsWithErrno(ECONNREFUSED));
   810  
   811    // The next write should succeed again since the last write call would have
   812    // retrieved and cleared the socket error.
   813    ASSERT_THAT(send(sock_.get(), buf, sizeof(buf), 0), SyscallSucceeds());
   814  
   815    // Poll to make sure we get the ICMP error back before issuing more writes.
   816    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, IcmpTimeoutMillis()),
   817                SyscallSucceedsWithValue(1));
   818  
   819    // Next write should fail with ECONNREFUSED due to the ICMP error generated in
   820    // response to the previous write.
   821    ASSERT_THAT(send(sock_.get(), buf, sizeof(buf), 0),
   822                SyscallFailsWithErrno(ECONNREFUSED));
   823  }
   824  
   825  #ifdef __linux__
   826  TEST_P(UdpSocketTest, RecvErrorConnRefusedOtherAFSockOpt) {
   827    int got;
   828    socklen_t got_len = sizeof(got);
   829    if (GetParam() == AF_INET) {
   830      EXPECT_THAT(setsockopt(sock_.get(), SOL_IPV6, IPV6_RECVERR, &kSockOptOn,
   831                             sizeof(kSockOptOn)),
   832                  SyscallFailsWithErrno(ENOPROTOOPT));
   833      EXPECT_THAT(getsockopt(sock_.get(), SOL_IPV6, IPV6_RECVERR, &got, &got_len),
   834                  SyscallFailsWithErrno(ENOTSUP));
   835      ASSERT_THAT(got_len, sizeof(got));
   836      return;
   837    }
   838    ASSERT_THAT(setsockopt(sock_.get(), SOL_IP, IP_RECVERR, &kSockOptOn,
   839                           sizeof(kSockOptOn)),
   840                SyscallSucceeds());
   841    {
   842      EXPECT_THAT(getsockopt(sock_.get(), SOL_IP, IP_RECVERR, &got, &got_len),
   843                  SyscallSucceeds());
   844      ASSERT_THAT(got_len, sizeof(got));
   845      EXPECT_THAT(got, kSockOptOn);
   846    }
   847  
   848    // We will simulate an ICMP error and verify that we don't receive that error
   849    // via recvmsg(MSG_ERRQUEUE) since we set another address family's RECVERR
   850    // flag.
   851    ASSERT_NO_ERRNO(BindLoopback());
   852    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   853    // Close the bind socket to release the port so that we get an ICMP error
   854    // when sending packets to it.
   855    ASSERT_THAT(close(bind_.release()), SyscallSucceeds());
   856  
   857    // Send to an unbound port which should trigger a port unreachable error.
   858    char buf[1];
   859    EXPECT_THAT(send(sock_.get(), buf, sizeof(buf), 0),
   860                SyscallSucceedsWithValue(sizeof(buf)));
   861  
   862    // Should not have the error since we did not set the right socket option.
   863    msghdr msg = {};
   864    EXPECT_THAT(recvmsg(sock_.get(), &msg, MSG_ERRQUEUE),
   865                SyscallFailsWithErrno(EAGAIN));
   866  }
   867  
   868  TEST_P(UdpSocketTest, RecvErrorConnRefused) {
   869    // We will simulate an ICMP error and verify that we do receive that error via
   870    // recvmsg(MSG_ERRQUEUE).
   871    ASSERT_NO_ERRNO(BindLoopback());
   872    // Close the socket to release the port so that we get an ICMP error.
   873    ASSERT_THAT(close(bind_.release()), SyscallSucceeds());
   874  
   875    // Set IP_RECVERR socket option to enable error queueing.
   876    int v = kSockOptOn;
   877    socklen_t optlen = sizeof(v);
   878    int opt_level = SOL_IP;
   879    int opt_type = IP_RECVERR;
   880    if (GetParam() == AF_INET6) {
   881      opt_level = SOL_IPV6;
   882      opt_type = IPV6_RECVERR;
   883    }
   884    ASSERT_THAT(setsockopt(sock_.get(), opt_level, opt_type, &v, optlen),
   885                SyscallSucceeds());
   886    {
   887      int got;
   888      socklen_t got_len = sizeof(got);
   889      EXPECT_THAT(getsockopt(sock_.get(), opt_level, opt_type, &got, &got_len),
   890                  SyscallSucceeds());
   891      ASSERT_THAT(got_len, sizeof(got));
   892      EXPECT_THAT(got, kSockOptOn);
   893    }
   894  
   895    // Connect to loopback:bind_addr_ which should *hopefully* not be bound by an
   896    // UDP socket. There is no easy way to ensure that the UDP port is not bound
   897    // by another conncurrently running test. *This is potentially flaky*.
   898    const int kBufLen = 300;
   899    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
   900    char buf[kBufLen];
   901    RandomizeBuffer(buf, sizeof(buf));
   902    // Send from sock_ to an unbound port. This should cause ECONNREFUSED.
   903    EXPECT_THAT(send(sock_.get(), buf, sizeof(buf), 0),
   904                SyscallSucceedsWithValue(sizeof(buf)));
   905  
   906    // Dequeue error using recvmsg(MSG_ERRQUEUE).
   907    char got[kBufLen];
   908    struct iovec iov;
   909    iov.iov_base = reinterpret_cast<void*>(got);
   910    iov.iov_len = kBufLen;
   911  
   912    size_t control_buf_len = CMSG_SPACE(sizeof(sock_extended_err) + addrlen_);
   913    std::vector<char> control_buf(control_buf_len);
   914    struct sockaddr_storage remote;
   915    memset(&remote, 0, sizeof(remote));
   916    struct msghdr msg = {};
   917    msg.msg_iov = &iov;
   918    msg.msg_iovlen = 1;
   919    msg.msg_flags = 0;
   920    msg.msg_control = control_buf.data();
   921    msg.msg_controllen = control_buf_len;
   922    msg.msg_name = reinterpret_cast<void*>(&remote);
   923    msg.msg_namelen = addrlen_;
   924    ASSERT_THAT(recvmsg(sock_.get(), &msg, MSG_ERRQUEUE),
   925                SyscallSucceedsWithValue(kBufLen));
   926  
   927    // Check the contents of msg.
   928    EXPECT_EQ(memcmp(got, buf, sizeof(buf)), 0);  // iovec check
   929    EXPECT_NE(msg.msg_flags & MSG_ERRQUEUE, 0);
   930    EXPECT_EQ(memcmp(&remote, bind_addr_, addrlen_), 0);
   931  
   932    // Check the contents of the control message.
   933    struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
   934    ASSERT_NE(cmsg, nullptr);
   935    EXPECT_EQ(CMSG_NXTHDR(&msg, cmsg), nullptr);
   936    EXPECT_EQ(cmsg->cmsg_level, opt_level);
   937    EXPECT_EQ(cmsg->cmsg_type, opt_type);
   938  
   939    // Check the contents of socket error.
   940    struct sock_extended_err* sock_err =
   941        (struct sock_extended_err*)CMSG_DATA(cmsg);
   942    EXPECT_EQ(sock_err->ee_errno, ECONNREFUSED);
   943    if (GetParam() == AF_INET) {
   944      EXPECT_EQ(sock_err->ee_origin, SO_EE_ORIGIN_ICMP);
   945      EXPECT_EQ(sock_err->ee_type, ICMP_DEST_UNREACH);
   946      EXPECT_EQ(sock_err->ee_code, ICMP_PORT_UNREACH);
   947    } else {
   948      EXPECT_EQ(sock_err->ee_origin, SO_EE_ORIGIN_ICMP6);
   949      EXPECT_EQ(sock_err->ee_type, ICMP6_DST_UNREACH);
   950      EXPECT_EQ(sock_err->ee_code, ICMP6_DST_UNREACH_NOPORT);
   951    }
   952  
   953    // Now verify that the socket error was cleared by recvmsg(MSG_ERRQUEUE).
   954    int err;
   955    optlen = sizeof(err);
   956    ASSERT_THAT(getsockopt(sock_.get(), SOL_SOCKET, SO_ERROR, &err, &optlen),
   957                SyscallSucceeds());
   958    ASSERT_EQ(err, 0);
   959    ASSERT_EQ(optlen, sizeof(err));
   960  }
   961  #endif  // __linux__
   962  
   963  TEST_P(UdpSocketTest, ZerolengthWriteAllowed) {
   964    // TODO(gvisor.dev/issue/1202): Hostinet does not support zero length writes.
   965    SKIP_IF(IsRunningWithHostinet());
   966  
   967    ASSERT_NO_ERRNO(BindLoopback());
   968  
   969    // Bind `sock_` to loopback.
   970    struct sockaddr_storage addr_storage = InetLoopbackAddr();
   971    struct sockaddr* addr = AsSockAddr(&addr_storage);
   972    ASSERT_NO_ERRNO(BindSocket(sock_.get(), addr));
   973  
   974    // Connect `bind_` to `sock_`.
   975    ASSERT_THAT(connect(bind_.get(), addr, addrlen_), SyscallSucceeds());
   976  
   977    char buf[3];
   978    // Send zero length packet from bind_ to sock_.
   979    ASSERT_THAT(write(bind_.get(), buf, 0), SyscallSucceedsWithValue(0));
   980  
   981    struct pollfd pfd = {sock_.get(), POLLIN, 0};
   982    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, /*timeout*/ 1000),
   983                SyscallSucceedsWithValue(1));
   984  
   985    // Receive the packet.
   986    char received[3];
   987    EXPECT_THAT(read(sock_.get(), received, sizeof(received)),
   988                SyscallSucceedsWithValue(0));
   989  }
   990  
   991  TEST_P(UdpSocketTest, ZerolengthWriteAllowedNonBlockRead) {
   992    // TODO(gvisor.dev/issue/1202): Hostinet does not support zero length writes.
   993    SKIP_IF(IsRunningWithHostinet());
   994  
   995    ASSERT_NO_ERRNO(BindLoopback());
   996  
   997    // Bind `sock_` to loopback.
   998    struct sockaddr_storage addr_storage = InetLoopbackAddr();
   999    struct sockaddr* addr = AsSockAddr(&addr_storage);
  1000    ASSERT_NO_ERRNO(BindSocket(sock_.get(), addr));
  1001  
  1002    // Connect `bind_` to `sock_`.
  1003    ASSERT_THAT(connect(bind_.get(), addr, addrlen_), SyscallSucceeds());
  1004  
  1005    // Set sock to non-blocking.
  1006    int opts = 0;
  1007    ASSERT_THAT(opts = fcntl(sock_.get(), F_GETFL), SyscallSucceeds());
  1008    ASSERT_THAT(fcntl(sock_.get(), F_SETFL, opts | O_NONBLOCK),
  1009                SyscallSucceeds());
  1010  
  1011    char buf[3];
  1012    // Send zero length packet from bind_ to sock_.
  1013    ASSERT_THAT(write(bind_.get(), buf, 0), SyscallSucceedsWithValue(0));
  1014  
  1015    struct pollfd pfd = {sock_.get(), POLLIN, 0};
  1016    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, /*timeout=*/1000),
  1017                SyscallSucceedsWithValue(1));
  1018  
  1019    // Receive the packet.
  1020    char received[3];
  1021    EXPECT_THAT(read(sock_.get(), received, sizeof(received)),
  1022                SyscallSucceedsWithValue(0));
  1023    EXPECT_THAT(read(sock_.get(), received, sizeof(received)),
  1024                SyscallFailsWithErrno(EAGAIN));
  1025  }
  1026  
  1027  TEST_P(UdpSocketTest, SendAndReceiveNotConnected) {
  1028    ASSERT_NO_ERRNO(BindLoopback());
  1029  
  1030    // Send some data to bind_.
  1031    char buf[512];
  1032    RandomizeBuffer(buf, sizeof(buf));
  1033  
  1034    ASSERT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0, bind_addr_, addrlen_),
  1035                SyscallSucceedsWithValue(sizeof(buf)));
  1036  
  1037    // Receive the data.
  1038    char received[sizeof(buf)];
  1039    EXPECT_THAT(recv(bind_.get(), received, sizeof(received), 0),
  1040                SyscallSucceedsWithValue(sizeof(received)));
  1041    EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);
  1042  }
  1043  
  1044  TEST_P(UdpSocketTest, SendAndReceiveConnected) {
  1045    ASSERT_NO_ERRNO(BindLoopback());
  1046  
  1047    // Bind `sock_` to loopback.
  1048    struct sockaddr_storage addr_storage = InetLoopbackAddr();
  1049    struct sockaddr* addr = AsSockAddr(&addr_storage);
  1050    ASSERT_NO_ERRNO(BindSocket(sock_.get(), addr));
  1051  
  1052    // Connect `bind_` to `sock_`.
  1053    ASSERT_THAT(connect(bind_.get(), addr, addrlen_), SyscallSucceeds());
  1054  
  1055    // Send some data from sock to bind_.
  1056    char buf[512];
  1057    RandomizeBuffer(buf, sizeof(buf));
  1058  
  1059    ASSERT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0, bind_addr_, addrlen_),
  1060                SyscallSucceedsWithValue(sizeof(buf)));
  1061  
  1062    // Receive the data.
  1063    char received[sizeof(buf)];
  1064    EXPECT_THAT(recv(bind_.get(), received, sizeof(received), 0),
  1065                SyscallSucceedsWithValue(sizeof(received)));
  1066    EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);
  1067  }
  1068  
  1069  TEST_P(UdpSocketTest, ReceiveFromNotConnected) {
  1070    ASSERT_NO_ERRNO(BindLoopback());
  1071  
  1072    // Bind `sock_` to loopback.
  1073    struct sockaddr_storage addr_storage = InetLoopbackAddr();
  1074    struct sockaddr* addr = AsSockAddr(&addr_storage);
  1075    ASSERT_NO_ERRNO(BindSocket(sock_.get(), addr));
  1076  
  1077    // Connect `bind_` to itself.
  1078    ASSERT_THAT(connect(bind_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1079  
  1080    // Send some data from sock to bind_.
  1081    char buf[512];
  1082    ASSERT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0, bind_addr_, addrlen_),
  1083                SyscallSucceedsWithValue(sizeof(buf)));
  1084  
  1085    // Check that the data isn't received because it was sent from a different
  1086    // address than we're connected.
  1087    EXPECT_THAT(recv(bind_.get(), buf, sizeof(buf), MSG_DONTWAIT),
  1088                SyscallFailsWithErrno(EWOULDBLOCK));
  1089  }
  1090  
  1091  TEST_P(UdpSocketTest, ReceiveBeforeConnect) {
  1092    ASSERT_NO_ERRNO(BindLoopback());
  1093  
  1094    // Bind `sock_` to loopback.
  1095    struct sockaddr_storage addr_storage = InetLoopbackAddr();
  1096    struct sockaddr* addr = AsSockAddr(&addr_storage);
  1097    ASSERT_NO_ERRNO(BindSocket(sock_.get(), addr));
  1098  
  1099    // Send some data from sock to bind_.
  1100    char buf[512];
  1101    RandomizeBuffer(buf, sizeof(buf));
  1102  
  1103    ASSERT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0, bind_addr_, addrlen_),
  1104                SyscallSucceedsWithValue(sizeof(buf)));
  1105  
  1106    // Wait for the data to arrive.
  1107    ASSERT_NO_FATAL_FAILURE(BlockUntilPollin(bind_.get()));
  1108  
  1109    // Connect `bind_` to itself.
  1110    ASSERT_THAT(connect(bind_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1111  
  1112    // Receive the data. It works because it was sent before the connect.
  1113    char received[sizeof(buf)];
  1114    EXPECT_THAT(
  1115        RecvTimeout(bind_.get(), received, sizeof(received), 1 /*timeout*/),
  1116        IsPosixErrorOkAndHolds(sizeof(received)));
  1117    EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);
  1118  
  1119    // Send again. This time it should not be received.
  1120    ASSERT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0, bind_addr_, addrlen_),
  1121                SyscallSucceedsWithValue(sizeof(buf)));
  1122  
  1123    EXPECT_THAT(recv(bind_.get(), buf, sizeof(buf), MSG_DONTWAIT),
  1124                SyscallFailsWithErrno(EWOULDBLOCK));
  1125  }
  1126  
  1127  TEST_P(UdpSocketTest, ReceiveFrom) {
  1128    ASSERT_NO_ERRNO(BindLoopback());
  1129  
  1130    // Bind `sock_` to loopback.
  1131    struct sockaddr_storage addr_storage = InetLoopbackAddr();
  1132    struct sockaddr* addr = AsSockAddr(&addr_storage);
  1133    ASSERT_NO_ERRNO(BindSocket(sock_.get(), addr));
  1134  
  1135    // Connect `bind_` to `sock_`.
  1136    ASSERT_THAT(connect(bind_.get(), addr, addrlen_), SyscallSucceeds());
  1137  
  1138    // Send some data from sock to bind_.
  1139    char buf[512];
  1140    RandomizeBuffer(buf, sizeof(buf));
  1141  
  1142    ASSERT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0, bind_addr_, addrlen_),
  1143                SyscallSucceedsWithValue(sizeof(buf)));
  1144  
  1145    // Receive the data and sender address.
  1146    char received[sizeof(buf)];
  1147    struct sockaddr_storage addr2;
  1148    socklen_t addr2len = sizeof(addr2);
  1149    EXPECT_THAT(recvfrom(bind_.get(), received, sizeof(received), 0,
  1150                         AsSockAddr(&addr2), &addr2len),
  1151                SyscallSucceedsWithValue(sizeof(received)));
  1152    EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);
  1153    EXPECT_EQ(addr2len, addrlen_);
  1154    EXPECT_EQ(memcmp(addr, &addr2, addrlen_), 0);
  1155  }
  1156  
  1157  TEST_P(UdpSocketTest, Listen) {
  1158    ASSERT_THAT(listen(sock_.get(), SOMAXCONN),
  1159                SyscallFailsWithErrno(EOPNOTSUPP));
  1160  }
  1161  
  1162  TEST_P(UdpSocketTest, Accept) {
  1163    ASSERT_THAT(accept(sock_.get(), nullptr, nullptr),
  1164                SyscallFailsWithErrno(EOPNOTSUPP));
  1165  }
  1166  
  1167  // This test validates that a read shutdown with pending data allows the read
  1168  // to proceed with the data before returning EAGAIN.
  1169  TEST_P(UdpSocketTest, ReadShutdownNonblockPendingData) {
  1170    ASSERT_NO_ERRNO(BindLoopback());
  1171  
  1172    // Bind `sock_` to loopback.
  1173    struct sockaddr_storage addr_storage = InetLoopbackAddr();
  1174    struct sockaddr* addr = AsSockAddr(&addr_storage);
  1175    ASSERT_NO_ERRNO(BindSocket(sock_.get(), addr));
  1176  
  1177    // Connect `bind_` to `sock_`.
  1178    ASSERT_THAT(connect(bind_.get(), addr, addrlen_), SyscallSucceeds());
  1179  
  1180    // Connect `sock_` to `bind_addr_`.
  1181    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1182  
  1183    // Verify that we get EWOULDBLOCK when there is nothing to read.
  1184    char received[512];
  1185    EXPECT_THAT(recv(bind_.get(), received, sizeof(received), MSG_DONTWAIT),
  1186                SyscallFailsWithErrno(EWOULDBLOCK));
  1187  
  1188    const char* buf = "abc";
  1189    EXPECT_THAT(write(sock_.get(), buf, 3), SyscallSucceedsWithValue(3));
  1190  
  1191    int opts = 0;
  1192    ASSERT_THAT(opts = fcntl(bind_.get(), F_GETFL), SyscallSucceeds());
  1193    ASSERT_THAT(fcntl(bind_.get(), F_SETFL, opts | O_NONBLOCK),
  1194                SyscallSucceeds());
  1195    ASSERT_THAT(opts = fcntl(bind_.get(), F_GETFL), SyscallSucceeds());
  1196    ASSERT_NE(opts & O_NONBLOCK, 0);
  1197  
  1198    // Wait for the data to arrive.
  1199    ASSERT_NO_FATAL_FAILURE(BlockUntilPollin(bind_.get()));
  1200  
  1201    EXPECT_THAT(shutdown(bind_.get(), SHUT_RD), SyscallSucceeds());
  1202  
  1203    // We should get the data even though read has been shutdown.
  1204    EXPECT_THAT(RecvTimeout(bind_.get(), received, 2 /*buf_size*/, 1 /*timeout*/),
  1205                IsPosixErrorOkAndHolds(2));
  1206  
  1207    // Because we read less than the entire packet length, since it's a packet
  1208    // based socket any subsequent reads should return EWOULDBLOCK.
  1209    EXPECT_THAT(recv(bind_.get(), received, 1, 0),
  1210                SyscallFailsWithErrno(EWOULDBLOCK));
  1211  }
  1212  
  1213  // This test is validating that even after a socket is shutdown if it's
  1214  // reconnected it will reset the shutdown state.
  1215  TEST_P(UdpSocketTest, ReadShutdownSameSocketResetsShutdownState) {
  1216    char received[512];
  1217    EXPECT_THAT(recv(bind_.get(), received, sizeof(received), MSG_DONTWAIT),
  1218                SyscallFailsWithErrno(EWOULDBLOCK));
  1219  
  1220    EXPECT_THAT(shutdown(bind_.get(), SHUT_RD), SyscallFailsWithErrno(ENOTCONN));
  1221  
  1222    EXPECT_THAT(recv(bind_.get(), received, sizeof(received), MSG_DONTWAIT),
  1223                SyscallFailsWithErrno(EWOULDBLOCK));
  1224  
  1225    // Connect the socket, then try to shutdown again.
  1226    ASSERT_NO_ERRNO(BindLoopback());
  1227  
  1228    // Connect `bind_` to itself since we know the port number is valid.
  1229    struct sockaddr_storage addr_storage = InetLoopbackAddr();
  1230    struct sockaddr* addr = AsSockAddr(&addr_storage);
  1231    SetPort(&addr_storage, *Port(&bind_addr_storage_));
  1232    ASSERT_THAT(connect(bind_.get(), addr, addrlen_), SyscallSucceeds());
  1233  
  1234    EXPECT_THAT(recv(bind_.get(), received, sizeof(received), MSG_DONTWAIT),
  1235                SyscallFailsWithErrno(EWOULDBLOCK));
  1236  }
  1237  
  1238  TEST_P(UdpSocketTest, ReadShutdown) {
  1239    // TODO(gvisor.dev/issue/1202): Calling recv() after shutdown without
  1240    // MSG_DONTWAIT blocks indefinitely.
  1241    SKIP_IF(IsRunningWithHostinet());
  1242  
  1243    ASSERT_NO_ERRNO(BindLoopback());
  1244  
  1245    char received[512];
  1246    EXPECT_THAT(recv(sock_.get(), received, sizeof(received), MSG_DONTWAIT),
  1247                SyscallFailsWithErrno(EWOULDBLOCK));
  1248  
  1249    EXPECT_THAT(shutdown(sock_.get(), SHUT_RD), SyscallFailsWithErrno(ENOTCONN));
  1250  
  1251    EXPECT_THAT(recv(sock_.get(), received, sizeof(received), MSG_DONTWAIT),
  1252                SyscallFailsWithErrno(EWOULDBLOCK));
  1253  
  1254    // Connect the socket, then try to shutdown again.
  1255    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1256  
  1257    EXPECT_THAT(recv(sock_.get(), received, sizeof(received), MSG_DONTWAIT),
  1258                SyscallFailsWithErrno(EWOULDBLOCK));
  1259  
  1260    EXPECT_THAT(shutdown(sock_.get(), SHUT_RD), SyscallSucceeds());
  1261  
  1262    EXPECT_THAT(recv(sock_.get(), received, sizeof(received), 0),
  1263                SyscallSucceedsWithValue(0));
  1264  }
  1265  
  1266  TEST_P(UdpSocketTest, ReadShutdownDifferentThread) {
  1267    // TODO(gvisor.dev/issue/1202): Calling recv() after shutdown without
  1268    // MSG_DONTWAIT blocks indefinitely.
  1269    SKIP_IF(IsRunningWithHostinet());
  1270    ASSERT_NO_ERRNO(BindLoopback());
  1271  
  1272    char received[512];
  1273    EXPECT_THAT(recv(sock_.get(), received, sizeof(received), MSG_DONTWAIT),
  1274                SyscallFailsWithErrno(EWOULDBLOCK));
  1275  
  1276    // Connect the socket, then shutdown from another thread.
  1277    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1278  
  1279    EXPECT_THAT(recv(sock_.get(), received, sizeof(received), MSG_DONTWAIT),
  1280                SyscallFailsWithErrno(EWOULDBLOCK));
  1281  
  1282    ScopedThread t([&] {
  1283      absl::SleepFor(absl::Milliseconds(200));
  1284      EXPECT_THAT(shutdown(sock_.get(), SHUT_RD), SyscallSucceeds());
  1285    });
  1286    EXPECT_THAT(RetryEINTR(recv)(sock_.get(), received, sizeof(received), 0),
  1287                SyscallSucceedsWithValue(0));
  1288    t.Join();
  1289  
  1290    EXPECT_THAT(RetryEINTR(recv)(sock_.get(), received, sizeof(received), 0),
  1291                SyscallSucceedsWithValue(0));
  1292  }
  1293  
  1294  TEST_P(UdpSocketTest, WriteShutdown) {
  1295    ASSERT_NO_ERRNO(BindLoopback());
  1296    EXPECT_THAT(shutdown(sock_.get(), SHUT_WR), SyscallFailsWithErrno(ENOTCONN));
  1297    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1298    EXPECT_THAT(shutdown(sock_.get(), SHUT_WR), SyscallSucceeds());
  1299  }
  1300  
  1301  TEST_P(UdpSocketTest, SynchronousReceive) {
  1302    ASSERT_NO_ERRNO(BindLoopback());
  1303  
  1304    // Send some data to bind_ from another thread.
  1305    char buf[512];
  1306    RandomizeBuffer(buf, sizeof(buf));
  1307  
  1308    // Receive the data prior to actually starting the other thread.
  1309    char received[512];
  1310    EXPECT_THAT(
  1311        RetryEINTR(recv)(bind_.get(), received, sizeof(received), MSG_DONTWAIT),
  1312        SyscallFailsWithErrno(EWOULDBLOCK));
  1313  
  1314    // Start the thread.
  1315    ScopedThread t([&] {
  1316      absl::SleepFor(absl::Milliseconds(200));
  1317      ASSERT_THAT(sendto(sock_.get(), buf, sizeof(buf), 0, this->bind_addr_,
  1318                         this->addrlen_),
  1319                  SyscallSucceedsWithValue(sizeof(buf)));
  1320    });
  1321  
  1322    EXPECT_THAT(RetryEINTR(recv)(bind_.get(), received, sizeof(received), 0),
  1323                SyscallSucceedsWithValue(512));
  1324    EXPECT_EQ(memcmp(buf, received, sizeof(buf)), 0);
  1325  }
  1326  
  1327  TEST_P(UdpSocketTest, BoundaryPreserved_SendRecv) {
  1328    ASSERT_NO_ERRNO(BindLoopback());
  1329  
  1330    // Send 3 packets from sock to bind_.
  1331    constexpr int psize = 100;
  1332    char buf[3 * psize];
  1333    RandomizeBuffer(buf, sizeof(buf));
  1334  
  1335    for (int i = 0; i < 3; ++i) {
  1336      ASSERT_THAT(
  1337          sendto(sock_.get(), buf + i * psize, psize, 0, bind_addr_, addrlen_),
  1338          SyscallSucceedsWithValue(psize));
  1339    }
  1340  
  1341    // Receive the data as 3 separate packets.
  1342    char received[6 * psize];
  1343    for (int i = 0; i < 3; ++i) {
  1344      EXPECT_THAT(recv(bind_.get(), received + i * psize, 3 * psize, 0),
  1345                  SyscallSucceedsWithValue(psize));
  1346    }
  1347    EXPECT_EQ(memcmp(buf, received, 3 * psize), 0);
  1348  }
  1349  
  1350  TEST_P(UdpSocketTest, BoundaryPreserved_WritevReadv) {
  1351    ASSERT_NO_ERRNO(BindLoopback());
  1352  
  1353    // Direct writes from sock to bind_.
  1354    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1355  
  1356    // Send 2 packets from sock to bind_, where each packet's data consists of
  1357    // 2 discontiguous iovecs.
  1358    constexpr size_t kPieceSize = 100;
  1359    char buf[4 * kPieceSize];
  1360    RandomizeBuffer(buf, sizeof(buf));
  1361  
  1362    for (int i = 0; i < 2; i++) {
  1363      struct iovec iov[2];
  1364      for (int j = 0; j < 2; j++) {
  1365        iov[j].iov_base = reinterpret_cast<void*>(
  1366            reinterpret_cast<uintptr_t>(buf) + (i + 2 * j) * kPieceSize);
  1367        iov[j].iov_len = kPieceSize;
  1368      }
  1369      ASSERT_THAT(writev(sock_.get(), iov, 2),
  1370                  SyscallSucceedsWithValue(2 * kPieceSize));
  1371    }
  1372  
  1373    // Receive the data as 2 separate packets.
  1374    char received[6 * kPieceSize];
  1375    for (int i = 0; i < 2; i++) {
  1376      struct iovec iov[3];
  1377      for (int j = 0; j < 3; j++) {
  1378        iov[j].iov_base = reinterpret_cast<void*>(
  1379            reinterpret_cast<uintptr_t>(received) + (i + 2 * j) * kPieceSize);
  1380        iov[j].iov_len = kPieceSize;
  1381      }
  1382      ASSERT_THAT(readv(bind_.get(), iov, 3),
  1383                  SyscallSucceedsWithValue(2 * kPieceSize));
  1384    }
  1385    EXPECT_EQ(memcmp(buf, received, 4 * kPieceSize), 0);
  1386  }
  1387  
  1388  TEST_P(UdpSocketTest, BoundaryPreserved_SendMsgRecvMsg) {
  1389    ASSERT_NO_ERRNO(BindLoopback());
  1390  
  1391    // Send 2 packets from sock to bind_, where each packet's data consists of
  1392    // 2 discontiguous iovecs.
  1393    constexpr size_t kPieceSize = 100;
  1394    char buf[4 * kPieceSize];
  1395    RandomizeBuffer(buf, sizeof(buf));
  1396  
  1397    for (int i = 0; i < 2; i++) {
  1398      struct iovec iov[2];
  1399      for (int j = 0; j < 2; j++) {
  1400        iov[j].iov_base = reinterpret_cast<void*>(
  1401            reinterpret_cast<uintptr_t>(buf) + (i + 2 * j) * kPieceSize);
  1402        iov[j].iov_len = kPieceSize;
  1403      }
  1404      struct msghdr msg = {};
  1405      msg.msg_name = bind_addr_;
  1406      msg.msg_namelen = addrlen_;
  1407      msg.msg_iov = iov;
  1408      msg.msg_iovlen = 2;
  1409      ASSERT_THAT(sendmsg(sock_.get(), &msg, 0),
  1410                  SyscallSucceedsWithValue(2 * kPieceSize));
  1411    }
  1412  
  1413    // Receive the data as 2 separate packets.
  1414    char received[6 * kPieceSize];
  1415    for (int i = 0; i < 2; i++) {
  1416      struct iovec iov[3];
  1417      for (int j = 0; j < 3; j++) {
  1418        iov[j].iov_base = reinterpret_cast<void*>(
  1419            reinterpret_cast<uintptr_t>(received) + (i + 2 * j) * kPieceSize);
  1420        iov[j].iov_len = kPieceSize;
  1421      }
  1422      struct msghdr msg = {};
  1423      msg.msg_iov = iov;
  1424      msg.msg_iovlen = 3;
  1425      ASSERT_THAT(recvmsg(bind_.get(), &msg, 0),
  1426                  SyscallSucceedsWithValue(2 * kPieceSize));
  1427    }
  1428    EXPECT_EQ(memcmp(buf, received, 4 * kPieceSize), 0);
  1429  }
  1430  
  1431  TEST_P(UdpSocketTest, FIONREADShutdown) {
  1432    ASSERT_NO_ERRNO(BindLoopback());
  1433  
  1434    int n = -1;
  1435    EXPECT_THAT(ioctl(sock_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1436    EXPECT_EQ(n, 0);
  1437  
  1438    // A UDP socket must be connected before it can be shutdown.
  1439    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1440  
  1441    n = -1;
  1442    EXPECT_THAT(ioctl(sock_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1443    EXPECT_EQ(n, 0);
  1444  
  1445    EXPECT_THAT(shutdown(sock_.get(), SHUT_RD), SyscallSucceeds());
  1446  
  1447    n = -1;
  1448    EXPECT_THAT(ioctl(sock_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1449    EXPECT_EQ(n, 0);
  1450  }
  1451  
  1452  TEST_P(UdpSocketTest, FIONREADWriteShutdown) {
  1453    int n = -1;
  1454    EXPECT_THAT(ioctl(bind_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1455    EXPECT_EQ(n, 0);
  1456  
  1457    ASSERT_NO_ERRNO(BindLoopback());
  1458  
  1459    // A UDP socket must be connected before it can be shutdown.
  1460    ASSERT_THAT(connect(bind_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1461  
  1462    n = -1;
  1463    EXPECT_THAT(ioctl(bind_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1464    EXPECT_EQ(n, 0);
  1465  
  1466    const char str[] = "abc";
  1467    ASSERT_THAT(send(bind_.get(), str, sizeof(str), 0),
  1468                SyscallSucceedsWithValue(sizeof(str)));
  1469  
  1470    struct pollfd pfd = {bind_.get(), POLLIN, 0};
  1471    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, /*timeout=*/1000),
  1472                SyscallSucceedsWithValue(1));
  1473  
  1474    n = -1;
  1475    EXPECT_THAT(ioctl(bind_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1476    EXPECT_EQ(n, sizeof(str));
  1477  
  1478    EXPECT_THAT(shutdown(bind_.get(), SHUT_RD), SyscallSucceeds());
  1479  
  1480    n = -1;
  1481    EXPECT_THAT(ioctl(bind_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1482    EXPECT_EQ(n, sizeof(str));
  1483  }
  1484  
  1485  // NOTE: Do not use `FIONREAD` as test name because it will be replaced by the
  1486  // corresponding macro and become `0x541B`.
  1487  TEST_P(UdpSocketTest, Fionread) {
  1488    ASSERT_NO_ERRNO(BindLoopback());
  1489  
  1490    // Check that the bound socket with an empty buffer reports an empty first
  1491    // packet.
  1492    int n = -1;
  1493    EXPECT_THAT(ioctl(bind_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1494    EXPECT_EQ(n, 0);
  1495  
  1496    // Send 3 packets from sock to bind_.
  1497    constexpr int psize = 100;
  1498    char buf[3 * psize];
  1499    RandomizeBuffer(buf, sizeof(buf));
  1500  
  1501    struct pollfd pfd = {bind_.get(), POLLIN, 0};
  1502    for (int i = 0; i < 3; ++i) {
  1503      ASSERT_THAT(
  1504          sendto(sock_.get(), buf + i * psize, psize, 0, bind_addr_, addrlen_),
  1505          SyscallSucceedsWithValue(psize));
  1506  
  1507      ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, /*timeout=*/1000),
  1508                  SyscallSucceedsWithValue(1));
  1509  
  1510      // Check that regardless of how many packets are in the queue, the size
  1511      // reported is that of a single packet.
  1512      n = -1;
  1513      EXPECT_THAT(ioctl(bind_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1514      EXPECT_EQ(n, psize);
  1515    }
  1516  }
  1517  
  1518  TEST_P(UdpSocketTest, FIONREADZeroLengthPacket) {
  1519    ASSERT_NO_ERRNO(BindLoopback());
  1520  
  1521    // Check that the bound socket with an empty buffer reports an empty first
  1522    // packet.
  1523    int n = -1;
  1524    EXPECT_THAT(ioctl(bind_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1525    EXPECT_EQ(n, 0);
  1526  
  1527    // Send 3 packets from sock to bind_.
  1528    constexpr int psize = 100;
  1529    char buf[3 * psize];
  1530    RandomizeBuffer(buf, sizeof(buf));
  1531  
  1532    struct pollfd pfd = {bind_.get(), POLLIN, 0};
  1533    for (int i = 0; i < 3; ++i) {
  1534      ASSERT_THAT(
  1535          sendto(sock_.get(), buf + i * psize, 0, 0, bind_addr_, addrlen_),
  1536          SyscallSucceedsWithValue(0));
  1537  
  1538      ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, /*timeout=*/1000),
  1539                  SyscallSucceedsWithValue(1));
  1540  
  1541      // Check that regardless of how many packets are in the queue, the size
  1542      // reported is that of a single packet.
  1543      n = -1;
  1544      EXPECT_THAT(ioctl(bind_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1545      EXPECT_EQ(n, 0);
  1546    }
  1547  }
  1548  
  1549  TEST_P(UdpSocketTest, FIONREADZeroLengthWriteShutdown) {
  1550    int n = -1;
  1551    EXPECT_THAT(ioctl(bind_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1552    EXPECT_EQ(n, 0);
  1553  
  1554    ASSERT_NO_ERRNO(BindLoopback());
  1555  
  1556    // A UDP socket must be connected before it can be shutdown.
  1557    ASSERT_THAT(connect(bind_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1558  
  1559    n = -1;
  1560    EXPECT_THAT(ioctl(bind_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1561    EXPECT_EQ(n, 0);
  1562  
  1563    const char str[] = "abc";
  1564    ASSERT_THAT(send(bind_.get(), str, 0, 0), SyscallSucceedsWithValue(0));
  1565  
  1566    n = -1;
  1567    EXPECT_THAT(ioctl(bind_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1568    EXPECT_EQ(n, 0);
  1569  
  1570    EXPECT_THAT(shutdown(bind_.get(), SHUT_RD), SyscallSucceeds());
  1571  
  1572    n = -1;
  1573    EXPECT_THAT(ioctl(bind_.get(), FIONREAD, &n), SyscallSucceedsWithValue(0));
  1574    EXPECT_EQ(n, 0);
  1575  }
  1576  
  1577  TEST_P(UdpSocketTest, SoNoCheckOffByDefault) {
  1578    int v = -1;
  1579    socklen_t optlen = sizeof(v);
  1580    ASSERT_THAT(getsockopt(bind_.get(), SOL_SOCKET, SO_NO_CHECK, &v, &optlen),
  1581                SyscallSucceeds());
  1582    ASSERT_EQ(v, kSockOptOff);
  1583    ASSERT_EQ(optlen, sizeof(v));
  1584  }
  1585  
  1586  TEST_P(UdpSocketTest, SoNoCheck) {
  1587    int v = kSockOptOn;
  1588    socklen_t optlen = sizeof(v);
  1589    ASSERT_THAT(setsockopt(bind_.get(), SOL_SOCKET, SO_NO_CHECK, &v, optlen),
  1590                SyscallSucceeds());
  1591    v = -1;
  1592    ASSERT_THAT(getsockopt(bind_.get(), SOL_SOCKET, SO_NO_CHECK, &v, &optlen),
  1593                SyscallSucceeds());
  1594    ASSERT_EQ(v, kSockOptOn);
  1595    ASSERT_EQ(optlen, sizeof(v));
  1596  
  1597    v = kSockOptOff;
  1598    ASSERT_THAT(setsockopt(bind_.get(), SOL_SOCKET, SO_NO_CHECK, &v, optlen),
  1599                SyscallSucceeds());
  1600    v = -1;
  1601    ASSERT_THAT(getsockopt(bind_.get(), SOL_SOCKET, SO_NO_CHECK, &v, &optlen),
  1602                SyscallSucceeds());
  1603    ASSERT_EQ(v, kSockOptOff);
  1604    ASSERT_EQ(optlen, sizeof(v));
  1605  }
  1606  
  1607  #ifdef __linux__
  1608  TEST_P(UdpSocketTest, ErrorQueue) {
  1609    char cmsgbuf[CMSG_SPACE(sizeof(sock_extended_err))];
  1610    msghdr msg;
  1611    memset(&msg, 0, sizeof(msg));
  1612    iovec iov;
  1613    memset(&iov, 0, sizeof(iov));
  1614    msg.msg_iov = &iov;
  1615    msg.msg_iovlen = 1;
  1616    msg.msg_control = cmsgbuf;
  1617    msg.msg_controllen = sizeof(cmsgbuf);
  1618  
  1619    // recv*(MSG_ERRQUEUE) never blocks, even without MSG_DONTWAIT.
  1620    EXPECT_THAT(RetryEINTR(recvmsg)(bind_.get(), &msg, MSG_ERRQUEUE),
  1621                SyscallFailsWithErrno(EAGAIN));
  1622  }
  1623  #endif  // __linux__
  1624  
  1625  TEST_P(UdpSocketTest, SoTimestampOffByDefault) {
  1626    int v = -1;
  1627    socklen_t optlen = sizeof(v);
  1628    ASSERT_THAT(getsockopt(bind_.get(), SOL_SOCKET, SO_TIMESTAMP, &v, &optlen),
  1629                SyscallSucceeds());
  1630    ASSERT_EQ(v, kSockOptOff);
  1631    ASSERT_EQ(optlen, sizeof(v));
  1632  }
  1633  
  1634  TEST_P(UdpSocketTest, SoTimestamp) {
  1635    ASSERT_NO_ERRNO(BindLoopback());
  1636    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1637  
  1638    int v = 1;
  1639    ASSERT_THAT(setsockopt(bind_.get(), SOL_SOCKET, SO_TIMESTAMP, &v, sizeof(v)),
  1640                SyscallSucceeds());
  1641  
  1642    char buf[3];
  1643    // Send zero length packet from sock to bind_.
  1644    ASSERT_THAT(RetryEINTR(write)(sock_.get(), buf, sizeof(buf)),
  1645                SyscallSucceedsWithValue(sizeof(buf)));
  1646  
  1647    struct pollfd pfd = {bind_.get(), POLLIN, 0};
  1648    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, /*timeout=*/1000),
  1649                SyscallSucceedsWithValue(1));
  1650  
  1651    char cmsgbuf[CMSG_SPACE(sizeof(struct timeval))];
  1652    msghdr msg;
  1653    memset(&msg, 0, sizeof(msg));
  1654    iovec iov;
  1655    memset(&iov, 0, sizeof(iov));
  1656    msg.msg_iov = &iov;
  1657    msg.msg_iovlen = 1;
  1658    msg.msg_control = cmsgbuf;
  1659    msg.msg_controllen = sizeof(cmsgbuf);
  1660  
  1661    ASSERT_THAT(RetryEINTR(recvmsg)(bind_.get(), &msg, 0),
  1662                SyscallSucceedsWithValue(0));
  1663  
  1664    struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
  1665    ASSERT_NE(cmsg, nullptr);
  1666    ASSERT_EQ(cmsg->cmsg_level, SOL_SOCKET);
  1667    ASSERT_EQ(cmsg->cmsg_type, SO_TIMESTAMP);
  1668    ASSERT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(struct timeval)));
  1669  
  1670    struct timeval tv = {};
  1671    memcpy(&tv, CMSG_DATA(cmsg), sizeof(struct timeval));
  1672  
  1673    ASSERT_TRUE(tv.tv_sec != 0 || tv.tv_usec != 0);
  1674  
  1675    // TODO(gvisor.dev/issue/1202): ioctl(SIOCGSTAMP) is not supported by
  1676    // hostinet.
  1677    if (!IsRunningWithHostinet()) {
  1678      // There should be nothing to get via ioctl.
  1679      ASSERT_THAT(ioctl(bind_.get(), SIOCGSTAMP, &tv),
  1680                  SyscallFailsWithErrno(ENOENT));
  1681    }
  1682  }
  1683  
  1684  TEST_P(UdpSocketTest, WriteShutdownNotConnected) {
  1685    EXPECT_THAT(shutdown(bind_.get(), SHUT_WR), SyscallFailsWithErrno(ENOTCONN));
  1686  }
  1687  
  1688  TEST_P(UdpSocketTest, TimestampIoctl) {
  1689    // TODO(gvisor.dev/issue/1202): ioctl() is not supported by hostinet.
  1690    SKIP_IF(IsRunningWithHostinet());
  1691  
  1692    ASSERT_NO_ERRNO(BindLoopback());
  1693    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1694  
  1695    char buf[3];
  1696    // Send packet from sock to bind_.
  1697    ASSERT_THAT(RetryEINTR(write)(sock_.get(), buf, sizeof(buf)),
  1698                SyscallSucceedsWithValue(sizeof(buf)));
  1699  
  1700    struct pollfd pfd = {bind_.get(), POLLIN, 0};
  1701    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, /*timeout=*/1000),
  1702                SyscallSucceedsWithValue(1));
  1703  
  1704    // There should be no control messages.
  1705    char recv_buf[sizeof(buf)];
  1706    ASSERT_NO_FATAL_FAILURE(RecvNoCmsg(bind_.get(), recv_buf, sizeof(recv_buf)));
  1707  
  1708    // A nonzero timeval should be available via ioctl.
  1709    struct timeval tv = {};
  1710    ASSERT_THAT(ioctl(bind_.get(), SIOCGSTAMP, &tv), SyscallSucceeds());
  1711    ASSERT_TRUE(tv.tv_sec != 0 || tv.tv_usec != 0);
  1712  }
  1713  
  1714  TEST_P(UdpSocketTest, TimestampIoctlNothingRead) {
  1715    // TODO(gvisor.dev/issue/1202): ioctl() is not supported by hostinet.
  1716    SKIP_IF(IsRunningWithHostinet());
  1717  
  1718    ASSERT_NO_ERRNO(BindLoopback());
  1719    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1720  
  1721    struct timeval tv = {};
  1722    ASSERT_THAT(ioctl(sock_.get(), SIOCGSTAMP, &tv),
  1723                SyscallFailsWithErrno(ENOENT));
  1724  }
  1725  
  1726  // Test that the timestamp accessed via SIOCGSTAMP is still accessible after
  1727  // SO_TIMESTAMP is enabled and used to retrieve a timestamp.
  1728  TEST_P(UdpSocketTest, TimestampIoctlPersistence) {
  1729    // TODO(gvisor.dev/issue/1202): ioctl() and SO_TIMESTAMP socket option are not
  1730    // supported by hostinet.
  1731    SKIP_IF(IsRunningWithHostinet());
  1732  
  1733    ASSERT_NO_ERRNO(BindLoopback());
  1734    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  1735  
  1736    char buf[3];
  1737    // Send packet from sock to bind_.
  1738    ASSERT_THAT(RetryEINTR(write)(sock_.get(), buf, sizeof(buf)),
  1739                SyscallSucceedsWithValue(sizeof(buf)));
  1740    ASSERT_THAT(RetryEINTR(write)(sock_.get(), buf, 0),
  1741                SyscallSucceedsWithValue(0));
  1742  
  1743    struct pollfd pfd = {bind_.get(), POLLIN, 0};
  1744    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, /*timeout=*/1000),
  1745                SyscallSucceedsWithValue(1));
  1746  
  1747    // There should be no control messages.
  1748    char recv_buf[sizeof(buf)];
  1749    ASSERT_NO_FATAL_FAILURE(RecvNoCmsg(bind_.get(), recv_buf, sizeof(recv_buf)));
  1750  
  1751    // A nonzero timeval should be available via ioctl.
  1752    struct timeval tv = {};
  1753    ASSERT_THAT(ioctl(bind_.get(), SIOCGSTAMP, &tv), SyscallSucceeds());
  1754    ASSERT_TRUE(tv.tv_sec != 0 || tv.tv_usec != 0);
  1755  
  1756    // Enable SO_TIMESTAMP and send a message.
  1757    int v = 1;
  1758    EXPECT_THAT(setsockopt(bind_.get(), SOL_SOCKET, SO_TIMESTAMP, &v, sizeof(v)),
  1759                SyscallSucceeds());
  1760    ASSERT_THAT(RetryEINTR(write)(sock_.get(), buf, 0),
  1761                SyscallSucceedsWithValue(0));
  1762  
  1763    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, /*timeout=*/1000),
  1764                SyscallSucceedsWithValue(1));
  1765  
  1766    // There should be a message for SO_TIMESTAMP.
  1767    char cmsgbuf[CMSG_SPACE(sizeof(struct timeval))];
  1768    msghdr msg = {};
  1769    iovec iov = {};
  1770    msg.msg_iov = &iov;
  1771    msg.msg_iovlen = 1;
  1772    msg.msg_control = cmsgbuf;
  1773    msg.msg_controllen = sizeof(cmsgbuf);
  1774    ASSERT_THAT(RetryEINTR(recvmsg)(bind_.get(), &msg, 0),
  1775                SyscallSucceedsWithValue(0));
  1776    struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
  1777    ASSERT_NE(cmsg, nullptr);
  1778  
  1779    // The ioctl should return the exact same values as before.
  1780    struct timeval tv2 = {};
  1781    ASSERT_THAT(ioctl(bind_.get(), SIOCGSTAMP, &tv2), SyscallSucceeds());
  1782    ASSERT_EQ(tv.tv_sec, tv2.tv_sec);
  1783    ASSERT_EQ(tv.tv_usec, tv2.tv_usec);
  1784  }
  1785  
  1786  TEST_P(UdpSocketTest, RecvBufLimitsEmptyRcvBuf) {
  1787    // Discover minimum buffer size by setting it to zero.
  1788    constexpr int kRcvBufSz = 0;
  1789    ASSERT_THAT(setsockopt(bind_.get(), SOL_SOCKET, SO_RCVBUF, &kRcvBufSz,
  1790                           sizeof(kRcvBufSz)),
  1791                SyscallSucceeds());
  1792  
  1793    int min = 0;
  1794    socklen_t min_len = sizeof(min);
  1795    ASSERT_THAT(getsockopt(bind_.get(), SOL_SOCKET, SO_RCVBUF, &min, &min_len),
  1796                SyscallSucceeds());
  1797  
  1798    // Bind bind_ to loopback.
  1799    ASSERT_NO_ERRNO(BindLoopback());
  1800  
  1801    {
  1802      // Send data of size min and verify that it's received.
  1803      std::vector<char> buf(min);
  1804      RandomizeBuffer(buf.data(), buf.size());
  1805      ASSERT_THAT(
  1806          sendto(sock_.get(), buf.data(), buf.size(), 0, bind_addr_, addrlen_),
  1807          SyscallSucceedsWithValue(buf.size()));
  1808      std::vector<char> received(buf.size());
  1809      EXPECT_THAT(RecvTimeout(bind_.get(), received.data(), received.size(),
  1810                              1 /*timeout*/),
  1811                  IsPosixErrorOkAndHolds(received.size()));
  1812    }
  1813  
  1814    {
  1815      // Send data of size min + 1 and verify that its received. Both linux and
  1816      // Netstack accept a dgram that exceeds rcvBuf limits if the receive buffer
  1817      // is currently empty.
  1818      std::vector<char> buf(min + 1);
  1819      RandomizeBuffer(buf.data(), buf.size());
  1820      ASSERT_THAT(
  1821          sendto(sock_.get(), buf.data(), buf.size(), 0, bind_addr_, addrlen_),
  1822          SyscallSucceedsWithValue(buf.size()));
  1823  
  1824      std::vector<char> received(buf.size());
  1825      ASSERT_THAT(RecvTimeout(bind_.get(), received.data(), received.size(),
  1826                              1 /*timeout*/),
  1827                  IsPosixErrorOkAndHolds(received.size()));
  1828    }
  1829  }
  1830  
  1831  // Test that receive buffer limits are enforced.
  1832  TEST_P(UdpSocketTest, RecvBufLimits) {
  1833    // Bind s_ to loopback.
  1834    ASSERT_NO_ERRNO(BindLoopback());
  1835  
  1836    int min = 0;
  1837    {
  1838      // Discover minimum buffer size by trying to set it to zero.
  1839      constexpr int kRcvBufSz = 0;
  1840      ASSERT_THAT(setsockopt(bind_.get(), SOL_SOCKET, SO_RCVBUF, &kRcvBufSz,
  1841                             sizeof(kRcvBufSz)),
  1842                  SyscallSucceeds());
  1843  
  1844      socklen_t min_len = sizeof(min);
  1845      ASSERT_THAT(getsockopt(bind_.get(), SOL_SOCKET, SO_RCVBUF, &min, &min_len),
  1846                  SyscallSucceeds());
  1847    }
  1848  
  1849    // Now set the limit to min * 2.
  1850    int new_rcv_buf_sz = min * 2;
  1851    ASSERT_THAT(setsockopt(bind_.get(), SOL_SOCKET, SO_RCVBUF, &new_rcv_buf_sz,
  1852                           sizeof(new_rcv_buf_sz)),
  1853                SyscallSucceeds());
  1854    int rcv_buf_sz = 0;
  1855    {
  1856      socklen_t rcv_buf_len = sizeof(rcv_buf_sz);
  1857      ASSERT_THAT(getsockopt(bind_.get(), SOL_SOCKET, SO_RCVBUF, &rcv_buf_sz,
  1858                             &rcv_buf_len),
  1859                  SyscallSucceeds());
  1860    }
  1861  
  1862    {
  1863      std::vector<char> buf(min);
  1864      RandomizeBuffer(buf.data(), buf.size());
  1865  
  1866      ASSERT_THAT(
  1867          sendto(sock_.get(), buf.data(), buf.size(), 0, bind_addr_, addrlen_),
  1868          SyscallSucceedsWithValue(buf.size()));
  1869      ASSERT_THAT(
  1870          sendto(sock_.get(), buf.data(), buf.size(), 0, bind_addr_, addrlen_),
  1871          SyscallSucceedsWithValue(buf.size()));
  1872      ASSERT_THAT(
  1873          sendto(sock_.get(), buf.data(), buf.size(), 0, bind_addr_, addrlen_),
  1874          SyscallSucceedsWithValue(buf.size()));
  1875      ASSERT_THAT(
  1876          sendto(sock_.get(), buf.data(), buf.size(), 0, bind_addr_, addrlen_),
  1877          SyscallSucceedsWithValue(buf.size()));
  1878      int sent = 4;
  1879      if (IsRunningOnGvisor() && !IsRunningWithHostinet()) {
  1880        // Linux seems to drop the 4th packet even though technically it should
  1881        // fit in the receive buffer.
  1882        ASSERT_THAT(
  1883            sendto(sock_.get(), buf.data(), buf.size(), 0, bind_addr_, addrlen_),
  1884            SyscallSucceedsWithValue(buf.size()));
  1885        sent++;
  1886      }
  1887  
  1888      for (int i = 0; i < sent - 1; i++) {
  1889        // Receive the data.
  1890        std::vector<char> received(buf.size());
  1891        EXPECT_THAT(RecvTimeout(bind_.get(), received.data(), received.size(),
  1892                                1 /*timeout*/),
  1893                    IsPosixErrorOkAndHolds(received.size()));
  1894        EXPECT_EQ(memcmp(buf.data(), received.data(), buf.size()), 0);
  1895      }
  1896  
  1897      // The last receive should fail with EAGAIN as the last packet should have
  1898      // been dropped due to lack of space in the receive buffer.
  1899      std::vector<char> received(buf.size());
  1900      EXPECT_THAT(
  1901          recv(bind_.get(), received.data(), received.size(), MSG_DONTWAIT),
  1902          SyscallFailsWithErrno(EAGAIN));
  1903    }
  1904  }
  1905  
  1906  #ifdef __linux__
  1907  
  1908  // TODO(gvisor.dev/2746): Support SO_ATTACH_FILTER/SO_DETACH_FILTER.
  1909  // gVisor currently silently ignores attaching a filter.
  1910  TEST_P(UdpSocketTest, SetSocketDetachFilter) {
  1911    // Program generated using sudo tcpdump -i lo udp and port 1234 -dd
  1912    struct sock_filter code[] = {
  1913        {0x28, 0, 0, 0x0000000c},  {0x15, 0, 6, 0x000086dd},
  1914        {0x30, 0, 0, 0x00000014},  {0x15, 0, 15, 0x00000011},
  1915        {0x28, 0, 0, 0x00000036},  {0x15, 12, 0, 0x000004d2},
  1916        {0x28, 0, 0, 0x00000038},  {0x15, 10, 11, 0x000004d2},
  1917        {0x15, 0, 10, 0x00000800}, {0x30, 0, 0, 0x00000017},
  1918        {0x15, 0, 8, 0x00000011},  {0x28, 0, 0, 0x00000014},
  1919        {0x45, 6, 0, 0x00001fff},  {0xb1, 0, 0, 0x0000000e},
  1920        {0x48, 0, 0, 0x0000000e},  {0x15, 2, 0, 0x000004d2},
  1921        {0x48, 0, 0, 0x00000010},  {0x15, 0, 1, 0x000004d2},
  1922        {0x6, 0, 0, 0x00040000},   {0x6, 0, 0, 0x00000000},
  1923    };
  1924    struct sock_fprog bpf = {
  1925        .len = ABSL_ARRAYSIZE(code),
  1926        .filter = code,
  1927    };
  1928    ASSERT_THAT(
  1929        setsockopt(sock_.get(), SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf)),
  1930        SyscallSucceeds());
  1931  
  1932    constexpr int val = 0;
  1933    ASSERT_THAT(
  1934        setsockopt(sock_.get(), SOL_SOCKET, SO_DETACH_FILTER, &val, sizeof(val)),
  1935        SyscallSucceeds());
  1936  }
  1937  
  1938  #endif  // __linux__
  1939  
  1940  TEST_P(UdpSocketTest, SetSocketDetachFilterNoInstalledFilter) {
  1941    // TODO(gvisor.dev/2746): Support SO_ATTACH_FILTER/SO_DETACH_FILTER.
  1942    SKIP_IF(IsRunningOnGvisor());
  1943    constexpr int val = 0;
  1944    ASSERT_THAT(
  1945        setsockopt(sock_.get(), SOL_SOCKET, SO_DETACH_FILTER, &val, sizeof(val)),
  1946        SyscallFailsWithErrno(ENOENT));
  1947  }
  1948  
  1949  TEST_P(UdpSocketTest, GetSocketDetachFilter) {
  1950    int val = 0;
  1951    socklen_t val_len = sizeof(val);
  1952    ASSERT_THAT(
  1953        getsockopt(sock_.get(), SOL_SOCKET, SO_DETACH_FILTER, &val, &val_len),
  1954        SyscallFailsWithErrno(ENOPROTOOPT));
  1955  }
  1956  
  1957  TEST_P(UdpSocketTest, SendToZeroPort) {
  1958    char buf[8];
  1959    struct sockaddr_storage addr = InetLoopbackAddr();
  1960  
  1961    // Sending to an invalid port should fail.
  1962    SetPort(&addr, 0);
  1963    EXPECT_THAT(
  1964        sendto(sock_.get(), buf, sizeof(buf), 0, AsSockAddr(&addr), sizeof(addr)),
  1965        SyscallFailsWithErrno(EINVAL));
  1966  
  1967    SetPort(&addr, 1234);
  1968    EXPECT_THAT(
  1969        sendto(sock_.get(), buf, sizeof(buf), 0, AsSockAddr(&addr), sizeof(addr)),
  1970        SyscallSucceedsWithValue(sizeof(buf)));
  1971  }
  1972  
  1973  TEST_P(UdpSocketTest, ConnectToZeroPortUnbound) {
  1974    struct sockaddr_storage addr = InetLoopbackAddr();
  1975    SetPort(&addr, 0);
  1976    ASSERT_THAT(connect(sock_.get(), AsSockAddr(&addr), addrlen_),
  1977                SyscallSucceeds());
  1978  }
  1979  
  1980  TEST_P(UdpSocketTest, ConnectToZeroPortBound) {
  1981    struct sockaddr_storage addr = InetLoopbackAddr();
  1982    ASSERT_NO_ERRNO(BindSocket(sock_.get(), AsSockAddr(&addr)));
  1983  
  1984    SetPort(&addr, 0);
  1985    ASSERT_THAT(connect(sock_.get(), AsSockAddr(&addr), addrlen_),
  1986                SyscallSucceeds());
  1987    socklen_t len = sizeof(sockaddr_storage);
  1988    ASSERT_THAT(getsockname(sock_.get(), AsSockAddr(&addr), &len),
  1989                SyscallSucceeds());
  1990    ASSERT_EQ(len, addrlen_);
  1991  }
  1992  
  1993  TEST_P(UdpSocketTest, ConnectToZeroPortConnected) {
  1994    struct sockaddr_storage addr = InetLoopbackAddr();
  1995    ASSERT_NO_ERRNO(BindSocket(sock_.get(), AsSockAddr(&addr)));
  1996  
  1997    // Connect to an address with non-zero port should succeed.
  1998    ASSERT_THAT(connect(sock_.get(), AsSockAddr(&addr), addrlen_),
  1999                SyscallSucceeds());
  2000    sockaddr_storage peername;
  2001    socklen_t peerlen = sizeof(peername);
  2002    ASSERT_THAT(getpeername(sock_.get(), AsSockAddr(&peername), &peerlen),
  2003                SyscallSucceeds());
  2004    ASSERT_EQ(peerlen, addrlen_);
  2005    ASSERT_EQ(memcmp(&peername, &addr, addrlen_), 0);
  2006  
  2007    // However connect() to an address with port 0 will make the following
  2008    // getpeername() fail.
  2009    SetPort(&addr, 0);
  2010    ASSERT_THAT(connect(sock_.get(), AsSockAddr(&addr), addrlen_),
  2011                SyscallSucceeds());
  2012    ASSERT_THAT(getpeername(sock_.get(), AsSockAddr(&peername), &peerlen),
  2013                SyscallFailsWithErrno(ENOTCONN));
  2014  }
  2015  
  2016  INSTANTIATE_TEST_SUITE_P(AllInetTests, UdpSocketTest,
  2017                           ::testing::Values(AF_INET, AF_INET6));
  2018  
  2019  class UdpSocketControlMessagesTest
  2020      : public ::testing::TestWithParam<gvisor::testing::AddressFamily> {
  2021   protected:
  2022    void SetUp() override {
  2023      switch (GetParam()) {
  2024        case AddressFamily::kIpv4: {
  2025          server_ =
  2026              ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP));
  2027          TestAddress addr = V4Loopback().WithPort(port_);
  2028          ASSERT_THAT(
  2029              bind(server_.get(), reinterpret_cast<const sockaddr*>(&addr.addr),
  2030                   addr.addr_len),
  2031              SyscallSucceeds());
  2032  
  2033          client_ =
  2034              ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP));
  2035          ASSERT_THAT(connect(client_.get(),
  2036                              reinterpret_cast<const sockaddr*>(&addr.addr),
  2037                              addr.addr_len),
  2038                      SyscallSucceeds());
  2039          break;
  2040        }
  2041  
  2042        case AddressFamily::kIpv6: {
  2043          server_ = ASSERT_NO_ERRNO_AND_VALUE(
  2044              Socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP));
  2045          TestAddress addr = V6Loopback().WithPort(port_);
  2046          ASSERT_THAT(
  2047              bind(server_.get(), reinterpret_cast<const sockaddr*>(&addr.addr),
  2048                   addr.addr_len),
  2049              SyscallSucceeds());
  2050  
  2051          client_ = ASSERT_NO_ERRNO_AND_VALUE(
  2052              Socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP));
  2053          ASSERT_THAT(connect(client_.get(),
  2054                              reinterpret_cast<const sockaddr*>(&addr.addr),
  2055                              addr.addr_len),
  2056                      SyscallSucceeds());
  2057          break;
  2058        }
  2059  
  2060        case AddressFamily::kDualStack: {
  2061          server_ = ASSERT_NO_ERRNO_AND_VALUE(
  2062              Socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP));
  2063  
  2064          TestAddress bind_addr = V4MappedLoopback().WithPort(port_);
  2065          ASSERT_THAT(bind(server_.get(),
  2066                           reinterpret_cast<const sockaddr*>(&bind_addr.addr),
  2067                           bind_addr.addr_len),
  2068                      SyscallSucceeds());
  2069  
  2070          client_ =
  2071              ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP));
  2072          TestAddress connect_addr = V4Loopback().WithPort(port_);
  2073          ASSERT_THAT(
  2074              connect(client_.get(),
  2075                      reinterpret_cast<const sockaddr*>(&connect_addr.addr),
  2076                      connect_addr.addr_len),
  2077              SyscallSucceeds());
  2078          break;
  2079        }
  2080  
  2081        default:
  2082          FAIL() << "unknown address family: " << static_cast<int>(GetParam());
  2083      }
  2084    }
  2085  
  2086    int ClientAddressFamily() const {
  2087      if (GetParam() == AddressFamily::kIpv6) {
  2088        return AF_INET6;
  2089      }
  2090      return AF_INET;
  2091    }
  2092  
  2093    int ServerAddressFamily() const {
  2094      if (GetParam() == AddressFamily::kIpv4) {
  2095        return AF_INET;
  2096      }
  2097      return AF_INET6;
  2098    }
  2099  
  2100    FileDescriptor server_;
  2101    FileDescriptor client_;
  2102  
  2103   private:
  2104    static constexpr uint16_t port_ = 1337;
  2105  };
  2106  
  2107  TEST_P(UdpSocketControlMessagesTest, SetAndReceiveTOSOrTClass) {
  2108    // TODO(b/267210840): Test is flaky on hostinet.
  2109    SKIP_IF(IsRunningWithHostinet());
  2110  
  2111    // Enable receiving TOS and maybe TClass on the receiver.
  2112    ASSERT_THAT(setsockopt(server_.get(), SOL_IP, IP_RECVTOS, &kSockOptOn,
  2113                           sizeof(kSockOptOn)),
  2114                SyscallSucceeds());
  2115    if (ServerAddressFamily() == AF_INET6) {
  2116      ASSERT_THAT(setsockopt(server_.get(), SOL_IPV6, IPV6_RECVTCLASS,
  2117                             &kSockOptOn, sizeof(kSockOptOn)),
  2118                  SyscallSucceeds());
  2119    }
  2120  
  2121    // Set custom TOS and maybe TClass on the sender.
  2122    constexpr int kTOS = IPTOS_LOWDELAY;
  2123    constexpr int kTClass = IPTOS_THROUGHPUT;
  2124    ASSERT_NE(kTOS, kTClass);
  2125  
  2126    ASSERT_THAT(setsockopt(client_.get(), SOL_IP, IP_TOS, &kTOS, sizeof(kTOS)),
  2127                SyscallSucceeds());
  2128    if (ClientAddressFamily() == AF_INET6) {
  2129      ASSERT_THAT(setsockopt(client_.get(), SOL_IPV6, IPV6_TCLASS, &kTClass,
  2130                             sizeof(kTClass)),
  2131                  SyscallSucceeds());
  2132    }
  2133  
  2134    constexpr size_t kArbitrarySendSize = 1042;
  2135    constexpr char sent_data[kArbitrarySendSize] = {};
  2136    ASSERT_THAT(RetryEINTR(send)(client_.get(), sent_data, sizeof(sent_data), 0),
  2137                SyscallSucceedsWithValue(sizeof(sent_data)));
  2138  
  2139    char recv_data[sizeof(sent_data) + 1];
  2140    size_t recv_data_len = sizeof(recv_data);
  2141  
  2142    if (ClientAddressFamily() == AF_INET) {
  2143      uint8_t tos;
  2144      ASSERT_NO_FATAL_FAILURE(
  2145          RecvTOS(server_.get(), recv_data, &recv_data_len, &tos));
  2146      EXPECT_EQ(static_cast<int>(tos), kTOS);
  2147    } else {
  2148      int tclass;
  2149      ASSERT_NO_FATAL_FAILURE(
  2150          RecvTClass(server_.get(), recv_data, &recv_data_len, &tclass));
  2151      EXPECT_EQ(tclass, kTClass);
  2152    }
  2153    EXPECT_EQ(recv_data_len, sizeof(sent_data));
  2154  }
  2155  
  2156  TEST_P(UdpSocketControlMessagesTest, SendAndReceiveTOSorTClass) {
  2157    // TODO(b/146661005): Setting TOS via sendmsg is not supported by netstack.
  2158    SKIP_IF(IsRunningOnGvisor() && !IsRunningWithHostinet());
  2159  
  2160    // Enable receiving TOS and maybe TClass on the receiver.
  2161    ASSERT_THAT(setsockopt(server_.get(), SOL_IP, IP_RECVTOS, &kSockOptOn,
  2162                           sizeof(kSockOptOn)),
  2163                SyscallSucceeds());
  2164    if (ServerAddressFamily() == AF_INET6) {
  2165      ASSERT_THAT(setsockopt(server_.get(), SOL_IPV6, IPV6_RECVTCLASS,
  2166                             &kSockOptOn, sizeof(kSockOptOn)),
  2167                  SyscallSucceeds());
  2168    }
  2169  
  2170    constexpr uint8_t kSendCmsgValue = IPTOS_LOWDELAY;
  2171    constexpr size_t kArbitrarySendSize = 1024;
  2172    char sent_data[kArbitrarySendSize];
  2173    char recv_data[sizeof(sent_data) + 1];
  2174    size_t recv_data_len = sizeof(recv_data);
  2175  
  2176    if (ClientAddressFamily() == AF_INET) {
  2177      ASSERT_NO_FATAL_FAILURE(SendTOS(client_.get(), sent_data,
  2178                                      size_t(sizeof(sent_data)), kSendCmsgValue));
  2179      uint8_t tos;
  2180      ASSERT_NO_FATAL_FAILURE(
  2181          RecvTOS(server_.get(), recv_data, &recv_data_len, &tos));
  2182      EXPECT_EQ(static_cast<int>(tos), kSendCmsgValue);
  2183    } else {
  2184      ASSERT_NO_FATAL_FAILURE(SendTClass(
  2185          client_.get(), sent_data, size_t(sizeof(sent_data)), kSendCmsgValue));
  2186      int tclass;
  2187      ASSERT_NO_FATAL_FAILURE(
  2188          RecvTClass(server_.get(), recv_data, &recv_data_len, &tclass));
  2189      EXPECT_EQ(tclass, kSendCmsgValue);
  2190    }
  2191    EXPECT_EQ(recv_data_len, sizeof(sent_data));
  2192  }
  2193  
  2194  TEST_P(UdpSocketControlMessagesTest, SetAndReceiveTTLOrHopLimit) {
  2195    // Enable receiving TTL and maybe HOPLIMIT on the receiver.
  2196    ASSERT_THAT(setsockopt(server_.get(), SOL_IP, IP_RECVTTL, &kSockOptOn,
  2197                           sizeof(kSockOptOn)),
  2198                SyscallSucceeds());
  2199    if (ServerAddressFamily() == AF_INET6) {
  2200      ASSERT_THAT(setsockopt(server_.get(), SOL_IPV6, IPV6_RECVHOPLIMIT,
  2201                             &kSockOptOn, sizeof(kSockOptOn)),
  2202                  SyscallSucceeds());
  2203    }
  2204  
  2205    // Set custom TTL and maybe HOPLIMIT on the sender.
  2206    constexpr int kTTL = 21;
  2207    constexpr int kHopLimit = 42;
  2208    ASSERT_NE(kTTL, kHopLimit);
  2209  
  2210    ASSERT_THAT(setsockopt(client_.get(), SOL_IP, IP_TTL, &kTTL, sizeof(kTTL)),
  2211                SyscallSucceeds());
  2212    if (ClientAddressFamily() == AF_INET6) {
  2213      ASSERT_THAT(setsockopt(client_.get(), SOL_IPV6, IPV6_UNICAST_HOPS,
  2214                             &kHopLimit, sizeof(kHopLimit)),
  2215                  SyscallSucceeds());
  2216    }
  2217  
  2218    constexpr size_t kArbitrarySendSize = 1042;
  2219    constexpr char sent_data[kArbitrarySendSize] = {};
  2220    ASSERT_THAT(RetryEINTR(send)(client_.get(), sent_data, sizeof(sent_data), 0),
  2221                SyscallSucceedsWithValue(sizeof(sent_data)));
  2222  
  2223    char recv_data[sizeof(sent_data)];
  2224    size_t recv_data_len = sizeof(recv_data);
  2225  
  2226    if (ClientAddressFamily() == AF_INET) {
  2227      int ttl;
  2228      ASSERT_NO_FATAL_FAILURE(
  2229          RecvTTL(server_.get(), recv_data, &recv_data_len, &ttl));
  2230      EXPECT_EQ(ttl, kTTL);
  2231    } else {
  2232      int hoplimit;
  2233      ASSERT_NO_FATAL_FAILURE(
  2234          RecvHopLimit(server_.get(), recv_data, &recv_data_len, &hoplimit));
  2235      EXPECT_EQ(hoplimit, kHopLimit);
  2236    }
  2237    EXPECT_EQ(recv_data_len, sizeof(sent_data));
  2238  }
  2239  
  2240  TEST_P(UdpSocketControlMessagesTest, SendAndReceiveTTLOrHopLimit) {
  2241    // Enable receiving TTL and maybe HOPLIMIT on the receiver.
  2242    ASSERT_THAT(setsockopt(server_.get(), SOL_IP, IP_RECVTTL, &kSockOptOn,
  2243                           sizeof(kSockOptOn)),
  2244                SyscallSucceeds());
  2245    if (ServerAddressFamily() == AF_INET6) {
  2246      ASSERT_THAT(setsockopt(server_.get(), SOL_IPV6, IPV6_RECVHOPLIMIT,
  2247                             &kSockOptOn, sizeof(kSockOptOn)),
  2248                  SyscallSucceeds());
  2249    }
  2250  
  2251    constexpr int kSendCmsgValue = 42;
  2252    constexpr size_t kArbitrarySendSize = 1024;
  2253    char sent_data[kArbitrarySendSize];
  2254    char recv_data[sizeof(sent_data) + 1];
  2255    size_t recv_data_len = sizeof(recv_data);
  2256  
  2257    if (ClientAddressFamily() == AF_INET) {
  2258      ASSERT_NO_FATAL_FAILURE(SendTTL(client_.get(), sent_data,
  2259                                      size_t(sizeof(sent_data)), kSendCmsgValue));
  2260      int ttl;
  2261      ASSERT_NO_FATAL_FAILURE(
  2262          RecvTTL(server_.get(), recv_data, &recv_data_len, &ttl));
  2263      EXPECT_EQ(ttl, kSendCmsgValue);
  2264    } else {
  2265      ASSERT_NO_FATAL_FAILURE(SendHopLimit(
  2266          client_.get(), sent_data, size_t(sizeof(sent_data)), kSendCmsgValue));
  2267      int hoplimit;
  2268      ASSERT_NO_FATAL_FAILURE(
  2269          RecvHopLimit(server_.get(), recv_data, &recv_data_len, &hoplimit));
  2270      EXPECT_EQ(hoplimit, kSendCmsgValue);
  2271    }
  2272    EXPECT_EQ(recv_data_len, sizeof(sent_data));
  2273  }
  2274  
  2275  TEST_P(UdpSocketControlMessagesTest, SetAndReceivePktInfo) {
  2276    // Enable receiving IP_PKTINFO and maybe IPV6_PKTINFO on the receiver.
  2277    ASSERT_THAT(setsockopt(server_.get(), SOL_IP, IP_PKTINFO, &kSockOptOn,
  2278                           sizeof(kSockOptOn)),
  2279                SyscallSucceeds());
  2280    if (ServerAddressFamily() == AF_INET6) {
  2281      ASSERT_THAT(setsockopt(server_.get(), SOL_IPV6, IPV6_RECVPKTINFO,
  2282                             &kSockOptOn, sizeof(kSockOptOn)),
  2283                  SyscallSucceeds());
  2284    }
  2285  
  2286    constexpr size_t kArbitrarySendSize = 1042;
  2287    constexpr char sent_data[kArbitrarySendSize] = {};
  2288    ASSERT_THAT(RetryEINTR(send)(client_.get(), sent_data, sizeof(sent_data), 0),
  2289                SyscallSucceedsWithValue(sizeof(sent_data)));
  2290  
  2291    char recv_data[sizeof(sent_data) + 1];
  2292    size_t recv_data_len = sizeof(recv_data);
  2293    switch (GetParam()) {
  2294      case AddressFamily::kIpv4: {
  2295        in_pktinfo received_pktinfo;
  2296        ASSERT_NO_FATAL_FAILURE(RecvPktInfo(server_.get(), recv_data,
  2297                                            &recv_data_len, &received_pktinfo));
  2298        EXPECT_EQ(recv_data_len, sizeof(sent_data));
  2299        EXPECT_EQ(received_pktinfo.ipi_ifindex,
  2300                  ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()));
  2301        EXPECT_EQ(ntohl(received_pktinfo.ipi_spec_dst.s_addr), INADDR_LOOPBACK);
  2302        EXPECT_EQ(ntohl(received_pktinfo.ipi_addr.s_addr), INADDR_LOOPBACK);
  2303        break;
  2304      }
  2305  
  2306      case AddressFamily::kIpv6: {
  2307        in6_pktinfo received_pktinfo;
  2308        ASSERT_NO_FATAL_FAILURE(RecvIPv6PktInfo(
  2309            server_.get(), recv_data, &recv_data_len, &received_pktinfo));
  2310        EXPECT_EQ(recv_data_len, sizeof(sent_data));
  2311        EXPECT_EQ(received_pktinfo.ipi6_ifindex,
  2312                  ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()));
  2313        ASSERT_EQ(memcmp(&received_pktinfo.ipi6_addr, &in6addr_loopback,
  2314                         sizeof(in6addr_loopback)),
  2315                  0);
  2316        break;
  2317      }
  2318  
  2319      case AddressFamily::kDualStack: {
  2320        // TODO(https://gvisor.dev/issue/7144): On dual stack sockets, Linux can
  2321        // receive both the IPv4 and IPv6 packet info. gVisor should do the same.
  2322        iovec iov = {
  2323            iov.iov_base = recv_data,
  2324            iov.iov_len = recv_data_len,
  2325        };
  2326        // Add an extra byte to confirm we only read what we expected.
  2327        char control[CMSG_SPACE(sizeof(in_pktinfo)) +
  2328                     CMSG_SPACE(sizeof(in6_pktinfo)) + 1];
  2329        msghdr msg = {
  2330            .msg_iov = &iov,
  2331            .msg_iovlen = 1,
  2332            .msg_control = control,
  2333            .msg_controllen = sizeof(control),
  2334        };
  2335  
  2336        ASSERT_THAT(
  2337            recv_data_len = RetryEINTR(recvmsg)(server_.get(), &msg, /*flags=*/0),
  2338            SyscallSucceeds());
  2339        EXPECT_EQ(recv_data_len, sizeof(sent_data));
  2340        size_t expected_controllen = CMSG_SPACE(sizeof(in_pktinfo));
  2341        if (!IsRunningOnGvisor() || IsRunningWithHostinet()) {
  2342          expected_controllen += CMSG_SPACE(sizeof(in6_pktinfo));
  2343        }
  2344        EXPECT_EQ(msg.msg_controllen, expected_controllen);
  2345  
  2346        std::pair<in_pktinfo, bool> received_pktinfo;
  2347        std::pair<in6_pktinfo, bool> received_pktinfo6;
  2348  
  2349        struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg);
  2350        while (cmsg != nullptr) {
  2351          ASSERT_TRUE(cmsg->cmsg_level == SOL_IP || cmsg->cmsg_level == SOL_IPV6);
  2352          if (cmsg->cmsg_level == SOL_IP) {
  2353            ASSERT_FALSE(received_pktinfo.second);
  2354            ASSERT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(in_pktinfo)));
  2355            ASSERT_EQ(cmsg->cmsg_type, IP_PKTINFO);
  2356            received_pktinfo.second = true;
  2357            std::copy_n(CMSG_DATA(cmsg), sizeof(received_pktinfo.first),
  2358                        reinterpret_cast<uint8_t*>(&received_pktinfo.first));
  2359          } else {  // SOL_IPV6
  2360            ASSERT_FALSE(received_pktinfo6.second);
  2361            ASSERT_EQ(cmsg->cmsg_len, CMSG_LEN(sizeof(in6_pktinfo)));
  2362            ASSERT_EQ(cmsg->cmsg_type, IPV6_PKTINFO);
  2363            received_pktinfo6.second = true;
  2364            std::copy_n(CMSG_DATA(cmsg), sizeof(received_pktinfo6.first),
  2365                        reinterpret_cast<uint8_t*>(&received_pktinfo6.first));
  2366          }
  2367          cmsg = CMSG_NXTHDR(&msg, cmsg);
  2368        }
  2369  
  2370        ASSERT_TRUE(received_pktinfo.second);
  2371        EXPECT_EQ(received_pktinfo.first.ipi_ifindex,
  2372                  ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()));
  2373        EXPECT_EQ(ntohl(received_pktinfo.first.ipi_spec_dst.s_addr),
  2374                  INADDR_LOOPBACK);
  2375        EXPECT_EQ(ntohl(received_pktinfo.first.ipi_addr.s_addr), INADDR_LOOPBACK);
  2376  
  2377        if (!IsRunningOnGvisor() || IsRunningWithHostinet()) {
  2378          ASSERT_TRUE(received_pktinfo6.second);
  2379          EXPECT_EQ(received_pktinfo6.first.ipi6_ifindex,
  2380                    ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()));
  2381          struct in6_addr expected;
  2382          inet_pton(AF_INET6, "::ffff:127.0.0.1", &expected);
  2383          EXPECT_EQ(memcmp(&received_pktinfo6.first.ipi6_addr, &expected,
  2384                           sizeof(expected)),
  2385                    0);
  2386        } else {
  2387          ASSERT_FALSE(received_pktinfo6.second);
  2388        }
  2389  
  2390        break;
  2391      }
  2392    }
  2393  }
  2394  
  2395  TEST_P(UdpSocketTest, SendPacketLargerThanSendBufOnNonBlockingSocket) {
  2396    constexpr int kSendBufSize = 4096;
  2397    ASSERT_THAT(setsockopt(sock_.get(), SOL_SOCKET, SO_SNDBUF, &kSendBufSize,
  2398                           sizeof(kSendBufSize)),
  2399                SyscallSucceeds());
  2400  
  2401    // Set sock to non-blocking.
  2402    {
  2403      int opts = 0;
  2404      ASSERT_THAT(opts = fcntl(sock_.get(), F_GETFL), SyscallSucceeds());
  2405      ASSERT_THAT(fcntl(sock_.get(), F_SETFL, opts | O_NONBLOCK),
  2406                  SyscallSucceeds());
  2407    }
  2408  
  2409    {
  2410      sockaddr_storage addr = InetLoopbackAddr();
  2411      ASSERT_NO_ERRNO(BindSocket(sock_.get(), AsSockAddr(&addr)));
  2412    }
  2413  
  2414    sockaddr_storage addr;
  2415    socklen_t len = sizeof(sockaddr_storage);
  2416    ASSERT_THAT(getsockname(sock_.get(), AsSockAddr(&addr), &len),
  2417                SyscallSucceeds());
  2418    ASSERT_EQ(len, addrlen_);
  2419  
  2420    // We are allowed to send packets as large as we want as long as there is
  2421    // space in the send buffer, even if the new packet will result in more bytes
  2422    // being used than available in the send buffer.
  2423    char buf[kSendBufSize + 1];
  2424    ASSERT_THAT(
  2425        sendto(sock_.get(), buf, sizeof(buf), 0, AsSockAddr(&addr), sizeof(addr)),
  2426        SyscallSucceedsWithValue(sizeof(buf)));
  2427  
  2428    // The second write may fail with EAGAIN if the previous send is still
  2429    // in-flight.
  2430    ASSERT_THAT(
  2431        sendto(sock_.get(), buf, sizeof(buf), 0, AsSockAddr(&addr), sizeof(addr)),
  2432        AnyOf(SyscallSucceedsWithValue(sizeof(buf)),
  2433              SyscallFailsWithErrno(EAGAIN)));
  2434  }
  2435  
  2436  TEST_P(UdpSocketTest, ReadShutdownOnBoundSocket) {
  2437    ASSERT_NO_ERRNO(BindLoopback());
  2438  
  2439    // Bind `sock_` to loopback.
  2440    struct sockaddr_storage addr_storage = InetLoopbackAddr();
  2441    struct sockaddr* addr = AsSockAddr(&addr_storage);
  2442    ASSERT_NO_ERRNO(BindSocket(sock_.get(), addr));
  2443  
  2444    int shut_opts[] = {SHUT_RD, SHUT_WR, SHUT_RDWR};
  2445    for (int shut_opt : shut_opts) {
  2446      EXPECT_THAT(shutdown(sock_.get(), shut_opt),
  2447                  SyscallFailsWithErrno(ENOTCONN));
  2448    }
  2449  }
  2450  
  2451  TEST_P(UdpSocketTest, ReconnectDoesNotClearReadShutdown) {
  2452    // TODO(gvisor.dev/issue/1202): Reconnecting the UDP socket after shutdown
  2453    // fails on hostinet.
  2454    SKIP_IF(IsRunningWithHostinet());
  2455    ASSERT_NO_ERRNO(BindLoopback());
  2456    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  2457    ASSERT_THAT(shutdown(sock_.get(), SHUT_RD), SyscallSucceeds());
  2458  
  2459    char received[512];
  2460    EXPECT_THAT(recv(sock_.get(), received, sizeof(received), 0),
  2461                SyscallSucceedsWithValue(0));
  2462  
  2463    EXPECT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  2464    EXPECT_THAT(recv(sock_.get(), received, sizeof(received), 0),
  2465                SyscallSucceedsWithValue(0));
  2466  }
  2467  
  2468  TEST_P(UdpSocketTest, ReconnectDoesNotClearWriteShutdown) {
  2469    // TODO(gvisor.dev/issue/1202): Reconnecting the UDP socket after shutdown
  2470    // fails on hostinet.
  2471    SKIP_IF(IsRunningWithHostinet());
  2472    ASSERT_NO_ERRNO(BindLoopback());
  2473    ASSERT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  2474  
  2475    const char buf = 'A';
  2476    ASSERT_THAT(send(sock_.get(), &buf, 1, 0), SyscallSucceeds());
  2477  
  2478    ASSERT_THAT(shutdown(sock_.get(), SHUT_WR), SyscallSucceeds());
  2479    EXPECT_THAT(send(sock_.get(), &buf, 1, 0), SyscallFailsWithErrno(EPIPE));
  2480  
  2481    EXPECT_THAT(connect(sock_.get(), bind_addr_, addrlen_), SyscallSucceeds());
  2482    EXPECT_THAT(send(sock_.get(), &buf, 1, 0), SyscallFailsWithErrno(EPIPE));
  2483  }
  2484  
  2485  INSTANTIATE_TEST_SUITE_P(AllInetTests, UdpSocketControlMessagesTest,
  2486                           ::testing::Values(AddressFamily::kIpv4,
  2487                                             AddressFamily::kIpv6,
  2488                                             AddressFamily::kDualStack));
  2489  
  2490  TEST(UdpInet6SocketTest, ConnectInet4Sockaddr) {
  2491    // glibc getaddrinfo expects the invariant expressed by this test to be held.
  2492    const sockaddr_in connect_sockaddr = {
  2493        .sin_family = AF_INET, .sin_addr = {.s_addr = htonl(INADDR_LOOPBACK)}};
  2494    auto sock_ =
  2495        ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP));
  2496    ASSERT_THAT(
  2497        connect(sock_.get(),
  2498                reinterpret_cast<const struct sockaddr*>(&connect_sockaddr),
  2499                sizeof(sockaddr_in)),
  2500        SyscallSucceeds());
  2501    sockaddr_storage sockname;
  2502    socklen_t len = sizeof(sockaddr_storage);
  2503    ASSERT_THAT(getsockname(sock_.get(), AsSockAddr(&sockname), &len),
  2504                SyscallSucceeds());
  2505    ASSERT_EQ(sockname.ss_family, AF_INET6);
  2506    ASSERT_EQ(len, sizeof(sockaddr_in6));
  2507    auto sin6 = reinterpret_cast<struct sockaddr_in6*>(&sockname);
  2508    char addr_buf[INET6_ADDRSTRLEN];
  2509    const char* addr;
  2510    ASSERT_NE(addr = inet_ntop(sockname.ss_family, &sockname, addr_buf,
  2511                               sizeof(addr_buf)),
  2512              nullptr);
  2513    ASSERT_TRUE(IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) << addr;
  2514  }
  2515  
  2516  }  // namespace
  2517  
  2518  }  // namespace testing
  2519  }  // namespace gvisor