gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/test/syscalls/linux/packet_socket_dgram.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 <arpa/inet.h>
    16  #include <errno.h>
    17  #include <ifaddrs.h>
    18  #include <net/ethernet.h>
    19  #include <net/if.h>
    20  #include <net/if_arp.h>
    21  #include <netinet/in.h>
    22  #include <netinet/ip.h>
    23  #include <netinet/udp.h>
    24  #include <netpacket/packet.h>
    25  #include <poll.h>
    26  #include <sys/ioctl.h>
    27  #include <sys/socket.h>
    28  #include <sys/types.h>
    29  #include <unistd.h>
    30  
    31  #include "gtest/gtest.h"
    32  #include "absl/base/internal/endian.h"
    33  #include "test/syscalls/linux/ip_socket_test_util.h"
    34  #include "test/syscalls/linux/unix_domain_socket_test_util.h"
    35  #include "test/util/capability_util.h"
    36  #include "test/util/cleanup.h"
    37  #include "test/util/file_descriptor.h"
    38  #include "test/util/posix_error.h"
    39  #include "test/util/socket_util.h"
    40  #include "test/util/test_util.h"
    41  
    42  // Some of these tests involve sending packets via AF_PACKET sockets and the
    43  // loopback interface. Because AF_PACKET circumvents so much of the networking
    44  // stack, Linux sees these packets as "martian", i.e. they claim to be to/from
    45  // localhost but don't have the usual associated data. Thus Linux drops them by
    46  // default. You can see where this happens by following the code at:
    47  //
    48  // - net/ipv4/ip_input.c:ip_rcv_finish, which calls
    49  // - net/ipv4/route.c:ip_route_input_noref, which calls
    50  // - net/ipv4/route.c:ip_route_input_slow, which finds and drops martian
    51  //   packets.
    52  //
    53  // To tell Linux not to drop these packets, you need to tell it to accept our
    54  // funny packets (which are completely valid and correct, but lack associated
    55  // in-kernel data because we use AF_PACKET):
    56  //
    57  // echo 1 >> /proc/sys/net/ipv4/conf/lo/accept_local
    58  // echo 1 >> /proc/sys/net/ipv4/conf/lo/route_localnet
    59  //
    60  // These tests require CAP_NET_RAW to run.
    61  
    62  namespace gvisor {
    63  namespace testing {
    64  
    65  namespace {
    66  
    67  using ::testing::AnyOf;
    68  using ::testing::Eq;
    69  
    70  constexpr char kMessage[] = "soweoneul malhaebwa";
    71  constexpr in_port_t kPort = 0x409c;  // htons(40000)
    72  
    73  //
    74  // "Cooked" tests. Cooked AF_PACKET sockets do not contain link layer
    75  // headers, and provide link layer destination/source information via a
    76  // returned struct sockaddr_ll.
    77  //
    78  
    79  // Send kMessage via sock to loopback
    80  void SendUDPMessage(int sock) {
    81    struct sockaddr_in dest = {};
    82    dest.sin_port = kPort;
    83    dest.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    84    dest.sin_family = AF_INET;
    85    EXPECT_THAT(sendto(sock, kMessage, sizeof(kMessage), 0,
    86                       reinterpret_cast<struct sockaddr*>(&dest), sizeof(dest)),
    87                SyscallSucceedsWithValue(sizeof(kMessage)));
    88  }
    89  
    90  // Send an IP packet and make sure ETH_P_<something else> doesn't pick it up.
    91  TEST(BasicCookedPacketTest, WrongType) {
    92    if (!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {
    93      ASSERT_THAT(socket(AF_PACKET, SOCK_DGRAM, ETH_P_PUP),
    94                  SyscallFailsWithErrno(EPERM));
    95      GTEST_SKIP();
    96    }
    97  
    98    FileDescriptor sock = ASSERT_NO_ERRNO_AND_VALUE(
    99        Socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_PUP)));
   100  
   101    // Let's use a simple IP payload: a UDP datagram.
   102    FileDescriptor udp_sock =
   103        ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));
   104    SendUDPMessage(udp_sock.get());
   105  
   106    // Wait and make sure the socket never becomes readable.
   107    struct pollfd pfd = {};
   108    pfd.fd = sock.get();
   109    pfd.events = POLLIN;
   110    EXPECT_THAT(RetryEINTR(poll)(&pfd, 1, 1000), SyscallSucceedsWithValue(0));
   111  }
   112  
   113  // Tests for "cooked" (SOCK_DGRAM) packet(7) sockets.
   114  class CookedPacketTest : public ::testing::TestWithParam<int> {
   115   protected:
   116    // Creates a socket to be used in tests.
   117    void SetUp() override;
   118  
   119    // Closes the socket created by SetUp().
   120    void TearDown() override;
   121  
   122    // Gets the device index of the loopback device.
   123    int GetLoopbackIndex();
   124  
   125    // The socket used for both reading and writing.
   126    int socket_;
   127  
   128    // The function to restore the original system configuration.
   129    std::function<PosixError()> restore_config_;
   130  };
   131  
   132  void CookedPacketTest::SetUp() {
   133    if (!ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {
   134      ASSERT_THAT(socket(AF_PACKET, SOCK_DGRAM, htons(GetParam())),
   135                  SyscallFailsWithErrno(EPERM));
   136      GTEST_SKIP();
   137    }
   138  
   139    ASSERT_THAT(socket_ = socket(AF_PACKET, SOCK_DGRAM, htons(GetParam())),
   140                SyscallSucceeds());
   141  
   142    auto restore_config = AllowMartianPacketsOnLoopback();
   143    if (restore_config.ok()) {
   144      restore_config_ = restore_config.ValueOrDie();
   145    } else {
   146      ASSERT_THAT(restore_config.error(), PosixErrorIs(EACCES));
   147      GTEST_SKIP();
   148    }
   149  }
   150  
   151  void CookedPacketTest::TearDown() {
   152    if (restore_config_) {
   153      EXPECT_NO_ERRNO(restore_config_());
   154    }
   155  
   156    // TearDown will be run even if we skip the test.
   157    if (ASSERT_NO_ERRNO_AND_VALUE(HavePacketSocketCapability())) {
   158      EXPECT_THAT(close(socket_), SyscallSucceeds());
   159    }
   160  }
   161  
   162  int CookedPacketTest::GetLoopbackIndex() {
   163    int v = EXPECT_NO_ERRNO_AND_VALUE(gvisor::testing::GetLoopbackIndex());
   164    EXPECT_NE(v, 0);
   165    return v;
   166  }
   167  
   168  // Receive and verify the message via packet socket on interface.
   169  void ReceiveMessage(int sock, int ifindex) {
   170    // Wait for the socket to become readable.
   171    struct pollfd pfd = {};
   172    pfd.fd = sock;
   173    pfd.events = POLLIN;
   174    EXPECT_THAT(RetryEINTR(poll)(&pfd, 1, 2000), SyscallSucceedsWithValue(1));
   175  
   176    // Read and verify the data.
   177    constexpr size_t packet_size =
   178        sizeof(struct iphdr) + sizeof(struct udphdr) + sizeof(kMessage);
   179    char buf[64];
   180    struct sockaddr_ll src = {};
   181    socklen_t src_len = sizeof(src);
   182    ASSERT_THAT(recvfrom(sock, buf, sizeof(buf), 0,
   183                         reinterpret_cast<struct sockaddr*>(&src), &src_len),
   184                SyscallSucceedsWithValue(packet_size));
   185  
   186    // sockaddr_ll ends with an 8 byte physical address field, but ethernet
   187    // addresses only use 6 bytes.  Linux used to return sizeof(sockaddr_ll)-2
   188    // here, but since commit b2cf86e1563e33a14a1c69b3e508d15dc12f804c returns
   189    // sizeof(sockaddr_ll).
   190    ASSERT_THAT(src_len, AnyOf(Eq(sizeof(src)), Eq(sizeof(src) - 2)));
   191  
   192    // Verify the source address.
   193    EXPECT_EQ(src.sll_family, AF_PACKET);
   194    EXPECT_EQ(src.sll_ifindex, ifindex);
   195    EXPECT_EQ(src.sll_halen, ETH_ALEN);
   196    EXPECT_EQ(ntohs(src.sll_protocol), ETH_P_IP);
   197    // This came from the loopback device, so the address is all 0s.
   198    for (int i = 0; i < src.sll_halen; i++) {
   199      EXPECT_EQ(src.sll_addr[i], 0);
   200    }
   201  
   202    // Verify the IP header. We memcpy to deal with pointer aligment.
   203    struct iphdr ip = {};
   204    memcpy(&ip, buf, sizeof(ip));
   205    EXPECT_EQ(ip.ihl, 5);
   206    EXPECT_EQ(ip.version, 4);
   207    EXPECT_EQ(ip.tot_len, htons(packet_size));
   208    EXPECT_EQ(ip.protocol, IPPROTO_UDP);
   209    EXPECT_EQ(ip.daddr, htonl(INADDR_LOOPBACK));
   210    EXPECT_EQ(ip.saddr, htonl(INADDR_LOOPBACK));
   211  
   212    // Verify the UDP header. We memcpy to deal with pointer aligment.
   213    struct udphdr udp = {};
   214    memcpy(&udp, buf + sizeof(iphdr), sizeof(udp));
   215    EXPECT_EQ(udp.dest, kPort);
   216    EXPECT_EQ(udp.len, htons(sizeof(udphdr) + sizeof(kMessage)));
   217  
   218    // Verify the payload.
   219    char* payload = reinterpret_cast<char*>(buf + sizeof(iphdr) + sizeof(udphdr));
   220    EXPECT_EQ(strncmp(payload, kMessage, sizeof(kMessage)), 0);
   221  }
   222  
   223  // Receive via a packet socket.
   224  TEST_P(CookedPacketTest, Receive) {
   225    // Let's use a simple IP payload: a UDP datagram.
   226    FileDescriptor udp_sock =
   227        ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));
   228    SendUDPMessage(udp_sock.get());
   229  
   230    // Receive and verify the data.
   231    int loopback_index = GetLoopbackIndex();
   232    ReceiveMessage(socket_, loopback_index);
   233  }
   234  
   235  // Send via a packet socket.
   236  TEST_P(CookedPacketTest, Send) {
   237    // TODO(b/267210840): Fix this test for hostinet. Something is wrong with
   238    // poll().
   239    SKIP_IF(IsRunningWithHostinet());
   240  
   241    // Let's send a UDP packet and receive it using a regular UDP socket.
   242    FileDescriptor udp_sock =
   243        ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));
   244    struct sockaddr_in bind_addr = {};
   245    bind_addr.sin_family = AF_INET;
   246    bind_addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
   247    bind_addr.sin_port = kPort;
   248    ASSERT_THAT(
   249        bind(udp_sock.get(), reinterpret_cast<struct sockaddr*>(&bind_addr),
   250             sizeof(bind_addr)),
   251        SyscallSucceeds());
   252  
   253    // Set up the destination physical address.
   254    struct sockaddr_ll dest = {};
   255    dest.sll_family = AF_PACKET;
   256    dest.sll_halen = ETH_ALEN;
   257    dest.sll_ifindex = GetLoopbackIndex();
   258    dest.sll_protocol = htons(ETH_P_IP);
   259    // We're sending to the loopback device, so the address is all 0s.
   260    memset(dest.sll_addr, 0x00, ETH_ALEN);
   261  
   262    // Set up the IP header.
   263    struct iphdr iphdr = {0};
   264    iphdr.ihl = 5;
   265    iphdr.version = 4;
   266    iphdr.tos = 0;
   267    iphdr.tot_len =
   268        htons(sizeof(struct iphdr) + sizeof(struct udphdr) + sizeof(kMessage));
   269    // Get a pseudo-random ID. If we clash with an in-use ID the test will fail,
   270    // but we have no way of getting an ID we know to be good.
   271    srand(*reinterpret_cast<unsigned int*>(&iphdr));
   272    iphdr.id = rand();
   273    // Linux sets this bit ("do not fragment") for small packets.
   274    iphdr.frag_off = 1 << 6;
   275    iphdr.ttl = 64;
   276    iphdr.protocol = IPPROTO_UDP;
   277    iphdr.daddr = htonl(INADDR_LOOPBACK);
   278    iphdr.saddr = htonl(INADDR_LOOPBACK);
   279    iphdr.check = IPChecksum(iphdr);
   280  
   281    // Set up the UDP header.
   282    struct udphdr udphdr = {};
   283    udphdr.source = kPort;
   284    udphdr.dest = kPort;
   285    udphdr.len = htons(sizeof(udphdr) + sizeof(kMessage));
   286    udphdr.check = UDPChecksum(iphdr, udphdr, kMessage, sizeof(kMessage));
   287  
   288    // Copy both headers and the payload into our packet buffer.
   289    char send_buf[sizeof(iphdr) + sizeof(udphdr) + sizeof(kMessage)];
   290    memcpy(send_buf, &iphdr, sizeof(iphdr));
   291    memcpy(send_buf + sizeof(iphdr), &udphdr, sizeof(udphdr));
   292    memcpy(send_buf + sizeof(iphdr) + sizeof(udphdr), kMessage, sizeof(kMessage));
   293  
   294    // Send it.
   295    ASSERT_THAT(sendto(socket_, send_buf, sizeof(send_buf), 0,
   296                       reinterpret_cast<struct sockaddr*>(&dest), sizeof(dest)),
   297                SyscallSucceedsWithValue(sizeof(send_buf)));
   298  
   299    // Wait for the packet to become available on both sockets.
   300    struct pollfd pfd = {};
   301    pfd.fd = udp_sock.get();
   302    pfd.events = POLLIN;
   303    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, 5000), SyscallSucceedsWithValue(1));
   304    pfd.fd = socket_;
   305    pfd.events = POLLIN;
   306    ASSERT_THAT(RetryEINTR(poll)(&pfd, 1, 5000), SyscallSucceedsWithValue(1));
   307  
   308    // Receive on the packet socket.
   309    char recv_buf[sizeof(send_buf)];
   310    ASSERT_THAT(recv(socket_, recv_buf, sizeof(recv_buf), 0),
   311                SyscallSucceedsWithValue(sizeof(recv_buf)));
   312    ASSERT_EQ(memcmp(recv_buf, send_buf, sizeof(send_buf)), 0);
   313  
   314    // Receive on the UDP socket.
   315    struct sockaddr_in src;
   316    socklen_t src_len = sizeof(src);
   317    ASSERT_THAT(recvfrom(udp_sock.get(), recv_buf, sizeof(recv_buf), MSG_DONTWAIT,
   318                         reinterpret_cast<struct sockaddr*>(&src), &src_len),
   319                SyscallSucceedsWithValue(sizeof(kMessage)));
   320    // Check src and payload.
   321    EXPECT_EQ(strncmp(recv_buf, kMessage, sizeof(kMessage)), 0);
   322    EXPECT_EQ(src.sin_family, AF_INET);
   323    EXPECT_EQ(src.sin_port, kPort);
   324    EXPECT_EQ(src.sin_addr.s_addr, htonl(INADDR_LOOPBACK));
   325  }
   326  
   327  // Bind and receive via packet socket.
   328  TEST_P(CookedPacketTest, BindReceive) {
   329    struct sockaddr_ll bind_addr = {};
   330    bind_addr.sll_family = AF_PACKET;
   331    bind_addr.sll_protocol = htons(GetParam());
   332    bind_addr.sll_ifindex = GetLoopbackIndex();
   333  
   334    ASSERT_THAT(bind(socket_, reinterpret_cast<struct sockaddr*>(&bind_addr),
   335                     sizeof(bind_addr)),
   336                SyscallSucceeds());
   337  
   338    // Let's use a simple IP payload: a UDP datagram.
   339    FileDescriptor udp_sock =
   340        ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));
   341    SendUDPMessage(udp_sock.get());
   342  
   343    // Receive and verify the data.
   344    ReceiveMessage(socket_, bind_addr.sll_ifindex);
   345  }
   346  
   347  // Double Bind socket.
   348  TEST_P(CookedPacketTest, DoubleBindSucceeds) {
   349    struct sockaddr_ll bind_addr = {};
   350    bind_addr.sll_family = AF_PACKET;
   351    bind_addr.sll_protocol = htons(GetParam());
   352    bind_addr.sll_ifindex = GetLoopbackIndex();
   353  
   354    ASSERT_THAT(bind(socket_, reinterpret_cast<struct sockaddr*>(&bind_addr),
   355                     sizeof(bind_addr)),
   356                SyscallSucceeds());
   357  
   358    // Binding socket again should fail.
   359    ASSERT_THAT(bind(socket_, reinterpret_cast<struct sockaddr*>(&bind_addr),
   360                     sizeof(bind_addr)),
   361                // Linux 4.09 returns EINVAL here, but some time before 4.19 it
   362                // switched to EADDRINUSE.
   363                SyscallSucceeds());
   364  }
   365  
   366  // Bind and verify we do not receive data on interface which is not bound
   367  TEST_P(CookedPacketTest, BindDrop) {
   368    // Let's use a simple IP payload: a UDP datagram.
   369    FileDescriptor udp_sock =
   370        ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));
   371  
   372    struct ifaddrs* if_addr_list = nullptr;
   373    auto cleanup = Cleanup([&if_addr_list]() { freeifaddrs(if_addr_list); });
   374  
   375    ASSERT_THAT(getifaddrs(&if_addr_list), SyscallSucceeds());
   376  
   377    // Get interface other than loopback.
   378    struct ifreq ifr = {};
   379    for (struct ifaddrs* i = if_addr_list; i; i = i->ifa_next) {
   380      if (strcmp(i->ifa_name, "lo") != 0) {
   381        strncpy(ifr.ifr_name, i->ifa_name, sizeof(ifr.ifr_name));
   382        break;
   383      }
   384    }
   385  
   386    // Skip if no interface is available other than loopback.
   387    if (strlen(ifr.ifr_name) == 0) {
   388      GTEST_SKIP();
   389    }
   390  
   391    // Get interface index.
   392    EXPECT_THAT(ioctl(socket_, SIOCGIFINDEX, &ifr), SyscallSucceeds());
   393    EXPECT_NE(ifr.ifr_ifindex, 0);
   394  
   395    // Bind to packet socket requires only family, protocol and ifindex.
   396    struct sockaddr_ll bind_addr = {};
   397    bind_addr.sll_family = AF_PACKET;
   398    bind_addr.sll_protocol = htons(GetParam());
   399    bind_addr.sll_ifindex = ifr.ifr_ifindex;
   400  
   401    ASSERT_THAT(bind(socket_, reinterpret_cast<struct sockaddr*>(&bind_addr),
   402                     sizeof(bind_addr)),
   403                SyscallSucceeds());
   404  
   405    // Send to loopback interface.
   406    struct sockaddr_in dest = {};
   407    dest.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
   408    dest.sin_family = AF_INET;
   409    dest.sin_port = kPort;
   410    EXPECT_THAT(sendto(udp_sock.get(), kMessage, sizeof(kMessage), 0,
   411                       reinterpret_cast<struct sockaddr*>(&dest), sizeof(dest)),
   412                SyscallSucceedsWithValue(sizeof(kMessage)));
   413  
   414    // Wait and make sure the socket never receives any data.
   415    struct pollfd pfd = {};
   416    pfd.fd = socket_;
   417    pfd.events = POLLIN;
   418    EXPECT_THAT(RetryEINTR(poll)(&pfd, 1, 1000), SyscallSucceedsWithValue(0));
   419  }
   420  
   421  // Verify that we receive outbound packets. This test requires at least one
   422  // non loopback interface so that we can actually capture an outgoing packet.
   423  TEST_P(CookedPacketTest, ReceiveOutbound) {
   424    // Only ETH_P_ALL sockets can receive outbound packets on linux.
   425    SKIP_IF(GetParam() != ETH_P_ALL);
   426  
   427    // Let's use a simple IP payload: a UDP datagram.
   428    FileDescriptor udp_sock =
   429        ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET, SOCK_DGRAM, 0));
   430  
   431    struct ifaddrs* if_addr_list = nullptr;
   432    auto cleanup = Cleanup([&if_addr_list]() { freeifaddrs(if_addr_list); });
   433  
   434    ASSERT_THAT(getifaddrs(&if_addr_list), SyscallSucceeds());
   435  
   436    // Get interface other than loopback.
   437    struct ifreq ifr = {};
   438    for (struct ifaddrs* i = if_addr_list; i; i = i->ifa_next) {
   439      if (strcmp(i->ifa_name, "lo") != 0) {
   440        strncpy(ifr.ifr_name, i->ifa_name, sizeof(ifr.ifr_name));
   441        break;
   442      }
   443    }
   444  
   445    // Skip if no interface is available other than loopback.
   446    if (strlen(ifr.ifr_name) == 0) {
   447      GTEST_SKIP();
   448    }
   449  
   450    // Get interface index and name.
   451    EXPECT_THAT(ioctl(socket_, SIOCGIFINDEX, &ifr), SyscallSucceeds());
   452    EXPECT_NE(ifr.ifr_ifindex, 0);
   453    int ifindex = ifr.ifr_ifindex;
   454  
   455    constexpr int kMACSize = 6;
   456    char hwaddr[kMACSize];
   457    // Get interface address.
   458    ASSERT_THAT(ioctl(socket_, SIOCGIFHWADDR, &ifr), SyscallSucceeds());
   459    ASSERT_THAT(ifr.ifr_hwaddr.sa_family,
   460                AnyOf(Eq(ARPHRD_NONE), Eq(ARPHRD_ETHER)));
   461    memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, kMACSize);
   462  
   463    // Just send it to the google dns server 8.8.8.8. It's UDP we don't care
   464    // if it actually gets to the DNS Server we just want to see that we receive
   465    // it on our AF_PACKET socket.
   466    //
   467    // NOTE: We just want to pick an IP that is non-local to avoid having to
   468    // handle ARP as this should cause the UDP packet to be sent to the default
   469    // gateway configured for the system under test. Otherwise the only packet we
   470    // will see is the ARP query unless we picked an IP which will actually
   471    // resolve. The test is a bit brittle but this was the best compromise for
   472    // now.
   473    struct sockaddr_in dest = {};
   474    ASSERT_EQ(inet_pton(AF_INET, "8.8.8.8", &dest.sin_addr.s_addr), 1);
   475    dest.sin_family = AF_INET;
   476    dest.sin_port = kPort;
   477    EXPECT_THAT(sendto(udp_sock.get(), kMessage, sizeof(kMessage), 0,
   478                       reinterpret_cast<struct sockaddr*>(&dest), sizeof(dest)),
   479                SyscallSucceedsWithValue(sizeof(kMessage)));
   480  
   481    // Wait and make sure the socket receives the data.
   482    struct pollfd pfd = {};
   483    pfd.fd = socket_;
   484    pfd.events = POLLIN;
   485    EXPECT_THAT(RetryEINTR(poll)(&pfd, 1, 1000), SyscallSucceedsWithValue(1));
   486  
   487    // Now read and check that the packet is the one we just sent.
   488    // Read and verify the data.
   489    constexpr size_t packet_size =
   490        sizeof(struct iphdr) + sizeof(struct udphdr) + sizeof(kMessage);
   491    char buf[64];
   492    struct sockaddr_ll src = {};
   493    socklen_t src_len = sizeof(src);
   494    ASSERT_THAT(recvfrom(socket_, buf, sizeof(buf), 0,
   495                         reinterpret_cast<struct sockaddr*>(&src), &src_len),
   496                SyscallSucceedsWithValue(packet_size));
   497  
   498    // sockaddr_ll ends with an 8 byte physical address field, but ethernet
   499    // addresses only use 6 bytes.  Linux used to return sizeof(sockaddr_ll)-2
   500    // here, but since commit b2cf86e1563e33a14a1c69b3e508d15dc12f804c returns
   501    // sizeof(sockaddr_ll).
   502    ASSERT_THAT(src_len, AnyOf(Eq(sizeof(src)), Eq(sizeof(src) - 2)));
   503  
   504    // Verify the source address.
   505    EXPECT_EQ(src.sll_family, AF_PACKET);
   506    EXPECT_EQ(src.sll_ifindex, ifindex);
   507    EXPECT_EQ(src.sll_halen, ETH_ALEN);
   508    EXPECT_EQ(ntohs(src.sll_protocol), ETH_P_IP);
   509    EXPECT_EQ(src.sll_pkttype, PACKET_OUTGOING);
   510    // Verify the link address of the interface matches that of the non
   511    // non loopback interface address we stored above.
   512    for (int i = 0; i < src.sll_halen; i++) {
   513      EXPECT_EQ(src.sll_addr[i], hwaddr[i]);
   514    }
   515  
   516    // Verify the IP header.
   517    struct iphdr ip = {};
   518    memcpy(&ip, buf, sizeof(ip));
   519    EXPECT_EQ(ip.ihl, 5);
   520    EXPECT_EQ(ip.version, 4);
   521    EXPECT_EQ(ip.tot_len, htons(packet_size));
   522    EXPECT_EQ(ip.protocol, IPPROTO_UDP);
   523    EXPECT_EQ(ip.daddr, dest.sin_addr.s_addr);
   524    EXPECT_NE(ip.saddr, htonl(INADDR_LOOPBACK));
   525  
   526    // Verify the UDP header.
   527    struct udphdr udp = {};
   528    memcpy(&udp, buf + sizeof(iphdr), sizeof(udp));
   529    EXPECT_EQ(udp.dest, kPort);
   530    EXPECT_EQ(udp.len, htons(sizeof(udphdr) + sizeof(kMessage)));
   531  
   532    // Verify the payload.
   533    char* payload = reinterpret_cast<char*>(buf + sizeof(iphdr) + sizeof(udphdr));
   534    EXPECT_EQ(strncmp(payload, kMessage, sizeof(kMessage)), 0);
   535  }
   536  
   537  // Bind with invalid address.
   538  TEST_P(CookedPacketTest, BindFail) {
   539    // Null address.
   540    ASSERT_THAT(
   541        bind(socket_, nullptr, sizeof(struct sockaddr)),
   542        AnyOf(SyscallFailsWithErrno(EFAULT), SyscallFailsWithErrno(EINVAL)));
   543  
   544    // Address of size 1.
   545    uint8_t addr = 0;
   546    ASSERT_THAT(
   547        bind(socket_, reinterpret_cast<struct sockaddr*>(&addr), sizeof(addr)),
   548        SyscallFailsWithErrno(EINVAL));
   549  }
   550  
   551  INSTANTIATE_TEST_SUITE_P(AllInetTests, CookedPacketTest,
   552                           ::testing::Values(ETH_P_IP, ETH_P_ALL));
   553  
   554  }  // namespace
   555  
   556  }  // namespace testing
   557  }  // namespace gvisor