gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/test/syscalls/linux/socket_ipv4_udp_unbound.cc (about)

     1  // Copyright 2019 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 "test/syscalls/linux/socket_ipv4_udp_unbound.h"
    16  
    17  #include <arpa/inet.h>
    18  #include <sys/socket.h>
    19  #include <sys/types.h>
    20  #include <sys/un.h>
    21  
    22  #include <cstdio>
    23  #include <memory>
    24  
    25  #include "gtest/gtest.h"
    26  #include "absl/memory/memory.h"
    27  #include "test/syscalls/linux/ip_socket_test_util.h"
    28  #include "test/util/test_util.h"
    29  
    30  namespace gvisor {
    31  namespace testing {
    32  
    33  // Check that packets are not received without a group membership. Default send
    34  // interface configured by bind.
    35  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackNoGroup) {
    36    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
    37    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
    38  
    39    // Bind the first FD to the loopback. This is an alternative to
    40    // IP_MULTICAST_IF for setting the default send interface.
    41    auto sender_addr = V4Loopback();
    42    EXPECT_THAT(
    43        bind(socket1->get(), AsSockAddr(&sender_addr.addr), sender_addr.addr_len),
    44        SyscallSucceeds());
    45  
    46    // Bind the second FD to the v4 any address. If multicast worked like unicast,
    47    // this would ensure that we get the packet.
    48    auto receiver_addr = V4Any();
    49    EXPECT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
    50                     receiver_addr.addr_len),
    51                SyscallSucceeds());
    52    socklen_t receiver_addr_len = receiver_addr.addr_len;
    53    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
    54                            &receiver_addr_len),
    55                SyscallSucceeds());
    56    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
    57  
    58    // Send the multicast packet.
    59    auto send_addr = V4Multicast();
    60    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
    61        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
    62    char send_buf[200];
    63    RandomizeBuffer(send_buf, sizeof(send_buf));
    64    EXPECT_THAT(
    65        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
    66                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
    67        SyscallSucceedsWithValue(sizeof(send_buf)));
    68  
    69    // Check that we did not receive the multicast packet.
    70    char recv_buf[sizeof(send_buf)] = {};
    71    EXPECT_THAT(
    72        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
    73        PosixErrorIs(EAGAIN, ::testing::_));
    74  }
    75  
    76  // Check that not setting a default send interface prevents multicast packets
    77  // from being sent. Group membership interface configured by address.
    78  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackAddrNoDefaultSendIf) {
    79    // TODO(b/185517803): Fix for native test.
    80    SKIP_IF(!IsRunningOnGvisor());
    81    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
    82    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
    83  
    84    // Bind the second FD to the v4 any address to ensure that we can receive any
    85    // unicast packet.
    86    auto receiver_addr = V4Any();
    87    EXPECT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
    88                     receiver_addr.addr_len),
    89                SyscallSucceeds());
    90    socklen_t receiver_addr_len = receiver_addr.addr_len;
    91    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
    92                            &receiver_addr_len),
    93                SyscallSucceeds());
    94    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
    95  
    96    // Register to receive multicast packets.
    97    ip_mreq group = {};
    98    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
    99    group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   100    EXPECT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   101                           sizeof(group)),
   102                SyscallSucceeds());
   103  
   104    // Send a multicast packet.
   105    auto send_addr = V4Multicast();
   106    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   107        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   108    char send_buf[200];
   109    RandomizeBuffer(send_buf, sizeof(send_buf));
   110    EXPECT_THAT(
   111        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
   112                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
   113        SyscallFailsWithErrno(ENETUNREACH));
   114  }
   115  
   116  // Check that not setting a default send interface prevents multicast packets
   117  // from being sent. Group membership interface configured by NIC ID.
   118  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackNicNoDefaultSendIf) {
   119    // TODO(b/185517803): Fix for native test.
   120    SKIP_IF(!IsRunningOnGvisor());
   121    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   122    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   123  
   124    // Bind the second FD to the v4 any address to ensure that we can receive any
   125    // unicast packet.
   126    auto receiver_addr = V4Any();
   127    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
   128                     receiver_addr.addr_len),
   129                SyscallSucceeds());
   130    socklen_t receiver_addr_len = receiver_addr.addr_len;
   131    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
   132                            &receiver_addr_len),
   133                SyscallSucceeds());
   134    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   135  
   136    // Register to receive multicast packets.
   137    ip_mreqn group = {};
   138    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   139    group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   140    EXPECT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   141                           sizeof(group)),
   142                SyscallSucceeds());
   143  
   144    // Send a multicast packet.
   145    auto send_addr = V4Multicast();
   146    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   147        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   148    char send_buf[200];
   149    RandomizeBuffer(send_buf, sizeof(send_buf));
   150    EXPECT_THAT(
   151        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
   152                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
   153        SyscallFailsWithErrno(ENETUNREACH));
   154  }
   155  
   156  // Check that multicast works when the default send interface is configured by
   157  // bind and the group membership is configured by address.
   158  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackAddr) {
   159    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   160    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   161  
   162    // Bind the first FD to the loopback. This is an alternative to
   163    // IP_MULTICAST_IF for setting the default send interface.
   164    auto sender_addr = V4Loopback();
   165    ASSERT_THAT(
   166        bind(socket1->get(), AsSockAddr(&sender_addr.addr), sender_addr.addr_len),
   167        SyscallSucceeds());
   168  
   169    // Bind the second FD to the v4 any address to ensure that we can receive the
   170    // multicast packet.
   171    auto receiver_addr = V4Any();
   172    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
   173                     receiver_addr.addr_len),
   174                SyscallSucceeds());
   175    socklen_t receiver_addr_len = receiver_addr.addr_len;
   176    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
   177                            &receiver_addr_len),
   178                SyscallSucceeds());
   179    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   180  
   181    // Register to receive multicast packets.
   182    ip_mreq group = {};
   183    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   184    group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   185    ASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   186                           sizeof(group)),
   187                SyscallSucceeds());
   188  
   189    // Send a multicast packet.
   190    auto send_addr = V4Multicast();
   191    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   192        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   193    char send_buf[200];
   194    RandomizeBuffer(send_buf, sizeof(send_buf));
   195    ASSERT_THAT(
   196        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
   197                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
   198        SyscallSucceedsWithValue(sizeof(send_buf)));
   199  
   200    // Check that we received the multicast packet.
   201    char recv_buf[sizeof(send_buf)] = {};
   202    ASSERT_THAT(
   203        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   204        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
   205  
   206    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
   207  }
   208  
   209  // Check that multicast works when the default send interface is configured by
   210  // bind and the group membership is configured by NIC ID.
   211  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackNic) {
   212    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   213    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   214  
   215    // Bind the first FD to the loopback. This is an alternative to
   216    // IP_MULTICAST_IF for setting the default send interface.
   217    auto sender_addr = V4Loopback();
   218    ASSERT_THAT(
   219        bind(socket1->get(), AsSockAddr(&sender_addr.addr), sender_addr.addr_len),
   220        SyscallSucceeds());
   221  
   222    // Bind the second FD to the v4 any address to ensure that we can receive the
   223    // multicast packet.
   224    auto receiver_addr = V4Any();
   225    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
   226                     receiver_addr.addr_len),
   227                SyscallSucceeds());
   228    socklen_t receiver_addr_len = receiver_addr.addr_len;
   229    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
   230                            &receiver_addr_len),
   231                SyscallSucceeds());
   232    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   233  
   234    // Register to receive multicast packets.
   235    ip_mreqn group = {};
   236    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   237    group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   238    ASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   239                           sizeof(group)),
   240                SyscallSucceeds());
   241  
   242    // Send a multicast packet.
   243    auto send_addr = V4Multicast();
   244    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   245        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   246    char send_buf[200];
   247    RandomizeBuffer(send_buf, sizeof(send_buf));
   248    ASSERT_THAT(
   249        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
   250                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
   251        SyscallSucceedsWithValue(sizeof(send_buf)));
   252  
   253    // Check that we received the multicast packet.
   254    char recv_buf[sizeof(send_buf)] = {};
   255    ASSERT_THAT(
   256        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   257        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
   258  
   259    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
   260  }
   261  
   262  // Check that multicast works when an interface identifier and address are
   263  // provided for multicast registration. The interface should take priority.
   264  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfaceIndexAndAddr) {
   265    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   266    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   267  
   268    // Bind the first FD to the loopback. This is an alternative to
   269    // IP_MULTICAST_IF for setting the default send interface.
   270    auto sender_addr = V4Loopback();
   271    ASSERT_THAT(
   272        bind(socket1->get(), AsSockAddr(&sender_addr.addr), sender_addr.addr_len),
   273        SyscallSucceeds());
   274  
   275    // Bind the second FD to the v4 any address to ensure that we can receive the
   276    // multicast packet.
   277    auto receiver_addr = V4Any();
   278    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
   279                     receiver_addr.addr_len),
   280                SyscallSucceeds());
   281    socklen_t receiver_addr_len = receiver_addr.addr_len;
   282    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
   283                            &receiver_addr_len),
   284                SyscallSucceeds());
   285    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   286  
   287    // Register to receive multicast packets.
   288    ip_mreqn group = {};
   289    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   290    group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   291    // Intentionally use an address that isn't assigned to the loopback device.
   292    // The index should take precedence.
   293    group.imr_address.s_addr = htonl(0x08080808);
   294    ASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   295                           sizeof(group)),
   296                SyscallSucceeds());
   297  
   298    // Send a multicast packet.
   299    auto send_addr = V4Multicast();
   300    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   301        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   302    char send_buf[200];
   303    RandomizeBuffer(send_buf, sizeof(send_buf));
   304    ASSERT_THAT(
   305        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
   306                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
   307        SyscallSucceedsWithValue(sizeof(send_buf)));
   308  
   309    // Check that we received the multicast packet.
   310    char recv_buf[sizeof(send_buf)] = {};
   311    ASSERT_THAT(
   312        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   313        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
   314  
   315    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
   316  }
   317  
   318  // Check that multicast works when the default send interface is configured by
   319  // IP_MULTICAST_IF, the send address is specified in sendto, and the group
   320  // membership is configured by address.
   321  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfAddr) {
   322    // TODO(b/267210840): Get multicast working with hostinet.
   323    SKIP_IF(IsRunningWithHostinet());
   324  
   325    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   326    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   327  
   328    // Set the default send interface.
   329    ip_mreq iface = {};
   330    iface.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   331    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,
   332                           sizeof(iface)),
   333                SyscallSucceeds());
   334  
   335    // Bind the second FD to the v4 any address to ensure that we can receive the
   336    // multicast packet.
   337    auto receiver_addr = V4Any();
   338    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
   339                     receiver_addr.addr_len),
   340                SyscallSucceeds());
   341    socklen_t receiver_addr_len = receiver_addr.addr_len;
   342    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
   343                            &receiver_addr_len),
   344                SyscallSucceeds());
   345    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   346  
   347    // Register to receive multicast packets.
   348    ip_mreq group = {};
   349    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   350    group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   351    ASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   352                           sizeof(group)),
   353                SyscallSucceeds());
   354  
   355    // Send a multicast packet.
   356    auto send_addr = V4Multicast();
   357    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   358        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   359    char send_buf[200];
   360    RandomizeBuffer(send_buf, sizeof(send_buf));
   361    ASSERT_THAT(
   362        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
   363                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
   364        SyscallSucceedsWithValue(sizeof(send_buf)));
   365  
   366    // Check that we received the multicast packet.
   367    char recv_buf[sizeof(send_buf)] = {};
   368    ASSERT_THAT(
   369        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   370        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
   371  
   372    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
   373  }
   374  
   375  // Check that multicast works when the default send interface is configured by
   376  // IP_MULTICAST_IF, the send address is specified in sendto, and the group
   377  // membership is configured by NIC ID.
   378  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNic) {
   379    // TODO(b/267210840): Get multicast working with hostinet.
   380    SKIP_IF(IsRunningWithHostinet());
   381  
   382    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   383    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   384  
   385    // Set the default send interface.
   386    ip_mreqn iface = {};
   387    iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   388    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,
   389                           sizeof(iface)),
   390                SyscallSucceeds());
   391  
   392    // Bind the second FD to the v4 any address to ensure that we can receive the
   393    // multicast packet.
   394    auto receiver_addr = V4Any();
   395    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
   396                     receiver_addr.addr_len),
   397                SyscallSucceeds());
   398    socklen_t receiver_addr_len = receiver_addr.addr_len;
   399    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
   400                            &receiver_addr_len),
   401                SyscallSucceeds());
   402    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   403  
   404    // Register to receive multicast packets.
   405    ip_mreqn group = {};
   406    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   407    group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   408    ASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   409                           sizeof(group)),
   410                SyscallSucceeds());
   411  
   412    // Send a multicast packet.
   413    auto send_addr = V4Multicast();
   414    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   415        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   416    char send_buf[200];
   417    RandomizeBuffer(send_buf, sizeof(send_buf));
   418    ASSERT_THAT(
   419        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
   420                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
   421        SyscallSucceedsWithValue(sizeof(send_buf)));
   422  
   423    // Check that we received the multicast packet.
   424    char recv_buf[sizeof(send_buf)] = {};
   425    ASSERT_THAT(
   426        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   427        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
   428  
   429    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
   430  }
   431  
   432  // Check that multicast works when the default send interface is configured by
   433  // IP_MULTICAST_IF, the send address is specified in connect, and the group
   434  // membership is configured by address.
   435  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfAddrConnect) {
   436    // TODO(b/267210840): Get multicast working with hostinet.
   437    SKIP_IF(IsRunningWithHostinet());
   438  
   439    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   440    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   441  
   442    // Set the default send interface.
   443    ip_mreq iface = {};
   444    iface.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   445    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,
   446                           sizeof(iface)),
   447                SyscallSucceeds());
   448  
   449    // Bind the second FD to the v4 any address to ensure that we can receive the
   450    // multicast packet.
   451    auto receiver_addr = V4Any();
   452    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
   453                     receiver_addr.addr_len),
   454                SyscallSucceeds());
   455    socklen_t receiver_addr_len = receiver_addr.addr_len;
   456    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
   457                            &receiver_addr_len),
   458                SyscallSucceeds());
   459    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   460  
   461    // Register to receive multicast packets.
   462    ip_mreq group = {};
   463    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   464    group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   465    ASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   466                           sizeof(group)),
   467                SyscallSucceeds());
   468  
   469    // Send a multicast packet.
   470    auto connect_addr = V4Multicast();
   471    reinterpret_cast<sockaddr_in*>(&connect_addr.addr)->sin_port =
   472        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   473    ASSERT_THAT(
   474        RetryEINTR(connect)(socket1->get(), AsSockAddr(&connect_addr.addr),
   475                            connect_addr.addr_len),
   476        SyscallSucceeds());
   477  
   478    char send_buf[200];
   479    RandomizeBuffer(send_buf, sizeof(send_buf));
   480    ASSERT_THAT(RetryEINTR(send)(socket1->get(), send_buf, sizeof(send_buf), 0),
   481                SyscallSucceedsWithValue(sizeof(send_buf)));
   482  
   483    // Check that we received the multicast packet.
   484    char recv_buf[sizeof(send_buf)] = {};
   485    ASSERT_THAT(
   486        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   487        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
   488  
   489    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
   490  }
   491  
   492  // Check that multicast works when the default send interface is configured by
   493  // IP_MULTICAST_IF, the send address is specified in connect, and the group
   494  // membership is configured by NIC ID.
   495  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicConnect) {
   496    // TODO(b/267210840): Get multicast working with hostinet.
   497    SKIP_IF(IsRunningWithHostinet());
   498  
   499    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   500    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   501  
   502    // Set the default send interface.
   503    ip_mreqn iface = {};
   504    iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   505    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,
   506                           sizeof(iface)),
   507                SyscallSucceeds());
   508  
   509    // Bind the second FD to the v4 any address to ensure that we can receive the
   510    // multicast packet.
   511    auto receiver_addr = V4Any();
   512    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
   513                     receiver_addr.addr_len),
   514                SyscallSucceeds());
   515    socklen_t receiver_addr_len = receiver_addr.addr_len;
   516    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
   517                            &receiver_addr_len),
   518                SyscallSucceeds());
   519    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   520  
   521    // Register to receive multicast packets.
   522    ip_mreqn group = {};
   523    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   524    group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   525    ASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   526                           sizeof(group)),
   527                SyscallSucceeds());
   528  
   529    // Send a multicast packet.
   530    auto connect_addr = V4Multicast();
   531    reinterpret_cast<sockaddr_in*>(&connect_addr.addr)->sin_port =
   532        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   533    ASSERT_THAT(
   534        RetryEINTR(connect)(socket1->get(), AsSockAddr(&connect_addr.addr),
   535                            connect_addr.addr_len),
   536        SyscallSucceeds());
   537  
   538    char send_buf[200];
   539    RandomizeBuffer(send_buf, sizeof(send_buf));
   540    ASSERT_THAT(RetryEINTR(send)(socket1->get(), send_buf, sizeof(send_buf), 0),
   541                SyscallSucceedsWithValue(sizeof(send_buf)));
   542  
   543    // Check that we received the multicast packet.
   544    char recv_buf[sizeof(send_buf)] = {};
   545    ASSERT_THAT(
   546        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   547        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
   548  
   549    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
   550  }
   551  
   552  // Check that multicast works when the default send interface is configured by
   553  // IP_MULTICAST_IF, the send address is specified in sendto, and the group
   554  // membership is configured by address.
   555  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfAddrSelf) {
   556    // TODO(b/267210840): Get multicast working with hostinet.
   557    SKIP_IF(IsRunningWithHostinet());
   558  
   559    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   560    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   561  
   562    // Set the default send interface.
   563    ip_mreq iface = {};
   564    iface.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   565    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,
   566                           sizeof(iface)),
   567                SyscallSucceeds());
   568  
   569    // Bind the first FD to the v4 any address to ensure that we can receive the
   570    // multicast packet.
   571    auto receiver_addr = V4Any();
   572    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&receiver_addr.addr),
   573                     receiver_addr.addr_len),
   574                SyscallSucceeds());
   575    socklen_t receiver_addr_len = receiver_addr.addr_len;
   576    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&receiver_addr.addr),
   577                            &receiver_addr_len),
   578                SyscallSucceeds());
   579    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   580  
   581    // Register to receive multicast packets.
   582    ip_mreq group = {};
   583    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   584    group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   585    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   586                           sizeof(group)),
   587                SyscallSucceeds());
   588  
   589    // Send a multicast packet.
   590    auto send_addr = V4Multicast();
   591    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   592        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   593    char send_buf[200];
   594    RandomizeBuffer(send_buf, sizeof(send_buf));
   595    ASSERT_THAT(
   596        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
   597                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
   598        SyscallSucceedsWithValue(sizeof(send_buf)));
   599  
   600    // Check that we received the multicast packet.
   601    char recv_buf[sizeof(send_buf)] = {};
   602    ASSERT_THAT(
   603        RecvTimeout(socket1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   604        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
   605  
   606    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
   607  }
   608  
   609  // Check that multicast works when the default send interface is configured by
   610  // IP_MULTICAST_IF, the send address is specified in sendto, and the group
   611  // membership is configured by NIC ID.
   612  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicSelf) {
   613    // TODO(b/267210840): Get multicast working with hostinet.
   614    SKIP_IF(IsRunningWithHostinet());
   615  
   616    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   617    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   618  
   619    // Set the default send interface.
   620    ip_mreqn iface = {};
   621    iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   622    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,
   623                           sizeof(iface)),
   624                SyscallSucceeds());
   625  
   626    // Bind the first FD to the v4 any address to ensure that we can receive the
   627    // multicast packet.
   628    auto receiver_addr = V4Any();
   629    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&receiver_addr.addr),
   630                     receiver_addr.addr_len),
   631                SyscallSucceeds());
   632    socklen_t receiver_addr_len = receiver_addr.addr_len;
   633    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&receiver_addr.addr),
   634                            &receiver_addr_len),
   635                SyscallSucceeds());
   636    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   637  
   638    // Register to receive multicast packets.
   639    ip_mreqn group = {};
   640    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   641    group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   642    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   643                           sizeof(group)),
   644                SyscallSucceeds());
   645  
   646    // Send a multicast packet.
   647    auto send_addr = V4Multicast();
   648    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   649        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   650    char send_buf[200];
   651    RandomizeBuffer(send_buf, sizeof(send_buf));
   652    ASSERT_THAT(
   653        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
   654                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
   655        SyscallSucceedsWithValue(sizeof(send_buf)));
   656  
   657    // Check that we received the multicast packet.
   658    char recv_buf[sizeof(send_buf)] = {};
   659    ASSERT_THAT(
   660        RecvTimeout(socket1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   661        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
   662  
   663    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
   664  }
   665  
   666  // Check that multicast works when the default send interface is configured by
   667  // IP_MULTICAST_IF, the send address is specified in connect, and the group
   668  // membership is configured by address.
   669  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfAddrSelfConnect) {
   670    // TODO(b/267210840): Get multicast working with hostinet.
   671    SKIP_IF(IsRunningWithHostinet());
   672  
   673    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   674    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   675  
   676    // Set the default send interface.
   677    ip_mreq iface = {};
   678    iface.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   679    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,
   680                           sizeof(iface)),
   681                SyscallSucceeds());
   682  
   683    // Bind the first FD to the v4 any address to ensure that we can receive the
   684    // multicast packet.
   685    auto receiver_addr = V4Any();
   686    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&receiver_addr.addr),
   687                     receiver_addr.addr_len),
   688                SyscallSucceeds());
   689    socklen_t receiver_addr_len = receiver_addr.addr_len;
   690    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&receiver_addr.addr),
   691                            &receiver_addr_len),
   692                SyscallSucceeds());
   693    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   694  
   695    // Register to receive multicast packets.
   696    ip_mreq group = {};
   697    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   698    group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   699    EXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   700                           sizeof(group)),
   701                SyscallSucceeds());
   702  
   703    // Send a multicast packet.
   704    auto connect_addr = V4Multicast();
   705    reinterpret_cast<sockaddr_in*>(&connect_addr.addr)->sin_port =
   706        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   707    EXPECT_THAT(
   708        RetryEINTR(connect)(socket1->get(), AsSockAddr(&connect_addr.addr),
   709                            connect_addr.addr_len),
   710        SyscallSucceeds());
   711  
   712    char send_buf[200];
   713    RandomizeBuffer(send_buf, sizeof(send_buf));
   714    ASSERT_THAT(RetryEINTR(send)(socket1->get(), send_buf, sizeof(send_buf), 0),
   715                SyscallSucceedsWithValue(sizeof(send_buf)));
   716  
   717    // Check that we did not receive the multicast packet.
   718    char recv_buf[sizeof(send_buf)] = {};
   719    EXPECT_THAT(
   720        RecvTimeout(socket1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   721        PosixErrorIs(EAGAIN, ::testing::_));
   722  }
   723  
   724  // Check that multicast works when the default send interface is configured by
   725  // IP_MULTICAST_IF, the send address is specified in connect, and the group
   726  // membership is configured by NIC ID.
   727  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicSelfConnect) {
   728    // TODO(b/267210840): Get multicast working with hostinet.
   729    SKIP_IF(IsRunningWithHostinet());
   730  
   731    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   732    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   733  
   734    // Set the default send interface.
   735    ip_mreqn iface = {};
   736    iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   737    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,
   738                           sizeof(iface)),
   739                SyscallSucceeds());
   740  
   741    // Bind the first FD to the v4 any address to ensure that we can receive the
   742    // multicast packet.
   743    auto receiver_addr = V4Any();
   744    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&receiver_addr.addr),
   745                     receiver_addr.addr_len),
   746                SyscallSucceeds());
   747    socklen_t receiver_addr_len = receiver_addr.addr_len;
   748    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&receiver_addr.addr),
   749                            &receiver_addr_len),
   750                SyscallSucceeds());
   751    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   752  
   753    // Register to receive multicast packets.
   754    ip_mreqn group = {};
   755    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   756    group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   757    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   758                           sizeof(group)),
   759                SyscallSucceeds());
   760  
   761    // Send a multicast packet.
   762    auto connect_addr = V4Multicast();
   763    reinterpret_cast<sockaddr_in*>(&connect_addr.addr)->sin_port =
   764        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   765    ASSERT_THAT(
   766        RetryEINTR(connect)(socket1->get(), AsSockAddr(&connect_addr.addr),
   767                            connect_addr.addr_len),
   768        SyscallSucceeds());
   769  
   770    char send_buf[200];
   771    RandomizeBuffer(send_buf, sizeof(send_buf));
   772    ASSERT_THAT(RetryEINTR(send)(socket1->get(), send_buf, sizeof(send_buf), 0),
   773                SyscallSucceedsWithValue(sizeof(send_buf)));
   774  
   775    // Check that we did not receive the multicast packet.
   776    char recv_buf[sizeof(send_buf)] = {};
   777    EXPECT_THAT(
   778        RecvTimeout(socket1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   779        PosixErrorIs(EAGAIN, ::testing::_));
   780  }
   781  
   782  // Check that multicast works when the default send interface is configured by
   783  // IP_MULTICAST_IF, the send address is specified in sendto, and the group
   784  // membership is configured by address.
   785  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfAddrSelfNoLoop) {
   786    // TODO(b/267210840): Get multicast working with hostinet.
   787    SKIP_IF(IsRunningWithHostinet());
   788  
   789    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   790    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   791  
   792    // Set the default send interface.
   793    ip_mreq iface = {};
   794    iface.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   795    EXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,
   796                           sizeof(iface)),
   797                SyscallSucceeds());
   798  
   799    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_LOOP,
   800                           &kSockOptOff, sizeof(kSockOptOff)),
   801                SyscallSucceeds());
   802  
   803    // Bind the first FD to the v4 any address to ensure that we can receive the
   804    // multicast packet.
   805    auto receiver_addr = V4Any();
   806    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&receiver_addr.addr),
   807                     receiver_addr.addr_len),
   808                SyscallSucceeds());
   809    socklen_t receiver_addr_len = receiver_addr.addr_len;
   810    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&receiver_addr.addr),
   811                            &receiver_addr_len),
   812                SyscallSucceeds());
   813    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   814  
   815    // Register to receive multicast packets.
   816    ip_mreq group = {};
   817    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   818    group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   819    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   820                           sizeof(group)),
   821                SyscallSucceeds());
   822  
   823    // Send a multicast packet.
   824    auto send_addr = V4Multicast();
   825    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   826        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   827    char send_buf[200];
   828    RandomizeBuffer(send_buf, sizeof(send_buf));
   829    ASSERT_THAT(
   830        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
   831                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
   832        SyscallSucceedsWithValue(sizeof(send_buf)));
   833  
   834    // Check that we received the multicast packet.
   835    char recv_buf[sizeof(send_buf)] = {};
   836    ASSERT_THAT(
   837        RecvTimeout(socket1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   838        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
   839  
   840    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
   841  }
   842  
   843  // Check that multicast works when the default send interface is configured by
   844  // IP_MULTICAST_IF, the send address is specified in sendto, and the group
   845  // membership is configured by NIC ID.
   846  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastLoopbackIfNicSelfNoLoop) {
   847    // TODO(b/267210840): Get multicast working with hostinet.
   848    SKIP_IF(IsRunningWithHostinet());
   849  
   850    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   851    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   852  
   853    // Set the default send interface.
   854    ip_mreqn iface = {};
   855    iface.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   856    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,
   857                           sizeof(iface)),
   858                SyscallSucceeds());
   859  
   860    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_LOOP,
   861                           &kSockOptOff, sizeof(kSockOptOff)),
   862                SyscallSucceeds());
   863  
   864    // Bind the second FD to the v4 any address to ensure that we can receive the
   865    // multicast packet.
   866    auto receiver_addr = V4Any();
   867    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&receiver_addr.addr),
   868                     receiver_addr.addr_len),
   869                SyscallSucceeds());
   870    socklen_t receiver_addr_len = receiver_addr.addr_len;
   871    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&receiver_addr.addr),
   872                            &receiver_addr_len),
   873                SyscallSucceeds());
   874    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   875  
   876    // Register to receive multicast packets.
   877    ip_mreqn group = {};
   878    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   879    group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   880    EXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   881                           sizeof(group)),
   882                SyscallSucceeds());
   883  
   884    // Send a multicast packet.
   885    auto send_addr = V4Multicast();
   886    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   887        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   888    char send_buf[200];
   889    RandomizeBuffer(send_buf, sizeof(send_buf));
   890    ASSERT_THAT(
   891        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
   892                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
   893        SyscallSucceedsWithValue(sizeof(send_buf)));
   894  
   895    // Check that we received the multicast packet.
   896    char recv_buf[sizeof(send_buf)] = {};
   897    ASSERT_THAT(
   898        RecvTimeout(socket1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   899        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
   900  
   901    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
   902  }
   903  
   904  // Check that dropping a group membership prevents multicast packets from being
   905  // delivered. Default send address configured by bind and group membership
   906  // interface configured by address.
   907  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastDropAddr) {
   908    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   909    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   910  
   911    // Bind the first FD to the loopback. This is an alternative to
   912    // IP_MULTICAST_IF for setting the default send interface.
   913    auto sender_addr = V4Loopback();
   914    EXPECT_THAT(
   915        bind(socket1->get(), AsSockAddr(&sender_addr.addr), sender_addr.addr_len),
   916        SyscallSucceeds());
   917  
   918    // Bind the second FD to the v4 any address to ensure that we can receive the
   919    // multicast packet.
   920    auto receiver_addr = V4Any();
   921    EXPECT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
   922                     receiver_addr.addr_len),
   923                SyscallSucceeds());
   924    socklen_t receiver_addr_len = receiver_addr.addr_len;
   925    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
   926                            &receiver_addr_len),
   927                SyscallSucceeds());
   928    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   929  
   930    // Register and unregister to receive multicast packets.
   931    ip_mreq group = {};
   932    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   933    group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
   934    EXPECT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   935                           sizeof(group)),
   936                SyscallSucceeds());
   937    EXPECT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_DROP_MEMBERSHIP, &group,
   938                           sizeof(group)),
   939                SyscallSucceeds());
   940  
   941    // Send a multicast packet.
   942    auto send_addr = V4Multicast();
   943    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   944        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
   945    char send_buf[200];
   946    RandomizeBuffer(send_buf, sizeof(send_buf));
   947    EXPECT_THAT(
   948        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
   949                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
   950        SyscallSucceedsWithValue(sizeof(send_buf)));
   951  
   952    // Check that we did not receive the multicast packet.
   953    char recv_buf[sizeof(send_buf)] = {};
   954    EXPECT_THAT(
   955        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
   956        PosixErrorIs(EAGAIN, ::testing::_));
   957  }
   958  
   959  // Check that dropping a group membership prevents multicast packets from being
   960  // delivered. Default send address configured by bind and group membership
   961  // interface configured by NIC ID.
   962  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastDropNic) {
   963    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   964    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
   965  
   966    // Bind the first FD to the loopback. This is an alternative to
   967    // IP_MULTICAST_IF for setting the default send interface.
   968    auto sender_addr = V4Loopback();
   969    EXPECT_THAT(
   970        bind(socket1->get(), AsSockAddr(&sender_addr.addr), sender_addr.addr_len),
   971        SyscallSucceeds());
   972  
   973    // Bind the second FD to the v4 any address to ensure that we can receive the
   974    // multicast packet.
   975    auto receiver_addr = V4Any();
   976    EXPECT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
   977                     receiver_addr.addr_len),
   978                SyscallSucceeds());
   979    socklen_t receiver_addr_len = receiver_addr.addr_len;
   980    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
   981                            &receiver_addr_len),
   982                SyscallSucceeds());
   983    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
   984  
   985    // Register and unregister to receive multicast packets.
   986    ip_mreqn group = {};
   987    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
   988    group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
   989    EXPECT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
   990                           sizeof(group)),
   991                SyscallSucceeds());
   992    EXPECT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_DROP_MEMBERSHIP, &group,
   993                           sizeof(group)),
   994                SyscallSucceeds());
   995  
   996    // Send a multicast packet.
   997    auto send_addr = V4Multicast();
   998    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
   999        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
  1000    char send_buf[200];
  1001    RandomizeBuffer(send_buf, sizeof(send_buf));
  1002    EXPECT_THAT(
  1003        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
  1004                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
  1005        SyscallSucceedsWithValue(sizeof(send_buf)));
  1006  
  1007    // Check that we did not receive the multicast packet.
  1008    char recv_buf[sizeof(send_buf)] = {};
  1009    EXPECT_THAT(
  1010        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
  1011        PosixErrorIs(EAGAIN, ::testing::_));
  1012  }
  1013  
  1014  // Check that two sockets can join the same multicast group at the same time.
  1015  TEST_P(IPv4UDPUnboundSocketTest, TestTwoSocketsJoinSameMulticastGroup) {
  1016    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1017    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1018  
  1019    ip_mreqn group = {};
  1020    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
  1021    group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
  1022    EXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
  1023                           sizeof(group)),
  1024                SyscallSucceeds());
  1025    EXPECT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
  1026                           sizeof(group)),
  1027                SyscallSucceeds());
  1028  
  1029    // Drop the membership twice on each socket, the second call for each socket
  1030    // should fail.
  1031    EXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_DROP_MEMBERSHIP, &group,
  1032                           sizeof(group)),
  1033                SyscallSucceeds());
  1034    EXPECT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_DROP_MEMBERSHIP, &group,
  1035                           sizeof(group)),
  1036                SyscallFailsWithErrno(EADDRNOTAVAIL));
  1037    EXPECT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_DROP_MEMBERSHIP, &group,
  1038                           sizeof(group)),
  1039                SyscallSucceeds());
  1040    EXPECT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_DROP_MEMBERSHIP, &group,
  1041                           sizeof(group)),
  1042                SyscallFailsWithErrno(EADDRNOTAVAIL));
  1043  }
  1044  
  1045  // Check that two sockets can join the same multicast group at the same time,
  1046  // and both will receive data on it.
  1047  TEST_P(IPv4UDPUnboundSocketTest, TestMcastReceptionOnTwoSockets) {
  1048    // TODO(b/267210840): Get multicast working with hostinet.
  1049    SKIP_IF(IsRunningWithHostinet());
  1050  
  1051    std::unique_ptr<SocketPair> socket_pairs[2] = {
  1052        std::make_unique<FDSocketPair>(ASSERT_NO_ERRNO_AND_VALUE(NewSocket()),
  1053                                       ASSERT_NO_ERRNO_AND_VALUE(NewSocket())),
  1054        std::make_unique<FDSocketPair>(ASSERT_NO_ERRNO_AND_VALUE(NewSocket()),
  1055                                       ASSERT_NO_ERRNO_AND_VALUE(NewSocket()))};
  1056  
  1057    ip_mreq iface = {}, group = {};
  1058    iface.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
  1059    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
  1060    group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
  1061    auto receiver_addr = V4Any();
  1062    int bound_port = 0;
  1063  
  1064    // Create two socketpairs with the exact same configuration.
  1065    for (auto& sockets : socket_pairs) {
  1066      ASSERT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF,
  1067                             &iface, sizeof(iface)),
  1068                  SyscallSucceeds());
  1069      ASSERT_THAT(setsockopt(sockets->second_fd(), SOL_SOCKET, SO_REUSEPORT,
  1070                             &kSockOptOn, sizeof(kSockOptOn)),
  1071                  SyscallSucceeds());
  1072      ASSERT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,
  1073                             &group, sizeof(group)),
  1074                  SyscallSucceeds());
  1075      ASSERT_THAT(bind(sockets->second_fd(), AsSockAddr(&receiver_addr.addr),
  1076                       receiver_addr.addr_len),
  1077                  SyscallSucceeds());
  1078      // Get the port assigned.
  1079      socklen_t receiver_addr_len = receiver_addr.addr_len;
  1080      ASSERT_THAT(
  1081          getsockname(sockets->second_fd(), AsSockAddr(&receiver_addr.addr),
  1082                      &receiver_addr_len),
  1083          SyscallSucceeds());
  1084      EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
  1085      // On the first iteration, save the port we are bound to. On the second
  1086      // iteration, verify the port is the same as the one from the first
  1087      // iteration. In other words, both sockets listen on the same port.
  1088      if (bound_port == 0) {
  1089        bound_port =
  1090            reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
  1091      } else {
  1092        EXPECT_EQ(bound_port,
  1093                  reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port);
  1094      }
  1095    }
  1096  
  1097    // Send a multicast packet to the group from two different sockets and verify
  1098    // it is received by both sockets that joined that group.
  1099    auto send_addr = V4Multicast();
  1100    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port = bound_port;
  1101    for (auto& sockets : socket_pairs) {
  1102      char send_buf[200];
  1103      RandomizeBuffer(send_buf, sizeof(send_buf));
  1104      ASSERT_THAT(
  1105          RetryEINTR(sendto)(sockets->first_fd(), send_buf, sizeof(send_buf), 0,
  1106                             AsSockAddr(&send_addr.addr), send_addr.addr_len),
  1107          SyscallSucceedsWithValue(sizeof(send_buf)));
  1108  
  1109      // Check that we received the multicast packet on both sockets.
  1110      for (auto& sockets : socket_pairs) {
  1111        char recv_buf[sizeof(send_buf)] = {};
  1112        ASSERT_THAT(RecvTimeout(sockets->second_fd(), recv_buf, sizeof(recv_buf),
  1113                                1 /*timeout*/),
  1114                    IsPosixErrorOkAndHolds(sizeof(recv_buf)));
  1115        EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
  1116      }
  1117    }
  1118  }
  1119  
  1120  // Check that on two sockets that joined a group and listen on ANY, dropping
  1121  // memberships one by one will continue to deliver packets to both sockets until
  1122  // both memberships have been dropped.
  1123  TEST_P(IPv4UDPUnboundSocketTest, TestMcastReceptionWhenDroppingMemberships) {
  1124    // TODO(b/267210840): Get multicast working with hostinet.
  1125    SKIP_IF(IsRunningWithHostinet());
  1126  
  1127    std::unique_ptr<SocketPair> socket_pairs[2] = {
  1128        std::make_unique<FDSocketPair>(ASSERT_NO_ERRNO_AND_VALUE(NewSocket()),
  1129                                       ASSERT_NO_ERRNO_AND_VALUE(NewSocket())),
  1130        std::make_unique<FDSocketPair>(ASSERT_NO_ERRNO_AND_VALUE(NewSocket()),
  1131                                       ASSERT_NO_ERRNO_AND_VALUE(NewSocket()))};
  1132  
  1133    ip_mreq iface = {}, group = {};
  1134    iface.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
  1135    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
  1136    group.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
  1137    auto receiver_addr = V4Any();
  1138    int bound_port = 0;
  1139  
  1140    // Create two socketpairs with the exact same configuration.
  1141    for (auto& sockets : socket_pairs) {
  1142      ASSERT_THAT(setsockopt(sockets->first_fd(), IPPROTO_IP, IP_MULTICAST_IF,
  1143                             &iface, sizeof(iface)),
  1144                  SyscallSucceeds());
  1145      ASSERT_THAT(setsockopt(sockets->second_fd(), SOL_SOCKET, SO_REUSEPORT,
  1146                             &kSockOptOn, sizeof(kSockOptOn)),
  1147                  SyscallSucceeds());
  1148      ASSERT_THAT(setsockopt(sockets->second_fd(), IPPROTO_IP, IP_ADD_MEMBERSHIP,
  1149                             &group, sizeof(group)),
  1150                  SyscallSucceeds());
  1151      ASSERT_THAT(bind(sockets->second_fd(), AsSockAddr(&receiver_addr.addr),
  1152                       receiver_addr.addr_len),
  1153                  SyscallSucceeds());
  1154      // Get the port assigned.
  1155      socklen_t receiver_addr_len = receiver_addr.addr_len;
  1156      ASSERT_THAT(
  1157          getsockname(sockets->second_fd(), AsSockAddr(&receiver_addr.addr),
  1158                      &receiver_addr_len),
  1159          SyscallSucceeds());
  1160      EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
  1161      // On the first iteration, save the port we are bound to. On the second
  1162      // iteration, verify the port is the same as the one from the first
  1163      // iteration. In other words, both sockets listen on the same port.
  1164      if (bound_port == 0) {
  1165        bound_port =
  1166            reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
  1167      } else {
  1168        EXPECT_EQ(bound_port,
  1169                  reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port);
  1170      }
  1171    }
  1172  
  1173    // Drop the membership of the first socket pair and verify data is still
  1174    // received.
  1175    ASSERT_THAT(setsockopt(socket_pairs[0]->second_fd(), IPPROTO_IP,
  1176                           IP_DROP_MEMBERSHIP, &group, sizeof(group)),
  1177                SyscallSucceeds());
  1178    // Send a packet from each socket_pair.
  1179    auto send_addr = V4Multicast();
  1180    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port = bound_port;
  1181    for (auto& sockets : socket_pairs) {
  1182      char send_buf[200];
  1183      RandomizeBuffer(send_buf, sizeof(send_buf));
  1184      ASSERT_THAT(
  1185          RetryEINTR(sendto)(sockets->first_fd(), send_buf, sizeof(send_buf), 0,
  1186                             AsSockAddr(&send_addr.addr), send_addr.addr_len),
  1187          SyscallSucceedsWithValue(sizeof(send_buf)));
  1188  
  1189      // Check that we received the multicast packet on both sockets.
  1190      for (auto& sockets : socket_pairs) {
  1191        char recv_buf[sizeof(send_buf)] = {};
  1192        ASSERT_THAT(RecvTimeout(sockets->second_fd(), recv_buf, sizeof(recv_buf),
  1193                                1 /*timeout*/),
  1194                    IsPosixErrorOkAndHolds(sizeof(recv_buf)));
  1195        EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
  1196      }
  1197    }
  1198  
  1199    // Drop the membership of the second socket pair and verify data stops being
  1200    // received.
  1201    ASSERT_THAT(setsockopt(socket_pairs[1]->second_fd(), IPPROTO_IP,
  1202                           IP_DROP_MEMBERSHIP, &group, sizeof(group)),
  1203                SyscallSucceeds());
  1204    // Send a packet from each socket_pair.
  1205    for (auto& sockets : socket_pairs) {
  1206      char send_buf[200];
  1207      ASSERT_THAT(
  1208          RetryEINTR(sendto)(sockets->first_fd(), send_buf, sizeof(send_buf), 0,
  1209                             AsSockAddr(&send_addr.addr), send_addr.addr_len),
  1210          SyscallSucceedsWithValue(sizeof(send_buf)));
  1211  
  1212      char recv_buf[sizeof(send_buf)] = {};
  1213      for (auto& sockets : socket_pairs) {
  1214        ASSERT_THAT(RecvTimeout(sockets->second_fd(), recv_buf, sizeof(recv_buf),
  1215                                1 /*timeout*/),
  1216                    PosixErrorIs(EAGAIN, ::testing::_));
  1217      }
  1218    }
  1219  }
  1220  
  1221  // Check that a receiving socket can bind to the multicast address before
  1222  // joining the group and receive data once the group has been joined.
  1223  TEST_P(IPv4UDPUnboundSocketTest, TestBindToMcastThenJoinThenReceive) {
  1224    // TODO(b/267210840): Get multicast working with hostinet.
  1225    SKIP_IF(IsRunningWithHostinet());
  1226  
  1227    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1228    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1229  
  1230    // Bind second socket (receiver) to the multicast address.
  1231    auto receiver_addr = V4Multicast();
  1232    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
  1233                     receiver_addr.addr_len),
  1234                SyscallSucceeds());
  1235    // Update receiver_addr with the correct port number.
  1236    socklen_t receiver_addr_len = receiver_addr.addr_len;
  1237    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
  1238                            &receiver_addr_len),
  1239                SyscallSucceeds());
  1240    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
  1241  
  1242    // Register to receive multicast packets.
  1243    ip_mreqn group = {};
  1244    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
  1245    group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
  1246    ASSERT_THAT(setsockopt(socket2->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &group,
  1247                           sizeof(group)),
  1248                SyscallSucceeds());
  1249  
  1250    // Send a multicast packet on the first socket out the loopback interface.
  1251    ip_mreq iface = {};
  1252    iface.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
  1253    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,
  1254                           sizeof(iface)),
  1255                SyscallSucceeds());
  1256    auto sendto_addr = V4Multicast();
  1257    reinterpret_cast<sockaddr_in*>(&sendto_addr.addr)->sin_port =
  1258        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
  1259    char send_buf[200];
  1260    RandomizeBuffer(send_buf, sizeof(send_buf));
  1261    ASSERT_THAT(
  1262        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
  1263                           AsSockAddr(&sendto_addr.addr), sendto_addr.addr_len),
  1264        SyscallSucceedsWithValue(sizeof(send_buf)));
  1265  
  1266    // Check that we received the multicast packet.
  1267    char recv_buf[sizeof(send_buf)] = {};
  1268    ASSERT_THAT(
  1269        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
  1270        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
  1271    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
  1272  }
  1273  
  1274  // Check that a receiving socket can bind to the multicast address and won't
  1275  // receive multicast data if it hasn't joined the group.
  1276  TEST_P(IPv4UDPUnboundSocketTest, TestBindToMcastThenNoJoinThenNoReceive) {
  1277    // TODO(b/267210840): Get multicast working with hostinet.
  1278    SKIP_IF(IsRunningWithHostinet());
  1279  
  1280    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1281    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1282  
  1283    // Bind second socket (receiver) to the multicast address.
  1284    auto receiver_addr = V4Multicast();
  1285    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
  1286                     receiver_addr.addr_len),
  1287                SyscallSucceeds());
  1288    // Update receiver_addr with the correct port number.
  1289    socklen_t receiver_addr_len = receiver_addr.addr_len;
  1290    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
  1291                            &receiver_addr_len),
  1292                SyscallSucceeds());
  1293    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
  1294  
  1295    // Send a multicast packet on the first socket out the loopback interface.
  1296    ip_mreq iface = {};
  1297    iface.imr_interface.s_addr = htonl(INADDR_LOOPBACK);
  1298    ASSERT_THAT(setsockopt(socket1->get(), IPPROTO_IP, IP_MULTICAST_IF, &iface,
  1299                           sizeof(iface)),
  1300                SyscallSucceeds());
  1301    auto sendto_addr = V4Multicast();
  1302    reinterpret_cast<sockaddr_in*>(&sendto_addr.addr)->sin_port =
  1303        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
  1304    char send_buf[200];
  1305    RandomizeBuffer(send_buf, sizeof(send_buf));
  1306    ASSERT_THAT(
  1307        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
  1308                           AsSockAddr(&sendto_addr.addr), sendto_addr.addr_len),
  1309        SyscallSucceedsWithValue(sizeof(send_buf)));
  1310  
  1311    // Check that we don't receive the multicast packet.
  1312    char recv_buf[sizeof(send_buf)] = {};
  1313    ASSERT_THAT(
  1314        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
  1315        PosixErrorIs(EAGAIN, ::testing::_));
  1316  }
  1317  
  1318  // Check that a socket can bind to a multicast address and still send out
  1319  // packets.
  1320  TEST_P(IPv4UDPUnboundSocketTest, TestBindToMcastThenSend) {
  1321    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1322    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1323  
  1324    // Bind second socket (receiver) to the ANY address.
  1325    auto receiver_addr = V4Any();
  1326    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
  1327                     receiver_addr.addr_len),
  1328                SyscallSucceeds());
  1329    socklen_t receiver_addr_len = receiver_addr.addr_len;
  1330    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
  1331                            &receiver_addr_len),
  1332                SyscallSucceeds());
  1333    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
  1334  
  1335    // Bind the first socket (sender) to the multicast address.
  1336    auto sender_addr = V4Multicast();
  1337    ASSERT_THAT(
  1338        bind(socket1->get(), AsSockAddr(&sender_addr.addr), sender_addr.addr_len),
  1339        SyscallSucceeds());
  1340    socklen_t sender_addr_len = sender_addr.addr_len;
  1341    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&sender_addr.addr),
  1342                            &sender_addr_len),
  1343                SyscallSucceeds());
  1344    EXPECT_EQ(sender_addr_len, sender_addr.addr_len);
  1345  
  1346    // Send a packet on the first socket to the loopback address.
  1347    auto sendto_addr = V4Loopback();
  1348    reinterpret_cast<sockaddr_in*>(&sendto_addr.addr)->sin_port =
  1349        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
  1350    char send_buf[200];
  1351    RandomizeBuffer(send_buf, sizeof(send_buf));
  1352    ASSERT_THAT(
  1353        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
  1354                           AsSockAddr(&sendto_addr.addr), sendto_addr.addr_len),
  1355        SyscallSucceedsWithValue(sizeof(send_buf)));
  1356  
  1357    // Check that we received the packet.
  1358    char recv_buf[sizeof(send_buf)] = {};
  1359    ASSERT_THAT(
  1360        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
  1361        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
  1362    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
  1363  }
  1364  
  1365  // Check that a receiving socket can bind to the broadcast address and receive
  1366  // broadcast packets.
  1367  TEST_P(IPv4UDPUnboundSocketTest, TestBindToBcastThenReceive) {
  1368    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1369    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1370  
  1371    // Bind second socket (receiver) to the broadcast address.
  1372    auto receiver_addr = V4Broadcast();
  1373    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
  1374                     receiver_addr.addr_len),
  1375                SyscallSucceeds());
  1376    socklen_t receiver_addr_len = receiver_addr.addr_len;
  1377    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
  1378                            &receiver_addr_len),
  1379                SyscallSucceeds());
  1380    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
  1381  
  1382    // Send a broadcast packet on the first socket out the loopback interface.
  1383    EXPECT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_BROADCAST, &kSockOptOn,
  1384                           sizeof(kSockOptOn)),
  1385                SyscallSucceedsWithValue(0));
  1386    // Note: Binding to the loopback interface makes the broadcast go out of it.
  1387    auto sender_bind_addr = V4Loopback();
  1388    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&sender_bind_addr.addr),
  1389                     sender_bind_addr.addr_len),
  1390                SyscallSucceeds());
  1391    auto sendto_addr = V4Broadcast();
  1392    reinterpret_cast<sockaddr_in*>(&sendto_addr.addr)->sin_port =
  1393        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
  1394    char send_buf[200];
  1395    RandomizeBuffer(send_buf, sizeof(send_buf));
  1396    ASSERT_THAT(
  1397        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
  1398                           AsSockAddr(&sendto_addr.addr), sendto_addr.addr_len),
  1399        SyscallSucceedsWithValue(sizeof(send_buf)));
  1400  
  1401    // Check that we received the multicast packet.
  1402    char recv_buf[sizeof(send_buf)] = {};
  1403    ASSERT_THAT(
  1404        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
  1405        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
  1406    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
  1407  }
  1408  
  1409  // Check that a socket can bind to the broadcast address and still send out
  1410  // packets.
  1411  TEST_P(IPv4UDPUnboundSocketTest, TestBindToBcastThenSend) {
  1412    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1413    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1414  
  1415    // Bind second socket (receiver) to the ANY address.
  1416    auto receiver_addr = V4Any();
  1417    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&receiver_addr.addr),
  1418                     receiver_addr.addr_len),
  1419                SyscallSucceeds());
  1420    socklen_t receiver_addr_len = receiver_addr.addr_len;
  1421    ASSERT_THAT(getsockname(socket2->get(), AsSockAddr(&receiver_addr.addr),
  1422                            &receiver_addr_len),
  1423                SyscallSucceeds());
  1424    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
  1425  
  1426    // Bind the first socket (sender) to the broadcast address.
  1427    auto sender_addr = V4Broadcast();
  1428    ASSERT_THAT(
  1429        bind(socket1->get(), AsSockAddr(&sender_addr.addr), sender_addr.addr_len),
  1430        SyscallSucceeds());
  1431    socklen_t sender_addr_len = sender_addr.addr_len;
  1432    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&sender_addr.addr),
  1433                            &sender_addr_len),
  1434                SyscallSucceeds());
  1435    EXPECT_EQ(sender_addr_len, sender_addr.addr_len);
  1436  
  1437    // Send a packet on the first socket to the loopback address.
  1438    auto sendto_addr = V4Loopback();
  1439    reinterpret_cast<sockaddr_in*>(&sendto_addr.addr)->sin_port =
  1440        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
  1441    char send_buf[200];
  1442    RandomizeBuffer(send_buf, sizeof(send_buf));
  1443    ASSERT_THAT(
  1444        RetryEINTR(sendto)(socket1->get(), send_buf, sizeof(send_buf), 0,
  1445                           AsSockAddr(&sendto_addr.addr), sendto_addr.addr_len),
  1446        SyscallSucceedsWithValue(sizeof(send_buf)));
  1447  
  1448    // Check that we received the packet.
  1449    char recv_buf[sizeof(send_buf)] = {};
  1450    ASSERT_THAT(
  1451        RecvTimeout(socket2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
  1452        IsPosixErrorOkAndHolds(sizeof(recv_buf)));
  1453    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
  1454  }
  1455  
  1456  // Check that SO_REUSEADDR always delivers to the most recently bound socket.
  1457  //
  1458  // FIXME(gvisor.dev/issue/873): Endpoint order is not restored correctly. Enable
  1459  // random and co-op save (below) once that is fixed.
  1460  TEST_P(IPv4UDPUnboundSocketTest, ReuseAddrDistribution) {
  1461    std::vector<std::unique_ptr<FileDescriptor>> sockets;
  1462    sockets.emplace_back(ASSERT_NO_ERRNO_AND_VALUE(NewSocket()));
  1463  
  1464    ASSERT_THAT(setsockopt(sockets[0]->get(), SOL_SOCKET, SO_REUSEADDR,
  1465                           &kSockOptOn, sizeof(kSockOptOn)),
  1466                SyscallSucceeds());
  1467  
  1468    // Bind the first socket to the loopback and take note of the selected port.
  1469    auto addr = V4Loopback();
  1470    ASSERT_THAT(bind(sockets[0]->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1471                SyscallSucceeds());
  1472    socklen_t addr_len = addr.addr_len;
  1473    ASSERT_THAT(getsockname(sockets[0]->get(), AsSockAddr(&addr.addr), &addr_len),
  1474                SyscallSucceeds());
  1475    EXPECT_EQ(addr_len, addr.addr_len);
  1476  
  1477    constexpr int kMessageSize = 200;
  1478  
  1479    // FIXME(gvisor.dev/issue/873): Endpoint order is not restored correctly.
  1480    const DisableSave ds;
  1481  
  1482    for (int i = 0; i < 10; i++) {
  1483      // Add a new receiver.
  1484      sockets.emplace_back(ASSERT_NO_ERRNO_AND_VALUE(NewSocket()));
  1485      auto& last = sockets.back();
  1486      ASSERT_THAT(setsockopt(last->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1487                             sizeof(kSockOptOn)),
  1488                  SyscallSucceeds());
  1489      ASSERT_THAT(bind(last->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1490                  SyscallSucceeds());
  1491  
  1492      // Send a new message to the SO_REUSEADDR group. We use a new socket each
  1493      // time so that a new ephemeral port will be used each time. This ensures
  1494      // that we aren't doing REUSEPORT-like hash load blancing.
  1495      auto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1496      char send_buf[kMessageSize];
  1497      RandomizeBuffer(send_buf, sizeof(send_buf));
  1498      EXPECT_THAT(RetryEINTR(sendto)(sender->get(), send_buf, sizeof(send_buf), 0,
  1499                                     AsSockAddr(&addr.addr), addr.addr_len),
  1500                  SyscallSucceedsWithValue(sizeof(send_buf)));
  1501  
  1502      // Verify that the most recent socket got the message. We don't expect any
  1503      // of the other sockets to have received it, but we will check that later.
  1504      char recv_buf[sizeof(send_buf)] = {};
  1505      EXPECT_THAT(
  1506          RecvTimeout(last->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
  1507          IsPosixErrorOkAndHolds(sizeof(send_buf)));
  1508      EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
  1509    }
  1510  
  1511    // Verify that no other messages were received.
  1512    for (auto& socket : sockets) {
  1513      char recv_buf[kMessageSize] = {};
  1514      EXPECT_THAT(
  1515          RecvTimeout(socket->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
  1516          PosixErrorIs(EAGAIN, ::testing::_));
  1517    }
  1518  }
  1519  
  1520  TEST_P(IPv4UDPUnboundSocketTest, BindReuseAddrThenReusePort) {
  1521    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1522    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1523  
  1524    // Bind socket1 with REUSEADDR.
  1525    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1526                           sizeof(kSockOptOn)),
  1527                SyscallSucceeds());
  1528  
  1529    // Bind the first socket to the loopback and take note of the selected port.
  1530    auto addr = V4Loopback();
  1531    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1532                SyscallSucceeds());
  1533    socklen_t addr_len = addr.addr_len;
  1534    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&addr.addr), &addr_len),
  1535                SyscallSucceeds());
  1536    EXPECT_EQ(addr_len, addr.addr_len);
  1537  
  1538    // Bind socket2 to the same address as socket1, only with REUSEPORT.
  1539    ASSERT_THAT(setsockopt(socket2->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1540                           sizeof(kSockOptOn)),
  1541                SyscallSucceeds());
  1542    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1543                SyscallFailsWithErrno(EADDRINUSE));
  1544  }
  1545  
  1546  TEST_P(IPv4UDPUnboundSocketTest, BindReusePortThenReuseAddr) {
  1547    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1548    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1549  
  1550    // Bind socket1 with REUSEPORT.
  1551    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1552                           sizeof(kSockOptOn)),
  1553                SyscallSucceeds());
  1554  
  1555    // Bind the first socket to the loopback and take note of the selected port.
  1556    auto addr = V4Loopback();
  1557    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1558                SyscallSucceeds());
  1559    socklen_t addr_len = addr.addr_len;
  1560    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&addr.addr), &addr_len),
  1561                SyscallSucceeds());
  1562    EXPECT_EQ(addr_len, addr.addr_len);
  1563  
  1564    // Bind socket2 to the same address as socket1, only with REUSEADDR.
  1565    ASSERT_THAT(setsockopt(socket2->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1566                           sizeof(kSockOptOn)),
  1567                SyscallSucceeds());
  1568    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1569                SyscallFailsWithErrno(EADDRINUSE));
  1570  }
  1571  
  1572  TEST_P(IPv4UDPUnboundSocketTest, BindReuseAddrReusePortConvertibleToReusePort) {
  1573    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1574    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1575    auto socket3 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1576  
  1577    // Bind socket1 with REUSEADDR and REUSEPORT.
  1578    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1579                           sizeof(kSockOptOn)),
  1580                SyscallSucceeds());
  1581    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1582                           sizeof(kSockOptOn)),
  1583                SyscallSucceeds());
  1584  
  1585    // Bind the first socket to the loopback and take note of the selected port.
  1586    auto addr = V4Loopback();
  1587    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1588                SyscallSucceeds());
  1589    socklen_t addr_len = addr.addr_len;
  1590    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&addr.addr), &addr_len),
  1591                SyscallSucceeds());
  1592    EXPECT_EQ(addr_len, addr.addr_len);
  1593  
  1594    // Bind socket2 to the same address as socket1, only with REUSEPORT.
  1595    ASSERT_THAT(setsockopt(socket2->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1596                           sizeof(kSockOptOn)),
  1597                SyscallSucceeds());
  1598    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1599                SyscallSucceeds());
  1600  
  1601    // Bind socket3 to the same address as socket1, only with REUSEADDR.
  1602    ASSERT_THAT(setsockopt(socket3->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1603                           sizeof(kSockOptOn)),
  1604                SyscallSucceeds());
  1605    ASSERT_THAT(bind(socket3->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1606                SyscallFailsWithErrno(EADDRINUSE));
  1607  }
  1608  
  1609  TEST_P(IPv4UDPUnboundSocketTest, BindReuseAddrReusePortConvertibleToReuseAddr) {
  1610    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1611    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1612    auto socket3 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1613  
  1614    // Bind socket1 with REUSEADDR and REUSEPORT.
  1615    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1616                           sizeof(kSockOptOn)),
  1617                SyscallSucceeds());
  1618    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1619                           sizeof(kSockOptOn)),
  1620                SyscallSucceeds());
  1621  
  1622    // Bind the first socket to the loopback and take note of the selected port.
  1623    auto addr = V4Loopback();
  1624    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1625                SyscallSucceeds());
  1626    socklen_t addr_len = addr.addr_len;
  1627    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&addr.addr), &addr_len),
  1628                SyscallSucceeds());
  1629    EXPECT_EQ(addr_len, addr.addr_len);
  1630  
  1631    // Bind socket2 to the same address as socket1, only with REUSEADDR.
  1632    ASSERT_THAT(setsockopt(socket2->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1633                           sizeof(kSockOptOn)),
  1634                SyscallSucceeds());
  1635    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1636                SyscallSucceeds());
  1637  
  1638    // Bind socket3 to the same address as socket1, only with REUSEPORT.
  1639    ASSERT_THAT(setsockopt(socket3->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1640                           sizeof(kSockOptOn)),
  1641                SyscallSucceeds());
  1642    ASSERT_THAT(bind(socket3->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1643                SyscallFailsWithErrno(EADDRINUSE));
  1644  }
  1645  
  1646  TEST_P(IPv4UDPUnboundSocketTest, BindReuseAddrReusePortConversionReversable1) {
  1647    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1648    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1649    auto socket3 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1650  
  1651    // Bind socket1 with REUSEADDR and REUSEPORT.
  1652    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1653                           sizeof(kSockOptOn)),
  1654                SyscallSucceeds());
  1655    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1656                           sizeof(kSockOptOn)),
  1657                SyscallSucceeds());
  1658  
  1659    // Bind the first socket to the loopback and take note of the selected port.
  1660    auto addr = V4Loopback();
  1661    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1662                SyscallSucceeds());
  1663    socklen_t addr_len = addr.addr_len;
  1664    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&addr.addr), &addr_len),
  1665                SyscallSucceeds());
  1666    EXPECT_EQ(addr_len, addr.addr_len);
  1667  
  1668    // Bind socket2 to the same address as socket1, only with REUSEPORT.
  1669    ASSERT_THAT(setsockopt(socket2->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1670                           sizeof(kSockOptOn)),
  1671                SyscallSucceeds());
  1672    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1673                SyscallSucceeds());
  1674  
  1675    // Close socket2 to revert to just socket1 with REUSEADDR and REUSEPORT.
  1676    socket2->reset();
  1677  
  1678    // Bind socket3 to the same address as socket1, only with REUSEADDR.
  1679    ASSERT_THAT(setsockopt(socket3->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1680                           sizeof(kSockOptOn)),
  1681                SyscallSucceeds());
  1682    ASSERT_THAT(bind(socket3->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1683                SyscallSucceeds());
  1684  }
  1685  
  1686  TEST_P(IPv4UDPUnboundSocketTest, BindReuseAddrReusePortConversionReversable2) {
  1687    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1688    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1689    auto socket3 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1690  
  1691    // Bind socket1 with REUSEADDR and REUSEPORT.
  1692    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1693                           sizeof(kSockOptOn)),
  1694                SyscallSucceeds());
  1695    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1696                           sizeof(kSockOptOn)),
  1697                SyscallSucceeds());
  1698  
  1699    // Bind the first socket to the loopback and take note of the selected port.
  1700    auto addr = V4Loopback();
  1701    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1702                SyscallSucceeds());
  1703    socklen_t addr_len = addr.addr_len;
  1704    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&addr.addr), &addr_len),
  1705                SyscallSucceeds());
  1706    EXPECT_EQ(addr_len, addr.addr_len);
  1707  
  1708    // Bind socket2 to the same address as socket1, only with REUSEADDR.
  1709    ASSERT_THAT(setsockopt(socket2->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1710                           sizeof(kSockOptOn)),
  1711                SyscallSucceeds());
  1712    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1713                SyscallSucceeds());
  1714  
  1715    // Close socket2 to revert to just socket1 with REUSEADDR and REUSEPORT.
  1716    socket2->reset();
  1717  
  1718    // Bind socket3 to the same address as socket1, only with REUSEPORT.
  1719    ASSERT_THAT(setsockopt(socket3->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1720                           sizeof(kSockOptOn)),
  1721                SyscallSucceeds());
  1722    ASSERT_THAT(bind(socket3->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1723                SyscallSucceeds());
  1724  }
  1725  
  1726  TEST_P(IPv4UDPUnboundSocketTest, BindDoubleReuseAddrReusePortThenReusePort) {
  1727    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1728    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1729    auto socket3 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1730  
  1731    // Bind socket1 with REUSEADDR and REUSEPORT.
  1732    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1733                           sizeof(kSockOptOn)),
  1734                SyscallSucceeds());
  1735    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1736                           sizeof(kSockOptOn)),
  1737                SyscallSucceeds());
  1738  
  1739    // Bind the first socket to the loopback and take note of the selected port.
  1740    auto addr = V4Loopback();
  1741    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1742                SyscallSucceeds());
  1743    socklen_t addr_len = addr.addr_len;
  1744    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&addr.addr), &addr_len),
  1745                SyscallSucceeds());
  1746    EXPECT_EQ(addr_len, addr.addr_len);
  1747  
  1748    // Bind socket2 to the same address as socket1, also with REUSEADDR and
  1749    // REUSEPORT.
  1750    ASSERT_THAT(setsockopt(socket2->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1751                           sizeof(kSockOptOn)),
  1752                SyscallSucceeds());
  1753    ASSERT_THAT(setsockopt(socket2->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1754                           sizeof(kSockOptOn)),
  1755                SyscallSucceeds());
  1756  
  1757    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1758                SyscallSucceeds());
  1759  
  1760    // Bind socket3 to the same address as socket1, only with REUSEPORT.
  1761    ASSERT_THAT(setsockopt(socket3->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1762                           sizeof(kSockOptOn)),
  1763                SyscallSucceeds());
  1764    ASSERT_THAT(bind(socket3->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1765                SyscallSucceeds());
  1766  }
  1767  
  1768  TEST_P(IPv4UDPUnboundSocketTest, BindDoubleReuseAddrReusePortThenReuseAddr) {
  1769    auto socket1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1770    auto socket2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1771    auto socket3 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1772  
  1773    // Bind socket1 with REUSEADDR and REUSEPORT.
  1774    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1775                           sizeof(kSockOptOn)),
  1776                SyscallSucceeds());
  1777    ASSERT_THAT(setsockopt(socket1->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1778                           sizeof(kSockOptOn)),
  1779                SyscallSucceeds());
  1780  
  1781    // Bind the first socket to the loopback and take note of the selected port.
  1782    auto addr = V4Loopback();
  1783    ASSERT_THAT(bind(socket1->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1784                SyscallSucceeds());
  1785    socklen_t addr_len = addr.addr_len;
  1786    ASSERT_THAT(getsockname(socket1->get(), AsSockAddr(&addr.addr), &addr_len),
  1787                SyscallSucceeds());
  1788    EXPECT_EQ(addr_len, addr.addr_len);
  1789  
  1790    // Bind socket2 to the same address as socket1, also with REUSEADDR and
  1791    // REUSEPORT.
  1792    ASSERT_THAT(setsockopt(socket2->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1793                           sizeof(kSockOptOn)),
  1794                SyscallSucceeds());
  1795    ASSERT_THAT(setsockopt(socket2->get(), SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
  1796                           sizeof(kSockOptOn)),
  1797                SyscallSucceeds());
  1798  
  1799    ASSERT_THAT(bind(socket2->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1800                SyscallSucceeds());
  1801  
  1802    // Bind socket3 to the same address as socket1, only with REUSEADDR.
  1803    ASSERT_THAT(setsockopt(socket3->get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
  1804                           sizeof(kSockOptOn)),
  1805                SyscallSucceeds());
  1806    ASSERT_THAT(bind(socket3->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1807                SyscallSucceeds());
  1808  }
  1809  
  1810  // Check that REUSEPORT takes precedence over REUSEADDR.
  1811  TEST_P(IPv4UDPUnboundSocketTest, ReuseAddrReusePortDistribution) {
  1812    auto receiver1 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1813    auto receiver2 = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1814  
  1815    ASSERT_THAT(setsockopt(receiver1->get(), SOL_SOCKET, SO_REUSEADDR,
  1816                           &kSockOptOn, sizeof(kSockOptOn)),
  1817                SyscallSucceeds());
  1818    ASSERT_THAT(setsockopt(receiver1->get(), SOL_SOCKET, SO_REUSEPORT,
  1819                           &kSockOptOn, sizeof(kSockOptOn)),
  1820                SyscallSucceeds());
  1821  
  1822    // Bind the first socket to the loopback and take note of the selected port.
  1823    auto addr = V4Loopback();
  1824    ASSERT_THAT(bind(receiver1->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1825                SyscallSucceeds());
  1826    socklen_t addr_len = addr.addr_len;
  1827    ASSERT_THAT(getsockname(receiver1->get(), AsSockAddr(&addr.addr), &addr_len),
  1828                SyscallSucceeds());
  1829    EXPECT_EQ(addr_len, addr.addr_len);
  1830  
  1831    // Bind receiver2 to the same address as socket1, also with REUSEADDR and
  1832    // REUSEPORT.
  1833    ASSERT_THAT(setsockopt(receiver2->get(), SOL_SOCKET, SO_REUSEADDR,
  1834                           &kSockOptOn, sizeof(kSockOptOn)),
  1835                SyscallSucceeds());
  1836    ASSERT_THAT(setsockopt(receiver2->get(), SOL_SOCKET, SO_REUSEPORT,
  1837                           &kSockOptOn, sizeof(kSockOptOn)),
  1838                SyscallSucceeds());
  1839    ASSERT_THAT(bind(receiver2->get(), AsSockAddr(&addr.addr), addr.addr_len),
  1840                SyscallSucceeds());
  1841  
  1842    constexpr int kMessageSize = 10;
  1843  
  1844    // Saving during each iteration of the following loop is too expensive.
  1845    DisableSave ds;
  1846  
  1847    for (int i = 0; i < 100; ++i) {
  1848      // Send a new message to the REUSEADDR/REUSEPORT group. We use a new socket
  1849      // each time so that a new ephemerial port will be used each time. This
  1850      // ensures that we cycle through hashes.
  1851      auto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1852      char send_buf[kMessageSize] = {};
  1853      EXPECT_THAT(RetryEINTR(sendto)(sender->get(), send_buf, sizeof(send_buf), 0,
  1854                                     AsSockAddr(&addr.addr), addr.addr_len),
  1855                  SyscallSucceedsWithValue(sizeof(send_buf)));
  1856    }
  1857  
  1858    ds.reset();
  1859  
  1860    // Check that both receivers got messages. This checks that we are using load
  1861    // balancing (REUSEPORT) instead of the most recently bound socket
  1862    // (REUSEADDR).
  1863    char recv_buf[kMessageSize] = {};
  1864    EXPECT_THAT(
  1865        RecvTimeout(receiver1->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
  1866        IsPosixErrorOkAndHolds(kMessageSize));
  1867    EXPECT_THAT(
  1868        RecvTimeout(receiver2->get(), recv_buf, sizeof(recv_buf), 1 /*timeout*/),
  1869        IsPosixErrorOkAndHolds(kMessageSize));
  1870  }
  1871  
  1872  // Test that socket will receive packet info control message.
  1873  TEST_P(IPv4UDPUnboundSocketTest, SetAndReceiveIPPKTINFO) {
  1874    // TODO(gvisor.dev/issue/1202): ioctl() is not supported by hostinet.
  1875    SKIP_IF((IsRunningWithHostinet()));
  1876  
  1877    auto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1878    auto receiver = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1879    auto sender_addr = V4Loopback();
  1880    int level = SOL_IP;
  1881    int type = IP_PKTINFO;
  1882  
  1883    ASSERT_THAT(bind(receiver->get(), AsSockAddr(&sender_addr.addr),
  1884                     sender_addr.addr_len),
  1885                SyscallSucceeds());
  1886    socklen_t sender_addr_len = sender_addr.addr_len;
  1887    ASSERT_THAT(getsockname(receiver->get(), AsSockAddr(&sender_addr.addr),
  1888                            &sender_addr_len),
  1889                SyscallSucceeds());
  1890    EXPECT_EQ(sender_addr_len, sender_addr.addr_len);
  1891  
  1892    auto receiver_addr = V4Loopback();
  1893    reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port =
  1894        reinterpret_cast<sockaddr_in*>(&sender_addr.addr)->sin_port;
  1895    ASSERT_THAT(connect(sender->get(), AsSockAddr(&receiver_addr.addr),
  1896                        receiver_addr.addr_len),
  1897                SyscallSucceeds());
  1898  
  1899    // Allow socket to receive control message.
  1900    ASSERT_THAT(
  1901        setsockopt(receiver->get(), level, type, &kSockOptOn, sizeof(kSockOptOn)),
  1902        SyscallSucceeds());
  1903  
  1904    // Prepare message to send.
  1905    constexpr size_t kDataLength = 1024;
  1906    msghdr sent_msg = {};
  1907    iovec sent_iov = {};
  1908    char sent_data[kDataLength];
  1909    sent_iov.iov_base = sent_data;
  1910    sent_iov.iov_len = kDataLength;
  1911    sent_msg.msg_iov = &sent_iov;
  1912    sent_msg.msg_iovlen = 1;
  1913    sent_msg.msg_flags = 0;
  1914  
  1915    ASSERT_THAT(RetryEINTR(sendmsg)(sender->get(), &sent_msg, 0),
  1916                SyscallSucceedsWithValue(kDataLength));
  1917  
  1918    msghdr received_msg = {};
  1919    iovec received_iov = {};
  1920    char received_data[kDataLength];
  1921    char received_cmsg_buf[CMSG_SPACE(sizeof(in_pktinfo))] = {};
  1922    size_t cmsg_data_len = sizeof(in_pktinfo);
  1923    received_iov.iov_base = received_data;
  1924    received_iov.iov_len = kDataLength;
  1925    received_msg.msg_iov = &received_iov;
  1926    received_msg.msg_iovlen = 1;
  1927    received_msg.msg_controllen = CMSG_LEN(cmsg_data_len);
  1928    received_msg.msg_control = received_cmsg_buf;
  1929  
  1930    ASSERT_THAT(RecvMsgTimeout(receiver->get(), &received_msg, 1 /*timeout*/),
  1931                IsPosixErrorOkAndHolds(kDataLength));
  1932  
  1933    cmsghdr* cmsg = CMSG_FIRSTHDR(&received_msg);
  1934    ASSERT_NE(cmsg, nullptr);
  1935    EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(cmsg_data_len));
  1936    EXPECT_EQ(cmsg->cmsg_level, level);
  1937    EXPECT_EQ(cmsg->cmsg_type, type);
  1938  
  1939    // Check the data
  1940    in_pktinfo received_pktinfo = {};
  1941    memcpy(&received_pktinfo, CMSG_DATA(cmsg), sizeof(in_pktinfo));
  1942    EXPECT_EQ(received_pktinfo.ipi_ifindex,
  1943              ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()));
  1944    EXPECT_EQ(received_pktinfo.ipi_spec_dst.s_addr, htonl(INADDR_LOOPBACK));
  1945    EXPECT_EQ(received_pktinfo.ipi_addr.s_addr, htonl(INADDR_LOOPBACK));
  1946  }
  1947  
  1948  // Test that socket will receive IP_RECVORIGDSTADDR control message.
  1949  TEST_P(IPv4UDPUnboundSocketTest, SetAndReceiveIPReceiveOrigDstAddr) {
  1950    auto sender = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1951    auto receiver = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  1952    auto receiver_addr = V4Loopback();
  1953    int level = SOL_IP;
  1954    int type = IP_RECVORIGDSTADDR;
  1955  
  1956    ASSERT_THAT(bind(receiver->get(), AsSockAddr(&receiver_addr.addr),
  1957                     receiver_addr.addr_len),
  1958                SyscallSucceeds());
  1959  
  1960    // Retrieve the port bound by the receiver.
  1961    socklen_t receiver_addr_len = receiver_addr.addr_len;
  1962    ASSERT_THAT(getsockname(receiver->get(), AsSockAddr(&receiver_addr.addr),
  1963                            &receiver_addr_len),
  1964                SyscallSucceeds());
  1965    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
  1966  
  1967    ASSERT_THAT(connect(sender->get(), AsSockAddr(&receiver_addr.addr),
  1968                        receiver_addr.addr_len),
  1969                SyscallSucceeds());
  1970  
  1971    // Get address and port bound by the sender.
  1972    sockaddr_storage sender_addr_storage;
  1973    socklen_t sender_addr_len = sizeof(sender_addr_storage);
  1974    ASSERT_THAT(getsockname(sender->get(), AsSockAddr(&sender_addr_storage),
  1975                            &sender_addr_len),
  1976                SyscallSucceeds());
  1977    ASSERT_EQ(sender_addr_len, sizeof(struct sockaddr_in));
  1978  
  1979    // Enable IP_RECVORIGDSTADDR on socket so that we get the original destination
  1980    // address of the datagram as auxiliary information in the control message.
  1981    ASSERT_THAT(
  1982        setsockopt(receiver->get(), level, type, &kSockOptOn, sizeof(kSockOptOn)),
  1983        SyscallSucceeds());
  1984  
  1985    // Prepare message to send.
  1986    constexpr size_t kDataLength = 1024;
  1987    msghdr sent_msg = {};
  1988    iovec sent_iov = {};
  1989    char sent_data[kDataLength];
  1990    sent_iov.iov_base = sent_data;
  1991    sent_iov.iov_len = kDataLength;
  1992    sent_msg.msg_iov = &sent_iov;
  1993    sent_msg.msg_iovlen = 1;
  1994    sent_msg.msg_flags = 0;
  1995  
  1996    ASSERT_THAT(RetryEINTR(sendmsg)(sender->get(), &sent_msg, 0),
  1997                SyscallSucceedsWithValue(kDataLength));
  1998  
  1999    msghdr received_msg = {};
  2000    iovec received_iov = {};
  2001    char received_data[kDataLength];
  2002    char received_cmsg_buf[CMSG_SPACE(sizeof(sockaddr_in))] = {};
  2003    size_t cmsg_data_len = sizeof(sockaddr_in);
  2004    received_iov.iov_base = received_data;
  2005    received_iov.iov_len = kDataLength;
  2006    received_msg.msg_iov = &received_iov;
  2007    received_msg.msg_iovlen = 1;
  2008    received_msg.msg_controllen = CMSG_LEN(cmsg_data_len);
  2009    received_msg.msg_control = received_cmsg_buf;
  2010  
  2011    ASSERT_THAT(RecvMsgTimeout(receiver->get(), &received_msg, 1 /*timeout*/),
  2012                IsPosixErrorOkAndHolds(kDataLength));
  2013  
  2014    cmsghdr* cmsg = CMSG_FIRSTHDR(&received_msg);
  2015    ASSERT_NE(cmsg, nullptr);
  2016    EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(cmsg_data_len));
  2017    EXPECT_EQ(cmsg->cmsg_level, level);
  2018    EXPECT_EQ(cmsg->cmsg_type, type);
  2019  
  2020    // Check the data
  2021    sockaddr_in received_addr = {};
  2022    memcpy(&received_addr, CMSG_DATA(cmsg), sizeof(received_addr));
  2023    auto orig_receiver_addr = reinterpret_cast<sockaddr_in*>(&receiver_addr.addr);
  2024    EXPECT_EQ(received_addr.sin_addr.s_addr, orig_receiver_addr->sin_addr.s_addr);
  2025    EXPECT_EQ(received_addr.sin_port, orig_receiver_addr->sin_port);
  2026  }
  2027  
  2028  // Check that setting SO_RCVBUF below min is clamped to the minimum
  2029  // receive buffer size.
  2030  TEST_P(IPv4UDPUnboundSocketTest, SetSocketRecvBufBelowMin) {
  2031    auto s = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  2032  
  2033    // Discover minimum buffer size by setting it to zero.
  2034    constexpr int kRcvBufSz = 0;
  2035    ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &kRcvBufSz,
  2036                           sizeof(kRcvBufSz)),
  2037                SyscallSucceeds());
  2038  
  2039    int min = 0;
  2040    socklen_t min_len = sizeof(min);
  2041    ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &min, &min_len),
  2042                SyscallSucceeds());
  2043  
  2044    // Linux doubles the value so let's use a value that when doubled will still
  2045    // be smaller than min.
  2046    int below_min = min / 2 - 1;
  2047    ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &below_min,
  2048                           sizeof(below_min)),
  2049                SyscallSucceeds());
  2050  
  2051    int val = 0;
  2052    socklen_t val_len = sizeof(val);
  2053    ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &val, &val_len),
  2054                SyscallSucceeds());
  2055  
  2056    ASSERT_EQ(min, val);
  2057  }
  2058  
  2059  // Check that setting SO_RCVBUF above max is clamped to the maximum
  2060  // receive buffer size.
  2061  TEST_P(IPv4UDPUnboundSocketTest, SetSocketRecvBufAboveMax) {
  2062    auto s = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  2063  
  2064    // Discover maxmimum buffer size by setting to a really large value.
  2065    constexpr int kRcvBufSz = 0xffffffff;
  2066    ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &kRcvBufSz,
  2067                           sizeof(kRcvBufSz)),
  2068                SyscallSucceeds());
  2069  
  2070    int max = 0;
  2071    socklen_t max_len = sizeof(max);
  2072    ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &max, &max_len),
  2073                SyscallSucceeds());
  2074  
  2075    int above_max = max + 1;
  2076    ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &above_max,
  2077                           sizeof(above_max)),
  2078                SyscallSucceeds());
  2079  
  2080    int val = 0;
  2081    socklen_t val_len = sizeof(val);
  2082    ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &val, &val_len),
  2083                SyscallSucceeds());
  2084    ASSERT_EQ(max, val);
  2085  }
  2086  
  2087  // Check that setting SO_RCVBUF min <= rcvBufSz <= max is honored.
  2088  TEST_P(IPv4UDPUnboundSocketTest, SetSocketRecvBuf) {
  2089    auto s = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  2090  
  2091    int max = 0;
  2092    int min = 0;
  2093    {
  2094      // Discover maxmimum buffer size by setting to a really large value.
  2095      constexpr int kRcvBufSz = 0xffffffff;
  2096      ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &kRcvBufSz,
  2097                             sizeof(kRcvBufSz)),
  2098                  SyscallSucceeds());
  2099  
  2100      max = 0;
  2101      socklen_t max_len = sizeof(max);
  2102      ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &max, &max_len),
  2103                  SyscallSucceeds());
  2104    }
  2105  
  2106    {
  2107      // Discover minimum buffer size by setting it to zero.
  2108      constexpr int kRcvBufSz = 0;
  2109      ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &kRcvBufSz,
  2110                             sizeof(kRcvBufSz)),
  2111                  SyscallSucceeds());
  2112  
  2113      socklen_t min_len = sizeof(min);
  2114      ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &min, &min_len),
  2115                  SyscallSucceeds());
  2116    }
  2117  
  2118    int quarter_sz = min + (max - min) / 4;
  2119    ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &quarter_sz,
  2120                           sizeof(quarter_sz)),
  2121                SyscallSucceeds());
  2122  
  2123    int val = 0;
  2124    socklen_t val_len = sizeof(val);
  2125    ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_RCVBUF, &val, &val_len),
  2126                SyscallSucceeds());
  2127  
  2128    // Linux doubles the value set by SO_SNDBUF/SO_RCVBUF.
  2129    quarter_sz *= 2;
  2130    ASSERT_EQ(quarter_sz, val);
  2131  }
  2132  
  2133  // Check that setting SO_SNDBUF below min is clamped to the minimum
  2134  // send buffer size.
  2135  TEST_P(IPv4UDPUnboundSocketTest, SetSocketSendBufBelowMin) {
  2136    auto s = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  2137  
  2138    // Discover minimum buffer size by setting it to zero.
  2139    constexpr int kSndBufSz = 0;
  2140    ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &kSndBufSz,
  2141                           sizeof(kSndBufSz)),
  2142                SyscallSucceeds());
  2143  
  2144    int min = 0;
  2145    socklen_t min_len = sizeof(min);
  2146    ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &min, &min_len),
  2147                SyscallSucceeds());
  2148  
  2149    // Linux doubles the value so let's use a value that when doubled will still
  2150    // be smaller than min.
  2151    int below_min = min / 2 - 1;
  2152    ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &below_min,
  2153                           sizeof(below_min)),
  2154                SyscallSucceeds());
  2155  
  2156    int val = 0;
  2157    socklen_t val_len = sizeof(val);
  2158    ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &val, &val_len),
  2159                SyscallSucceeds());
  2160  
  2161    ASSERT_EQ(min, val);
  2162  }
  2163  
  2164  // Check that setting SO_SNDBUF above max is clamped to the maximum
  2165  // send buffer size.
  2166  TEST_P(IPv4UDPUnboundSocketTest, SetSocketSendBufAboveMax) {
  2167    auto s = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  2168  
  2169    // Discover maxmimum buffer size by setting to a really large value.
  2170    constexpr int kSndBufSz = 0xffffffff;
  2171    ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &kSndBufSz,
  2172                           sizeof(kSndBufSz)),
  2173                SyscallSucceeds());
  2174  
  2175    int max = 0;
  2176    socklen_t max_len = sizeof(max);
  2177    ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &max, &max_len),
  2178                SyscallSucceeds());
  2179  
  2180    int above_max = max + 1;
  2181    ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &above_max,
  2182                           sizeof(above_max)),
  2183                SyscallSucceeds());
  2184  
  2185    int val = 0;
  2186    socklen_t val_len = sizeof(val);
  2187    ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &val, &val_len),
  2188                SyscallSucceeds());
  2189    ASSERT_EQ(max, val);
  2190  }
  2191  
  2192  // Check that setting SO_SNDBUF min <= kSndBufSz <= max is honored.
  2193  TEST_P(IPv4UDPUnboundSocketTest, SetSocketSendBuf) {
  2194    auto s = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  2195  
  2196    int max = 0;
  2197    int min = 0;
  2198    {
  2199      // Discover maxmimum buffer size by setting to a really large value.
  2200      constexpr int kSndBufSz = 0xffffffff;
  2201      ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &kSndBufSz,
  2202                             sizeof(kSndBufSz)),
  2203                  SyscallSucceeds());
  2204  
  2205      max = 0;
  2206      socklen_t max_len = sizeof(max);
  2207      ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &max, &max_len),
  2208                  SyscallSucceeds());
  2209    }
  2210  
  2211    {
  2212      // Discover minimum buffer size by setting it to zero.
  2213      constexpr int kSndBufSz = 0;
  2214      ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &kSndBufSz,
  2215                             sizeof(kSndBufSz)),
  2216                  SyscallSucceeds());
  2217  
  2218      socklen_t min_len = sizeof(min);
  2219      ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &min, &min_len),
  2220                  SyscallSucceeds());
  2221    }
  2222  
  2223    int quarter_sz = min + (max - min) / 4;
  2224    ASSERT_THAT(setsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &quarter_sz,
  2225                           sizeof(quarter_sz)),
  2226                SyscallSucceeds());
  2227  
  2228    int val = 0;
  2229    socklen_t val_len = sizeof(val);
  2230    ASSERT_THAT(getsockopt(s->get(), SOL_SOCKET, SO_SNDBUF, &val, &val_len),
  2231                SyscallSucceeds());
  2232  
  2233    quarter_sz *= 2;
  2234    ASSERT_EQ(quarter_sz, val);
  2235  }
  2236  
  2237  TEST_P(IPv4UDPUnboundSocketTest, IpMulticastIPPacketInfo) {
  2238    // TODO(b/267210840): Get multicast working with hostinet.
  2239    SKIP_IF(IsRunningWithHostinet());
  2240  
  2241    auto sender_socket = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  2242    auto receiver_socket = ASSERT_NO_ERRNO_AND_VALUE(NewSocket());
  2243  
  2244    // Bind the first FD to the loopback. This is an alternative to
  2245    // IP_MULTICAST_IF for setting the default send interface.
  2246    auto sender_addr = V4Loopback();
  2247    ASSERT_THAT(bind(sender_socket->get(), AsSockAddr(&sender_addr.addr),
  2248                     sender_addr.addr_len),
  2249                SyscallSucceeds());
  2250  
  2251    // Bind the second FD to the v4 any address to ensure that we can receive the
  2252    // multicast packet.
  2253    auto receiver_addr = V4Any();
  2254    ASSERT_THAT(bind(receiver_socket->get(), AsSockAddr(&receiver_addr.addr),
  2255                     receiver_addr.addr_len),
  2256                SyscallSucceeds());
  2257    socklen_t receiver_addr_len = receiver_addr.addr_len;
  2258    ASSERT_THAT(getsockname(receiver_socket->get(),
  2259                            AsSockAddr(&receiver_addr.addr), &receiver_addr_len),
  2260                SyscallSucceeds());
  2261    EXPECT_EQ(receiver_addr_len, receiver_addr.addr_len);
  2262  
  2263    // Register to receive multicast packets.
  2264    ip_mreqn group = {};
  2265    group.imr_multiaddr.s_addr = inet_addr(kMulticastAddress);
  2266    group.imr_ifindex = ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex());
  2267    ASSERT_THAT(setsockopt(receiver_socket->get(), IPPROTO_IP, IP_ADD_MEMBERSHIP,
  2268                           &group, sizeof(group)),
  2269                SyscallSucceeds());
  2270  
  2271    // Register to receive IP packet info.
  2272    const int one = 1;
  2273    ASSERT_THAT(setsockopt(receiver_socket->get(), IPPROTO_IP, IP_PKTINFO, &one,
  2274                           sizeof(one)),
  2275                SyscallSucceeds());
  2276  
  2277    // Send a multicast packet.
  2278    auto send_addr = V4Multicast();
  2279    reinterpret_cast<sockaddr_in*>(&send_addr.addr)->sin_port =
  2280        reinterpret_cast<sockaddr_in*>(&receiver_addr.addr)->sin_port;
  2281    char send_buf[200];
  2282    RandomizeBuffer(send_buf, sizeof(send_buf));
  2283    ASSERT_THAT(
  2284        RetryEINTR(sendto)(sender_socket->get(), send_buf, sizeof(send_buf), 0,
  2285                           AsSockAddr(&send_addr.addr), send_addr.addr_len),
  2286        SyscallSucceedsWithValue(sizeof(send_buf)));
  2287  
  2288    // Check that we received the multicast packet.
  2289    msghdr recv_msg = {};
  2290    iovec recv_iov = {};
  2291    char recv_buf[sizeof(send_buf)];
  2292    char recv_cmsg_buf[CMSG_SPACE(sizeof(in_pktinfo))] = {};
  2293    size_t cmsg_data_len = sizeof(in_pktinfo);
  2294    recv_iov.iov_base = recv_buf;
  2295    recv_iov.iov_len = sizeof(recv_buf);
  2296    recv_msg.msg_iov = &recv_iov;
  2297    recv_msg.msg_iovlen = 1;
  2298    recv_msg.msg_controllen = CMSG_LEN(cmsg_data_len);
  2299    recv_msg.msg_control = recv_cmsg_buf;
  2300    ASSERT_THAT(RetryEINTR(recvmsg)(receiver_socket->get(), &recv_msg, 0),
  2301                SyscallSucceedsWithValue(sizeof(send_buf)));
  2302    EXPECT_EQ(0, memcmp(send_buf, recv_buf, sizeof(send_buf)));
  2303  
  2304    // Check the IP_PKTINFO control message.
  2305    cmsghdr* cmsg = CMSG_FIRSTHDR(&recv_msg);
  2306    ASSERT_NE(cmsg, nullptr);
  2307    EXPECT_EQ(cmsg->cmsg_len, CMSG_LEN(cmsg_data_len));
  2308    EXPECT_EQ(cmsg->cmsg_level, IPPROTO_IP);
  2309    EXPECT_EQ(cmsg->cmsg_type, IP_PKTINFO);
  2310  
  2311    in_pktinfo received_pktinfo = {};
  2312    memcpy(&received_pktinfo, CMSG_DATA(cmsg), sizeof(in_pktinfo));
  2313    EXPECT_EQ(received_pktinfo.ipi_ifindex,
  2314              ASSERT_NO_ERRNO_AND_VALUE(GetLoopbackIndex()));
  2315    if (IsRunningOnGvisor()) {
  2316      // This should actually be a unicast address assigned to the interface.
  2317      //
  2318      // TODO(gvisor.dev/issue/3556): This check is validating incorrect
  2319      // behaviour. We still include the test so that once the bug is
  2320      // resolved, this test will start to fail and the individual tasked
  2321      // with fixing this bug knows to also fix this test :).
  2322      EXPECT_EQ(received_pktinfo.ipi_spec_dst.s_addr, group.imr_multiaddr.s_addr);
  2323    } else {
  2324      EXPECT_EQ(received_pktinfo.ipi_spec_dst.s_addr, htonl(INADDR_LOOPBACK));
  2325    }
  2326    EXPECT_EQ(received_pktinfo.ipi_addr.s_addr, group.imr_multiaddr.s_addr);
  2327  }
  2328  
  2329  }  // namespace testing
  2330  }  // namespace gvisor