1 /*
2 * Copyright 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 * sock_diag_test.cpp - unit tests for SockDiag.cpp
17 */
18
19 #include <arpa/inet.h>
20 #include <netinet/in.h>
21 #include <linux/inet_diag.h>
22
23 #include <gtest/gtest.h>
24
25 #include "NetdConstants.h"
26 #include "SockDiag.h"
27 #include "UidRanges.h"
28
29 class SockDiagTest : public ::testing::Test {
30 };
31
bindAndListen(int s)32 uint16_t bindAndListen(int s) {
33 for (int i = 0; i < 10; i++) {
34 uint16_t port = 1024 + arc4random_uniform(0xffff - 1024);
35 sockaddr_in6 sin6 = { .sin6_family = AF_INET6, .sin6_port = htons(port) };
36 if (bind(s, (sockaddr *) &sin6, sizeof(sin6)) == 0) {
37 listen(s, 1);
38 return port;
39 }
40 }
41 close(s);
42 return 0;
43 }
44
tcpStateName(uint8_t state)45 const char *tcpStateName(uint8_t state) {
46 static const char *states[] = {
47 "???",
48 "TCP_ESTABLISHED",
49 "TCP_SYN_SENT",
50 "TCP_SYN_RECV",
51 "TCP_FIN_WAIT1",
52 "TCP_FIN_WAIT2",
53 "TCP_TIME_WAIT",
54 "TCP_CLOSE",
55 "TCP_CLOSE_WAIT",
56 "TCP_LAST_ACK",
57 "TCP_LISTEN",
58 "TCP_CLOSING",
59 "TCP_NEW_SYN_RECV",
60 };
61 return states[(state < ARRAY_SIZE(states)) ? state : 0];
62 }
63
TEST_F(SockDiagTest,TestDump)64 TEST_F(SockDiagTest, TestDump) {
65 int v4socket = socket(AF_INET, SOCK_STREAM, 0);
66 ASSERT_NE(-1, v4socket) << "Failed to open IPv4 socket: " << strerror(errno);
67 int v6socket = socket(AF_INET6, SOCK_STREAM, 0);
68 ASSERT_NE(-1, v6socket) << "Failed to open IPv6 socket: " << strerror(errno);
69 int listensocket = socket(AF_INET6, SOCK_STREAM, 0);
70 ASSERT_NE(-1, listensocket) << "Failed to open listen socket: " << strerror(errno);
71
72 uint16_t port = bindAndListen(listensocket);
73 ASSERT_NE(0, port) << "Can't bind to server port";
74
75 // Connect to loopback.
76 sockaddr_in server4 = { .sin_family = AF_INET, .sin_port = htons(port) };
77 sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_port = htons(port) };
78 ASSERT_EQ(0, connect(v4socket, (sockaddr *) &server4, sizeof(server4)))
79 << "IPv4 connect failed: " << strerror(errno);
80 ASSERT_EQ(0, connect(v6socket, (sockaddr *) &server6, sizeof(server6)))
81 << "IPv6 connect failed: " << strerror(errno);
82
83 sockaddr_in6 client46, client6;
84 socklen_t clientlen = std::max(sizeof(client46), sizeof(client6));
85 int accepted4 = accept(listensocket, (sockaddr *) &client46, &clientlen);
86 int accepted6 = accept(listensocket, (sockaddr *) &client6, &clientlen);
87 ASSERT_NE(-1, accepted4);
88 ASSERT_NE(-1, accepted6);
89
90 int v4SocketsSeen = 0;
91 bool seenclient46 = false;
92 bool seenNull = false;
93 char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
94
95 fprintf(stderr, "Ports:\n server=%d. client46=%d, client6=%d\n",
96 port, ntohs(client46.sin6_port), ntohs(client6.sin6_port));
97
98 auto checkIPv4Dump = [&] (uint8_t /* proto */, const inet_diag_msg *msg) {
99 if (msg == nullptr) {
100 EXPECT_FALSE(seenNull);
101 seenNull = true;
102 return false;
103 }
104 EXPECT_EQ(htonl(INADDR_LOOPBACK), msg->id.idiag_src[0]);
105 v4SocketsSeen++;
106 seenclient46 |= (msg->id.idiag_sport == client46.sin6_port);
107 inet_ntop(AF_INET, msg->id.idiag_src, src, sizeof(src));
108 inet_ntop(AF_INET, msg->id.idiag_src, dst, sizeof(dst));
109 fprintf(stderr, " v4 %s:%d -> %s:%d %s\n",
110 src, htons(msg->id.idiag_sport),
111 dst, htons(msg->id.idiag_dport),
112 tcpStateName(msg->idiag_state));
113 return false;
114 };
115
116 int v6SocketsSeen = 0;
117 bool seenClient6 = false, seenServer46 = false, seenServer6 = false;
118
119 auto checkIPv6Dump = [&] (uint8_t /* proto */, const inet_diag_msg *msg) {
120 if (msg == nullptr) {
121 EXPECT_FALSE(seenNull);
122 seenNull = true;
123 return false;
124 }
125 struct in6_addr *saddr = (struct in6_addr *) msg->id.idiag_src;
126 EXPECT_TRUE(
127 IN6_IS_ADDR_LOOPBACK(saddr) ||
128 (IN6_IS_ADDR_V4MAPPED(saddr) && saddr->s6_addr32[3] == htonl(INADDR_LOOPBACK)));
129 v6SocketsSeen++;
130 seenClient6 |= (msg->id.idiag_sport == client6.sin6_port);
131 seenServer46 |= (msg->id.idiag_sport == htons(port));
132 seenServer6 |= (msg->id.idiag_sport == htons(port));
133 inet_ntop(AF_INET6, msg->id.idiag_src, src, sizeof(src));
134 inet_ntop(AF_INET6, msg->id.idiag_src, dst, sizeof(dst));
135 fprintf(stderr, " v6 [%s]:%d -> [%s]:%d %s\n",
136 src, htons(msg->id.idiag_sport),
137 dst, htons(msg->id.idiag_dport),
138 tcpStateName(msg->idiag_state));
139 return false;
140 };
141
142 SockDiag sd;
143 ASSERT_TRUE(sd.open()) << "Failed to open SOCK_DIAG socket";
144
145 seenNull = false;
146 int ret = sd.sendDumpRequest(IPPROTO_TCP, AF_INET, "127.0.0.1");
147 ASSERT_EQ(0, ret) << "Failed to send IPv4 dump request: " << strerror(-ret);
148 fprintf(stderr, "Sent IPv4 dump\n");
149 sd.readDiagMsg(IPPROTO_TCP, checkIPv4Dump);
150 EXPECT_GE(v4SocketsSeen, 1);
151 EXPECT_TRUE(seenclient46);
152 EXPECT_FALSE(seenServer46);
153
154 seenNull = false;
155 ret = sd.sendDumpRequest(IPPROTO_TCP, AF_INET6, "127.0.0.1");
156 ASSERT_EQ(0, ret) << "Failed to send mapped dump request: " << strerror(-ret);
157 fprintf(stderr, "Sent mapped dump\n");
158 sd.readDiagMsg(IPPROTO_TCP, checkIPv6Dump);
159 EXPECT_TRUE(seenServer46);
160
161 seenNull = false;
162 ret = sd.sendDumpRequest(IPPROTO_TCP, AF_INET6, "::1");
163 ASSERT_EQ(0, ret) << "Failed to send IPv6 dump request: " << strerror(-ret);
164 fprintf(stderr, "Sent IPv6 dump\n");
165
166 sd.readDiagMsg(IPPROTO_TCP, checkIPv6Dump);
167 EXPECT_GE(v6SocketsSeen, 1);
168 EXPECT_TRUE(seenClient6);
169 EXPECT_TRUE(seenServer6);
170
171 close(v4socket);
172 close(v6socket);
173 close(listensocket);
174 close(accepted4);
175 close(accepted6);
176 }
177
178 enum MicroBenchmarkTestType {
179 ADDRESS,
180 UID,
181 UIDRANGE,
182 };
183
testTypeName(MicroBenchmarkTestType mode)184 const char *testTypeName(MicroBenchmarkTestType mode) {
185 #define TO_STRING_TYPE(x) case ((x)): return #x;
186 switch((mode)) {
187 TO_STRING_TYPE(ADDRESS);
188 TO_STRING_TYPE(UID);
189 TO_STRING_TYPE(UIDRANGE);
190 }
191 #undef TO_STRING_TYPE
192 }
193
194 class SockDiagMicroBenchmarkTest : public ::testing::TestWithParam<MicroBenchmarkTestType> {
195
196 public:
SetUp()197 void SetUp() {
198 ASSERT_TRUE(mSd.open()) << "Failed to open SOCK_DIAG socket";
199 }
200
201 protected:
202 SockDiag mSd;
203
204 constexpr static int MAX_SOCKETS = 500;
205 constexpr static int ADDRESS_SOCKETS = 500;
206 constexpr static int UID_SOCKETS = 100;
207 constexpr static uid_t START_UID = 8000; // START_UID + number of sockets must be <= 9999.
208 constexpr static int CLOSE_UID = START_UID + UID_SOCKETS - 42; // Close to the end
209 static_assert(START_UID + MAX_SOCKETS < 9999, "Too many sockets");
210
howManySockets()211 int howManySockets() {
212 MicroBenchmarkTestType mode = GetParam();
213 switch (mode) {
214 case ADDRESS:
215 return 500;
216 case UID:
217 case UIDRANGE:
218 return 50;
219 }
220 }
221
destroySockets()222 int destroySockets() {
223 MicroBenchmarkTestType mode = GetParam();
224 int ret;
225 switch (mode) {
226 case ADDRESS:
227 ret = mSd.destroySockets("::1");
228 EXPECT_LE(0, ret) << ": Failed to destroy sockets on ::1: " << strerror(-ret);
229 break;
230 case UID:
231 ret = mSd.destroySockets(IPPROTO_TCP, CLOSE_UID);
232 EXPECT_LE(0, ret) << ": Failed to destroy sockets for UID " << CLOSE_UID << ": " <<
233 strerror(-ret);
234 break;
235 case UIDRANGE: {
236 const char *uidRangeStrings[] = { "8005-8012", "8042", "8043", "8090-8099" };
237 std::set<uid_t> skipUids { 8007, 8043, 8098, 8099 };
238 UidRanges uidRanges;
239 uidRanges.parseFrom(ARRAY_SIZE(uidRangeStrings), (char **) uidRangeStrings);
240 ret = mSd.destroySockets(uidRanges, skipUids);
241 }
242 }
243 return ret;
244 }
245
shouldHaveClosedSocket(int i)246 bool shouldHaveClosedSocket(int i) {
247 MicroBenchmarkTestType mode = GetParam();
248 switch (mode) {
249 case ADDRESS:
250 return true;
251 case UID:
252 return i == CLOSE_UID - START_UID;
253 case UIDRANGE: {
254 uid_t uid = i + START_UID;
255 // Skip UIDs in skipUids.
256 if (uid == 8007 || uid == 8043 || uid == 8098 || uid == 8099) {
257 return false;
258 }
259 // Include UIDs in uidRanges.
260 if ((8005 <= uid && uid <= 8012) || uid == 8042 || (8090 <= uid && uid <= 8099)) {
261 return true;
262 }
263 return false;
264 }
265 }
266 }
267
checkSocketState(int i,int sock,const char * msg)268 void checkSocketState(int i, int sock, const char *msg) {
269 const char data[] = "foo";
270 const int ret = send(sock, data, sizeof(data), 0);
271 const int err = errno;
272 if (shouldHaveClosedSocket(i)) {
273 EXPECT_EQ(-1, ret) << msg << " " << i << " not closed";
274 if (ret == -1) {
275 // Since we're connected to ourselves, the error might be ECONNABORTED (if we
276 // destroyed the socket) or ECONNRESET (if the other end was destroyed and sent a
277 // RST).
278 EXPECT_TRUE(err == ECONNABORTED || err == ECONNRESET)
279 << msg << ": unexpected error: " << strerror(err);
280 }
281 } else {
282 EXPECT_EQ((ssize_t) sizeof(data), ret) <<
283 "Write on open socket failed: " << strerror(err);
284 }
285 }
286 };
287
TEST_P(SockDiagMicroBenchmarkTest,TestMicroBenchmark)288 TEST_P(SockDiagMicroBenchmarkTest, TestMicroBenchmark) {
289 MicroBenchmarkTestType mode = GetParam();
290
291 int numSockets = howManySockets();
292
293 fprintf(stderr, "Benchmarking closing %d sockets based on %s\n",
294 numSockets, testTypeName(mode));
295
296 int listensocket = socket(AF_INET6, SOCK_STREAM, 0);
297 ASSERT_NE(-1, listensocket) << "Failed to open listen socket";
298
299 uint16_t port = bindAndListen(listensocket);
300 ASSERT_NE(0, port) << "Can't bind to server port";
301 sockaddr_in6 server = { .sin6_family = AF_INET6, .sin6_port = htons(port) };
302
303 using ms = std::chrono::duration<float, std::ratio<1, 1000>>;
304
305 int clientsockets[MAX_SOCKETS], serversockets[MAX_SOCKETS];
306 uint16_t clientports[MAX_SOCKETS];
307 sockaddr_in6 client;
308 socklen_t clientlen;
309
310 auto start = std::chrono::steady_clock::now();
311 for (int i = 0; i < numSockets; i++) {
312 int s = socket(AF_INET6, SOCK_STREAM, 0);
313 uid_t uid = START_UID + i;
314 ASSERT_EQ(0, fchown(s, uid, -1));
315 clientlen = sizeof(client);
316 ASSERT_EQ(0, connect(s, (sockaddr *) &server, sizeof(server)))
317 << "Connecting socket " << i << " failed " << strerror(errno);
318 serversockets[i] = accept(listensocket, (sockaddr *) &client, &clientlen);
319 ASSERT_NE(-1, serversockets[i])
320 << "Accepting socket " << i << " failed " << strerror(errno);
321 clientports[i] = client.sin6_port;
322 clientsockets[i] = s;
323 }
324 fprintf(stderr, " Connecting: %6.1f ms\n",
325 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
326
327 start = std::chrono::steady_clock::now();
328 destroySockets();
329 fprintf(stderr, " Destroying: %6.1f ms\n",
330 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
331
332 start = std::chrono::steady_clock::now();
333 for (int i = 0; i < numSockets; i++) {
334 checkSocketState(i, clientsockets[i], "Client socket");
335 checkSocketState(i, serversockets[i], "Server socket");
336 }
337 fprintf(stderr, " Verifying: %6.1f ms\n",
338 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
339
340 start = std::chrono::steady_clock::now();
341 for (int i = 0; i < numSockets; i++) {
342 close(clientsockets[i]);
343 close(serversockets[i]);
344 }
345 fprintf(stderr, " Closing: %6.1f ms\n",
346 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
347
348 close(listensocket);
349 }
350
351 // "SockDiagTest.cpp:232: error: undefined reference to 'SockDiagMicroBenchmarkTest::CLOSE_UID'".
352 constexpr int SockDiagMicroBenchmarkTest::CLOSE_UID;
353
354 INSTANTIATE_TEST_CASE_P(Address, SockDiagMicroBenchmarkTest,
355 testing::Values(ADDRESS, UID, UIDRANGE));
356