1 /*
2 * Copyright 2022 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 #define LOG_TAG "bt_h4_unittest"
18
19 #include "h4_protocol.h"
20
21 #include <gmock/gmock.h>
22 #include <gtest/gtest.h>
23 #include <log/log.h>
24 #include <sys/socket.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27
28 #include <cstdint>
29 #include <cstring>
30 #include <future>
31 #include <vector>
32
33 #include "async_fd_watcher.h"
34 #include "log/log.h"
35
36 using android::hardware::bluetooth::async::AsyncFdWatcher;
37 using namespace android::hardware::bluetooth::hci;
38 using ::testing::Eq;
39
40 static char sample_data1[100] = "A point is that which has no part.";
41 static char sample_data2[100] = "A line is breadthless length.";
42 static char sample_data3[100] = "The ends of a line are points.";
43 static char sample_data4[100] =
44 "A plane surface is a surface which lies evenly with the straight ...";
45 static char acl_data[100] =
46 "A straight line is a line which lies evenly with the points on itself.";
47 static char sco_data[100] =
48 "A surface is that which has length and breadth only.";
49 static char event_data[100] = "The edges of a surface are lines.";
50 static char iso_data[100] =
51 "A plane angle is the inclination to one another of two lines in a ...";
52
53 // 5 seconds. Just don't hang.
54 static constexpr size_t kTimeoutMs = 5000;
55
56 MATCHER_P3(PacketMatches, header_, header_length, payload,
57 "Match header_length bytes of header and then the payload") {
58 size_t payload_length = strlen(payload);
59 if (header_length + payload_length != arg.size()) {
60 return false;
61 }
62
63 if (memcmp(header_, arg.data(), header_length) != 0) {
64 return false;
65 }
66
67 return memcmp(payload, arg.data() + header_length, payload_length) == 0;
68 };
69
ACTION_P(Notify,barrier)70 ACTION_P(Notify, barrier) {
71 ALOGD("%s", __func__);
72 barrier->set_value();
73 }
74
75 class H4ProtocolTest : public ::testing::Test {
76 protected:
SetUp()77 void SetUp() override {
78 ALOGD("%s", __func__);
79
80 int sockfd[2];
81 socketpair(AF_LOCAL, SOCK_STREAM, 0, sockfd);
82 chip_uart_fd_ = sockfd[1];
83 stack_uart_fd_ = sockfd[0];
84 h4_hci_ = std::make_shared<H4Protocol>(
85 stack_uart_fd_, cmd_cb_.AsStdFunction(), acl_cb_.AsStdFunction(),
86 sco_cb_.AsStdFunction(), event_cb_.AsStdFunction(),
87 iso_cb_.AsStdFunction(), disconnect_cb_.AsStdFunction());
88 }
89
TearDown()90 void TearDown() override {
91 close(stack_uart_fd_);
92 close(chip_uart_fd_);
93 }
94
CallDataReady()95 virtual void CallDataReady() { h4_hci_->OnDataReady(); }
96
SendAndReadUartOutbound(PacketType type,char * data)97 void SendAndReadUartOutbound(PacketType type, char* data) {
98 ALOGD("%s sending", __func__);
99 int data_length = strlen(data);
100 h4_hci_->Send(type, (uint8_t*)data, data_length);
101
102 int uart_length = data_length + 1; // + 1 for data type code
103 int i;
104
105 ALOGD("%s reading", __func__);
106 for (i = 0; i < uart_length; i++) {
107 fd_set read_fds;
108 FD_ZERO(&read_fds);
109 FD_SET(chip_uart_fd_, &read_fds);
110 TEMP_FAILURE_RETRY(
111 select(chip_uart_fd_ + 1, &read_fds, nullptr, nullptr, nullptr));
112
113 char byte;
114 TEMP_FAILURE_RETRY(read(chip_uart_fd_, &byte, 1));
115
116 EXPECT_EQ(i == 0 ? static_cast<uint8_t>(type) : data[i - 1], byte);
117 }
118
119 EXPECT_EQ(i, uart_length);
120 }
121
ExpectInboundAclData(char * payload,std::promise<void> * promise)122 void ExpectInboundAclData(char* payload, std::promise<void>* promise) {
123 // h4 type[1] + handle[2] + size[2]
124 header_[0] = static_cast<uint8_t>(PacketType::ACL_DATA);
125 header_[1] = 19;
126 header_[2] = 92;
127 int length = strlen(payload);
128 header_[3] = length & 0xFF;
129 header_[4] = (length >> 8) & 0xFF;
130 ALOGD("(%d bytes) %s", length, payload);
131
132 EXPECT_CALL(acl_cb_,
133 Call(PacketMatches(header_ + 1, kAclHeaderSize, payload)))
134 .WillOnce(Notify(promise));
135 }
136
WaitForTimeout(std::promise<void> * promise)137 void WaitForTimeout(std::promise<void>* promise) {
138 auto future = promise->get_future();
139 auto status = future.wait_for(std::chrono::milliseconds(kTimeoutMs));
140 EXPECT_EQ(status, std::future_status::ready);
141 }
142
WriteInboundAclData(char * payload)143 void WriteInboundAclData(char* payload) {
144 // Use the header_ computed in ExpectInboundAclData
145 TEMP_FAILURE_RETRY(write(chip_uart_fd_, header_, kAclHeaderSize + 1));
146 TEMP_FAILURE_RETRY(write(chip_uart_fd_, payload, strlen(payload)));
147 }
148
ExpectInboundScoData(char * payload,std::promise<void> * promise)149 void ExpectInboundScoData(char* payload, std::promise<void>* promise) {
150 // h4 type[1] + handle[2] + size[1]
151 header_[0] = static_cast<uint8_t>(PacketType::SCO_DATA);
152 header_[1] = 20;
153 header_[2] = 17;
154 header_[3] = strlen(payload) & 0xFF;
155 EXPECT_CALL(sco_cb_,
156 Call(PacketMatches(header_ + 1, kScoHeaderSize, payload)))
157 .WillOnce(Notify(promise));
158 }
159
WriteInboundScoData(char * payload)160 void WriteInboundScoData(char* payload) {
161 // Use the header_ computed in ExpectInboundScoData
162 ALOGD("%s writing", __func__);
163 TEMP_FAILURE_RETRY(write(chip_uart_fd_, header_, kScoHeaderSize + 1));
164 TEMP_FAILURE_RETRY(write(chip_uart_fd_, payload, strlen(payload)));
165 }
166
ExpectInboundEvent(char * payload,std::promise<void> * promise)167 void ExpectInboundEvent(char* payload, std::promise<void>* promise) {
168 // h4 type[1] + event_code[1] + size[1]
169 header_[0] = static_cast<uint8_t>(PacketType::EVENT);
170 header_[1] = 9;
171 header_[2] = strlen(payload) & 0xFF;
172 EXPECT_CALL(event_cb_,
173 Call(PacketMatches(header_ + 1, kEventHeaderSize, payload)))
174 .WillOnce(Notify(promise));
175 }
176
WriteInboundEvent(char * payload)177 void WriteInboundEvent(char* payload) {
178 // Use the header_ computed in ExpectInboundEvent
179 char preamble[3] = {static_cast<uint8_t>(PacketType::EVENT), 9, 0};
180 preamble[2] = strlen(payload) & 0xFF;
181 ALOGD("%s writing", __func__);
182 TEMP_FAILURE_RETRY(write(chip_uart_fd_, header_, kEventHeaderSize + 1));
183 TEMP_FAILURE_RETRY(write(chip_uart_fd_, payload, strlen(payload)));
184 }
185
ExpectInboundIsoData(char * payload,std::promise<void> * promise)186 void ExpectInboundIsoData(char* payload, std::promise<void>* promise) {
187 // h4 type[1] + handle[2] + size[1]
188 header_[0] = static_cast<uint8_t>(PacketType::ISO_DATA);
189 header_[1] = 19;
190 header_[2] = 92;
191 int length = strlen(payload);
192 header_[3] = length & 0xFF;
193 header_[4] = (length >> 8) & 0x3F;
194
195 EXPECT_CALL(iso_cb_,
196 Call(PacketMatches(header_ + 1, kIsoHeaderSize, payload)))
197 .WillOnce(Notify(promise));
198 }
199
WriteInboundIsoData(char * payload)200 void WriteInboundIsoData(char* payload) {
201 // Use the header_ computed in ExpectInboundIsoData
202 ALOGD("%s writing", __func__);
203 TEMP_FAILURE_RETRY(write(chip_uart_fd_, header_, kIsoHeaderSize + 1));
204 TEMP_FAILURE_RETRY(write(chip_uart_fd_, payload, strlen(payload)));
205 }
206
WriteAndExpectManyInboundAclDataPackets(char * payload)207 void WriteAndExpectManyInboundAclDataPackets(char* payload) {
208 size_t kNumPackets = 20;
209 // h4 type[1] + handle[2] + size[2]
210 char preamble[5] = {static_cast<uint8_t>(PacketType::ACL_DATA), 19, 92, 0,
211 0};
212 int length = strlen(payload);
213 preamble[3] = length & 0xFF;
214 preamble[4] = (length >> 8) & 0xFF;
215
216 EXPECT_CALL(acl_cb_, Call(PacketMatches(preamble + 1, sizeof(preamble) - 1,
217 payload)))
218 .Times(kNumPackets);
219
220 for (size_t i = 0; i < kNumPackets; i++) {
221 TEMP_FAILURE_RETRY(write(chip_uart_fd_, preamble, sizeof(preamble)));
222 TEMP_FAILURE_RETRY(write(chip_uart_fd_, payload, strlen(payload)));
223 }
224
225 CallDataReady();
226 }
227
228 testing::MockFunction<void(const std::vector<uint8_t>&)> cmd_cb_;
229 testing::MockFunction<void(const std::vector<uint8_t>&)> event_cb_;
230 testing::MockFunction<void(const std::vector<uint8_t>&)> acl_cb_;
231 testing::MockFunction<void(const std::vector<uint8_t>&)> sco_cb_;
232 testing::MockFunction<void(const std::vector<uint8_t>&)> iso_cb_;
233 testing::MockFunction<void(void)> disconnect_cb_;
234 std::shared_ptr<H4Protocol> h4_hci_;
235 int chip_uart_fd_;
236 int stack_uart_fd_;
237
238 char header_[5];
239 };
240
241 // Test sending data sends correct data onto the UART
TEST_F(H4ProtocolTest,TestSends)242 TEST_F(H4ProtocolTest, TestSends) {
243 SendAndReadUartOutbound(PacketType::COMMAND, sample_data1);
244 SendAndReadUartOutbound(PacketType::ACL_DATA, sample_data2);
245 SendAndReadUartOutbound(PacketType::SCO_DATA, sample_data3);
246 SendAndReadUartOutbound(PacketType::ISO_DATA, sample_data4);
247 }
248
249 // Ensure we properly parse data coming from the UART
TEST_F(H4ProtocolTest,TestReads)250 TEST_F(H4ProtocolTest, TestReads) {
251 std::promise<void> acl_promise;
252 std::promise<void> sco_promise;
253 std::promise<void> event_promise;
254 std::promise<void> iso_promise;
255
256 ExpectInboundAclData(acl_data, &acl_promise);
257 WriteInboundAclData(acl_data);
258 CallDataReady();
259 ExpectInboundScoData(sco_data, &sco_promise);
260 WriteInboundScoData(sco_data);
261 CallDataReady();
262 ExpectInboundEvent(event_data, &event_promise);
263 WriteInboundEvent(event_data);
264 CallDataReady();
265 ExpectInboundIsoData(iso_data, &iso_promise);
266 WriteInboundIsoData(iso_data);
267 CallDataReady();
268
269 WaitForTimeout(&acl_promise);
270 WaitForTimeout(&sco_promise);
271 WaitForTimeout(&event_promise);
272 WaitForTimeout(&iso_promise);
273 }
274
TEST_F(H4ProtocolTest,TestMultiplePackets)275 TEST_F(H4ProtocolTest, TestMultiplePackets) {
276 WriteAndExpectManyInboundAclDataPackets(sco_data);
277 }
278
TEST_F(H4ProtocolTest,TestDisconnect)279 TEST_F(H4ProtocolTest, TestDisconnect) {
280 EXPECT_CALL(disconnect_cb_, Call());
281 close(chip_uart_fd_);
282 CallDataReady();
283 }
284
TEST_F(H4ProtocolTest,TestPartialWrites)285 TEST_F(H4ProtocolTest, TestPartialWrites) {
286 size_t payload_len = strlen(acl_data);
287 const size_t kNumIntervals = payload_len + 1;
288 // h4 type[1] + handle[2] + size[2]
289 header_[0] = static_cast<uint8_t>(PacketType::ACL_DATA);
290 header_[1] = 19;
291 header_[2] = 92;
292 header_[3] = payload_len & 0xFF;
293 header_[4] = (payload_len >> 8) & 0xFF;
294
295 EXPECT_CALL(acl_cb_,
296 Call(PacketMatches(header_ + 1, sizeof(header_) - 1, acl_data)))
297 .Times(kNumIntervals);
298
299 for (size_t interval = 1; interval < kNumIntervals + 1; interval++) {
300 // Use the header_ data that expect already set up.
301 if (interval < kAclHeaderSize) {
302 TEMP_FAILURE_RETRY(write(chip_uart_fd_, header_, interval));
303 CallDataReady();
304 TEMP_FAILURE_RETRY(write(chip_uart_fd_, header_ + interval,
305 kAclHeaderSize + 1 - interval));
306 CallDataReady();
307 } else {
308 TEMP_FAILURE_RETRY(write(chip_uart_fd_, header_, kAclHeaderSize + 1));
309 CallDataReady();
310 }
311
312 for (size_t bytes = 0; bytes + interval <= payload_len; bytes += interval) {
313 TEMP_FAILURE_RETRY(write(chip_uart_fd_, acl_data + bytes, interval));
314 CallDataReady();
315 }
316 size_t extra_bytes = payload_len % interval;
317 if (extra_bytes) {
318 TEMP_FAILURE_RETRY(write(
319 chip_uart_fd_, acl_data + payload_len - extra_bytes, extra_bytes));
320 CallDataReady();
321 }
322 }
323 }
324
325 class H4ProtocolAsyncTest : public H4ProtocolTest {
326 protected:
SetUp()327 void SetUp() override {
328 H4ProtocolTest::SetUp();
329 fd_watcher_.WatchFdForNonBlockingReads(
330 stack_uart_fd_, [this](int) { h4_hci_->OnDataReady(); });
331 }
332
TearDown()333 void TearDown() override { fd_watcher_.StopWatchingFileDescriptors(); }
334
CallDataReady()335 void CallDataReady() override {
336 // The Async test can't call data ready.
337 FAIL();
338 }
339
SendAndReadUartOutbound(PacketType type,char * data)340 void SendAndReadUartOutbound(PacketType type, char* data) {
341 ALOGD("%s sending", __func__);
342 int data_length = strlen(data);
343 h4_hci_->Send(type, (uint8_t*)data, data_length);
344
345 int uart_length = data_length + 1; // + 1 for data type code
346 int i;
347
348 ALOGD("%s reading", __func__);
349 for (i = 0; i < uart_length; i++) {
350 fd_set read_fds;
351 FD_ZERO(&read_fds);
352 FD_SET(chip_uart_fd_, &read_fds);
353 TEMP_FAILURE_RETRY(
354 select(chip_uart_fd_ + 1, &read_fds, nullptr, nullptr, nullptr));
355
356 char byte;
357 TEMP_FAILURE_RETRY(read(chip_uart_fd_, &byte, 1));
358
359 EXPECT_EQ(i == 0 ? static_cast<uint8_t>(type) : data[i - 1], byte);
360 }
361
362 EXPECT_EQ(i, uart_length);
363 }
364
WriteAndExpectInboundAclData(char * payload)365 void WriteAndExpectInboundAclData(char* payload) {
366 std::promise<void> promise;
367 ExpectInboundAclData(payload, &promise);
368 WriteInboundAclData(payload);
369 WaitForTimeout(&promise);
370 }
371
WriteAndExpectInboundScoData(char * payload)372 void WriteAndExpectInboundScoData(char* payload) {
373 std::promise<void> promise;
374 ExpectInboundScoData(payload, &promise);
375 WriteInboundScoData(payload);
376 WaitForTimeout(&promise);
377 }
378
WriteAndExpectInboundEvent(char * payload)379 void WriteAndExpectInboundEvent(char* payload) {
380 std::promise<void> promise;
381 ExpectInboundEvent(payload, &promise);
382 WriteInboundEvent(payload);
383 WaitForTimeout(&promise);
384 }
385
WriteAndExpectInboundIsoData(char * payload)386 void WriteAndExpectInboundIsoData(char* payload) {
387 std::promise<void> promise;
388 ExpectInboundIsoData(payload, &promise);
389 WriteInboundIsoData(payload);
390 WaitForTimeout(&promise);
391 }
392
WriteAndExpectManyInboundAclDataPackets(char * payload)393 void WriteAndExpectManyInboundAclDataPackets(char* payload) {
394 const size_t kNumPackets = 20;
395 // h4 type[1] + handle[2] + size[2]
396 char preamble[5] = {static_cast<uint8_t>(PacketType::ACL_DATA), 19, 92, 0,
397 0};
398 int length = strlen(payload);
399 preamble[3] = length & 0xFF;
400 preamble[4] = (length >> 8) & 0xFF;
401
402 EXPECT_CALL(acl_cb_, Call(PacketMatches(preamble + 1, sizeof(preamble) - 1,
403 payload)))
404 .Times(kNumPackets);
405
406 for (size_t i = 0; i < kNumPackets; i++) {
407 TEMP_FAILURE_RETRY(write(chip_uart_fd_, preamble, sizeof(preamble)));
408 TEMP_FAILURE_RETRY(write(chip_uart_fd_, payload, strlen(payload)));
409 }
410
411 WriteAndExpectInboundEvent(event_data);
412 }
413
414 AsyncFdWatcher fd_watcher_;
415 };
416
417 // Test sending data sends correct data onto the UART
TEST_F(H4ProtocolAsyncTest,TestSends)418 TEST_F(H4ProtocolAsyncTest, TestSends) {
419 SendAndReadUartOutbound(PacketType::COMMAND, sample_data1);
420 SendAndReadUartOutbound(PacketType::ACL_DATA, sample_data2);
421 SendAndReadUartOutbound(PacketType::SCO_DATA, sample_data3);
422 SendAndReadUartOutbound(PacketType::ISO_DATA, sample_data4);
423 }
424
425 // Ensure we properly parse data coming from the UART
TEST_F(H4ProtocolAsyncTest,TestReads)426 TEST_F(H4ProtocolAsyncTest, TestReads) {
427 WriteAndExpectInboundAclData(acl_data);
428 WriteAndExpectInboundScoData(sco_data);
429 WriteAndExpectInboundEvent(event_data);
430 WriteAndExpectInboundIsoData(iso_data);
431 }
432
TEST_F(H4ProtocolAsyncTest,TestMultiplePackets)433 TEST_F(H4ProtocolAsyncTest, TestMultiplePackets) {
434 WriteAndExpectManyInboundAclDataPackets(sco_data);
435 }
436
TEST_F(H4ProtocolAsyncTest,TestDisconnect)437 TEST_F(H4ProtocolAsyncTest, TestDisconnect) {
438 std::promise<void> promise;
439 EXPECT_CALL(disconnect_cb_, Call()).WillOnce(Notify(&promise));
440 close(chip_uart_fd_);
441
442 WaitForTimeout(&promise);
443 }
444