2 * Copyright 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 * sock_diag_test.cpp - unit tests for SockDiag.cpp
19 #include <arpa/inet.h>
20 #include <netinet/in.h>
21 #include <linux/inet_diag.h>
23 #include <gtest/gtest.h>
25 #include "NetdConstants.h"
27 #include "UidRanges.h"
29 class SockDiagTest : public ::testing::Test {
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) {
45 const char *tcpStateName(uint8_t state) {
46 static const char *states[] = {
61 return states[(state < ARRAY_SIZE(states)) ? state : 0];
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);
72 uint16_t port = bindAndListen(listensocket);
73 ASSERT_NE(0, port) << "Can't bind to server port";
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);
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);
90 int v4SocketsSeen = 0;
91 bool seenclient46 = false;
92 bool seenNull = false;
93 char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
95 fprintf(stderr, "Ports:\n server=%d. client46=%d, client6=%d\n",
96 port, ntohs(client46.sin6_port), ntohs(client6.sin6_port));
98 auto checkIPv4Dump = [&] (uint8_t /* proto */, const inet_diag_msg *msg) {
100 EXPECT_FALSE(seenNull);
104 EXPECT_EQ(htonl(INADDR_LOOPBACK), msg->id.idiag_src[0]);
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));
116 int v6SocketsSeen = 0;
117 bool seenClient6 = false, seenServer46 = false, seenServer6 = false;
119 auto checkIPv6Dump = [&] (uint8_t /* proto */, const inet_diag_msg *msg) {
120 if (msg == nullptr) {
121 EXPECT_FALSE(seenNull);
125 struct in6_addr *saddr = (struct in6_addr *) msg->id.idiag_src;
127 IN6_IS_ADDR_LOOPBACK(saddr) ||
128 (IN6_IS_ADDR_V4MAPPED(saddr) && saddr->s6_addr32[3] == htonl(INADDR_LOOPBACK)));
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));
143 ASSERT_TRUE(sd.open()) << "Failed to open SOCK_DIAG socket";
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);
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);
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");
166 sd.readDiagMsg(IPPROTO_TCP, checkIPv6Dump);
167 EXPECT_GE(v6SocketsSeen, 1);
168 EXPECT_TRUE(seenClient6);
169 EXPECT_TRUE(seenServer6);
178 enum MicroBenchmarkTestType {
184 const char *testTypeName(MicroBenchmarkTestType mode) {
185 #define TO_STRING_TYPE(x) case ((x)): return #x;
187 TO_STRING_TYPE(ADDRESS);
189 TO_STRING_TYPE(UIDRANGE);
191 #undef TO_STRING_TYPE
194 class SockDiagMicroBenchmarkTest : public ::testing::TestWithParam<MicroBenchmarkTestType> {
198 ASSERT_TRUE(mSd.open()) << "Failed to open SOCK_DIAG socket";
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");
211 int howManySockets() {
212 MicroBenchmarkTestType mode = GetParam();
222 int destroySockets() {
223 MicroBenchmarkTestType mode = GetParam();
227 ret = mSd.destroySockets("::1");
228 EXPECT_LE(0, ret) << ": Failed to destroy sockets on ::1: " << strerror(-ret);
231 ret = mSd.destroySockets(IPPROTO_TCP, CLOSE_UID);
232 EXPECT_LE(0, ret) << ": Failed to destroy sockets for UID " << CLOSE_UID << ": " <<
236 const char *uidRangeStrings[] = { "8005-8012", "8042", "8043", "8090-8099" };
237 std::set<uid_t> skipUids { 8007, 8043, 8098, 8099 };
239 uidRanges.parseFrom(ARRAY_SIZE(uidRangeStrings), (char **) uidRangeStrings);
240 ret = mSd.destroySockets(uidRanges, skipUids);
246 bool shouldHaveClosedSocket(int i) {
247 MicroBenchmarkTestType mode = GetParam();
252 return i == CLOSE_UID - START_UID;
254 uid_t uid = i + START_UID;
255 // Skip UIDs in skipUids.
256 if (uid == 8007 || uid == 8043 || uid == 8098 || uid == 8099) {
259 // Include UIDs in uidRanges.
260 if ((8005 <= uid && uid <= 8012) || uid == 8042 || (8090 <= uid && uid <= 8099)) {
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";
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
278 EXPECT_TRUE(err == ECONNABORTED || err == ECONNRESET)
279 << msg << ": unexpected error: " << strerror(err);
282 EXPECT_EQ((ssize_t) sizeof(data), ret) <<
283 "Write on open socket failed: " << strerror(err);
288 TEST_P(SockDiagMicroBenchmarkTest, TestMicroBenchmark) {
289 MicroBenchmarkTestType mode = GetParam();
291 int numSockets = howManySockets();
293 fprintf(stderr, "Benchmarking closing %d sockets based on %s\n",
294 numSockets, testTypeName(mode));
296 int listensocket = socket(AF_INET6, SOCK_STREAM, 0);
297 ASSERT_NE(-1, listensocket) << "Failed to open listen socket";
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) };
303 using ms = std::chrono::duration<float, std::ratio<1, 1000>>;
305 int clientsockets[MAX_SOCKETS], serversockets[MAX_SOCKETS];
306 uint16_t clientports[MAX_SOCKETS];
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;
324 fprintf(stderr, " Connecting: %6.1f ms\n",
325 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
327 start = std::chrono::steady_clock::now();
329 fprintf(stderr, " Destroying: %6.1f ms\n",
330 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
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");
337 fprintf(stderr, " Verifying: %6.1f ms\n",
338 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
340 start = std::chrono::steady_clock::now();
341 for (int i = 0; i < numSockets; i++) {
342 close(clientsockets[i]);
343 close(serversockets[i]);
345 fprintf(stderr, " Closing: %6.1f ms\n",
346 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
351 // "SockDiagTest.cpp:232: error: undefined reference to 'SockDiagMicroBenchmarkTest::CLOSE_UID'".
352 constexpr int SockDiagMicroBenchmarkTest::CLOSE_UID;
354 INSTANTIATE_TEST_CASE_P(Address, SockDiagMicroBenchmarkTest,
355 testing::Values(ADDRESS, UID, UIDRANGE));