xref: /linux/tools/testing/selftests/net/bind_wildcard.c (revision 2895d879dd41a588d80acde1aa832deb38d67823)
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 };
14 
15 FIXTURE_VARIANT(bind_wildcard)
16 {
17 	const __u32 addr4_const;
18 	const struct in6_addr *addr6_const;
19 	int expected_errno;
20 };
21 
22 FIXTURE_VARIANT_ADD(bind_wildcard, v4_any_v6_any)
23 {
24 	.addr4_const = INADDR_ANY,
25 	.addr6_const = &in6addr_any,
26 	.expected_errno = EADDRINUSE,
27 };
28 
29 FIXTURE_VARIANT_ADD(bind_wildcard, v4_any_v6_local)
30 {
31 	.addr4_const = INADDR_ANY,
32 	.addr6_const = &in6addr_loopback,
33 	.expected_errno = 0,
34 };
35 
36 FIXTURE_VARIANT_ADD(bind_wildcard, v4_local_v6_any)
37 {
38 	.addr4_const = INADDR_LOOPBACK,
39 	.addr6_const = &in6addr_any,
40 	.expected_errno = EADDRINUSE,
41 };
42 
43 FIXTURE_VARIANT_ADD(bind_wildcard, v4_local_v6_local)
44 {
45 	.addr4_const = INADDR_LOOPBACK,
46 	.addr6_const = &in6addr_loopback,
47 	.expected_errno = 0,
48 };
49 
50 FIXTURE_SETUP(bind_wildcard)
51 {
52 	self->addr4.sin_family = AF_INET;
53 	self->addr4.sin_port = htons(0);
54 	self->addr4.sin_addr.s_addr = htonl(variant->addr4_const);
55 
56 	self->addr6.sin6_family = AF_INET6;
57 	self->addr6.sin6_port = htons(0);
58 	self->addr6.sin6_addr = *variant->addr6_const;
59 }
60 
61 FIXTURE_TEARDOWN(bind_wildcard)
62 {
63 }
64 
65 void bind_sockets(struct __test_metadata *_metadata,
66 		  FIXTURE_DATA(bind_wildcard) *self,
67 		  int expected_errno,
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 (expected_errno) {
90 		ASSERT_EQ(ret, -1);
91 		ASSERT_EQ(errno, 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, variant->expected_errno,
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, variant->expected_errno,
110 		     (struct sockaddr *)&self->addr6, sizeof(self->addr6),
111 		     (struct sockaddr *)&self->addr4, sizeof(self->addr4));
112 }
113 
114 TEST_HARNESS_MAIN
115