blob: 6425c67ed817c36913f7ca16183af2b30e176aeb [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"
27
28
29#define NUM_SOCKETS 500
Lorenzo Colitti94a7b432016-03-24 16:47:12 +090030#define START_UID 8000 // START_UID + NUM_SOCKETS must be <= 9999.
31#define CLOSE_UID (START_UID + NUM_SOCKETS - 42) // Close to the end
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090032
33
34class SockDiagTest : public ::testing::Test {
35};
36
37uint16_t bindAndListen(int s) {
38 for (int i = 0; i < 10; i++) {
39 uint16_t port = 1024 + arc4random_uniform(0xffff - 1024);
40 sockaddr_in6 sin6 = { .sin6_family = AF_INET6, .sin6_port = htons(port) };
41 if (bind(s, (sockaddr *) &sin6, sizeof(sin6)) == 0) {
42 listen(s, 1);
43 return port;
44 }
45 }
46 close(s);
47 return 0;
48}
49
50const char *tcpStateName(uint8_t state) {
51 static const char *states[] = {
52 "???",
53 "TCP_ESTABLISHED",
54 "TCP_SYN_SENT",
55 "TCP_SYN_RECV",
56 "TCP_FIN_WAIT1",
57 "TCP_FIN_WAIT2",
58 "TCP_TIME_WAIT",
59 "TCP_CLOSE",
60 "TCP_CLOSE_WAIT",
61 "TCP_LAST_ACK",
62 "TCP_LISTEN",
63 "TCP_CLOSING",
64 "TCP_NEW_SYN_RECV",
65 };
66 return states[(state < ARRAY_SIZE(states)) ? state : 0];
67}
68
69TEST_F(SockDiagTest, TestDump) {
70 int v4socket = socket(AF_INET, SOCK_STREAM, 0);
Pierre Imaib19fcc72016-03-11 17:54:48 +090071 ASSERT_NE(-1, v4socket) << "Failed to open IPv4 socket: " << strerror(errno);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090072 int v6socket = socket(AF_INET6, SOCK_STREAM, 0);
Pierre Imaib19fcc72016-03-11 17:54:48 +090073 ASSERT_NE(-1, v6socket) << "Failed to open IPv6 socket: " << strerror(errno);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090074 int listensocket = socket(AF_INET6, SOCK_STREAM, 0);
Pierre Imaib19fcc72016-03-11 17:54:48 +090075 ASSERT_NE(-1, listensocket) << "Failed to open listen socket: " << strerror(errno);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090076
77 uint16_t port = bindAndListen(listensocket);
78 ASSERT_NE(0, port) << "Can't bind to server port";
79
80 // Connect to loopback.
81 sockaddr_in server4 = { .sin_family = AF_INET, .sin_port = htons(port) };
82 sockaddr_in6 server6 = { .sin6_family = AF_INET6, .sin6_port = htons(port) };
83 ASSERT_EQ(0, connect(v4socket, (sockaddr *) &server4, sizeof(server4)))
84 << "IPv4 connect failed: " << strerror(errno);
85 ASSERT_EQ(0, connect(v6socket, (sockaddr *) &server6, sizeof(server6)))
86 << "IPv6 connect failed: " << strerror(errno);
87
88 sockaddr_in6 client46, client6;
89 socklen_t clientlen = std::max(sizeof(client46), sizeof(client6));
90 int accepted4 = accept(listensocket, (sockaddr *) &client46, &clientlen);
91 int accepted6 = accept(listensocket, (sockaddr *) &client6, &clientlen);
92 ASSERT_NE(-1, accepted4);
93 ASSERT_NE(-1, accepted6);
94
95 int v4SocketsSeen = 0;
96 bool seenclient46 = false;
97 bool seenNull = false;
98 char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
99
100 fprintf(stderr, "Ports:\n server=%d. client46=%d, client6=%d\n",
101 port, ntohs(client46.sin6_port), ntohs(client6.sin6_port));
102
103 auto checkIPv4Dump = [&] (uint8_t /* proto */, const inet_diag_msg *msg) {
104 if (msg == nullptr) {
105 EXPECT_FALSE(seenNull);
106 seenNull = true;
107 return 0;
108 }
109 EXPECT_EQ(htonl(INADDR_LOOPBACK), msg->id.idiag_src[0]);
110 v4SocketsSeen++;
111 seenclient46 |= (msg->id.idiag_sport == client46.sin6_port);
112 inet_ntop(AF_INET, msg->id.idiag_src, src, sizeof(src));
113 inet_ntop(AF_INET, msg->id.idiag_src, dst, sizeof(dst));
114 fprintf(stderr, " v4 %s:%d -> %s:%d %s\n",
115 src, htons(msg->id.idiag_sport),
116 dst, htons(msg->id.idiag_dport),
117 tcpStateName(msg->idiag_state));
118 return 0;
119 };
120
121 int v6SocketsSeen = 0;
122 bool seenClient6 = false, seenServer46 = false, seenServer6 = false;
123
124 auto checkIPv6Dump = [&] (uint8_t /* proto */, const inet_diag_msg *msg) {
125 if (msg == nullptr) {
126 EXPECT_FALSE(seenNull);
127 seenNull = true;
128 return 0;
129 }
130 struct in6_addr *saddr = (struct in6_addr *) msg->id.idiag_src;
131 EXPECT_TRUE(
132 IN6_IS_ADDR_LOOPBACK(saddr) ||
133 (IN6_IS_ADDR_V4MAPPED(saddr) && saddr->s6_addr32[3] == htonl(INADDR_LOOPBACK)));
134 v6SocketsSeen++;
135 seenClient6 |= (msg->id.idiag_sport == client6.sin6_port);
136 seenServer46 |= (msg->id.idiag_sport == htons(port));
137 seenServer6 |= (msg->id.idiag_sport == htons(port));
138 inet_ntop(AF_INET6, msg->id.idiag_src, src, sizeof(src));
139 inet_ntop(AF_INET6, msg->id.idiag_src, dst, sizeof(dst));
140 fprintf(stderr, " v6 [%s]:%d -> [%s]:%d %s\n",
141 src, htons(msg->id.idiag_sport),
142 dst, htons(msg->id.idiag_dport),
143 tcpStateName(msg->idiag_state));
144 return 0;
145 };
146
147 SockDiag sd;
148 ASSERT_TRUE(sd.open()) << "Failed to open SOCK_DIAG socket";
149
150 seenNull = false;
151 int ret = sd.sendDumpRequest(IPPROTO_TCP, AF_INET, "127.0.0.1");
152 ASSERT_EQ(0, ret) << "Failed to send IPv4 dump request: " << strerror(-ret);
153 fprintf(stderr, "Sent IPv4 dump\n");
154 sd.readDiagMsg(IPPROTO_TCP, checkIPv4Dump);
155 EXPECT_GE(v4SocketsSeen, 1);
156 EXPECT_TRUE(seenclient46);
157 EXPECT_FALSE(seenServer46);
158
159 seenNull = false;
160 ret = sd.sendDumpRequest(IPPROTO_TCP, AF_INET6, "127.0.0.1");
161 ASSERT_EQ(0, ret) << "Failed to send mapped dump request: " << strerror(-ret);
162 fprintf(stderr, "Sent mapped dump\n");
163 sd.readDiagMsg(IPPROTO_TCP, checkIPv6Dump);
164 EXPECT_TRUE(seenServer46);
165
166 seenNull = false;
167 ret = sd.sendDumpRequest(IPPROTO_TCP, AF_INET6, "::1");
168 ASSERT_EQ(0, ret) << "Failed to send IPv6 dump request: " << strerror(-ret);
169 fprintf(stderr, "Sent IPv6 dump\n");
170
171 sd.readDiagMsg(IPPROTO_TCP, checkIPv6Dump);
172 EXPECT_GE(v6SocketsSeen, 1);
173 EXPECT_TRUE(seenClient6);
174 EXPECT_TRUE(seenServer6);
175
176 close(v4socket);
177 close(v6socket);
178 close(listensocket);
179 close(accepted4);
180 close(accepted6);
181}
182
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900183enum MicroBenchmarkTestType {
184 ADDRESS,
185 UID,
186};
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900187
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900188const char *testTypeName(MicroBenchmarkTestType mode) {
189#define TO_STRING_TYPE(x) case ((x)): return #x;
190 switch((mode)) {
191 TO_STRING_TYPE(ADDRESS);
192 TO_STRING_TYPE(UID);
193 }
194#undef TO_STRING_TYPE
195}
196
197class SockDiagMicroBenchmarkTest : public ::testing::TestWithParam<MicroBenchmarkTestType> {
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900198
199public:
200 void SetUp() {
201 ASSERT_TRUE(mSd.open()) << "Failed to open SOCK_DIAG socket";
202 }
203
204protected:
205 SockDiag mSd;
206
207 int destroySockets() {
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900208 MicroBenchmarkTestType mode = GetParam();
209 int ret;
210 if (mode == ADDRESS) {
211 ret = mSd.destroySockets("::1");
212 EXPECT_LE(0, ret) << ": Failed to destroy sockets on ::1: " << strerror(-ret);
213 } else {
214 ret = mSd.destroySockets(IPPROTO_TCP, CLOSE_UID);
215 EXPECT_LE(0, ret) << ": Failed to destroy sockets for UID " << CLOSE_UID << ": " <<
216 strerror(-ret);
217 }
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900218 return ret;
219 }
220
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900221 bool shouldHaveClosedSocket(int i) {
222 MicroBenchmarkTestType mode = GetParam();
223 switch (mode) {
224 case ADDRESS:
225 return true;
226 case UID:
227 return i == CLOSE_UID - START_UID;
228 }
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900229 }
230
231 void checkSocketState(int i, int sock, const char *msg) {
232 const char data[] = "foo";
233 const int ret = send(sock, data, sizeof(data), 0);
234 const int err = errno;
235 if (shouldHaveClosedSocket(i)) {
236 EXPECT_EQ(-1, ret) << msg << " " << i << " not closed";
237 if (ret == -1) {
238 // Since we're connected to ourselves, the error might be ECONNABORTED (if we
239 // destroyed the socket) or ECONNRESET (if the other end was destroyed and sent a
240 // RST).
241 EXPECT_TRUE(err == ECONNABORTED || err == ECONNRESET)
242 << msg << ": unexpected error: " << strerror(err);
243 }
244 } else {
245 EXPECT_EQ((ssize_t) sizeof(data), ret) <<
246 "Write on open socket failed: " << strerror(err);
247 }
248 }
249};
250
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900251TEST_P(SockDiagMicroBenchmarkTest, TestMicroBenchmark) {
252 MicroBenchmarkTestType mode = GetParam();
253
254 fprintf(stderr, "Benchmarking closing %d sockets based on %s\n",
255 NUM_SOCKETS, testTypeName(mode));
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900256
257 int listensocket = socket(AF_INET6, SOCK_STREAM, 0);
258 ASSERT_NE(-1, listensocket) << "Failed to open listen socket";
259
260 uint16_t port = bindAndListen(listensocket);
261 ASSERT_NE(0, port) << "Can't bind to server port";
262 sockaddr_in6 server = { .sin6_family = AF_INET6, .sin6_port = htons(port) };
263
264 using ms = std::chrono::duration<float, std::ratio<1, 1000>>;
265
266 int clientsockets[NUM_SOCKETS], serversockets[NUM_SOCKETS];
267 uint16_t clientports[NUM_SOCKETS];
268 sockaddr_in6 client;
269 socklen_t clientlen;
270
271 auto start = std::chrono::steady_clock::now();
272 for (int i = 0; i < NUM_SOCKETS; i++) {
273 int s = socket(AF_INET6, SOCK_STREAM, 0);
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900274 uid_t uid = START_UID + i;
275 ASSERT_EQ(0, fchown(s, uid, -1));
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900276 clientlen = sizeof(client);
277 ASSERT_EQ(0, connect(s, (sockaddr *) &server, sizeof(server)))
278 << "Connecting socket " << i << " failed " << strerror(errno);
279 serversockets[i] = accept(listensocket, (sockaddr *) &client, &clientlen);
280 ASSERT_NE(-1, serversockets[i])
281 << "Accepting socket " << i << " failed " << strerror(errno);
282 clientports[i] = client.sin6_port;
283 clientsockets[i] = s;
284 }
285 fprintf(stderr, " Connecting: %6.1f ms\n",
286 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
287
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900288 start = std::chrono::steady_clock::now();
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900289 destroySockets();
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900290 fprintf(stderr, " Destroying: %6.1f ms\n",
291 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
292
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900293 start = std::chrono::steady_clock::now();
294 for (int i = 0; i < NUM_SOCKETS; i++) {
Lorenzo Colitti1f457712016-03-24 17:19:28 +0900295 checkSocketState(i, clientsockets[i], "Client socket");
296 checkSocketState(i, serversockets[i], "Server socket");
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900297 }
298 fprintf(stderr, " Verifying: %6.1f ms\n",
299 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
300
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +0900301 start = std::chrono::steady_clock::now();
302 for (int i = 0; i < NUM_SOCKETS; i++) {
303 close(clientsockets[i]);
304 close(serversockets[i]);
305 }
306 fprintf(stderr, " Closing: %6.1f ms\n",
307 std::chrono::duration_cast<ms>(std::chrono::steady_clock::now() - start).count());
308
309 close(listensocket);
310}
Lorenzo Colitti94a7b432016-03-24 16:47:12 +0900311
312INSTANTIATE_TEST_CASE_P(Address, SockDiagMicroBenchmarkTest, testing::Values(ADDRESS, UID));