blob: 2b1bf026a0482e2c04edeafe546322778a0d8dc1 [file] [log] [blame]
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +09001/*
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"
Lorenzo Colittifff4bd32016-04-14 00:56:01 +090027#include "UidRanges.h"
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090028
29class SockDiagTest : public ::testing::Test {
30};
31
32uint16_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
45const 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
64TEST_F(SockDiagTest, TestDump) {
65 int v4socket = socket(AF_INET, SOCK_STREAM, 0);
Pierre Imaib19fcc72016-03-11 17:54:48 +090066 ASSERT_NE(-1, v4socket) << "Failed to open IPv4 socket: " << strerror(errno);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090067 int v6socket = socket(AF_INET6, SOCK_STREAM, 0);
Pierre Imaib19fcc72016-03-11 17:54:48 +090068 ASSERT_NE(-1, v6socket) << "Failed to open IPv6 socket: " << strerror(errno);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090069 int listensocket = socket(AF_INET6, SOCK_STREAM, 0);
Pierre Imaib19fcc72016-03-11 17:54:48 +090070 ASSERT_NE(-1, listensocket) << "Failed to open listen socket: " << strerror(errno);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090071
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;
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900102 return false;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900103 }
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));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900113 return false;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900114 };
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;
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900123 return false;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900124 }
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));
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900139 return false;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900140 };
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
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900178enum MicroBenchmarkTestType {
179 ADDRESS,
180 UID,
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900181 UIDRANGE,
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900182};
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900183
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900184const 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);
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900189 TO_STRING_TYPE(UIDRANGE);
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900190 }
191#undef TO_STRING_TYPE
192}
193
194class SockDiagMicroBenchmarkTest : public ::testing::TestWithParam<MicroBenchmarkTestType> {
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900195
196public:
197 void SetUp() {
198 ASSERT_TRUE(mSd.open()) << "Failed to open SOCK_DIAG socket";
199 }
200
201protected:
202 SockDiag mSd;
203
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900204 constexpr static int MAX_SOCKETS = 500;
205 constexpr static int ADDRESS_SOCKETS = 500;
Lorenzo Colitti6bdc41f2016-06-10 01:54:52 +0900206 constexpr static int UID_SOCKETS = 50;
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900207 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
211 int howManySockets() {
212 MicroBenchmarkTestType mode = GetParam();
213 switch (mode) {
214 case ADDRESS:
Lorenzo Colitti6bdc41f2016-06-10 01:54:52 +0900215 return ADDRESS_SOCKETS;
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900216 case UID:
217 case UIDRANGE:
Lorenzo Colitti6bdc41f2016-06-10 01:54:52 +0900218 return UID_SOCKETS;
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900219 }
220 }
221
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900222 int destroySockets() {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900223 MicroBenchmarkTestType mode = GetParam();
224 int ret;
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900225 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 }
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900242 }
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900243 return ret;
244 }
245
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900246 bool shouldHaveClosedSocket(int i) {
247 MicroBenchmarkTestType mode = GetParam();
248 switch (mode) {
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900249 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 }
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900265 }
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900266 }
267
Lorenzo Colitti6bdc41f2016-06-10 01:54:52 +0900268 bool checkSocketState(int i, int sock, const char *msg) {
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900269 const char data[] = "foo";
270 const int ret = send(sock, data, sizeof(data), 0);
271 const int err = errno;
Lorenzo Colitti6bdc41f2016-06-10 01:54:52 +0900272 if (!shouldHaveClosedSocket(i)) {
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900273 EXPECT_EQ((ssize_t) sizeof(data), ret) <<
274 "Write on open socket failed: " << strerror(err);
Lorenzo Colitti6bdc41f2016-06-10 01:54:52 +0900275 return false;
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900276 }
Lorenzo Colitti6bdc41f2016-06-10 01:54:52 +0900277
278 EXPECT_EQ(-1, ret) << msg << " " << i << " not closed";
279 if (ret != -1) {
280 return false;
281 }
282
283 // Since we're connected to ourselves, the error might be ECONNABORTED (if we destroyed the
284 // socket) or ECONNRESET (if the other end was destroyed and sent a RST).
285 EXPECT_TRUE(err == ECONNABORTED || err == ECONNRESET)
286 << msg << ": unexpected error: " << strerror(err);
287 return (err == ECONNABORTED); // Return true iff. SOCK_DESTROY closed this socket.
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900288 }
289};
290
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900291TEST_P(SockDiagMicroBenchmarkTest, TestMicroBenchmark) {
292 MicroBenchmarkTestType mode = GetParam();
293
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900294 int numSockets = howManySockets();
295
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900296 fprintf(stderr, "Benchmarking closing %d sockets based on %s\n",
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900297 numSockets, testTypeName(mode));
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900298
299 int listensocket = socket(AF_INET6, SOCK_STREAM, 0);
300 ASSERT_NE(-1, listensocket) << "Failed to open listen socket";
301
302 uint16_t port = bindAndListen(listensocket);
303 ASSERT_NE(0, port) << "Can't bind to server port";
304 sockaddr_in6 server = { .sin6_family = AF_INET6, .sin6_port = htons(port) };
305
306 using ms = std::chrono::duration<float, std::ratio<1, 1000>>;
307
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900308 int clientsockets[MAX_SOCKETS], serversockets[MAX_SOCKETS];
309 uint16_t clientports[MAX_SOCKETS];
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900310 sockaddr_in6 client;
311 socklen_t clientlen;
312
313 auto start = std::chrono::steady_clock::now();
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900314 for (int i = 0; i < numSockets; i++) {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900315 int s = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900316 uid_t uid = START_UID + i;
317 ASSERT_EQ(0, fchown(s, uid, -1));
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900318 clientlen = sizeof(client);
319 ASSERT_EQ(0, connect(s, (sockaddr *) &server, sizeof(server)))
320 << "Connecting socket " << i << " failed " << strerror(errno);
321 serversockets[i] = accept(listensocket, (sockaddr *) &client, &clientlen);
322 ASSERT_NE(-1, serversockets[i])
323 << "Accepting socket " << i << " failed " << strerror(errno);
324 clientports[i] = client.sin6_port;
325 clientsockets[i] = s;
326 }
327 fprintf(stderr, " Connecting: %6.1f ms\n",
328 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
329
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900330 start = std::chrono::steady_clock::now();
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900331 destroySockets();
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900332 fprintf(stderr, " Destroying: %6.1f ms\n",
333 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
334
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900335 start = std::chrono::steady_clock::now();
Lorenzo Colitti6bdc41f2016-06-10 01:54:52 +0900336 int socketsClosed = 0;
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900337 for (int i = 0; i < numSockets; i++) {
Lorenzo Colitti6bdc41f2016-06-10 01:54:52 +0900338 socketsClosed += checkSocketState(i, clientsockets[i], "Client socket");
339 socketsClosed += checkSocketState(i, serversockets[i], "Server socket");
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900340 }
Lorenzo Colitti6bdc41f2016-06-10 01:54:52 +0900341 fprintf(stderr, " Verifying: %6.1f ms (%d sockets destroyed)\n",
342 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count(),
343 socketsClosed);
344 EXPECT_GT(socketsClosed, 0); // Just in case there's a bug in the test.
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900345
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900346 start = std::chrono::steady_clock::now();
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900347 for (int i = 0; i < numSockets; i++) {
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900348 close(clientsockets[i]);
349 close(serversockets[i]);
350 }
351 fprintf(stderr, " Closing: %6.1f ms\n",
352 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
353
354 close(listensocket);
355}
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900356
Lorenzo Colittifff4bd32016-04-14 00:56:01 +0900357// "SockDiagTest.cpp:232: error: undefined reference to 'SockDiagMicroBenchmarkTest::CLOSE_UID'".
358constexpr int SockDiagMicroBenchmarkTest::CLOSE_UID;
359
360INSTANTIATE_TEST_CASE_P(Address, SockDiagMicroBenchmarkTest,
361 testing::Values(ADDRESS, UID, UIDRANGE));