1 // SPDX-License-Identifier: GPL-2.0 2 /* Copyright Amazon.com Inc. or its affiliates. */ 3 4 #include <sys/socket.h> 5 #include <netinet/in.h> 6 7 #include "../kselftest_harness.h" 8 9 FIXTURE(bind_wildcard) 10 { 11 struct sockaddr_in addr4; 12 struct sockaddr_in6 addr6; 13 int expected_errno; 14 }; 15 16 FIXTURE_VARIANT(bind_wildcard) 17 { 18 const __u32 addr4_const; 19 const struct in6_addr *addr6_const; 20 }; 21 22 FIXTURE_VARIANT_ADD(bind_wildcard, v4_any_v6_any) 23 { 24 .addr4_const = INADDR_ANY, 25 .addr6_const = &in6addr_any, 26 }; 27 28 FIXTURE_VARIANT_ADD(bind_wildcard, v4_any_v6_local) 29 { 30 .addr4_const = INADDR_ANY, 31 .addr6_const = &in6addr_loopback, 32 }; 33 34 FIXTURE_VARIANT_ADD(bind_wildcard, v4_local_v6_any) 35 { 36 .addr4_const = INADDR_LOOPBACK, 37 .addr6_const = &in6addr_any, 38 }; 39 40 FIXTURE_VARIANT_ADD(bind_wildcard, v4_local_v6_local) 41 { 42 .addr4_const = INADDR_LOOPBACK, 43 .addr6_const = &in6addr_loopback, 44 }; 45 46 FIXTURE_SETUP(bind_wildcard) 47 { 48 self->addr4.sin_family = AF_INET; 49 self->addr4.sin_port = htons(0); 50 self->addr4.sin_addr.s_addr = htonl(variant->addr4_const); 51 52 self->addr6.sin6_family = AF_INET6; 53 self->addr6.sin6_port = htons(0); 54 self->addr6.sin6_addr = *variant->addr6_const; 55 56 if (variant->addr6_const == &in6addr_any) 57 self->expected_errno = EADDRINUSE; 58 else 59 self->expected_errno = 0; 60 } 61 62 FIXTURE_TEARDOWN(bind_wildcard) 63 { 64 } 65 66 void bind_sockets(struct __test_metadata *_metadata, 67 FIXTURE_DATA(bind_wildcard) *self, 68 struct sockaddr *addr1, socklen_t addrlen1, 69 struct sockaddr *addr2, socklen_t addrlen2) 70 { 71 int fd[2]; 72 int ret; 73 74 fd[0] = socket(addr1->sa_family, SOCK_STREAM, 0); 75 ASSERT_GT(fd[0], 0); 76 77 ret = bind(fd[0], addr1, addrlen1); 78 ASSERT_EQ(ret, 0); 79 80 ret = getsockname(fd[0], addr1, &addrlen1); 81 ASSERT_EQ(ret, 0); 82 83 ((struct sockaddr_in *)addr2)->sin_port = ((struct sockaddr_in *)addr1)->sin_port; 84 85 fd[1] = socket(addr2->sa_family, SOCK_STREAM, 0); 86 ASSERT_GT(fd[1], 0); 87 88 ret = bind(fd[1], addr2, addrlen2); 89 if (self->expected_errno) { 90 ASSERT_EQ(ret, -1); 91 ASSERT_EQ(errno, self->expected_errno); 92 } else { 93 ASSERT_EQ(ret, 0); 94 } 95 96 close(fd[1]); 97 close(fd[0]); 98 } 99 100 TEST_F(bind_wildcard, v4_v6) 101 { 102 bind_sockets(_metadata, self, 103 (struct sockaddr *)&self->addr4, sizeof(self->addr4), 104 (struct sockaddr *)&self->addr6, sizeof(self->addr6)); 105 } 106 107 TEST_F(bind_wildcard, v6_v4) 108 { 109 bind_sockets(_metadata, self, 110 (struct sockaddr *)&self->addr6, sizeof(self->addr6), 111 (struct sockaddr *)&self->addr4, sizeof(self->addr4)); 112 } 113 114 TEST_HARNESS_MAIN 115