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