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.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_test.h"
33#include "socket.h"
34#include "sysdeps.h"
35#include "sysdeps/chrono.h"
36
37struct ThreadArg {
38    int first_read_fd;
39    int last_write_fd;
40    size_t middle_pipe_count;
41};
42
43class LocalSocketTest : public FdeventTest {};
44
45constexpr auto SLEEP_FOR_FDEVENT = 100ms;
46
47TEST_F(LocalSocketTest, smoke) {
48    // Join two socketpairs with a chain of intermediate socketpairs.
49    int first[2];
50    std::vector<std::array<int, 2>> intermediates;
51    int last[2];
52
53    constexpr size_t INTERMEDIATE_COUNT = 50;
54    constexpr size_t MESSAGE_LOOP_COUNT = 100;
55    const std::string MESSAGE = "socket_test";
56
57    intermediates.resize(INTERMEDIATE_COUNT);
58    ASSERT_EQ(0, adb_socketpair(first)) << strerror(errno);
59    ASSERT_EQ(0, adb_socketpair(last)) << strerror(errno);
60    asocket* prev_tail = create_local_socket(first[1]);
61    ASSERT_NE(nullptr, prev_tail);
62
63    auto connect = [](asocket* tail, asocket* head) {
64        tail->peer = head;
65        head->peer = tail;
66        tail->ready(tail);
67    };
68
69    for (auto& intermediate : intermediates) {
70        ASSERT_EQ(0, adb_socketpair(intermediate.data())) << strerror(errno);
71
72        asocket* head = create_local_socket(intermediate[0]);
73        ASSERT_NE(nullptr, head);
74
75        asocket* tail = create_local_socket(intermediate[1]);
76        ASSERT_NE(nullptr, tail);
77
78        connect(prev_tail, head);
79        prev_tail = tail;
80    }
81
82    asocket* end = create_local_socket(last[0]);
83    ASSERT_NE(nullptr, end);
84    connect(prev_tail, end);
85
86    PrepareThread();
87    std::thread thread(fdevent_loop);
88
89    for (size_t i = 0; i < MESSAGE_LOOP_COUNT; ++i) {
90        std::string read_buffer = MESSAGE;
91        std::string write_buffer(MESSAGE.size(), 'a');
92        ASSERT_TRUE(WriteFdExactly(first[0], &read_buffer[0], read_buffer.size()));
93        ASSERT_TRUE(ReadFdExactly(last[1], &write_buffer[0], write_buffer.size()));
94        ASSERT_EQ(read_buffer, write_buffer);
95    }
96
97    ASSERT_EQ(0, adb_close(first[0]));
98    ASSERT_EQ(0, adb_close(last[1]));
99
100    // Wait until the local sockets are closed.
101    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
102    ASSERT_EQ(GetAdditionalLocalSocketCount(), fdevent_installed_count());
103    TerminateThread(thread);
104}
105
106struct CloseWithPacketArg {
107    int socket_fd;
108    size_t bytes_written;
109    int cause_close_fd;
110};
111
112static void CloseWithPacketThreadFunc(CloseWithPacketArg* arg) {
113    asocket* s = create_local_socket(arg->socket_fd);
114    ASSERT_TRUE(s != nullptr);
115    arg->bytes_written = 0;
116    while (true) {
117        apacket* p = get_apacket();
118        p->len = sizeof(p->data);
119        arg->bytes_written += p->len;
120        int ret = s->enqueue(s, p);
121        if (ret == 1) {
122            // The writer has one packet waiting to send.
123            break;
124        }
125    }
126
127    asocket* cause_close_s = create_local_socket(arg->cause_close_fd);
128    ASSERT_TRUE(cause_close_s != nullptr);
129    cause_close_s->peer = s;
130    s->peer = cause_close_s;
131    cause_close_s->ready(cause_close_s);
132
133    fdevent_loop();
134}
135
136// This test checks if we can close local socket in the following situation:
137// The socket is closing but having some packets, so it is not closed. Then
138// some write error happens in the socket's file handler, e.g., the file
139// handler is closed.
140TEST_F(LocalSocketTest, close_socket_with_packet) {
141    int socket_fd[2];
142    ASSERT_EQ(0, adb_socketpair(socket_fd));
143    int cause_close_fd[2];
144    ASSERT_EQ(0, adb_socketpair(cause_close_fd));
145    CloseWithPacketArg arg;
146    arg.socket_fd = socket_fd[1];
147    arg.cause_close_fd = cause_close_fd[1];
148
149    PrepareThread();
150    std::thread thread(CloseWithPacketThreadFunc, &arg);
151    // Wait until the fdevent_loop() starts.
152    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
153    ASSERT_EQ(0, adb_close(cause_close_fd[0]));
154    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
155    EXPECT_EQ(1u + GetAdditionalLocalSocketCount(), fdevent_installed_count());
156    ASSERT_EQ(0, adb_close(socket_fd[0]));
157    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
158    ASSERT_EQ(GetAdditionalLocalSocketCount(), fdevent_installed_count());
159    TerminateThread(thread);
160}
161
162// This test checks if we can read packets from a closing local socket.
163TEST_F(LocalSocketTest, read_from_closing_socket) {
164    int socket_fd[2];
165    ASSERT_EQ(0, adb_socketpair(socket_fd));
166    int cause_close_fd[2];
167    ASSERT_EQ(0, adb_socketpair(cause_close_fd));
168    CloseWithPacketArg arg;
169    arg.socket_fd = socket_fd[1];
170    arg.cause_close_fd = cause_close_fd[1];
171
172    PrepareThread();
173    std::thread thread(CloseWithPacketThreadFunc, &arg);
174    // Wait until the fdevent_loop() starts.
175    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
176    ASSERT_EQ(0, adb_close(cause_close_fd[0]));
177    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
178    EXPECT_EQ(1u + GetAdditionalLocalSocketCount(), fdevent_installed_count());
179
180    // Verify if we can read successfully.
181    std::vector<char> buf(arg.bytes_written);
182    ASSERT_NE(0u, arg.bytes_written);
183    ASSERT_EQ(true, ReadFdExactly(socket_fd[0], buf.data(), buf.size()));
184    ASSERT_EQ(0, adb_close(socket_fd[0]));
185
186    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
187    ASSERT_EQ(GetAdditionalLocalSocketCount(), fdevent_installed_count());
188    TerminateThread(thread);
189}
190
191// This test checks if we can close local socket in the following situation:
192// The socket is not closed and has some packets. When it fails to write to
193// the socket's file handler because the other end is closed, we check if the
194// socket is closed.
195TEST_F(LocalSocketTest, write_error_when_having_packets) {
196    int socket_fd[2];
197    ASSERT_EQ(0, adb_socketpair(socket_fd));
198    int cause_close_fd[2];
199    ASSERT_EQ(0, adb_socketpair(cause_close_fd));
200    CloseWithPacketArg arg;
201    arg.socket_fd = socket_fd[1];
202    arg.cause_close_fd = cause_close_fd[1];
203
204    PrepareThread();
205    std::thread thread(CloseWithPacketThreadFunc, &arg);
206    // Wait until the fdevent_loop() starts.
207    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
208    EXPECT_EQ(2u + GetAdditionalLocalSocketCount(), fdevent_installed_count());
209    ASSERT_EQ(0, adb_close(socket_fd[0]));
210
211    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
212    ASSERT_EQ(GetAdditionalLocalSocketCount(), fdevent_installed_count());
213    TerminateThread(thread);
214}
215
216#if defined(__linux__)
217
218static void ClientThreadFunc() {
219    std::string error;
220    int fd = network_loopback_client(5038, SOCK_STREAM, &error);
221    ASSERT_GE(fd, 0) << error;
222    std::this_thread::sleep_for(200ms);
223    ASSERT_EQ(0, adb_close(fd));
224}
225
226struct CloseRdHupSocketArg {
227    int socket_fd;
228};
229
230static void CloseRdHupSocketThreadFunc(CloseRdHupSocketArg* arg) {
231    asocket* s = create_local_socket(arg->socket_fd);
232    ASSERT_TRUE(s != nullptr);
233
234    fdevent_loop();
235}
236
237// This test checks if we can close sockets in CLOSE_WAIT state.
238TEST_F(LocalSocketTest, close_socket_in_CLOSE_WAIT_state) {
239    std::string error;
240    int listen_fd = network_inaddr_any_server(5038, SOCK_STREAM, &error);
241    ASSERT_GE(listen_fd, 0);
242
243    std::thread client_thread(ClientThreadFunc);
244
245    int accept_fd = adb_socket_accept(listen_fd, nullptr, nullptr);
246    ASSERT_GE(accept_fd, 0);
247    CloseRdHupSocketArg arg;
248    arg.socket_fd = accept_fd;
249
250    PrepareThread();
251    std::thread thread(CloseRdHupSocketThreadFunc, &arg);
252
253    // Wait until the fdevent_loop() starts.
254    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
255    EXPECT_EQ(1u + GetAdditionalLocalSocketCount(), fdevent_installed_count());
256
257    // Wait until the client closes its socket.
258    client_thread.join();
259
260    std::this_thread::sleep_for(SLEEP_FOR_FDEVENT);
261    ASSERT_EQ(GetAdditionalLocalSocketCount(), fdevent_installed_count());
262    TerminateThread(thread);
263}
264
265#endif  // defined(__linux__)
266
267#if ADB_HOST
268
269// Checks that skip_host_serial(serial) returns a pointer to the part of |serial| which matches
270// |expected|, otherwise logs the failure to gtest.
271void VerifySkipHostSerial(std::string serial, const char* expected) {
272    char* result = internal::skip_host_serial(&serial[0]);
273    if (expected == nullptr) {
274        EXPECT_EQ(nullptr, result);
275    } else {
276        EXPECT_STREQ(expected, result);
277    }
278}
279
280// Check [tcp:|udp:]<serial>[:<port>]:<command> format.
281TEST(socket_test, test_skip_host_serial) {
282    for (const std::string& protocol : {"", "tcp:", "udp:"}) {
283        VerifySkipHostSerial(protocol, nullptr);
284        VerifySkipHostSerial(protocol + "foo", nullptr);
285
286        VerifySkipHostSerial(protocol + "foo:bar", ":bar");
287        VerifySkipHostSerial(protocol + "foo:bar:baz", ":bar:baz");
288
289        VerifySkipHostSerial(protocol + "foo:123:bar", ":bar");
290        VerifySkipHostSerial(protocol + "foo:123:456", ":456");
291        VerifySkipHostSerial(protocol + "foo:123:bar:baz", ":bar:baz");
292
293        // Don't register a port unless it's all numbers and ends with ':'.
294        VerifySkipHostSerial(protocol + "foo:123", ":123");
295        VerifySkipHostSerial(protocol + "foo:123bar:baz", ":123bar:baz");
296
297        VerifySkipHostSerial(protocol + "100.100.100.100:5555:foo", ":foo");
298        VerifySkipHostSerial(protocol + "[0123:4567:89ab:CDEF:0:9:a:f]:5555:foo", ":foo");
299        VerifySkipHostSerial(protocol + "[::1]:5555:foo", ":foo");
300
301        // If we can't find both [] then treat it as a normal serial with [ in it.
302        VerifySkipHostSerial(protocol + "[0123:foo", ":foo");
303
304        // Don't be fooled by random IPv6 addresses in the command string.
305        VerifySkipHostSerial(protocol + "foo:ping [0123:4567:89ab:CDEF:0:9:a:f]:5555",
306                             ":ping [0123:4567:89ab:CDEF:0:9:a:f]:5555");
307    }
308}
309
310// Check <prefix>:<serial>:<command> format.
311TEST(socket_test, test_skip_host_serial_prefix) {
312    for (const std::string& prefix : {"usb:", "product:", "model:", "device:"}) {
313        VerifySkipHostSerial(prefix, nullptr);
314        VerifySkipHostSerial(prefix + "foo", nullptr);
315
316        VerifySkipHostSerial(prefix + "foo:bar", ":bar");
317        VerifySkipHostSerial(prefix + "foo:bar:baz", ":bar:baz");
318        VerifySkipHostSerial(prefix + "foo:123:bar", ":123:bar");
319    }
320}
321
322#endif  // ADB_HOST
323