blob: 373abc35e8e72a5de5a2ecbc1fd26bce010e2dea [file] [log] [blame]
David Pursell815c7be2015-12-09 17:09:54 -08001/*
2 * Copyright (C) 2015 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
David Pursellc3a46692016-01-29 08:10:50 -080017// Tests socket functionality using loopback connections. The UDP tests assume that no packets are
18// lost, which should be the case for loopback communication, but is not guaranteed.
19//
20// Also tests our SocketMock class to make sure it works as expected and reports errors properly
21// if the mock expectations aren't met during a test.
David Pursell815c7be2015-12-09 17:09:54 -080022
23#include "socket.h"
David Pursellc3a46692016-01-29 08:10:50 -080024#include "socket_mock.h"
David Pursell815c7be2015-12-09 17:09:54 -080025
David Pursellb34e4a02016-02-01 09:42:09 -080026#include <list>
27
David Pursellc3a46692016-01-29 08:10:50 -080028#include <gtest/gtest-spi.h>
David Pursellb34e4a02016-02-01 09:42:09 -080029#include <gtest/gtest.h>
David Pursell815c7be2015-12-09 17:09:54 -080030
David Pursellc742a7f2016-02-04 15:21:58 -080031static constexpr int kShortTimeoutMs = 10;
32static constexpr int kTestTimeoutMs = 3000;
David Pursell815c7be2015-12-09 17:09:54 -080033
David Pursell572bce22016-01-15 14:19:56 -080034// Creates connected sockets |server| and |client|. Returns true on success.
35bool MakeConnectedSockets(Socket::Protocol protocol, std::unique_ptr<Socket>* server,
David Pursellc3a46692016-01-29 08:10:50 -080036 std::unique_ptr<Socket>* client,
Chih-Hung Hsieha32ce532016-07-28 16:38:15 -070037 const std::string& hostname = "localhost") {
David Pursellc3a46692016-01-29 08:10:50 -080038 *server = Socket::NewServer(protocol, 0);
David Pursell572bce22016-01-15 14:19:56 -080039 if (*server == nullptr) {
40 ADD_FAILURE() << "Failed to create server.";
41 return false;
David Pursell815c7be2015-12-09 17:09:54 -080042 }
43
David Pursellc3a46692016-01-29 08:10:50 -080044 *client = Socket::NewClient(protocol, hostname, (*server)->GetLocalPort(), nullptr);
David Pursell572bce22016-01-15 14:19:56 -080045 if (*client == nullptr) {
46 ADD_FAILURE() << "Failed to create client.";
47 return false;
David Pursell815c7be2015-12-09 17:09:54 -080048 }
49
David Pursell572bce22016-01-15 14:19:56 -080050 // TCP passes the client off to a new socket.
51 if (protocol == Socket::Protocol::kTcp) {
52 *server = (*server)->Accept();
53 if (*server == nullptr) {
54 ADD_FAILURE() << "Failed to accept client connection.";
55 return false;
56 }
David Pursell815c7be2015-12-09 17:09:54 -080057 }
58
David Pursell572bce22016-01-15 14:19:56 -080059 return true;
60}
David Pursell815c7be2015-12-09 17:09:54 -080061
David Pursell572bce22016-01-15 14:19:56 -080062// Sends a string over a Socket. Returns true if the full string (without terminating char)
David Pursell815c7be2015-12-09 17:09:54 -080063// was sent.
David Pursell572bce22016-01-15 14:19:56 -080064static bool SendString(Socket* sock, const std::string& message) {
David Pursellb34e4a02016-02-01 09:42:09 -080065 return sock->Send(message.c_str(), message.length());
David Pursell815c7be2015-12-09 17:09:54 -080066}
67
David Pursell572bce22016-01-15 14:19:56 -080068// Receives a string from a Socket. Returns true if the full string (without terminating char)
69// was received.
70static bool ReceiveString(Socket* sock, const std::string& message) {
71 std::string received(message.length(), '\0');
72 ssize_t bytes = sock->ReceiveAll(&received[0], received.length(), kTestTimeoutMs);
73 return static_cast<size_t>(bytes) == received.length() && received == message;
David Pursell815c7be2015-12-09 17:09:54 -080074}
75
76// Tests sending packets client -> server, then server -> client.
David Pursell572bce22016-01-15 14:19:56 -080077TEST(SocketTest, TestSendAndReceive) {
78 std::unique_ptr<Socket> server, client;
David Pursell815c7be2015-12-09 17:09:54 -080079
David Pursell572bce22016-01-15 14:19:56 -080080 for (Socket::Protocol protocol : {Socket::Protocol::kUdp, Socket::Protocol::kTcp}) {
81 ASSERT_TRUE(MakeConnectedSockets(protocol, &server, &client));
David Pursell815c7be2015-12-09 17:09:54 -080082
David Pursell572bce22016-01-15 14:19:56 -080083 EXPECT_TRUE(SendString(client.get(), "foo"));
84 EXPECT_TRUE(ReceiveString(server.get(), "foo"));
85
86 EXPECT_TRUE(SendString(server.get(), "bar baz"));
87 EXPECT_TRUE(ReceiveString(client.get(), "bar baz"));
88 }
David Pursell815c7be2015-12-09 17:09:54 -080089}
90
David Pursellc742a7f2016-02-04 15:21:58 -080091TEST(SocketTest, TestReceiveTimeout) {
92 std::unique_ptr<Socket> server, client;
93 char buffer[16];
94
95 for (Socket::Protocol protocol : {Socket::Protocol::kUdp, Socket::Protocol::kTcp}) {
96 ASSERT_TRUE(MakeConnectedSockets(protocol, &server, &client));
97
98 EXPECT_EQ(-1, server->Receive(buffer, sizeof(buffer), kShortTimeoutMs));
99 EXPECT_TRUE(server->ReceiveTimedOut());
100
101 EXPECT_EQ(-1, client->Receive(buffer, sizeof(buffer), kShortTimeoutMs));
102 EXPECT_TRUE(client->ReceiveTimedOut());
103 }
104
105 // UDP will wait for timeout if the other side closes.
106 ASSERT_TRUE(MakeConnectedSockets(Socket::Protocol::kUdp, &server, &client));
107 EXPECT_EQ(0, server->Close());
108 EXPECT_EQ(-1, client->Receive(buffer, sizeof(buffer), kShortTimeoutMs));
109 EXPECT_TRUE(client->ReceiveTimedOut());
110}
111
112TEST(SocketTest, TestReceiveFailure) {
113 std::unique_ptr<Socket> server, client;
114 char buffer[16];
115
116 for (Socket::Protocol protocol : {Socket::Protocol::kUdp, Socket::Protocol::kTcp}) {
117 ASSERT_TRUE(MakeConnectedSockets(protocol, &server, &client));
118
119 EXPECT_EQ(0, server->Close());
120 EXPECT_EQ(-1, server->Receive(buffer, sizeof(buffer), kTestTimeoutMs));
121 EXPECT_FALSE(server->ReceiveTimedOut());
122
123 EXPECT_EQ(0, client->Close());
124 EXPECT_EQ(-1, client->Receive(buffer, sizeof(buffer), kTestTimeoutMs));
125 EXPECT_FALSE(client->ReceiveTimedOut());
126 }
127
128 // TCP knows right away when the other side closes and returns 0 to indicate EOF.
129 ASSERT_TRUE(MakeConnectedSockets(Socket::Protocol::kTcp, &server, &client));
130 EXPECT_EQ(0, server->Close());
131 EXPECT_EQ(0, client->Receive(buffer, sizeof(buffer), kTestTimeoutMs));
132 EXPECT_FALSE(client->ReceiveTimedOut());
133}
134
David Pursell815c7be2015-12-09 17:09:54 -0800135// Tests sending and receiving large packets.
David Pursell572bce22016-01-15 14:19:56 -0800136TEST(SocketTest, TestLargePackets) {
137 std::string message(1024, '\0');
138 std::unique_ptr<Socket> server, client;
David Pursell815c7be2015-12-09 17:09:54 -0800139
David Pursell572bce22016-01-15 14:19:56 -0800140 for (Socket::Protocol protocol : {Socket::Protocol::kUdp, Socket::Protocol::kTcp}) {
141 ASSERT_TRUE(MakeConnectedSockets(protocol, &server, &client));
David Pursell815c7be2015-12-09 17:09:54 -0800142
David Pursell572bce22016-01-15 14:19:56 -0800143 // Run through the test a few times.
144 for (int i = 0; i < 10; ++i) {
145 // Use a different message each iteration to prevent false positives.
146 for (size_t j = 0; j < message.length(); ++j) {
147 message[j] = static_cast<char>(i + j);
148 }
149
150 EXPECT_TRUE(SendString(client.get(), message));
151 EXPECT_TRUE(ReceiveString(server.get(), message));
David Pursell815c7be2015-12-09 17:09:54 -0800152 }
David Pursell815c7be2015-12-09 17:09:54 -0800153 }
154}
155
David Pursell572bce22016-01-15 14:19:56 -0800156// Tests UDP receive overflow when the UDP packet is larger than the receive buffer.
157TEST(SocketTest, TestUdpReceiveOverflow) {
158 std::unique_ptr<Socket> server, client;
159 ASSERT_TRUE(MakeConnectedSockets(Socket::Protocol::kUdp, &server, &client));
David Pursell815c7be2015-12-09 17:09:54 -0800160
David Pursell572bce22016-01-15 14:19:56 -0800161 EXPECT_TRUE(SendString(client.get(), "1234567890"));
David Pursell815c7be2015-12-09 17:09:54 -0800162
David Pursell572bce22016-01-15 14:19:56 -0800163 // This behaves differently on different systems, either truncating the packet or returning -1.
164 char buffer[5];
165 ssize_t bytes = server->Receive(buffer, 5, kTestTimeoutMs);
166 if (bytes == 5) {
167 EXPECT_EQ(0, memcmp(buffer, "12345", 5));
168 } else {
169 EXPECT_EQ(-1, bytes);
David Pursell815c7be2015-12-09 17:09:54 -0800170 }
171}
David Pursellc3a46692016-01-29 08:10:50 -0800172
David Pursellb34e4a02016-02-01 09:42:09 -0800173// Tests UDP multi-buffer send.
174TEST(SocketTest, TestUdpSendBuffers) {
175 std::unique_ptr<Socket> sock = Socket::NewServer(Socket::Protocol::kUdp, 0);
176 std::vector<std::string> data{"foo", "bar", "12345"};
177 std::vector<cutils_socket_buffer_t> buffers{{data[0].data(), data[0].length()},
178 {data[1].data(), data[1].length()},
179 {data[2].data(), data[2].length()}};
180 ssize_t mock_return_value = 0;
181
182 // Mock out socket_send_buffers() to verify we're sending in the correct buffers and
183 // return |mock_return_value|.
184 sock->socket_send_buffers_function_ = [&buffers, &mock_return_value](
185 cutils_socket_t /*cutils_sock*/, cutils_socket_buffer_t* sent_buffers,
186 size_t num_sent_buffers) -> ssize_t {
187 EXPECT_EQ(buffers.size(), num_sent_buffers);
188 for (size_t i = 0; i < num_sent_buffers; ++i) {
189 EXPECT_EQ(buffers[i].data, sent_buffers[i].data);
190 EXPECT_EQ(buffers[i].length, sent_buffers[i].length);
191 }
192 return mock_return_value;
193 };
194
195 mock_return_value = strlen("foobar12345");
196 EXPECT_TRUE(sock->Send(buffers));
197
198 mock_return_value -= 1;
199 EXPECT_FALSE(sock->Send(buffers));
200
201 mock_return_value = 0;
202 EXPECT_FALSE(sock->Send(buffers));
203
204 mock_return_value = -1;
205 EXPECT_FALSE(sock->Send(buffers));
206}
207
208// Tests TCP re-sending until socket_send_buffers() sends all data. This is a little complicated,
209// but the general idea is that we intercept calls to socket_send_buffers() using a lambda mock
210// function that simulates partial writes.
211TEST(SocketTest, TestTcpSendBuffers) {
212 std::unique_ptr<Socket> sock = Socket::NewServer(Socket::Protocol::kTcp, 0);
213 std::vector<std::string> data{"foo", "bar", "12345"};
214 std::vector<cutils_socket_buffer_t> buffers{{data[0].data(), data[0].length()},
215 {data[1].data(), data[1].length()},
216 {data[2].data(), data[2].length()}};
217
218 // Test breaking up the buffered send at various points.
219 std::list<std::string> test_sends[] = {
220 // Successes.
221 {"foobar12345"},
222 {"f", "oob", "ar12345"},
223 {"fo", "obar12", "345"},
224 {"foo", "bar12345"},
225 {"foob", "ar123", "45"},
226 {"f", "o", "o", "b", "a", "r", "1", "2", "3", "4", "5"},
227
228 // Failures.
229 {},
230 {"f"},
231 {"foo", "bar"},
232 {"fo", "obar12"},
233 {"foobar1234"}
234 };
235
236 for (auto& test : test_sends) {
237 ssize_t bytes_sent = 0;
238 bool expect_success = true;
239
240 // Create a mock function for custom socket_send_buffers() behavior. This function will
241 // check to make sure the input buffers start at the next unsent byte, then return the
242 // number of bytes indicated by the next entry in |test|.
243 sock->socket_send_buffers_function_ = [&bytes_sent, &data, &expect_success, &test](
244 cutils_socket_t /*cutils_sock*/, cutils_socket_buffer_t* buffers,
245 size_t num_buffers) -> ssize_t {
246 EXPECT_TRUE(num_buffers > 0);
247
248 // Failure case - pretend we errored out before sending all the buffers.
249 if (test.empty()) {
250 expect_success = false;
251 return -1;
252 }
253
254 // Count the bytes we've sent to find where the next buffer should start and how many
255 // bytes should be left in it.
256 size_t byte_count = bytes_sent, data_index = 0;
257 while (data_index < data.size()) {
258 if (byte_count >= data[data_index].length()) {
259 byte_count -= data[data_index].length();
260 ++data_index;
261 } else {
262 break;
263 }
264 }
265 void* expected_next_byte = &data[data_index][byte_count];
266 size_t expected_next_size = data[data_index].length() - byte_count;
267
268 EXPECT_EQ(data.size() - data_index, num_buffers);
269 EXPECT_EQ(expected_next_byte, buffers[0].data);
270 EXPECT_EQ(expected_next_size, buffers[0].length);
271
272 std::string to_send = std::move(test.front());
273 test.pop_front();
274 bytes_sent += to_send.length();
275 return to_send.length();
276 };
277
278 EXPECT_EQ(expect_success, sock->Send(buffers));
279 EXPECT_TRUE(test.empty());
280 }
281}
282
David Pursellc3a46692016-01-29 08:10:50 -0800283TEST(SocketMockTest, TestSendSuccess) {
284 SocketMock mock;
285
286 mock.ExpectSend("foo");
287 EXPECT_TRUE(SendString(&mock, "foo"));
288
289 mock.ExpectSend("abc");
290 mock.ExpectSend("123");
291 EXPECT_TRUE(SendString(&mock, "abc"));
292 EXPECT_TRUE(SendString(&mock, "123"));
293}
294
295TEST(SocketMockTest, TestSendFailure) {
296 SocketMock* mock = new SocketMock;
297
David Pursell2c094f72016-02-03 10:23:05 -0800298 mock->ExpectSendFailure("foo");
299 EXPECT_FALSE(SendString(mock, "foo"));
300
David Pursellc3a46692016-01-29 08:10:50 -0800301 EXPECT_NONFATAL_FAILURE(SendString(mock, "foo"), "no message was expected");
302
303 mock->ExpectSend("foo");
304 EXPECT_NONFATAL_FAILURE(SendString(mock, "bar"), "expected foo, but got bar");
305 EXPECT_TRUE(SendString(mock, "foo"));
306
307 mock->AddReceive("foo");
308 EXPECT_NONFATAL_FAILURE(SendString(mock, "foo"), "called out-of-order");
309 EXPECT_TRUE(ReceiveString(mock, "foo"));
310
311 mock->ExpectSend("foo");
312 EXPECT_NONFATAL_FAILURE(delete mock, "1 event(s) were not handled");
313}
314
315TEST(SocketMockTest, TestReceiveSuccess) {
316 SocketMock mock;
317
318 mock.AddReceive("foo");
319 EXPECT_TRUE(ReceiveString(&mock, "foo"));
320
321 mock.AddReceive("abc");
322 mock.AddReceive("123");
323 EXPECT_TRUE(ReceiveString(&mock, "abc"));
324 EXPECT_TRUE(ReceiveString(&mock, "123"));
David Pursell2c094f72016-02-03 10:23:05 -0800325
326 // Make sure ReceiveAll() can piece together multiple receives.
327 mock.AddReceive("foo");
328 mock.AddReceive("bar");
329 mock.AddReceive("123");
330 EXPECT_TRUE(ReceiveString(&mock, "foobar123"));
David Pursellc3a46692016-01-29 08:10:50 -0800331}
332
333TEST(SocketMockTest, TestReceiveFailure) {
334 SocketMock* mock = new SocketMock;
335
David Pursell2c094f72016-02-03 10:23:05 -0800336 mock->AddReceiveFailure();
337 EXPECT_FALSE(ReceiveString(mock, "foo"));
David Pursellc742a7f2016-02-04 15:21:58 -0800338 EXPECT_FALSE(mock->ReceiveTimedOut());
339
340 mock->AddReceiveTimeout();
341 EXPECT_FALSE(ReceiveString(mock, "foo"));
342 EXPECT_TRUE(mock->ReceiveTimedOut());
David Pursell2c094f72016-02-03 10:23:05 -0800343
344 mock->AddReceive("foo");
345 mock->AddReceiveFailure();
346 EXPECT_FALSE(ReceiveString(mock, "foobar"));
347
David Pursellc3a46692016-01-29 08:10:50 -0800348 EXPECT_NONFATAL_FAILURE(ReceiveString(mock, "foo"), "no message was ready");
349
350 mock->ExpectSend("foo");
351 EXPECT_NONFATAL_FAILURE(ReceiveString(mock, "foo"), "called out-of-order");
352 EXPECT_TRUE(SendString(mock, "foo"));
353
354 char c;
355 mock->AddReceive("foo");
356 EXPECT_NONFATAL_FAILURE(mock->Receive(&c, 1, 0), "not enough bytes (1) for foo");
357 EXPECT_TRUE(ReceiveString(mock, "foo"));
358
359 mock->AddReceive("foo");
360 EXPECT_NONFATAL_FAILURE(delete mock, "1 event(s) were not handled");
361}
362
363TEST(SocketMockTest, TestAcceptSuccess) {
364 SocketMock mock;
365
366 SocketMock* mock_handler = new SocketMock;
367 mock.AddAccept(std::unique_ptr<SocketMock>(mock_handler));
368 EXPECT_EQ(mock_handler, mock.Accept().get());
369
370 mock.AddAccept(nullptr);
371 EXPECT_EQ(nullptr, mock.Accept().get());
372}
373
374TEST(SocketMockTest, TestAcceptFailure) {
375 SocketMock* mock = new SocketMock;
376
377 EXPECT_NONFATAL_FAILURE(mock->Accept(), "no socket was ready");
378
379 mock->ExpectSend("foo");
380 EXPECT_NONFATAL_FAILURE(mock->Accept(), "called out-of-order");
381 EXPECT_TRUE(SendString(mock, "foo"));
382
383 mock->AddAccept(nullptr);
384 EXPECT_NONFATAL_FAILURE(delete mock, "1 event(s) were not handled");
385}