1 /*
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
17 #include "fdevent/fdevent.h"
18
19 #include <gtest/gtest.h>
20
21 #include <array>
22 #include <limits>
23 #include <queue>
24 #include <string>
25 #include <thread>
26 #include <vector>
27
28 #include <unistd.h>
29
30 #include "adb.h"
31 #include "adb_io.h"
32 #include "fdevent/fdevent_test.h"
33 #include "socket.h"
34 #include "sysdeps.h"
35 #include "sysdeps/chrono.h"
36 #include "test_utils/test_utils.h"
37
38 using namespace std::string_literals;
39 using namespace std::string_view_literals;
40
41 struct ThreadArg {
42 int first_read_fd;
43 int last_write_fd;
44 size_t middle_pipe_count;
45 };
46
47 class LocalSocketTest : public FdeventTest {};
48
TEST_F(LocalSocketTest,smoke)49 TEST_F(LocalSocketTest, smoke) {
50 // Join two socketpairs with a chain of intermediate socketpairs.
51 int first[2];
52 std::vector<std::array<int, 2>> intermediates;
53 int last[2];
54
55 constexpr size_t INTERMEDIATE_COUNT = 50;
56 constexpr size_t MESSAGE_LOOP_COUNT = 100;
57 const std::string MESSAGE = "socket_test";
58
59 intermediates.resize(INTERMEDIATE_COUNT);
60 ASSERT_EQ(0, adb_socketpair(first)) << strerror(errno);
61 ASSERT_EQ(0, adb_socketpair(last)) << strerror(errno);
62 asocket* prev_tail = create_local_socket(unique_fd(first[1]));
63 ASSERT_NE(nullptr, prev_tail);
64
65 auto connect = [](asocket* tail, asocket* head) {
66 tail->peer = head;
67 head->peer = tail;
68 tail->ready(tail);
69 };
70
71 for (auto& intermediate : intermediates) {
72 ASSERT_EQ(0, adb_socketpair(intermediate.data())) << strerror(errno);
73
74 asocket* head = create_local_socket(unique_fd(intermediate[0]));
75 ASSERT_NE(nullptr, head);
76
77 asocket* tail = create_local_socket(unique_fd(intermediate[1]));
78 ASSERT_NE(nullptr, tail);
79
80 connect(prev_tail, head);
81 prev_tail = tail;
82 }
83
84 asocket* end = create_local_socket(unique_fd(last[0]));
85 ASSERT_NE(nullptr, end);
86 connect(prev_tail, end);
87
88 PrepareThread();
89
90 for (size_t i = 0; i < MESSAGE_LOOP_COUNT; ++i) {
91 std::string read_buffer = MESSAGE;
92 std::string write_buffer(MESSAGE.size(), 'a');
93 ASSERT_TRUE(WriteFdExactly(first[0], &read_buffer[0], read_buffer.size()));
94 ASSERT_TRUE(ReadFdExactly(last[1], &write_buffer[0], write_buffer.size()));
95 ASSERT_EQ(read_buffer, write_buffer);
96 }
97
98 ASSERT_EQ(0, adb_close(first[0]));
99 ASSERT_EQ(0, adb_close(last[1]));
100
101 // Wait until the local sockets are closed.
102 WaitForFdeventLoop();
103 ASSERT_EQ(0u, fdevent_installed_count());
104 TerminateThread();
105 }
106
107 struct CloseWithPacketArg {
108 unique_fd socket_fd;
109 size_t bytes_written;
110 unique_fd cause_close_fd;
111 };
112
CreateCloser(CloseWithPacketArg * arg)113 static void CreateCloser(CloseWithPacketArg* arg) {
114 fdevent_run_on_looper([arg]() {
115 asocket* s = create_local_socket(std::move(arg->socket_fd));
116 ASSERT_TRUE(s != nullptr);
117 arg->bytes_written = 0;
118
119 // On platforms that implement sockets via underlying sockets (e.g. Wine),
120 // a socket can appear to be full, and then become available for writes
121 // again without read being called on the other end. Loop and sleep after
122 // each write to give the underlying implementation time to flush.
123 bool socket_filled = false;
124 for (int i = 0; i < 128; ++i) {
125 apacket::payload_type data;
126 data.resize(MAX_PAYLOAD);
127 arg->bytes_written += data.size();
128 int ret = s->enqueue(s, std::move(data));
129
130 // Return value of 0 implies that more data can be accepted.
131 if (ret == 1) {
132 socket_filled = true;
133 break;
134 }
135 ASSERT_NE(-1, ret);
136
137 std::this_thread::sleep_for(250ms);
138 }
139 ASSERT_TRUE(socket_filled);
140
141 asocket* cause_close_s = create_local_socket(std::move(arg->cause_close_fd));
142 ASSERT_TRUE(cause_close_s != nullptr);
143 cause_close_s->peer = s;
144 s->peer = cause_close_s;
145 cause_close_s->ready(cause_close_s);
146 });
147 WaitForFdeventLoop();
148 }
149
150 // This test checks if we can close local socket in the following situation:
151 // The socket is closing but having some packets, so it is not closed. Then
152 // some write error happens in the socket's file handler, e.g., the file
153 // handler is closed.
TEST_F(LocalSocketTest,close_socket_with_packet)154 TEST_F(LocalSocketTest, close_socket_with_packet) {
155 int socket_fd[2];
156 ASSERT_EQ(0, adb_socketpair(socket_fd));
157 int cause_close_fd[2];
158 ASSERT_EQ(0, adb_socketpair(cause_close_fd));
159 CloseWithPacketArg arg;
160 arg.socket_fd.reset(socket_fd[1]);
161 arg.cause_close_fd.reset(cause_close_fd[1]);
162
163 PrepareThread();
164 CreateCloser(&arg);
165
166 ASSERT_EQ(0, adb_close(cause_close_fd[0]));
167
168 WaitForFdeventLoop();
169 EXPECT_EQ(1u, fdevent_installed_count());
170 ASSERT_EQ(0, adb_close(socket_fd[0]));
171
172 WaitForFdeventLoop();
173 ASSERT_EQ(0u, fdevent_installed_count());
174 TerminateThread();
175 }
176
177 // This test checks if we can read packets from a closing local socket.
TEST_F(LocalSocketTest,read_from_closing_socket)178 TEST_F(LocalSocketTest, read_from_closing_socket) {
179 int socket_fd[2];
180 ASSERT_EQ(0, adb_socketpair(socket_fd));
181 int cause_close_fd[2];
182 ASSERT_EQ(0, adb_socketpair(cause_close_fd));
183 CloseWithPacketArg arg;
184 arg.socket_fd.reset(socket_fd[1]);
185 arg.cause_close_fd.reset(cause_close_fd[1]);
186
187 PrepareThread();
188 CreateCloser(&arg);
189
190 WaitForFdeventLoop();
191 ASSERT_EQ(0, adb_close(cause_close_fd[0]));
192
193 WaitForFdeventLoop();
194 EXPECT_EQ(1u, fdevent_installed_count());
195
196 // Verify if we can read successfully.
197 std::vector<char> buf(arg.bytes_written);
198 ASSERT_NE(0u, arg.bytes_written);
199
200 ASSERT_EQ(true, ReadFdExactly(socket_fd[0], buf.data(), buf.size())); // TODO: b/237341044
201
202 ASSERT_EQ(0, adb_close(socket_fd[0]));
203
204 WaitForFdeventLoop();
205 ASSERT_EQ(0u, fdevent_installed_count());
206 TerminateThread();
207 }
208
209 // This test checks if we can close local socket in the following situation:
210 // The socket is not closed and has some packets. When it fails to write to
211 // the socket's file handler because the other end is closed, we check if the
212 // socket is closed.
TEST_F(LocalSocketTest,write_error_when_having_packets)213 TEST_F(LocalSocketTest, write_error_when_having_packets) {
214 int socket_fd[2];
215 ASSERT_EQ(0, adb_socketpair(socket_fd));
216 int cause_close_fd[2];
217 ASSERT_EQ(0, adb_socketpair(cause_close_fd));
218 CloseWithPacketArg arg;
219 arg.socket_fd.reset(socket_fd[1]);
220 arg.cause_close_fd.reset(cause_close_fd[1]);
221
222 PrepareThread();
223 CreateCloser(&arg);
224
225 WaitForFdeventLoop();
226 EXPECT_EQ(2u, fdevent_installed_count());
227 ASSERT_EQ(0, adb_close(socket_fd[0]));
228
229 std::this_thread::sleep_for(2s);
230
231 WaitForFdeventLoop();
232 ASSERT_EQ(0u, fdevent_installed_count());
233 TerminateThread();
234 }
235
236 // Ensure that if we fail to write output to an fd, we will still flush data coming from it.
TEST_F(LocalSocketTest,flush_after_shutdown)237 TEST_F(LocalSocketTest, flush_after_shutdown) {
238 int head_fd[2];
239 int tail_fd[2];
240 ASSERT_EQ(0, adb_socketpair(head_fd));
241 ASSERT_EQ(0, adb_socketpair(tail_fd));
242
243 asocket* head = create_local_socket(unique_fd(head_fd[1]));
244 asocket* tail = create_local_socket(unique_fd(tail_fd[1]));
245
246 head->peer = tail;
247 head->ready(head);
248
249 tail->peer = head;
250 tail->ready(tail);
251
252 PrepareThread();
253
254 EXPECT_TRUE(WriteFdExactly(head_fd[0], "foo", 3));
255
256 EXPECT_EQ(0, adb_shutdown(head_fd[0], SHUT_RD));
257 const char* str = "write succeeds, but local_socket will fail to write";
258 EXPECT_TRUE(WriteFdExactly(tail_fd[0], str, strlen(str)));
259 EXPECT_TRUE(WriteFdExactly(head_fd[0], "bar", 3));
260
261 char buf[6];
262 EXPECT_TRUE(ReadFdExactly(tail_fd[0], buf, 6));
263 EXPECT_EQ(0, memcmp(buf, "foobar", 6));
264
265 adb_close(head_fd[0]);
266 adb_close(tail_fd[0]);
267
268 WaitForFdeventLoop();
269 ASSERT_EQ(0u, fdevent_installed_count());
270 TerminateThread();
271 }
272
273 #if defined(__linux__)
274
ClientThreadFunc(const int assigned_port)275 static void ClientThreadFunc(const int assigned_port) {
276 std::string error;
277 const int fd = network_loopback_client(assigned_port, SOCK_STREAM, &error);
278 ASSERT_GE(fd, 0) << error;
279 std::this_thread::sleep_for(1s);
280 ASSERT_EQ(0, adb_close(fd));
281 }
282
283 // This test checks if we can close sockets in CLOSE_WAIT state.
TEST_F(LocalSocketTest,close_socket_in_CLOSE_WAIT_state)284 TEST_F(LocalSocketTest, close_socket_in_CLOSE_WAIT_state) {
285 std::string error;
286 // Allow the system to allocate an available port.
287 unique_fd listen_fd;
288 const int assigned_port(test_utils::GetUnassignedPort(listen_fd));
289
290 std::thread client_thread(ClientThreadFunc, assigned_port);
291 const int accept_fd = adb_socket_accept(listen_fd.get(), nullptr, nullptr);
292
293 ASSERT_GE(accept_fd, 0);
294
295 PrepareThread();
296
297 fdevent_run_on_looper([accept_fd]() {
298 asocket* s = create_local_socket(unique_fd(accept_fd));
299 ASSERT_TRUE(s != nullptr);
300 });
301
302 WaitForFdeventLoop();
303 EXPECT_EQ(1u, fdevent_installed_count());
304
305 // Wait until the client closes its socket.
306 client_thread.join();
307
308 WaitForFdeventLoop();
309 ASSERT_EQ(0u, fdevent_installed_count());
310 TerminateThread();
311 }
312
313 #endif // defined(__linux__)
314
315 #if ADB_HOST
316
317 #define VerifyParseHostServiceFailed(s) \
318 do { \
319 std::string service(s); \
320 std::string_view serial, command; \
321 bool result = internal::parse_host_service(&serial, &command, service); \
322 EXPECT_FALSE(result); \
323 } while (0)
324
325 #define VerifyParseHostService(s, expected_serial, expected_command) \
326 do { \
327 std::string service(s); \
328 std::string_view serial, command; \
329 bool result = internal::parse_host_service(&serial, &command, service); \
330 EXPECT_TRUE(result); \
331 EXPECT_EQ(std::string(expected_serial), std::string(serial)); \
332 EXPECT_EQ(std::string(expected_command), std::string(command)); \
333 } while (0);
334
335 // Check [tcp:|udp:]<serial>[:<port>]:<command> format.
TEST(socket_test,test_parse_host_service)336 TEST(socket_test, test_parse_host_service) {
337 for (const std::string& protocol : {"", "tcp:", "udp:"}) {
338 VerifyParseHostServiceFailed(protocol);
339 VerifyParseHostServiceFailed(protocol + "foo");
340
341 {
342 std::string serial = protocol + "foo";
343 VerifyParseHostService(serial + ":bar", serial, "bar");
344 VerifyParseHostService(serial + " :bar:baz", serial, "bar:baz");
345 }
346
347 {
348 // With port.
349 std::string serial = protocol + "foo:123";
350 VerifyParseHostService(serial + ":bar", serial, "bar");
351 VerifyParseHostService(serial + ":456", serial, "456");
352 VerifyParseHostService(serial + ":bar:baz", serial, "bar:baz");
353 }
354
355 // Don't register a port unless it's all numbers and ends with ':'.
356 VerifyParseHostService(protocol + "foo:123", protocol + "foo", "123");
357 VerifyParseHostService(protocol + "foo:123bar:baz", protocol + "foo", "123bar:baz");
358
359 std::string addresses[] = {"100.100.100.100", "[0123:4567:89ab:CDEF:0:9:a:f]", "[::1]"};
360 for (const std::string& address : addresses) {
361 std::string serial = protocol + address;
362 std::string serial_with_port = protocol + address + ":5555";
363 VerifyParseHostService(serial + ":foo", serial, "foo");
364 VerifyParseHostService(serial_with_port + ":foo", serial_with_port, "foo");
365 }
366
367 // If we can't find both [] then treat it as a normal serial with [ in it.
368 VerifyParseHostService(protocol + "[0123:foo", protocol + "[0123", "foo");
369
370 // Don't be fooled by random IPv6 addresses in the command string.
371 VerifyParseHostService(protocol + "foo:ping [0123:4567:89ab:CDEF:0:9:a:f]:5555",
372 protocol + "foo", "ping [0123:4567:89ab:CDEF:0:9:a:f]:5555");
373
374 // Handle embedded NULs properly.
375 VerifyParseHostService(protocol + "foo:echo foo\0bar"s, protocol + "foo",
376 "echo foo\0bar"sv);
377 }
378 }
379
380 // Check <prefix>:<serial>:<command> format.
TEST(socket_test,test_parse_host_service_prefix)381 TEST(socket_test, test_parse_host_service_prefix) {
382 for (const std::string& prefix : {"usb:", "product:", "model:", "device:"}) {
383 VerifyParseHostServiceFailed(prefix);
384 VerifyParseHostServiceFailed(prefix + "foo");
385
386 VerifyParseHostService(prefix + "foo:bar", prefix + "foo", "bar");
387 VerifyParseHostService(prefix + "foo:bar:baz", prefix + "foo", "bar:baz");
388 VerifyParseHostService(prefix + "foo:123:bar", prefix + "foo", "123:bar");
389 }
390 }
391
392 #endif // ADB_HOST
393