1 //
2 // Copyright 2017 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 "android.hardware.bluetooth@1.1.sim"
18
19 #include "bluetooth_hci.h"
20
21 #include "log/log.h"
22 #include <cutils/properties.h>
23 #include <netdb.h>
24 #include <netinet/in.h>
25 #include <string.h>
26
27 #include "hci_internals.h"
28
29 namespace android {
30 namespace hardware {
31 namespace bluetooth {
32 namespace V1_1 {
33 namespace sim {
34
35 using android::hardware::hidl_vec;
36 using test_vendor_lib::AsyncTaskId;
37 using test_vendor_lib::DualModeController;
38 using test_vendor_lib::TaskCallback;
39
40 namespace {
41
BtTestConsoleEnabled()42 bool BtTestConsoleEnabled() {
43 // Assume enabled by default.
44 return property_get_bool("vendor.bt.rootcanal_test_console", true);
45 }
46
47 } // namespace
48
49 class BluetoothDeathRecipient : public hidl_death_recipient {
50 public:
BluetoothDeathRecipient(const sp<IBluetoothHci> hci)51 BluetoothDeathRecipient(const sp<IBluetoothHci> hci) : mHci(hci) {}
52
serviceDied(uint64_t,const wp<::android::hidl::base::V1_0::IBase> &)53 void serviceDied(
54 uint64_t /* cookie */,
55 const wp<::android::hidl::base::V1_0::IBase>& /* who */) override {
56 LOG_ERROR("BluetoothDeathRecipient::serviceDied - Bluetooth service died");
57 has_died_ = true;
58 mHci->close();
59 }
60 sp<IBluetoothHci> mHci;
getHasDied() const61 bool getHasDied() const {
62 return has_died_;
63 }
setHasDied(bool has_died)64 void setHasDied(bool has_died) {
65 has_died_ = has_died;
66 }
67
68 private:
69 bool has_died_;
70 };
71
BluetoothHci()72 BluetoothHci::BluetoothHci() : death_recipient_(new BluetoothDeathRecipient(this)) {}
73
initialize(const sp<V1_0::IBluetoothHciCallbacks> & cb)74 Return<void> BluetoothHci::initialize(
75 const sp<V1_0::IBluetoothHciCallbacks>& cb) {
76 return initialize_impl(cb, nullptr);
77 }
78
initialize_1_1(const sp<V1_1::IBluetoothHciCallbacks> & cb)79 Return<void> BluetoothHci::initialize_1_1(
80 const sp<V1_1::IBluetoothHciCallbacks>& cb) {
81 return initialize_impl(cb, cb);
82 }
83
initialize_impl(const sp<V1_0::IBluetoothHciCallbacks> & cb,const sp<V1_1::IBluetoothHciCallbacks> & cb_1_1)84 Return<void> BluetoothHci::initialize_impl(
85 const sp<V1_0::IBluetoothHciCallbacks>& cb,
86 const sp<V1_1::IBluetoothHciCallbacks>& cb_1_1) {
87 LOG_INFO("%s", __func__);
88 if (cb == nullptr) {
89 LOG_ERROR("cb == nullptr! -> Unable to call initializationComplete(ERR)");
90 return Void();
91 }
92
93 death_recipient_->setHasDied(false);
94 auto link_ret = cb->linkToDeath(death_recipient_, 0);
95 CHECK(link_ret.isOk()) << "Error calling linkToDeath.";
96
97 test_channel_transport_.RegisterCommandHandler(
98 [this](const std::string& name, const std::vector<std::string>& args) {
99 async_manager_.ExecAsync(
100 user_id_, std::chrono::milliseconds(0),
101 [this, name, args]() { test_channel_.HandleCommand(name, args); });
102 });
103
104 controller_ = std::make_shared<DualModeController>();
105
106 char mac_property[PROPERTY_VALUE_MAX] = "";
107 property_get("vendor.bt.rootcanal_mac_address", mac_property, "3C:5A:B4:01:02:03");
108 controller_->Initialize({"dmc", std::string(mac_property)});
109
110 controller_->RegisterEventChannel(
111 [this, cb](std::shared_ptr<std::vector<uint8_t>> packet) {
112 hidl_vec<uint8_t> hci_event(packet->begin(), packet->end());
113 auto ret = cb->hciEventReceived(hci_event);
114 if (!ret.isOk()) {
115 CHECK(death_recipient_->getHasDied())
116 << "Error sending event callback, but no death notification.";
117 }
118 });
119
120 controller_->RegisterAclChannel(
121 [this, cb](std::shared_ptr<std::vector<uint8_t>> packet) {
122 hidl_vec<uint8_t> acl_packet(packet->begin(), packet->end());
123 auto ret = cb->aclDataReceived(acl_packet);
124 if (!ret.isOk()) {
125 CHECK(death_recipient_->getHasDied())
126 << "Error sending acl callback, but no death notification.";
127 }
128 });
129
130 controller_->RegisterScoChannel(
131 [this, cb](std::shared_ptr<std::vector<uint8_t>> packet) {
132 hidl_vec<uint8_t> sco_packet(packet->begin(), packet->end());
133 auto ret = cb->aclDataReceived(sco_packet);
134 if (!ret.isOk()) {
135 CHECK(death_recipient_->getHasDied())
136 << "Error sending sco callback, but no death notification.";
137 }
138 });
139
140 if (cb_1_1 != nullptr) {
141 controller_->RegisterIsoChannel(
142 [this, cb_1_1](std::shared_ptr<std::vector<uint8_t>> packet) {
143 hidl_vec<uint8_t> iso_packet(packet->begin(), packet->end());
144 auto ret = cb_1_1->isoDataReceived(iso_packet);
145 if (!ret.isOk()) {
146 CHECK(death_recipient_->getHasDied())
147 << "Error sending iso callback, but no death notification.";
148 }
149 });
150 }
151
152 controller_->RegisterTaskScheduler(
153 [this](std::chrono::milliseconds delay, const TaskCallback& task) {
154 return async_manager_.ExecAsync(user_id_, delay, task);
155 });
156
157 controller_->RegisterPeriodicTaskScheduler(
158 [this](std::chrono::milliseconds delay, std::chrono::milliseconds period,
159 const TaskCallback& task) {
160 return async_manager_.ExecAsyncPeriodically(user_id_, delay, period,
161 task);
162 });
163
164 controller_->RegisterTaskCancel(
165 [this](AsyncTaskId task) { async_manager_.CancelAsyncTask(task); });
166
167 test_model_.Reset();
168
169 // Add the controller as a device in the model.
170 size_t controller_index = test_model_.Add(controller_);
171 size_t low_energy_phy_index =
172 test_model_.AddPhy(test_vendor_lib::Phy::Type::LOW_ENERGY);
173 size_t classic_phy_index =
174 test_model_.AddPhy(test_vendor_lib::Phy::Type::BR_EDR);
175 test_model_.AddDeviceToPhy(controller_index, low_energy_phy_index);
176 test_model_.AddDeviceToPhy(controller_index, classic_phy_index);
177 test_model_.SetTimerPeriod(std::chrono::milliseconds(10));
178 test_model_.StartTimer();
179
180 // Send responses to logcat if the test channel is not configured.
181 test_channel_.RegisterSendResponse([](const std::string& response) {
182 LOG_INFO("No test channel yet: %s", response.c_str());
183 });
184
185 if (BtTestConsoleEnabled()) {
186 SetUpTestChannel(6111);
187 SetUpHciServer(6211,
188 [this](int fd) { test_model_.IncomingHciConnection(fd); });
189 SetUpLinkLayerServer(
190 6311, [this](int fd) { test_model_.IncomingLinkLayerConnection(fd); });
191 } else {
192 // This should be configurable in the future.
193 LOG_INFO("Adding Beacons so the scan list is not empty.");
194 test_channel_.Add({"beacon", "be:ac:10:00:00:01", "1000"});
195 test_model_.AddDeviceToPhy(controller_index + 1, low_energy_phy_index);
196 test_channel_.Add({"beacon", "be:ac:10:00:00:02", "1000"});
197 test_model_.AddDeviceToPhy(controller_index + 2, low_energy_phy_index);
198 test_channel_.Add(
199 {"scripted_beacon", "5b:ea:c1:00:00:03",
200 "/data/vendor/bluetooth/bluetooth_sim_ble_playback_file",
201 "/data/vendor/bluetooth/bluetooth_sim_ble_playback_events"});
202 test_model_.AddDeviceToPhy(controller_index + 3, low_energy_phy_index);
203 test_channel_.List({});
204 }
205
206 unlink_cb_ = [this, cb](sp<BluetoothDeathRecipient>& death_recipient) {
207 if (death_recipient->getHasDied())
208 LOG_INFO("Skipping unlink call, service died.");
209 else {
210 auto ret = cb->unlinkToDeath(death_recipient);
211 if (!ret.isOk()) {
212 CHECK(death_recipient_->getHasDied())
213 << "Error calling unlink, but no death notification.";
214 }
215 }
216 };
217
218 auto init_ret = cb->initializationComplete(V1_0::Status::SUCCESS);
219 if (!init_ret.isOk()) {
220 CHECK(death_recipient_->getHasDied())
221 << "Error sending init callback, but no death notification.";
222 }
223 return Void();
224 }
225
close()226 Return<void> BluetoothHci::close() {
227 LOG_INFO("%s", __func__);
228 return Void();
229 }
230
sendHciCommand(const hidl_vec<uint8_t> & packet)231 Return<void> BluetoothHci::sendHciCommand(const hidl_vec<uint8_t>& packet) {
232 async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0),
233 [this, packet]() {
234 std::shared_ptr<std::vector<uint8_t>> packet_copy =
235 std::shared_ptr<std::vector<uint8_t>>(
236 new std::vector<uint8_t>(packet));
237 controller_->HandleCommand(packet_copy);
238 });
239 return Void();
240 }
241
sendAclData(const hidl_vec<uint8_t> & packet)242 Return<void> BluetoothHci::sendAclData(const hidl_vec<uint8_t>& packet) {
243 async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0),
244 [this, packet]() {
245 std::shared_ptr<std::vector<uint8_t>> packet_copy =
246 std::shared_ptr<std::vector<uint8_t>>(
247 new std::vector<uint8_t>(packet));
248 controller_->HandleAcl(packet_copy);
249 });
250 return Void();
251 }
252
sendScoData(const hidl_vec<uint8_t> & packet)253 Return<void> BluetoothHci::sendScoData(const hidl_vec<uint8_t>& packet) {
254 async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0),
255 [this, packet]() {
256 std::shared_ptr<std::vector<uint8_t>> packet_copy =
257 std::shared_ptr<std::vector<uint8_t>>(
258 new std::vector<uint8_t>(packet));
259 controller_->HandleSco(packet_copy);
260 });
261 return Void();
262 }
263
sendIsoData(const hidl_vec<uint8_t> & packet)264 Return<void> BluetoothHci::sendIsoData(const hidl_vec<uint8_t>& packet) {
265 async_manager_.ExecAsync(user_id_, std::chrono::milliseconds(0),
266 [this, packet]() {
267 std::shared_ptr<std::vector<uint8_t>> packet_copy =
268 std::shared_ptr<std::vector<uint8_t>>(
269 new std::vector<uint8_t>(packet));
270 controller_->HandleIso(packet_copy);
271 });
272 return Void();
273 }
274
SetUpHciServer(int port,const std::function<void (int)> & connection_callback)275 void BluetoothHci::SetUpHciServer(int port, const std::function<void(int)>& connection_callback) {
276 int socket_fd = remote_hci_transport_.SetUp(port);
277
278 test_channel_.RegisterSendResponse([](const std::string& response) {
279 LOG_INFO("No HCI Response channel: %s", response.c_str());
280 });
281
282 if (socket_fd == -1) {
283 LOG_ERROR("Remote HCI channel SetUp(%d) failed.", port);
284 return;
285 }
286
287 async_manager_.WatchFdForNonBlockingReads(socket_fd, [this, connection_callback](int socket_fd) {
288 int conn_fd = remote_hci_transport_.Accept(socket_fd);
289 if (conn_fd < 0) {
290 LOG_ERROR("Error watching remote HCI channel fd.");
291 return;
292 }
293 int flags = fcntl(conn_fd, F_GETFL, NULL);
294 int ret;
295 ret = fcntl(conn_fd, F_SETFL, flags | O_NONBLOCK);
296 CHECK(ret != -1) << "Error setting O_NONBLOCK " << strerror(errno);
297
298 connection_callback(conn_fd);
299 });
300 }
301
SetUpLinkLayerServer(int port,const std::function<void (int)> & connection_callback)302 void BluetoothHci::SetUpLinkLayerServer(int port, const std::function<void(int)>& connection_callback) {
303 int socket_fd = remote_link_layer_transport_.SetUp(port);
304
305 test_channel_.RegisterSendResponse([](const std::string& response) {
306 LOG_INFO("No LinkLayer Response channel: %s", response.c_str());
307 });
308
309 if (socket_fd == -1) {
310 LOG_ERROR("Remote LinkLayer channel SetUp(%d) failed.", port);
311 return;
312 }
313
314 async_manager_.WatchFdForNonBlockingReads(socket_fd, [this, connection_callback](int socket_fd) {
315 int conn_fd = remote_link_layer_transport_.Accept(socket_fd);
316 if (conn_fd < 0) {
317 LOG_ERROR("Error watching remote LinkLayer channel fd.");
318 return;
319 }
320 int flags = fcntl(conn_fd, F_GETFL, NULL);
321 int ret = fcntl(conn_fd, F_SETFL, flags | O_NONBLOCK);
322 CHECK(ret != -1) << "Error setting O_NONBLOCK " << strerror(errno);
323
324 connection_callback(conn_fd);
325 });
326 }
327
ConnectToRemoteServer(const std::string & server,int port)328 int BluetoothHci::ConnectToRemoteServer(const std::string& server, int port) {
329 int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
330 if (socket_fd < 1) {
331 LOG_INFO("socket() call failed: %s", strerror(errno));
332 return -1;
333 }
334
335 struct hostent* host;
336 host = gethostbyname(server.c_str());
337 if (host == NULL) {
338 LOG_INFO("gethostbyname() failed for %s: %s", server.c_str(),
339 strerror(errno));
340 return -1;
341 }
342
343 struct sockaddr_in serv_addr;
344 memset((void*)&serv_addr, 0, sizeof(serv_addr));
345 serv_addr.sin_family = AF_INET;
346 serv_addr.sin_addr.s_addr = INADDR_ANY;
347 serv_addr.sin_port = htons(port);
348
349 int result = connect(socket_fd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
350 if (result < 0) {
351 LOG_INFO("connect() failed for %s@%d: %s", server.c_str(), port,
352 strerror(errno));
353 return -1;
354 }
355
356 int flags = fcntl(socket_fd, F_GETFL, NULL);
357 int ret = fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK);
358 CHECK(ret != -1) << "Error setting O_NONBLOCK " << strerror(errno);
359
360 return socket_fd;
361 }
362
SetUpTestChannel(int port)363 void BluetoothHci::SetUpTestChannel(int port) {
364 int socket_fd = test_channel_transport_.SetUp(port);
365
366 test_channel_.RegisterSendResponse([](const std::string& response) {
367 LOG_INFO("No test channel: %s", response.c_str());
368 });
369
370 if (socket_fd == -1) {
371 LOG_ERROR("Test channel SetUp(%d) failed.", port);
372 return;
373 }
374
375 LOG_INFO("Test channel SetUp() successful");
376 async_manager_.WatchFdForNonBlockingReads(socket_fd, [this](int socket_fd) {
377 int conn_fd = test_channel_transport_.Accept(socket_fd);
378 if (conn_fd < 0) {
379 LOG_ERROR("Error watching test channel fd.");
380 return;
381 }
382 LOG_INFO("Test channel connection accepted.");
383 test_channel_.RegisterSendResponse(
384 [this, conn_fd](const std::string& response) { test_channel_transport_.SendResponse(conn_fd, response); });
385
386 async_manager_.WatchFdForNonBlockingReads(conn_fd, [this](int conn_fd) {
387 test_channel_transport_.OnCommandReady(conn_fd,
388 [this, conn_fd]() { async_manager_.StopWatchingFileDescriptor(conn_fd); });
389 });
390 });
391 }
392
393 /* Fallback to shared library if there is no service. */
HIDL_FETCH_IBluetoothHci(const char *)394 IBluetoothHci* HIDL_FETCH_IBluetoothHci(const char* /* name */) {
395 return new BluetoothHci();
396 }
397
398 } // namespace sim
399 } // namespace V1_1
400 } // namespace bluetooth
401 } // namespace hardware
402 } // namespace android
403