1 /*
2 * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <thread>
17
18 #include "bluetooth_a2dp_sink_server.h"
19 #include "bluetooth_a2dp_source_server.h"
20 #include "bluetooth_avrcp_ct_server.h"
21 #include "bluetooth_avrcp_tg_server.h"
22 #include "bluetooth_ble_advertiser_server.h"
23 #include "bluetooth_ble_central_manager_server.h"
24 #include "bluetooth_errorcode.h"
25 #include "bluetooth_gatt_client_server.h"
26 #include "bluetooth_gatt_server_server.h"
27 #include "bluetooth_hfp_ag_server.h"
28 #include "bluetooth_hfp_hf_server.h"
29 #include "bluetooth_hid_host_server.h"
30 #include "bluetooth_host_dumper.h"
31 #include "bluetooth_log.h"
32 #include "bluetooth_pan_server.h"
33 #include "bluetooth_socket_server.h"
34 #include "bluetooth_utils_server.h"
35 #include "file_ex.h"
36 #include "dialog_switch.h"
37 #include "hisysevent.h"
38 #include "interface_adapter_manager.h"
39 #include "permission_utils.h"
40 #include "permission_manager.h"
41 #include "bluetooth_host_server.h"
42
43
44 #include "interface_adapter_ble.h"
45 #include "interface_adapter_classic.h"
46 #include "interface_profile_manager.h"
47 #include "ipc_skeleton.h"
48 #include "raw_address.h"
49 #include "remote_observer_list.h"
50 #include "string_ex.h"
51 #include "system_ability_definition.h"
52 #include "ipc_types.h"
53 #include "safe_map.h"
54
55 namespace OHOS {
56 namespace Bluetooth {
57 using namespace OHOS::bluetooth;
58 struct BluetoothHostServer::impl {
59 impl();
60 ~impl();
61 void Init();
62 void Clear();
63
64 /// sys state observer
65 class SystemStateObserver;
66 std::unique_ptr<SystemStateObserver> systemStateObserver_ = nullptr;
67
68 /// adapter state observer
69 class AdapterStateObserver;
70 std::unique_ptr<AdapterStateObserver> observerImp_ = nullptr;
71
72 /// classic observer
73 class AdapterClassicObserver;
74 std::unique_ptr<AdapterClassicObserver> classicObserverImp_ = nullptr;
75
76 /// classic remote device observer
77 class ClassicRemoteDeviceObserver;
78 std::unique_ptr<ClassicRemoteDeviceObserver> remoteObserverImp_ = nullptr;
79
80 /// ble observer
81 class AdapterBleObserver;
82 std::unique_ptr<AdapterBleObserver> bleObserverImp_ = nullptr;
83
84 /// ble remote device observer
85 class BlePeripheralCallback;
86 std::unique_ptr<BlePeripheralCallback> bleRemoteObserverImp_ = nullptr;
87
88 /// user regist observers
89 RemoteObserverList<IBluetoothHostObserver> observers_;
90 RemoteObserverList<IBluetoothHostObserver> bleObservers_;
91 SafeMap<sptr<IRemoteObject>, uint32_t> observersToken_;
92 SafeMap<sptr<IRemoteObject>, uint32_t> bleObserversToken_;
93 SafeMap<sptr<IRemoteObject>, int32_t> observersPid_;
94 SafeMap<sptr<IRemoteObject>, int32_t> bleObserversPid_;
95
96 /// user regist remote observers
97 RemoteObserverList<IBluetoothRemoteDeviceObserver> remoteObservers_;
98 SafeMap<sptr<IRemoteObject>, uint32_t> remoteObserversToken_;
99 SafeMap<sptr<IRemoteObject>, int32_t> remoteObserversPid_;
100
101 /// user regist remote observers
102 RemoteObserverList<IBluetoothBlePeripheralObserver> bleRemoteObservers_;
103 SafeMap<sptr<IRemoteObject>, uint32_t> bleRemoteObserversToken_;
104
105 SafeMap<std::string, sptr<IRemoteObject>> servers_;
106 SafeMap<std::string, sptr<IRemoteObject>> bleServers_;
107
108 std::vector<sptr<IBluetoothHostObserver>> hostObservers_;
109 std::mutex hostObserversMutex;
110 std::vector<sptr<IBluetoothRemoteDeviceObserver>> remoteDeviceObservers_;
111 std::mutex remoteDeviceObserversMutex;
112 std::vector<sptr<IBluetoothHostObserver>> bleAdapterObservers_;
113 std::mutex bleAdapterObserversMutex;
114 std::vector<sptr<IBluetoothBlePeripheralObserver>> blePeripheralObservers_;
115 std::mutex blePeripheralObserversMutex;
116
117 private:
118 void createServers();
119 };
120
121 class BluetoothHostServer::impl::SystemStateObserver : public ISystemStateObserver {
122 public:
SystemStateObserver(BluetoothHostServer::impl * impl)123 SystemStateObserver(BluetoothHostServer::impl *impl) : impl_(impl) {};
124 ~SystemStateObserver() override = default;
125
OnSystemStateChange(const BTSystemState state)126 void OnSystemStateChange(const BTSystemState state) override
127 {
128 if (!impl_) {
129 HILOGI("failed: impl_ is null");
130 return;
131 }
132 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
133 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
134 switch (state) {
135 case BTSystemState::ON:
136 /// update service ptr
137 if (classicService) {
138 classicService->RegisterClassicAdapterObserver(
139 *(IAdapterClassicObserver *)impl_->classicObserverImp_.get());
140 classicService->RegisterRemoteDeviceObserver(
141 *(IClassicRemoteDeviceObserver *)impl_->remoteObserverImp_.get());
142 }
143 if (bleService) {
144 bleService->RegisterBleAdapterObserver(
145 *(IAdapterBleObserver *)impl_->bleObserverImp_.get());
146 bleService->RegisterBlePeripheralCallback(
147 *(IBlePeripheralCallback *)impl_->bleRemoteObserverImp_.get());
148 }
149 break;
150
151 case BTSystemState::OFF:
152 if (classicService) {
153 classicService->DeregisterClassicAdapterObserver(
154 *(IAdapterClassicObserver *)impl_->classicObserverImp_.get());
155 classicService->DeregisterRemoteDeviceObserver(
156 *(IClassicRemoteDeviceObserver *)impl_->remoteObserverImp_.get());
157 classicService = nullptr;
158 }
159 if (bleService) {
160 bleService->DeregisterBleAdapterObserver(
161 *(IAdapterBleObserver *)impl_->bleObserverImp_.get());
162 bleService->DeregisterBlePeripheralCallback(
163 *(IBlePeripheralCallback *)impl_->bleRemoteObserverImp_.get());
164 bleService = nullptr;
165 }
166 break;
167 default:
168 break;
169 }
170 }
171
172 private:
173 BluetoothHostServer::impl *impl_ = nullptr;
174 };
175
176 class BluetoothHostServer::impl::AdapterStateObserver : public IAdapterStateObserver {
177 public:
AdapterStateObserver(BluetoothHostServer::impl * impl)178 AdapterStateObserver(BluetoothHostServer::impl *impl) : impl_(impl){};
179 ~AdapterStateObserver() override = default;
180
OnStateChangeV2(BTTransport transport,BTStateID state,sptr<IBluetoothHostObserver> & observer)181 static void OnStateChangeV2(BTTransport transport, BTStateID state, sptr<IBluetoothHostObserver> &observer)
182 {
183 if (transport == BTTransport::ADAPTER_BREDR && state == BTStateID::STATE_TURN_ON) {
184 observer->OnBluetoothStateChanged(BluetoothSwitchState::STATE_ON);
185 }
186 if (transport == BTTransport::ADAPTER_BLE && state == BTStateID::STATE_TURN_OFF) {
187 observer->OnBluetoothStateChanged(BluetoothSwitchState::STATE_OFF);
188 }
189 }
190
OnStateChange(const BTTransport transport,const BTStateID state)191 void OnStateChange(const BTTransport transport, const BTStateID state) override
192 {
193 if (!impl_) {
194 return;
195 }
196 if (transport == BTTransport::ADAPTER_BREDR) {
197 impl_->observers_.ForEach([this, transport, state](sptr<IBluetoothHostObserver> observer) {
198 int32_t pid = this->impl_->observersPid_.ReadVal(observer->AsObject());
199 if (BluetoothBleCentralManagerServer::IsResourceScheduleControlApp(pid)) {
200 HILOGI("pid:%{public}d is proxy pid, not callback.", pid);
201 return;
202 }
203 uint32_t tokenId = this->impl_->observersToken_.ReadVal(observer->AsObject());
204 if (PermissionUtils::VerifyUseBluetoothPermission(tokenId) == PERMISSION_DENIED) {
205 HILOGE("false, check permission failed");
206 } else {
207 observer->OnStateChanged(transport, state);
208 OnStateChangeV2(transport, state, observer);
209 }
210 });
211 if (state == BTStateID::STATE_TURN_ON || state == BTStateID::STATE_TURN_OFF) {
212 int32_t pid = IPCSkeleton::GetCallingPid();
213 int32_t uid = IPCSkeleton::GetCallingUid();
214 HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BT_SERVICE, "BR_SWITCH_STATE",
215 HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid, "STATE", state);
216 }
217 } else if (transport == BTTransport::ADAPTER_BLE) {
218 impl_->bleObservers_.ForEach([this, transport, state](sptr<IBluetoothHostObserver> observer) {
219 int32_t pid = this->impl_->bleObserversPid_.ReadVal(observer->AsObject());
220 if (BluetoothBleCentralManagerServer::IsResourceScheduleControlApp(pid)) {
221 HILOGI("pid:%{public}d is proxy pid, not callback.", pid);
222 return;
223 }
224 uint32_t tokenId = this->impl_->bleObserversToken_.ReadVal(observer->AsObject());
225 if (PermissionUtils::VerifyUseBluetoothPermission(tokenId) == PERMISSION_DENIED) {
226 HILOGE("false, check permission failed");
227 } else {
228 observer->OnStateChanged(transport, state);
229 OnStateChangeV2(transport, state, observer);
230 }
231 });
232 if (state == BTStateID::STATE_TURN_ON || state == BTStateID::STATE_TURN_OFF) {
233 int32_t pid = IPCSkeleton::GetCallingPid();
234 int32_t uid = IPCSkeleton::GetCallingUid();
235 HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BT_SERVICE, "BLE_SWITCH_STATE",
236 HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid, "STATE", state);
237 }
238 }
239 }
240
241 private:
242 BluetoothHostServer::impl *impl_ = nullptr;
243 BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(AdapterStateObserver);
244 };
245 class BluetoothHostServer::impl::AdapterClassicObserver : public IAdapterClassicObserver {
246 public:
AdapterClassicObserver(BluetoothHostServer::impl * impl)247 AdapterClassicObserver(BluetoothHostServer::impl *impl) : impl_(impl) {};
248 ~AdapterClassicObserver() override = default;
249
OnDiscoveryStateChanged(const int32_t status)250 void OnDiscoveryStateChanged(const int32_t status) override
251 {
252 HILOGI("status: %{public}d", status);
253 impl_->observers_.ForEach([this, status](sptr<IBluetoothHostObserver> observer) {
254 int32_t pid = this->impl_->observersPid_.ReadVal(observer->AsObject());
255 if (BluetoothBleCentralManagerServer::IsResourceScheduleControlApp(pid)) {
256 HILOGI("pid:%{public}d is proxy pid, not callback.", pid);
257 return;
258 }
259 observer->OnDiscoveryStateChanged(static_cast<int32_t>(status));
260 });
261 if (status == DISCOVERY_STARTED || status == DISCOVERY_STOPED) {
262 int32_t pid = IPCSkeleton::GetCallingPid();
263 int32_t uid = IPCSkeleton::GetCallingUid();
264 HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::BT_SERVICE, "DISCOVERY_STATE",
265 HiviewDFX::HiSysEvent::EventType::STATISTIC, "PID", pid, "UID", uid, "STATE", status);
266 }
267 }
268
OnDiscoveryResult(const RawAddress & device,int rssi,const std::string deviceName,int deviceClass)269 void OnDiscoveryResult(
270 const RawAddress &device, int rssi, const std::string deviceName, int deviceClass) override
271 {
272 HILOGI("device: %{public}s, rssi: %{public}d, deviceName: %{pubiic}s, deviceClass: %{public}d",
273 GET_ENCRYPT_ADDR(device), rssi, deviceName.c_str(), deviceClass);
274 impl_->observers_.ForEach([this, device, rssi, deviceName, deviceClass](IBluetoothHostObserver *observer) {
275 int32_t pid = this->impl_->observersPid_.ReadVal(observer->AsObject());
276 if (BluetoothBleCentralManagerServer::IsResourceScheduleControlApp(pid)) {
277 HILOGI("pid:%{public}d is proxy pid, not callback.", pid);
278 return;
279 }
280 uint32_t tokenId = this->impl_->observersToken_.ReadVal(observer->AsObject());
281 if (PermissionUtils::VerifyDiscoverBluetoothPermission(tokenId) == PERMISSION_DENIED) {
282 HILOGE("OnDiscoveryResult() false, check permission failed");
283 } else {
284 observer->OnDiscoveryResult(device, rssi, deviceName, deviceClass);
285 }
286 });
287 }
288
OnPairRequested(const BTTransport transport,const RawAddress & device)289 void OnPairRequested(const BTTransport transport, const RawAddress &device) override
290 {
291 HILOGI("device: %{public}s", GET_ENCRYPT_ADDR(device));
292 impl_->observers_.ForEach(
293 [transport, device](IBluetoothHostObserver *observer) { observer->OnPairRequested(transport, device); });
294 }
295
OnPairConfirmed(const BTTransport transport,const RawAddress & device,int32_t reqType,int32_t number)296 void OnPairConfirmed(
297 const BTTransport transport, const RawAddress &device, int32_t reqType, int32_t number) override
298 {
299 HILOGI("device: %{public}s, reqType: %{public}d, number: %{public}d",
300 GET_ENCRYPT_ADDR(device), reqType, number);
301 impl_->observers_.ForEach([this, transport, device, reqType, number](IBluetoothHostObserver *observer) {
302 uint32_t tokenId = this->impl_->observersToken_.ReadVal(observer->AsObject());
303 if (PermissionUtils::VerifyUseBluetoothPermission(tokenId) == PERMISSION_DENIED) {
304 HILOGE("false, check permission failed");
305 } else {
306 observer->OnPairConfirmed(transport, device, reqType, number);
307 }
308 });
309 }
310
OnScanModeChanged(int32_t mode)311 void OnScanModeChanged(int32_t mode) override
312 {
313 HILOGI("mode: %{public}d", mode);
314 impl_->observers_.ForEach([mode](IBluetoothHostObserver *observer) { observer->OnScanModeChanged(mode); });
315 }
316
OnDeviceNameChanged(const std::string & deviceName)317 void OnDeviceNameChanged(const std::string &deviceName) override
318 {
319 HILOGI("deviceName: %{public}s", deviceName.c_str());
320 impl_->observers_.ForEach(
321 [deviceName](IBluetoothHostObserver *observer) { observer->OnDeviceNameChanged(deviceName); });
322 }
323
OnDeviceAddrChanged(const std::string & address)324 void OnDeviceAddrChanged(const std::string &address) override
325 {
326 HILOGI("address: %{public}s", GetEncryptAddr(address).c_str());
327 impl_->observers_.ForEach(
328 [address](IBluetoothHostObserver *observer) { observer->OnDeviceAddrChanged(address); });
329 }
330
331 private:
332 BluetoothHostServer::impl *impl_ = nullptr;
333 BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(AdapterClassicObserver);
334 };
335 class BluetoothHostServer::impl::ClassicRemoteDeviceObserver : public IClassicRemoteDeviceObserver {
336 public:
ClassicRemoteDeviceObserver(BluetoothHostServer::impl * impl)337 ClassicRemoteDeviceObserver(BluetoothHostServer::impl *impl) : impl_(impl) {};
338 ~ClassicRemoteDeviceObserver() override = default;
339
OnAclStateChanged(const RawAddress & device,int state,unsigned int reason)340 void OnAclStateChanged(const RawAddress &device, int state, unsigned int reason) override
341 {
342 return;
343 }
344
OnPairStatusChanged(const BTTransport transport,const RawAddress & device,const int32_t status)345 void OnPairStatusChanged(const BTTransport transport, const RawAddress &device, const int32_t status) override
346 {
347 HILOGI("device: %{public}s, status: %{public}d", GET_ENCRYPT_ADDR(device), status);
348 impl_->remoteObservers_.ForEach([this, transport, device, status](IBluetoothRemoteDeviceObserver *observer) {
349 int32_t pid = this->impl_->remoteObserversPid_.ReadVal(observer->AsObject());
350 if (BluetoothBleCentralManagerServer::IsResourceScheduleControlApp(pid)) {
351 HILOGI("pid:%{public}d is proxy pid, not callback.", pid);
352 return;
353 }
354 uint32_t tokenId = this->impl_->remoteObserversToken_.ReadVal(observer->AsObject());
355 if (PermissionUtils::VerifyUseBluetoothPermission(tokenId) == PERMISSION_DENIED) {
356 HILOGE("false, check permission failed");
357 } else {
358 observer->OnPairStatusChanged(transport, device, status, PAIR_COMMON_BOND_CAUSE);
359 }
360 });
361 }
362
OnRemoteUuidChanged(const RawAddress & device,const std::vector<Uuid> & uuids)363 void OnRemoteUuidChanged(const RawAddress &device, const std::vector<Uuid> &uuids) override
364 {
365 HILOGI("device: %{public}s", GET_ENCRYPT_ADDR(device));
366 std::vector<bluetooth::Uuid> btUuids;
367 for (const auto &val : uuids) {
368 btUuids.push_back(val);
369 }
370 impl_->remoteObservers_.ForEach([this, device, btUuids](IBluetoothRemoteDeviceObserver *observer) {
371 int32_t pid = this->impl_->remoteObserversPid_.ReadVal(observer->AsObject());
372 if (BluetoothBleCentralManagerServer::IsResourceScheduleControlApp(pid)) {
373 HILOGI("pid:%{public}d is proxy pid, not callback.", pid);
374 return;
375 }
376 observer->OnRemoteUuidChanged(device, btUuids);
377 });
378 }
379
OnRemoteNameChanged(const RawAddress & device,const std::string & deviceName)380 void OnRemoteNameChanged(const RawAddress &device, const std::string &deviceName) override
381 {
382 HILOGI("device: %{public}s, deviceName: %{public}s", GET_ENCRYPT_ADDR(device), deviceName.c_str());
383 impl_->remoteObservers_.ForEach([this, device, deviceName](IBluetoothRemoteDeviceObserver *observer) {
384 int32_t pid = this->impl_->remoteObserversPid_.ReadVal(observer->AsObject());
385 if (BluetoothBleCentralManagerServer::IsResourceScheduleControlApp(pid)) {
386 HILOGI("pid:%{public}d is proxy pid, not callback.", pid);
387 return;
388 }
389 observer->OnRemoteNameChanged(device, deviceName);
390 });
391 }
392
OnRemoteAliasChanged(const RawAddress & device,const std::string & alias)393 void OnRemoteAliasChanged(const RawAddress &device, const std::string &alias) override
394 {
395 HILOGI("device: %{public}s, alias: %{public}s", GET_ENCRYPT_ADDR(device), alias.c_str());
396 impl_->remoteObservers_.ForEach([device, alias](IBluetoothRemoteDeviceObserver *observer) {
397 observer->OnRemoteAliasChanged(device, alias);
398 });
399 }
400
OnRemoteCodChanged(const RawAddress & device,int32_t cod)401 void OnRemoteCodChanged(const RawAddress &device, int32_t cod) override
402 {
403 HILOGI("device: %{public}s, cod: %{public}d", GET_ENCRYPT_ADDR(device), cod);
404 impl_->remoteObservers_.ForEach([this, device, cod](IBluetoothRemoteDeviceObserver *observer) {
405 int32_t pid = this->impl_->remoteObserversPid_.ReadVal(observer->AsObject());
406 if (BluetoothBleCentralManagerServer::IsResourceScheduleControlApp(pid)) {
407 HILOGI("pid:%{public}d is proxy pid, not callback.", pid);
408 return;
409 }
410 observer->OnRemoteCodChanged(device, cod);
411 });
412 }
413
414 private:
415 BluetoothHostServer::impl *impl_ = nullptr;
416 BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(ClassicRemoteDeviceObserver);
417 };
418
419 class BluetoothHostServer::impl::AdapterBleObserver : public IAdapterBleObserver {
420 public:
AdapterBleObserver(BluetoothHostServer::impl * impl)421 AdapterBleObserver(BluetoothHostServer::impl *impl) : impl_(impl){};
422 ~AdapterBleObserver() override = default;
423
OnDiscoveryStateChanged(const int32_t status)424 void OnDiscoveryStateChanged(const int32_t status) override
425 {
426 HILOGI("status: %{public}d", status);
427 impl_->bleObservers_.ForEach([this, status](sptr<IBluetoothHostObserver> observer) {
428 int32_t pid = this->impl_->bleObserversPid_.ReadVal(observer->AsObject());
429 if (BluetoothBleCentralManagerServer::IsResourceScheduleControlApp(pid)) {
430 HILOGI("pid:%{public}d is proxy pid, not callback.", pid);
431 return;
432 }
433 observer->OnDiscoveryStateChanged(static_cast<int32_t>(status));
434 });
435 }
436
OnDiscoveryResult(const RawAddress & device,int rssi,const std::string deviceName,int deviceClass)437 void OnDiscoveryResult(
438 const RawAddress &device, int rssi, const std::string deviceName, int deviceClass) override
439 {
440 HILOGI("device: %{public}s, rssi: %{public}d, deviceName: %{pubiic}s, deviceClass: %{public}d",
441 GET_ENCRYPT_ADDR(device), rssi, deviceName.c_str(), deviceClass);
442 impl_->bleObservers_.ForEach([this, device, rssi, deviceName, deviceClass](IBluetoothHostObserver *observer) {
443 int32_t pid = this->impl_->bleObserversPid_.ReadVal(observer->AsObject());
444 if (BluetoothBleCentralManagerServer::IsResourceScheduleControlApp(pid)) {
445 HILOGI("pid:%{public}d is proxy pid, not callback.", pid);
446 return;
447 }
448 uint32_t tokenId = this->impl_->bleObserversToken_.ReadVal(observer->AsObject());
449 if (PermissionUtils::VerifyDiscoverBluetoothPermission(tokenId) == PERMISSION_DENIED) {
450 HILOGE("false, check permission failed");
451 } else {
452 observer->OnDiscoveryResult(device, rssi, deviceName, deviceClass);
453 }
454 });
455 }
456
OnPairRequested(const BTTransport transport,const RawAddress & device)457 void OnPairRequested(const BTTransport transport, const RawAddress &device) override
458 {
459 HILOGI("device: %{public}s", GET_ENCRYPT_ADDR(device));
460 impl_->bleObservers_.ForEach(
461 [transport, device](IBluetoothHostObserver *observer) { observer->OnPairRequested(transport, device); });
462 }
463
OnPairConfirmed(const BTTransport transport,const RawAddress & device,const int32_t reqType,const int32_t number)464 void OnPairConfirmed(
465 const BTTransport transport, const RawAddress &device, const int32_t reqType, const int32_t number) override
466 {
467 HILOGI("device: %{public}s, reqType: %{public}d, number: %{public}d",
468 GET_ENCRYPT_ADDR(device), reqType, number);
469 impl_->bleObservers_.ForEach([this, transport, device, reqType, number](IBluetoothHostObserver *observer) {
470 int32_t pid = this->impl_->bleObserversPid_.ReadVal(observer->AsObject());
471 if (BluetoothBleCentralManagerServer::IsResourceScheduleControlApp(pid)) {
472 HILOGI("pid:%{public}d is proxy pid, not callback.", pid);
473 return;
474 }
475 uint32_t tokenId = this->impl_->bleObserversToken_.ReadVal(observer->AsObject());
476 if (PermissionUtils::VerifyUseBluetoothPermission(tokenId) == PERMISSION_DENIED) {
477 HILOGE("OnPairConfirmed() false, check permission failed");
478 } else {
479 observer->OnPairConfirmed(transport, device, reqType, number);
480 }
481 });
482 }
483
OnScanModeChanged(const int32_t mode)484 void OnScanModeChanged(const int32_t mode) override
485 {
486 HILOGI("mode: %{public}d", mode);
487 impl_->bleObservers_.ForEach([mode](IBluetoothHostObserver *observer) { observer->OnScanModeChanged(mode); });
488 }
489
OnDeviceNameChanged(const std::string deviceName)490 void OnDeviceNameChanged(const std::string deviceName) override
491 {
492 HILOGI("deviceName: %{public}s", deviceName.c_str());
493 impl_->bleObservers_.ForEach(
494 [deviceName](IBluetoothHostObserver *observer) { observer->OnDeviceNameChanged(deviceName); });
495 }
496
OnDeviceAddrChanged(const std::string address)497 void OnDeviceAddrChanged(const std::string address) override
498 {
499 HILOGI("address: %{public}s", GetEncryptAddr(address).c_str());
500 impl_->bleObservers_.ForEach(
501 [address](IBluetoothHostObserver *observer) { observer->OnDeviceAddrChanged(address); });
502 }
503
OnAdvertisingStateChanged(const int32_t state)504 void OnAdvertisingStateChanged(const int32_t state) override
505 {}
506
507 private:
508 BluetoothHostServer::impl *impl_ = nullptr;
509 BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(AdapterBleObserver);
510 };
511 class BluetoothHostServer::impl::BlePeripheralCallback : public IBlePeripheralCallback {
512 public:
BlePeripheralCallback(BluetoothHostServer::impl * impl)513 BlePeripheralCallback(BluetoothHostServer::impl *impl) : impl_(impl) {};
514 ~BlePeripheralCallback() override = default;
515
OnReadRemoteRssiEvent(const RawAddress & device,int32_t rssi,int32_t status)516 void OnReadRemoteRssiEvent(const RawAddress &device, int32_t rssi, int32_t status) override
517 {
518 HILOGI("device: %{public}s, rssi: %{public}d, status: %{public}d",
519 GET_ENCRYPT_ADDR(device), rssi, status);
520 impl_->bleRemoteObservers_.ForEach([device, rssi, status](IBluetoothBlePeripheralObserver *observer) {
521 observer->OnReadRemoteRssiEvent(device, rssi, status);
522 });
523 }
524
OnPairStatusChanged(const BTTransport transport,const RawAddress & device,int32_t status)525 void OnPairStatusChanged(const BTTransport transport, const RawAddress &device, int32_t status) override
526 {
527 HILOGI("device: %{public}s, status: %{public}d", GET_ENCRYPT_ADDR(device), status);
528 impl_->bleRemoteObservers_.ForEach([this, transport, device, status](
529 IBluetoothBlePeripheralObserver *observer) {
530 uint32_t tokenId = this->impl_->bleRemoteObserversToken_.ReadVal(observer->AsObject());
531 if (PermissionUtils::VerifyUseBluetoothPermission(tokenId) == PERMISSION_DENIED) {
532 HILOGE("false, check permission failed");
533 } else {
534 observer->OnPairStatusChanged(transport, device, status, PAIR_COMMON_BOND_CAUSE);
535 }
536 });
537 }
538
OnAclStateChanged(const RawAddress & device,int state,unsigned int reason)539 void OnAclStateChanged(const RawAddress &device, int state, unsigned int reason) override
540 {
541 return;
542 }
543
544 private:
545 BluetoothHostServer::impl *impl_ = nullptr;
546 BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BlePeripheralCallback);
547 };
548
549 std::mutex BluetoothHostServer::instanceLock;
550 sptr<BluetoothHostServer> BluetoothHostServer::instance;
551
552 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(BluetoothHostServer::GetInstance().GetRefPtr());
553
impl()554 BluetoothHostServer::impl::impl()
555 {
556 HILOGI("starts");
557 systemStateObserver_ = std::make_unique<SystemStateObserver>(this);
558 observerImp_ = std::make_unique<AdapterStateObserver>(this);
559 classicObserverImp_ = std::make_unique<AdapterClassicObserver>(this);
560 remoteObserverImp_ = std::make_unique<ClassicRemoteDeviceObserver>(this);
561 bleObserverImp_ = std::make_unique<AdapterBleObserver>(this);
562 bleRemoteObserverImp_ = std::make_unique<BlePeripheralCallback>(this);
563 }
564
~impl()565 BluetoothHostServer::impl::~impl()
566 {
567 HILOGI("starts");
568 }
569
Init()570 void BluetoothHostServer::impl::Init()
571 {
572 HILOGI("starts");
573 IAdapterManager::GetInstance()->RegisterSystemStateObserver(*systemStateObserver_);
574
575 IAdapterManager::GetInstance()->Start();
576 IAdapterManager::GetInstance()->RegisterStateObserver(*observerImp_);
577
578 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
579 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
580 if (classicService) {
581 classicService->RegisterClassicAdapterObserver(*classicObserverImp_.get());
582 classicService->RegisterRemoteDeviceObserver(*remoteObserverImp_.get());
583 }
584 if (bleService) {
585 bleService->RegisterBleAdapterObserver(*bleObserverImp_.get());
586 bleService->RegisterBlePeripheralCallback(*bleRemoteObserverImp_.get());
587 }
588
589 createServers();
590 }
591
Clear()592 void BluetoothHostServer::impl::Clear()
593 {
594 /// systerm state observer
595 IAdapterManager::GetInstance()->DeregisterSystemStateObserver(*systemStateObserver_);
596
597 /// adapter state observer
598 IAdapterManager::GetInstance()->Stop();
599 IAdapterManager::GetInstance()->DeregisterStateObserver(*observerImp_);
600
601 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
602 if (classicService) {
603 /// classic observer
604 classicService->DeregisterClassicAdapterObserver(*classicObserverImp_.get());
605 /// classic remote observer
606 classicService->DeregisterRemoteDeviceObserver(*remoteObserverImp_.get());
607 }
608
609 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
610 if (bleService) {
611 /// ble observer
612 bleService->DeregisterBleAdapterObserver(*bleObserverImp_.get());
613 /// ble remote observer
614 bleService->DeregisterBlePeripheralCallback(*bleRemoteObserverImp_.get());
615 }
616 }
617
createServers()618 void BluetoothHostServer::impl::createServers()
619 {
620 sptr<BluetoothSocketServer> socket = new BluetoothSocketServer();
621 servers_.EnsureInsert(PROFILE_SOCKET, socket->AsObject());
622
623 sptr<BluetoothGattServerServer> gattserver = new BluetoothGattServerServer();
624 servers_.EnsureInsert(PROFILE_GATT_SERVER, gattserver->AsObject());
625
626 sptr<BluetoothGattClientServer> gattclient = new BluetoothGattClientServer();
627 servers_.EnsureInsert(PROFILE_GATT_CLIENT, gattclient->AsObject());
628
629 #ifdef BLUETOOTH_HFP_AG_FEATURE
630 sptr<BluetoothHfpAgServer> hfpAg = new BluetoothHfpAgServer();
631 servers_.EnsureInsert(PROFILE_HFP_AG, hfpAg->AsObject());
632 #endif
633
634 #ifdef BLUETOOTH_HFP_HF_FEATURE
635 sptr<BluetoothHfpHfServer> hfpHf = new BluetoothHfpHfServer();
636 servers_.EnsureInsert(PROFILE_HFP_HF, hfpHf->AsObject());
637 #endif
638
639 #ifdef BLUETOOTH_AVRCP_CT_FEATURE
640 sptr<BluetoothAvrcpCtServer> avrcpCtServer = new BluetoothAvrcpCtServer();
641 servers_.EnsureInsert(PROFILE_AVRCP_CT, avrcpCtServer->AsObject());
642 #endif
643
644 #ifdef BLUETOOTH_AVRCP_TG_FEATURE
645 sptr<BluetoothAvrcpTgServer> avrcpTgServer = new BluetoothAvrcpTgServer();
646 servers_.EnsureInsert(PROFILE_AVRCP_TG, avrcpTgServer->AsObject());
647 #endif
648
649 sptr<BluetoothBleAdvertiserServer> bleAdvertiser = new BluetoothBleAdvertiserServer();
650 bleServers_.EnsureInsert(BLE_ADVERTISER_SERVER, bleAdvertiser->AsObject());
651
652 sptr<BluetoothBleCentralManagerServer> bleCentralManger = new BluetoothBleCentralManagerServer();
653 bleServers_.EnsureInsert(BLE_CENTRAL_MANAGER_SERVER, bleCentralManger->AsObject());
654
655 #ifdef BLUETOOTH_MAP_SERVER_FEATURE
656 sptr<BluetoothMapMceServer> mapMce = new BluetoothMapMceServer();
657 servers_.EnsureInsert(PROFILE_MAP_MCE, mapMce->AsObject());
658 #endif
659
660 #ifdef BLUETOOTH_MAP_CLIENT_FEATURE
661 sptr<BluetoothMapMseServer> mapMse = new BluetoothMapMseServer();
662 servers_.EnsureInsert(PROFILE_MAP_MSE, mapMse->AsObject());
663 #endif
664
665 #ifdef BLUETOOTH_A2DP_SRC_FEATURE
666 sptr<BluetoothA2dpSourceServer> a2dpSource = new BluetoothA2dpSourceServer();
667 servers_.EnsureInsert(PROFILE_A2DP_SRC, a2dpSource->AsObject());
668 #endif
669
670 #ifdef BLUETOOTH_A2DP_SINK_FEATURE
671 sptr<BluetoothA2dpSinkServer> a2dpSink = new BluetoothA2dpSinkServer();
672 servers_.EnsureInsert(PROFILE_A2DP_SINK, a2dpSink->AsObject());
673 #endif
674
675 #ifdef BLUETOOTH_HID_HOST_FEATURE
676 sptr<BluetoothHidHostServer> hidHostServer = new BluetoothHidHostServer();
677 servers_.EnsureInsert(PROFILE_HID_HOST_SERVER, hidHostServer->AsObject());
678 #endif
679
680 #ifdef BLUETOOTH_PAN_FEATURE
681 sptr<BluetoothPanServer> panServer = new BluetoothPanServer();
682 servers_.EnsureInsert(PROFILE_PAN_SERVER, panServer->AsObject());
683 #endif
684
685 HILOGI("servers_ constructed, size is %{public}d", servers_.Size());
686 }
687
BluetoothHostServer()688 BluetoothHostServer::BluetoothHostServer() : SystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID, true)
689 {
690 pimpl = std::make_unique<impl>();
691 }
692
~BluetoothHostServer()693 BluetoothHostServer::~BluetoothHostServer()
694 {
695 HILOGI("~BluetoothHostServer called.");
696 }
697
GetInstance()698 sptr<BluetoothHostServer> BluetoothHostServer::GetInstance()
699 {
700 std::lock_guard<std::mutex> autoLock(instanceLock);
701 if (instance == nullptr) {
702 sptr<BluetoothHostServer> temp = new BluetoothHostServer();
703 instance = temp;
704 }
705 return instance;
706 }
707
OnStart()708 void BluetoothHostServer::OnStart()
709 {
710 HILOGI("starting service.");
711 if (state_ == ServiceRunningState::STATE_RUNNING) {
712 HILOGI("service is already started.");
713 return;
714 }
715
716 if (!Init()) {
717 HILOGE("initiation failed");
718 OnStop();
719 return;
720 }
721
722 state_ = ServiceRunningState::STATE_RUNNING;
723
724 HILOGI("service has been started successfully");
725 return;
726 }
727
Init()728 bool BluetoothHostServer::Init()
729 {
730 pimpl->Init();
731 if (!registeredToService_) {
732 bool ret = Publish(BluetoothHostServer::GetInstance());
733 if (!ret) {
734 HILOGE("init publish failed!");
735 return false;
736 }
737 registeredToService_ = true;
738 }
739 HILOGI("init success");
740 return true;
741 }
742
OnStop()743 void BluetoothHostServer::OnStop()
744 {
745 HILOGI("stopping service.");
746
747 pimpl->Clear();
748 state_ = ServiceRunningState::STATE_IDLE;
749 registeredToService_ = false;
750 return;
751 }
752
RegisterObserver(const sptr<IBluetoothHostObserver> & observer)753 void BluetoothHostServer::RegisterObserver(const sptr<IBluetoothHostObserver> &observer)
754 {
755 if (observer == nullptr) {
756 HILOGE("RegisterObserver observer is null");
757 return;
758 }
759
760 pimpl->observersToken_.EnsureInsert(observer->AsObject(), IPCSkeleton::GetCallingTokenID());
761 pimpl->observersPid_.EnsureInsert(observer->AsObject(), IPCSkeleton::GetCallingUid());
762 auto func = std::bind(&BluetoothHostServer::DeregisterObserver, this, std::placeholders::_1);
763 pimpl->observers_.Register(observer, func);
764 std::lock_guard<std::mutex> lock(pimpl->hostObserversMutex);
765 pimpl->hostObservers_.push_back(observer);
766 }
767
DeregisterObserver(const sptr<IBluetoothHostObserver> & observer)768 void BluetoothHostServer::DeregisterObserver(const sptr<IBluetoothHostObserver> &observer)
769 {
770 if (observer == nullptr || pimpl == nullptr) {
771 HILOGE("DeregisterObserver observer is null");
772 return;
773 }
774 {
775 std::lock_guard<std::mutex> lock(pimpl->hostObserversMutex);
776 for (auto iter = pimpl->hostObservers_.begin(); iter != pimpl->hostObservers_.end(); ++iter) {
777 if ((*iter)->AsObject() == observer->AsObject()) {
778 pimpl->observers_.Deregister(*iter);
779 pimpl->hostObservers_.erase(iter);
780 break;
781 }
782 }
783 }
784 pimpl->observersToken_.Erase(observer->AsObject());
785 pimpl->observersPid_.Erase(observer->AsObject());
786 }
787
EnableBt()788 int32_t BluetoothHostServer::EnableBt()
789 {
790 if (IAdapterManager::GetInstance()->Enable(bluetooth::BTTransport::ADAPTER_BREDR)) {
791 return NO_ERROR;
792 }
793 return BT_ERR_INTERNAL_ERROR;
794 }
795
DisableBt()796 int32_t BluetoothHostServer::DisableBt()
797 {
798 if (PermissionUtils::VerifyAccessBluetoothPermission() == PERMISSION_DENIED) {
799 HILOGE("false, check Access permission failed");
800 return BT_ERR_PERMISSION_FAILED;
801 }
802 if (IAdapterManager::GetInstance()->Disable(bluetooth::BTTransport::ADAPTER_BREDR)) {
803 return NO_ERROR;
804 }
805 return BT_ERR_INTERNAL_ERROR;
806 }
807
ConvertBTStateIDToBluetoothState(int32_t brState,int32_t bleState)808 static int32_t ConvertBTStateIDToBluetoothState(int32_t brState, int32_t bleState)
809 {
810 BluetoothState state = BluetoothState::STATE_OFF;
811 switch (brState) {
812 case BTStateID::STATE_TURN_ON: state = BluetoothState::STATE_ON; break;
813 case BTStateID::STATE_TURNING_ON: state = BluetoothState::STATE_TURNING_ON; break;
814 case BTStateID::STATE_TURNING_OFF: state = BluetoothState::STATE_TURNING_OFF; break;
815 case BTStateID::STATE_TURN_OFF: {
816 switch (bleState) {
817 case BTStateID::STATE_TURN_ON: state = BluetoothState::STATE_BLE_ON; break;
818 case BTStateID::STATE_TURNING_ON: state = BluetoothState::STATE_BLE_TURNING_ON; break;
819 case BTStateID::STATE_TURNING_OFF: state = BluetoothState::STATE_BLE_TURNING_OFF; break;
820 default: break;
821 }
822 }
823 default: HILOGE("Invalid bt state"); break;
824 }
825 return static_cast<int32_t>(state);
826 }
827
GetBtState(int32_t & state)828 int32_t BluetoothHostServer::GetBtState(int32_t &state)
829 {
830 int32_t brState = IAdapterManager::GetInstance()->GetState(bluetooth::BTTransport::ADAPTER_BREDR);
831 int32_t bleState = IAdapterManager::GetInstance()->GetState(bluetooth::BTTransport::ADAPTER_BLE);
832 state = ConvertBTStateIDToBluetoothState(brState, bleState);
833 return BT_NO_ERROR;
834 }
835
GetProfile(const std::string & name)836 sptr<IRemoteObject> BluetoothHostServer::GetProfile(const std::string &name)
837 {
838 HILOGI("seraching %{public}s ", name.c_str());
839 sptr<IRemoteObject> object = nullptr;
840 if (pimpl->servers_.Find(name, object)) {
841 return object;
842 }
843 return object;
844 }
845
GetBleRemote(const std::string & name)846 sptr<IRemoteObject> BluetoothHostServer::GetBleRemote(const std::string &name)
847 {
848 HILOGI("GetBleRemote %{public}s ", name.c_str());
849 sptr<IRemoteObject> object = nullptr;
850 if (pimpl->bleServers_.Find(name, object)) {
851 return object;
852 }
853 return object;
854 }
855
856 // Fac_Res_CODE
BluetoothFactoryReset()857 int32_t BluetoothHostServer::BluetoothFactoryReset()
858 {
859 bool ret = IAdapterManager::GetInstance()->FactoryReset();
860 return ret ? BT_NO_ERROR : BT_ERR_INTERNAL_ERROR;
861 }
862
GetDeviceType(int32_t transport,const std::string & address)863 int32_t BluetoothHostServer::GetDeviceType(int32_t transport, const std::string &address)
864 {
865 HILOGI("transport: %{public}d, address: %{public}s", transport, GetEncryptAddr(address).c_str());
866 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
867 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
868 RawAddress addr(address);
869 if ((transport == BTTransport::ADAPTER_BREDR) && IsBtEnabled() && classicService) {
870 return classicService->GetDeviceType(addr);
871 } else if ((transport == BTTransport::ADAPTER_BLE) && IsBleEnabled() && bleService) {
872 return bleService->GetDeviceType(addr);
873 } else {
874 HILOGE("transport invalid or BT current state is not enabled!");
875 }
876 return INVALID_VALUE;
877 }
878
GetLocalAddress(std::string & addr)879 int32_t BluetoothHostServer::GetLocalAddress(std::string &addr)
880 {
881 HILOGI("Enter!");
882 if (PermissionUtils::VerifyAccessBluetoothPermission() == PERMISSION_DENIED) {
883 HILOGE("false, check Access permission failed");
884 return BT_ERR_PERMISSION_FAILED;
885 }
886 if (PermissionUtils::VerifyGetBluetoothLocalMacPermission() == PERMISSION_DENIED) {
887 HILOGE("false, check GetLocalMac permission failed");
888 return BT_ERR_PERMISSION_FAILED;
889 }
890 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
891 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
892 if (IsBtEnabled() && classicService) {
893 addr = classicService->GetLocalAddress();
894 return NO_ERROR;
895 } else if (IsBleEnabled() && bleService) {
896 addr = bleService->GetLocalAddress();
897 return NO_ERROR;
898 } else {
899 HILOGW("BT current state is not enabled!");
900 return BT_ERR_INVALID_STATE;
901 }
902 }
903
EnableBle(bool noAutoConnect)904 int32_t BluetoothHostServer::EnableBle(bool noAutoConnect)
905 {
906 HILOGI("Enter!");
907 if (PermissionUtils::VerifyAccessBluetoothPermission() == PERMISSION_DENIED) {
908 HILOGE("false, check Access permission failed");
909 return BT_ERR_PERMISSION_FAILED;
910 }
911 if (!BluetoothHostServer::IsBleEnabled() && IAdapterManager::GetInstance()->Enable(BTTransport::ADAPTER_BLE)) {
912 return NO_ERROR;
913 }
914 return BT_ERR_INTERNAL_ERROR;
915 }
916
DisableBle()917 int32_t BluetoothHostServer::DisableBle()
918 {
919 HILOGI("Enter!");
920 if (IAdapterManager::GetInstance()->Disable(BTTransport::ADAPTER_BLE)) {
921 return NO_ERROR;
922 }
923 return BT_ERR_INTERNAL_ERROR;
924 }
925
IsBrEnabled()926 bool BluetoothHostServer::IsBrEnabled()
927 {
928 return IsBtEnabled();
929 }
930
IsBleEnabled()931 bool BluetoothHostServer::IsBleEnabled()
932 {
933 return IAdapterManager::GetInstance()->GetState(BTTransport::ADAPTER_BLE) == BTStateID::STATE_TURN_ON;
934 }
935
GetProfileList()936 std::vector<uint32_t> BluetoothHostServer::GetProfileList()
937 {
938 HILOGI("Enter!");
939 return IProfileManager::GetInstance()->GetProfileServicesList();
940 }
941
GetMaxNumConnectedAudioDevices()942 int32_t BluetoothHostServer::GetMaxNumConnectedAudioDevices()
943 {
944 HILOGI("Enter!");
945 return IAdapterManager::GetInstance()->GetMaxNumConnectedAudioDevices();
946 }
947
GetBtConnectionState(int32_t & state)948 int32_t BluetoothHostServer::GetBtConnectionState(int32_t &state)
949 {
950 if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) {
951 HILOGE("false, check permission failed");
952 return BT_ERR_PERMISSION_FAILED;
953 }
954 if (IsBtEnabled()) {
955 state = (int32_t)IAdapterManager::GetInstance()->GetAdapterConnectState();
956 HILOGI("state: %{public}d", state);
957 return NO_ERROR;
958 } else {
959 HILOGW("BT current state is not enabled!");
960 return BT_ERR_INVALID_STATE;
961 }
962 }
963
GetBtProfileConnState(uint32_t profileId,int & state)964 int32_t BluetoothHostServer::GetBtProfileConnState(uint32_t profileId, int &state)
965 {
966 HILOGI("Enter!");
967 if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) {
968 HILOGE("false, check permission failed");
969 return BT_ERR_PERMISSION_FAILED;
970 }
971 if (IsBtEnabled()) {
972 state = (int32_t)IProfileManager::GetInstance()->GetProfileServiceConnectState(profileId);
973 return NO_ERROR;
974 } else {
975 HILOGW("BT current state is not enabled!");
976 return BT_ERR_INVALID_STATE;
977 }
978 }
979
GetLocalSupportedUuids(std::vector<std::string> & uuids)980 void BluetoothHostServer::GetLocalSupportedUuids(std::vector<std::string> &uuids)
981 {
982 HILOGI("Enter!");
983 IProfileManager::GetInstance()->GetProfileServicesSupportedUuids(uuids);
984 }
985
GetLocalDeviceClass()986 int32_t BluetoothHostServer::GetLocalDeviceClass()
987 {
988 HILOGI("Enter!");
989 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
990 if (IsBtEnabled() && classicService) {
991 return classicService->GetLocalDeviceClass();
992 } else {
993 HILOGW("BT current state is not enabled!");
994 }
995 return 0;
996 }
997
SetLocalDeviceClass(const int32_t & deviceClass)998 bool BluetoothHostServer::SetLocalDeviceClass(const int32_t &deviceClass)
999 {
1000 HILOGI("Enter!");
1001 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1002 if (IsBtEnabled() && classicService) {
1003 return classicService->SetLocalDeviceClass(deviceClass);
1004 } else {
1005 HILOGW("BT current state is not enabled!");
1006 }
1007 return false;
1008 }
1009
GetLocalName(std::string & name)1010 int32_t BluetoothHostServer::GetLocalName(std::string &name)
1011 {
1012 HILOGI("Enter!");
1013 if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) {
1014 HILOGE("false, check permission failed");
1015 return BT_ERR_PERMISSION_FAILED;
1016 }
1017 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1018 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1019 if (IsBtEnabled() && classicService) {
1020 name = classicService->GetLocalName();
1021 return NO_ERROR;
1022 } else if (IsBleEnabled() && bleService) {
1023 name = bleService->GetLocalName();
1024 return NO_ERROR;
1025 } else {
1026 HILOGW("BT current state is not enabled!");
1027 return BT_ERR_INVALID_STATE;
1028 }
1029 }
1030
SetLocalName(const std::string & name)1031 int32_t BluetoothHostServer::SetLocalName(const std::string &name)
1032 {
1033 HILOGI("name: %{public}s", name.c_str());
1034 int api12 = 12;
1035 if (!PermissionUtils::CheckSystemHapApp() && PermissionUtils::GetApiVersion() >= api12) {
1036 return BT_ERR_API_NOT_SUPPORT;
1037 }
1038 if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
1039 HILOGE("false, check permission failed");
1040 return BT_ERR_PERMISSION_FAILED;
1041 }
1042 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1043 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1044 if (IsBtEnabled() && classicService) {
1045 bool ret = classicService->SetLocalName(name);
1046 if (ret && (IsBleEnabled() && bleService)) {
1047 if (bleService->SetLocalName(name)) {
1048 return NO_ERROR;
1049 }
1050 } else {
1051 HILOGE("failed!");
1052 return BT_ERR_INTERNAL_ERROR;
1053 }
1054 } else if (IsBleEnabled() && bleService) {
1055 if (bleService->SetLocalName(name)) {
1056 return NO_ERROR;
1057 }
1058 } else {
1059 HILOGW("BT current state is not enabled!");
1060 return BT_ERR_INVALID_STATE;
1061 }
1062 return BT_ERR_INTERNAL_ERROR;
1063 }
1064
GetBtScanMode(int32_t & scanMode)1065 int32_t BluetoothHostServer::GetBtScanMode(int32_t &scanMode)
1066 {
1067 HILOGI("Enter!");
1068 if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) {
1069 HILOGE("false, check permission failed");
1070 return BT_ERR_PERMISSION_FAILED;
1071 }
1072 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1073 if (IsBtEnabled() && classicService) {
1074 scanMode = classicService->GetBtScanMode();
1075 return NO_ERROR;
1076 } else {
1077 HILOGW("BT current state is not enabled!");
1078 return BT_ERR_INVALID_STATE;
1079 }
1080 }
1081
SetBtScanMode(int32_t mode,int32_t duration)1082 int32_t BluetoothHostServer::SetBtScanMode(int32_t mode, int32_t duration)
1083 {
1084 HILOGI("mode: %{public}d, duration: %{public}d", mode, duration);
1085 if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) {
1086 HILOGE("false, check permission failed");
1087 return BT_ERR_PERMISSION_FAILED;
1088 }
1089 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1090 if (IsBtEnabled() && classicService) {
1091 if (classicService->SetBtScanMode(mode, duration)) {
1092 return NO_ERROR;
1093 }
1094 } else {
1095 HILOGW("BT current state is not enabled!");
1096 return BT_ERR_INVALID_STATE;
1097 }
1098 return BT_ERR_INTERNAL_ERROR;
1099 }
1100
GetBondableMode(int32_t transport)1101 int32_t BluetoothHostServer::GetBondableMode(int32_t transport)
1102 {
1103 HILOGI("transport: %{public}d", transport);
1104 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1105 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1106 if ((transport == BTTransport::ADAPTER_BREDR) && IsBtEnabled() && classicService) {
1107 return classicService->GetBondableMode();
1108 } else if ((transport == BTTransport::ADAPTER_BLE) && IsBleEnabled() && bleService) {
1109 return bleService->GetBondableMode();
1110 } else {
1111 HILOGE("Parameter::transport invalid or BT current state is not enabled!");
1112 }
1113 return BONDABLE_MODE_OFF;
1114 }
1115
SetBondableMode(int32_t transport,int32_t mode)1116 bool BluetoothHostServer::SetBondableMode(int32_t transport, int32_t mode)
1117 {
1118 HILOGI("transport: %{public}d, mode: %{public}d", transport, mode);
1119 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1120 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1121 if ((transport == BTTransport::ADAPTER_BREDR) && IsBtEnabled() && classicService) {
1122 return classicService->SetBondableMode(mode);
1123 } else if ((transport == BTTransport::ADAPTER_BLE) && IsBleEnabled() && bleService) {
1124 return bleService->SetBondableMode(mode);
1125 } else {
1126 HILOGE("Parameter::transport invalid or BT current state is not enabled!");
1127 }
1128 return false;
1129 }
1130
StartBtDiscovery()1131 int32_t BluetoothHostServer::StartBtDiscovery()
1132 {
1133 HILOGI("Enter!");
1134 if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
1135 HILOGE("false, check permission failed");
1136 return BT_ERR_PERMISSION_FAILED;
1137 }
1138 if (PermissionUtils::VerifyApproximatelyPermission() == PERMISSION_DENIED &&
1139 PermissionUtils::VerifyLocationPermission() == PERMISSION_DENIED) {
1140 HILOGE("No location permission");
1141 return BT_ERR_PERMISSION_FAILED;
1142 }
1143 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1144 if (IsBtEnabled() && classicService) {
1145 if (classicService->StartBtDiscovery()) {
1146 return NO_ERROR;
1147 }
1148 } else {
1149 HILOGW("BT current state is not enabled!");
1150 return BT_ERR_INVALID_STATE;
1151 }
1152 return BT_ERR_INTERNAL_ERROR;
1153 }
1154
CancelBtDiscovery()1155 int32_t BluetoothHostServer::CancelBtDiscovery()
1156 {
1157 HILOGI("Enter!");
1158 if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
1159 HILOGE("false, check permission failed");
1160 return BT_ERR_PERMISSION_FAILED;
1161 }
1162 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1163 if (IsBtEnabled() && classicService) {
1164 if (classicService->CancelBtDiscovery()) {
1165 return NO_ERROR;
1166 }
1167 } else {
1168 HILOGW("BT current state is not enabled!");
1169 return BT_ERR_INVALID_STATE;
1170 }
1171 return BT_ERR_INTERNAL_ERROR;
1172 }
1173
IsBtDiscovering(bool & isDisCovering,int32_t transport)1174 int32_t BluetoothHostServer::IsBtDiscovering(bool &isDisCovering, int32_t transport)
1175 {
1176 HILOGI("transport: %{public}d", transport);
1177 if (PermissionUtils::VerifyAccessBluetoothPermission() == PERMISSION_DENIED) {
1178 HILOGE("false, check permission failed");
1179 return BT_ERR_PERMISSION_FAILED;
1180 }
1181 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1182 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1183 if ((transport == BTTransport::ADAPTER_BREDR) && IsBtEnabled() && classicService) {
1184 isDisCovering = classicService->IsBtDiscovering();
1185 } else if ((transport == BTTransport::ADAPTER_BLE) && IsBleEnabled() && bleService) {
1186 isDisCovering = bleService->IsBtDiscovering();
1187 } else {
1188 HILOGE("Parameter::transport invalid or BT current state is not enabled!");
1189 return BT_ERR_INVALID_STATE;
1190 }
1191 return BT_NO_ERROR;
1192 }
1193
GetBtDiscoveryEndMillis()1194 long BluetoothHostServer::GetBtDiscoveryEndMillis()
1195 {
1196 HILOGI("Enter!");
1197 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1198 if (IsBtEnabled() && classicService) {
1199 return classicService->GetBtDiscoveryEndMillis();
1200 } else {
1201 HILOGW("BT current state is not enabled!");
1202 }
1203 return INVALID_VALUE;
1204 }
1205
GetPairedDevices(std::vector<BluetoothRawAddress> & pairedAddr)1206 int32_t BluetoothHostServer::GetPairedDevices(std::vector<BluetoothRawAddress> &pairedAddr)
1207 {
1208 HILOGI("GetPairedDevices");
1209 if (PermissionUtils::GetApiVersion() >= 10) { // 10:api version
1210 if (PermissionUtils::VerifyAccessBluetoothPermission() == PERMISSION_DENIED) {
1211 HILOGE("false, check Access permission failed");
1212 return BT_ERR_PERMISSION_FAILED;
1213 }
1214 } else {
1215 if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) {
1216 HILOGE("false, check permission failed");
1217 return BT_ERR_SYSTEM_PERMISSION_FAILED;
1218 }
1219 }
1220 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1221 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1222 std::vector<RawAddress> rawAddrVec;
1223 if (IsBtEnabled() && classicService) {
1224 rawAddrVec = classicService->GetPairedDevices();
1225 } else {
1226 HILOGE("transport invalid or BT current state is not enabled!");
1227 return BT_ERR_INVALID_STATE;
1228 }
1229 for (auto it = rawAddrVec.begin(); it != rawAddrVec.end(); ++it) {
1230 BluetoothRawAddress rawAddr = BluetoothRawAddress(*it);
1231 pairedAddr.emplace_back(rawAddr);
1232 }
1233 if (IsBleEnabled() && bleService) {
1234 rawAddrVec = bleService->GetPairedDevices();
1235 } else {
1236 HILOGE("transport invalid or BT current state is not enabled!");
1237 return BT_ERR_INVALID_STATE;
1238 }
1239
1240 for (auto it = rawAddrVec.begin(); it != rawAddrVec.end(); ++it) {
1241 BluetoothRawAddress rawAddr = BluetoothRawAddress(*it);
1242 pairedAddr.emplace_back(rawAddr);
1243 }
1244 return NO_ERROR;
1245 }
1246
GetTransportByDeviceType(int32_t transport,const std::string & address)1247 int BluetoothHostServer::GetTransportByDeviceType(int32_t transport, const std::string &address)
1248 {
1249 if (transport == BT_TRANSPORT_NONE) {
1250 int deviceType = GetDeviceType(BT_TRANSPORT_BREDR, address);
1251 if (deviceType == INVALID_TYPE || deviceType == DEVICE_TYPE_LE) {
1252 transport = BT_TRANSPORT_BLE;
1253 } else {
1254 transport = BT_TRANSPORT_BREDR;
1255 }
1256 }
1257 return transport;
1258 }
1259
RemovePair(int32_t transport,const sptr<BluetoothRawAddress> & device)1260 int32_t BluetoothHostServer::RemovePair(int32_t transport, const sptr<BluetoothRawAddress> &device)
1261 {
1262 if (device == nullptr) {
1263 HILOGE("device is nullptr.");
1264 return BT_ERR_INTERNAL_ERROR;
1265 }
1266 HILOGI("addr:%{public}s, transport:%{public}d", GET_ENCRYPT_ADDR(*device), transport);
1267 if (!PermissionUtils::CheckSystemHapApp()) {
1268 HILOGE("check system api failed.");
1269 return BT_ERR_SYSTEM_PERMISSION_FAILED;
1270 }
1271 if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
1272 HILOGE("check permission failed.");
1273 return BT_ERR_PERMISSION_FAILED;
1274 }
1275 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1276 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1277 transport = GetTransportByDeviceType(transport, device->GetAddress());
1278 if ((transport == BTTransport::ADAPTER_BREDR) && IsBtEnabled() && classicService) {
1279 if (classicService->RemovePair(*device)) {
1280 return NO_ERROR;
1281 }
1282 } else if ((transport == BTTransport::ADAPTER_BLE) && IsBleEnabled() && bleService) {
1283 if (bleService->RemovePair(*device)) {
1284 return NO_ERROR;
1285 }
1286 } else {
1287 HILOGE("transport invalid or BT/BLE current state is not enabled!");
1288 return BT_ERR_INVALID_STATE;
1289 }
1290 return BT_ERR_INTERNAL_ERROR;
1291 }
1292
RemoveAllPairs()1293 bool BluetoothHostServer::RemoveAllPairs()
1294 {
1295 HILOGI("Enter!");
1296 if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
1297 HILOGE("check permission failed");
1298 return false;
1299 }
1300 if (BTStateID::STATE_TURN_ON != IAdapterManager::GetInstance()->GetState(BTTransport::ADAPTER_BREDR) &&
1301 BTStateID::STATE_TURN_ON != IAdapterManager::GetInstance()->GetState(BTTransport::ADAPTER_BLE)) {
1302 HILOGW("BT current state is not enabled!");
1303 return false;
1304 }
1305
1306 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1307 bool ret = true;
1308 if (IsBtEnabled() && classicService) {
1309 ret = classicService->RemoveAllPairs();
1310 if (!ret) {
1311 HILOGE("BREDR RemoveAllPairs failed");
1312 }
1313 }
1314
1315 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1316 if (IsBleEnabled() && bleService) {
1317 ret &= bleService->RemoveAllPairs();
1318 if (!ret) {
1319 HILOGE("BLE RemoveAllPairs failed");
1320 }
1321 }
1322 return ret;
1323 }
1324
GetBleMaxAdvertisingDataLength()1325 int32_t BluetoothHostServer::GetBleMaxAdvertisingDataLength()
1326 {
1327 HILOGI("Enter!");
1328 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1329 if (IsBleEnabled() && bleService) {
1330 return bleService->GetBleMaxAdvertisingDataLength();
1331 } else {
1332 HILOGW("BT current state is not enabled!");
1333 }
1334 return INVALID_VALUE;
1335 }
1336
GetPhonebookPermission(const std::string & address)1337 int32_t BluetoothHostServer::GetPhonebookPermission(const std::string &address)
1338 {
1339 HILOGI("address: %{public}s", GetEncryptAddr(address).c_str());
1340 return (int32_t)IAdapterManager::GetInstance()->GetPhonebookPermission(address);
1341 }
1342
SetPhonebookPermission(const std::string & address,int32_t permission)1343 bool BluetoothHostServer::SetPhonebookPermission(const std::string &address, int32_t permission)
1344 {
1345 HILOGI("address: %{public}s, permission: %{public}d", GetEncryptAddr(address).c_str(), permission);
1346 return IAdapterManager::GetInstance()->SetPhonebookPermission(address, (BTPermissionType)permission);
1347 }
1348
GetMessagePermission(const std::string & address)1349 int32_t BluetoothHostServer::GetMessagePermission(const std::string &address)
1350 {
1351 HILOGI("address: %{public}s", GetEncryptAddr(address).c_str());
1352 return (int32_t)IAdapterManager::GetInstance()->GetMessagePermission(address);
1353 }
1354
SetMessagePermission(const std::string & address,int32_t permission)1355 bool BluetoothHostServer::SetMessagePermission(const std::string &address, int32_t permission)
1356 {
1357 HILOGI("address: %{public}s, permission: %{public}d", GetEncryptAddr(address).c_str(), permission);
1358 return IAdapterManager::GetInstance()->SetMessagePermission(address, (BTPermissionType)permission);
1359 }
1360
GetPowerMode(const std::string & address)1361 int32_t BluetoothHostServer::GetPowerMode(const std::string &address)
1362 {
1363 HILOGI("address: %{public}s", GetEncryptAddr(address).c_str());
1364 return IAdapterManager::GetInstance()->GetPowerMode(address);
1365 }
1366
GetDeviceName(int32_t transport,const std::string & address,std::string & name,bool alias)1367 int32_t BluetoothHostServer::GetDeviceName(int32_t transport, const std::string &address, std::string &name, bool alias)
1368 {
1369 if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) {
1370 HILOGE("false, check permission failed");
1371 return BT_ERR_PERMISSION_FAILED;
1372 }
1373 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1374 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1375 RawAddress addr(address);
1376 transport = GetTransportByDeviceType(transport, address);
1377 if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled() && classicService) {
1378 name = classicService->GetDeviceName(addr);
1379 return NO_ERROR;
1380 } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled() && bleService) {
1381 name = bleService->GetDeviceName(addr);
1382 return NO_ERROR;
1383 } else {
1384 HILOGE("transport invalid or BT current state is not enabled!");
1385 return BT_ERR_INVALID_STATE;
1386 }
1387 }
1388
GetDeviceAlias(const std::string & address)1389 std::string BluetoothHostServer::GetDeviceAlias(const std::string &address)
1390 {
1391 HILOGI("address: %{public}s", GetEncryptAddr(address).c_str());
1392 if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) {
1393 HILOGE("false, check permission failed");
1394 return INVALID_NAME;
1395 }
1396 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1397 if (IsBtEnabled() && classicService) {
1398 RawAddress addr(address);
1399 return classicService->GetAliasName(addr);
1400 } else {
1401 HILOGE("BT current state is not enabled");
1402 }
1403 return INVALID_NAME;
1404 }
1405
SetDeviceAlias(const std::string & address,const std::string & aliasName)1406 int32_t BluetoothHostServer::SetDeviceAlias(const std::string &address, const std::string &aliasName)
1407 {
1408 HILOGI("address: %{public}s, aliasName: %{public}s", GetEncryptAddr(address).c_str(), aliasName.c_str());
1409 if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) {
1410 HILOGE("false, check permission failed");
1411 return BT_ERR_PERMISSION_FAILED;
1412 }
1413 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1414 if (IsBtEnabled() && classicService) {
1415 RawAddress addr(address);
1416 return classicService->SetAliasName(addr, aliasName) ? BT_NO_ERROR : BT_ERR_INVALID_PARAM;
1417 } else {
1418 HILOGE("BT current state is not enabled");
1419 }
1420 return BT_ERR_INVALID_STATE;
1421 }
1422
GetRemoteDeviceBatteryInfo(const std::string & address,BluetoothBatteryInfo & batteryInfo)1423 int32_t BluetoothHostServer::GetRemoteDeviceBatteryInfo(const std::string &address,
1424 BluetoothBatteryInfo &batteryInfo)
1425 {
1426 if (PermissionUtils::VerifyAccessBluetoothPermission() == PERMISSION_DENIED) {
1427 HILOGE("false, check Access permission failed");
1428 return BT_ERR_PERMISSION_FAILED;
1429 }
1430 return BT_ERR_INTERNAL_ERROR;
1431 }
1432
GetPairState(int32_t transport,const std::string & address,int32_t & pairState)1433 int32_t BluetoothHostServer::GetPairState(int32_t transport, const std::string &address, int32_t &pairState)
1434 {
1435 HILOGI("transport: %{public}d, address: %{public}s", transport, GetEncryptAddr(address).c_str());
1436 if (PermissionUtils::VerifyAccessBluetoothPermission() == PERMISSION_DENIED) {
1437 HILOGE("false, check Access permission failed");
1438 return BT_ERR_PERMISSION_FAILED;
1439 }
1440 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1441 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1442 RawAddress addr(address);
1443 if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled() && classicService) {
1444 pairState = classicService->GetPairState(addr);
1445 } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled() && bleService) {
1446 pairState = bleService->GetPairState(addr);
1447 } else {
1448 HILOGE("transport invalid or BT current state is not enabled!");
1449 }
1450 return BT_NO_ERROR;
1451 }
1452
StartPair(int32_t transport,const std::string & address)1453 int32_t BluetoothHostServer::StartPair(int32_t transport, const std::string &address)
1454 {
1455 HILOGI("transport: %{public}d, address: %{public}s", transport, GetEncryptAddr(address).c_str());
1456 if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
1457 HILOGE("StartPair false, check permission failed");
1458 return BT_ERR_PERMISSION_FAILED;
1459 }
1460 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1461 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1462 RawAddress addr(address);
1463 transport = GetTransportByDeviceType(transport, address);
1464 if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled() && classicService) {
1465 if (classicService->StartPair(addr)) {
1466 return NO_ERROR;
1467 }
1468 } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled() && bleService) {
1469 if (bleService->StartPair(addr)) {
1470 return NO_ERROR;
1471 }
1472 } else {
1473 HILOGE("transport invalid or BT current state is not enabled!");
1474 return BT_ERR_INVALID_STATE;
1475 }
1476 return BT_ERR_INTERNAL_ERROR;
1477 }
1478
CancelPairing(int32_t transport,const std::string & address)1479 bool BluetoothHostServer::CancelPairing(int32_t transport, const std::string &address)
1480 {
1481 HILOGI("transport: %{public}d, address: %{public}s", transport, GetEncryptAddr(address).c_str());
1482 if (!PermissionUtils::CheckSystemHapApp()) {
1483 HILOGE("check system api failed.");
1484 return BT_ERR_SYSTEM_PERMISSION_FAILED;
1485 }
1486 if (PermissionUtils::VerifyDiscoverBluetoothPermission() == PERMISSION_DENIED) {
1487 HILOGE("false, check permission failed");
1488 return false;
1489 }
1490 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1491 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1492 RawAddress addr(address);
1493 transport = GetTransportByDeviceType(transport, address);
1494 if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled() && classicService) {
1495 return classicService->CancelPairing(addr);
1496 } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled() && bleService) {
1497 return bleService->CancelPairing(addr);
1498 } else {
1499 HILOGE("transport invalid or BT current state is not enabled!");
1500 }
1501 return false;
1502 }
1503
IsBondedFromLocal(int32_t transport,const std::string & address)1504 bool BluetoothHostServer::IsBondedFromLocal(int32_t transport, const std::string &address)
1505 {
1506 HILOGI("transport: %{public}d, address: %{public}s", transport, GetEncryptAddr(address).c_str());
1507 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1508 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1509 RawAddress addr(address);
1510 if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled() && classicService) {
1511 return classicService->IsBondedFromLocal(addr);
1512 } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled() && bleService) {
1513 return bleService->IsBondedFromLocal(addr);
1514 } else {
1515 HILOGE("transport invalid or BT current state is not enabled!");
1516 }
1517 return false;
1518 }
1519
IsAclConnected(int32_t transport,const std::string & address)1520 bool BluetoothHostServer::IsAclConnected(int32_t transport, const std::string &address)
1521 {
1522 HILOGI("transport: %{public}d, address: %{public}s", transport, GetEncryptAddr(address).c_str());
1523 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1524 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1525 RawAddress addr(address);
1526 if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled() && classicService) {
1527 return classicService->IsAclConnected(addr);
1528 } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled() && bleService) {
1529 return bleService->IsAclConnected(addr);
1530 } else {
1531 HILOGE("transport invalid or BT current state is not enabled!");
1532 }
1533 return false;
1534 }
1535
IsAclEncrypted(int32_t transport,const std::string & address)1536 bool BluetoothHostServer::IsAclEncrypted(int32_t transport, const std::string &address)
1537 {
1538 HILOGI("transport: %{public}d, address: %{public}s", transport, GetEncryptAddr(address).c_str());
1539 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1540 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1541 RawAddress addr(address);
1542 if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled() && classicService) {
1543 return classicService->IsAclEncrypted(addr);
1544 } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled() && bleService) {
1545 return bleService->IsAclEncrypted(addr);
1546 } else {
1547 HILOGE("transport invalid or BT current state is not enabled!");
1548 }
1549 return false;
1550 }
1551
GetDeviceClass(const std::string & address,int32_t & cod)1552 int32_t BluetoothHostServer::GetDeviceClass(const std::string &address, int32_t &cod)
1553 {
1554 HILOGI("address: %{public}s", GetEncryptAddr(address).c_str());
1555 if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) {
1556 HILOGE("false, check permission failed");
1557 return BT_ERR_PERMISSION_FAILED;
1558 }
1559 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1560 if (IsBtEnabled() && classicService) {
1561 RawAddress addr(address);
1562 cod = classicService->GetDeviceClass(addr);
1563 } else {
1564 HILOGE("BT current state is not enabled!");
1565 return BT_ERR_INVALID_STATE;
1566 }
1567 return NO_ERROR;
1568 }
1569
GetDeviceUuids(const std::string & address,std::vector<std::string> & uuids)1570 int32_t BluetoothHostServer::GetDeviceUuids(const std::string &address, std::vector<std::string> &uuids)
1571 {
1572 std::vector<bluetooth::Uuid> parcelUuids;
1573 RawAddress addr(address);
1574 if (!IsBtEnabled()) {
1575 HILOGE("BT current state is not enabled");
1576 return BT_ERR_INVALID_STATE;
1577 }
1578
1579 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1580 if (classicService) {
1581 parcelUuids = classicService->GetDeviceUuids(addr);
1582 }
1583 for (auto Uuid : parcelUuids) {
1584 uuids.push_back(Uuid.ToString());
1585 }
1586 return NO_ERROR;
1587 }
1588
GetLocalProfileUuids(std::vector<std::string> & uuids)1589 int32_t BluetoothHostServer::GetLocalProfileUuids(std::vector<std::string> &uuids)
1590 {
1591 return NO_ERROR;
1592 }
1593
SetDevicePin(const std::string & address,const std::string & pin)1594 int32_t BluetoothHostServer::SetDevicePin(const std::string &address, const std::string &pin)
1595 {
1596 HILOGI("address: %{public}s, pin: %{public}s", GetEncryptAddr(address).c_str(), pin.c_str());
1597 if (PermissionUtils::VerifyManageBluetoothPermission() == PERMISSION_DENIED) {
1598 HILOGE("false, check permission failed");
1599 return BT_ERR_PERMISSION_FAILED;
1600 }
1601 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1602 if (IsBtEnabled() && classicService) {
1603 RawAddress addr(address);
1604 if (classicService->SetDevicePin(addr, pin)) {
1605 return NO_ERROR;
1606 }
1607 } else {
1608 HILOGE("BT current state is not enabled!");
1609 return BT_ERR_INVALID_STATE;
1610 }
1611 return BT_ERR_INTERNAL_ERROR;
1612 }
1613
SetDevicePairingConfirmation(int32_t transport,const std::string & address,bool accept)1614 int32_t BluetoothHostServer::SetDevicePairingConfirmation(int32_t transport, const std::string &address, bool accept)
1615 {
1616 HILOGI("transport: %{public}d, address: %{public}s, accept: %{public}d",
1617 transport, GetEncryptAddr(address).c_str(), accept);
1618 if (PermissionUtils::VerifyManageBluetoothPermission() == PERMISSION_DENIED) {
1619 HILOGE("false, check permission failed");
1620 return BT_ERR_PERMISSION_FAILED;
1621 }
1622 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1623 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1624 RawAddress addr(address);
1625 transport = GetTransportByDeviceType(transport, address);
1626 if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled() && classicService) {
1627 if (classicService->SetDevicePairingConfirmation(addr, accept)) {
1628 return NO_ERROR;
1629 }
1630 } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled() && bleService) {
1631 if (bleService->SetDevicePairingConfirmation(addr, accept)) {
1632 return NO_ERROR;
1633 }
1634 } else {
1635 HILOGE("transport invalid or BT current state is not enabled!");
1636 return BT_ERR_INVALID_STATE;
1637 }
1638 return BT_ERR_INTERNAL_ERROR;
1639 }
1640
SetDevicePasskey(int32_t transport,const std::string & address,int32_t passkey,bool accept)1641 bool BluetoothHostServer::SetDevicePasskey(int32_t transport, const std::string &address, int32_t passkey, bool accept)
1642 {
1643 HILOGI("transport: %{public}d, address: %{public}s, passkey: %{public}d, accept: %{public}d",
1644 transport, GetEncryptAddr(address).c_str(), passkey, accept);
1645 if (PermissionUtils::VerifyManageBluetoothPermission() == PERMISSION_DENIED) {
1646 HILOGE("false, check permission failed");
1647 return false;
1648 }
1649 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1650 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1651 RawAddress addr(address);
1652 if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled() && classicService) {
1653 return classicService->SetDevicePasskey(addr, passkey, accept);
1654 } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled() && bleService) {
1655 return bleService->SetDevicePasskey(addr, passkey, accept);
1656 } else {
1657 HILOGE("transport invalid or BT current state is not enabled!");
1658 }
1659 return false;
1660 }
1661
PairRequestReply(int32_t transport,const std::string & address,bool accept)1662 bool BluetoothHostServer::PairRequestReply(int32_t transport, const std::string &address, bool accept)
1663 {
1664 HILOGI("transport: %{public}d, address: %{public}s, accept: %{public}d",
1665 transport, GetEncryptAddr(address).c_str(), accept);
1666 auto classicService = IAdapterManager::GetInstance()->GetClassicAdapterInterface();
1667 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1668 RawAddress addr(address);
1669 if ((transport == BT_TRANSPORT_BREDR) && IsBtEnabled() && classicService) {
1670 return classicService->PairRequestReply(addr, accept);
1671 } else if ((transport == BT_TRANSPORT_BLE) && IsBleEnabled() && bleService) {
1672 return bleService->PairRequestReply(addr, accept);
1673 } else {
1674 HILOGE("transport invalid or BT current state is not enabled!");
1675 }
1676 return false;
1677 }
1678
ReadRemoteRssiValue(const std::string & address)1679 bool BluetoothHostServer::ReadRemoteRssiValue(const std::string &address)
1680 {
1681 HILOGI("address: %{public}s", GetEncryptAddr(address).c_str());
1682 if (PermissionUtils::VerifyUseBluetoothPermission() == PERMISSION_DENIED) {
1683 HILOGE("false, check permission failed");
1684 return false;
1685 }
1686 auto bleService = IAdapterManager::GetInstance()->GetBleAdapterInterface();
1687 if (IsBleEnabled() && bleService) {
1688 RawAddress addr(address);
1689 return bleService->ReadRemoteRssiValue(addr);
1690 } else {
1691 HILOGE("BT current state is not enabled!");
1692 }
1693 return false;
1694 }
1695
RegisterRemoteDeviceObserver(const sptr<IBluetoothRemoteDeviceObserver> & observer)1696 void BluetoothHostServer::RegisterRemoteDeviceObserver(const sptr<IBluetoothRemoteDeviceObserver> &observer)
1697 {
1698 HILOGI("Enter!");
1699 if (observer == nullptr) {
1700 HILOGE("observer is nullptr!");
1701 return;
1702 }
1703 pimpl->remoteObserversToken_.EnsureInsert(observer->AsObject(), IPCSkeleton::GetCallingTokenID());
1704 pimpl->remoteObserversPid_.EnsureInsert(observer->AsObject(), IPCSkeleton::GetCallingUid());
1705 auto func = std::bind(&BluetoothHostServer::DeregisterRemoteDeviceObserver,
1706 this, std::placeholders::_1);
1707 pimpl->remoteObservers_.Register(observer, func);
1708 std::lock_guard<std::mutex> lock(pimpl->remoteDeviceObserversMutex);
1709 pimpl->remoteDeviceObservers_.push_back(observer);
1710 }
1711
DeregisterRemoteDeviceObserver(const sptr<IBluetoothRemoteDeviceObserver> & observer)1712 void BluetoothHostServer::DeregisterRemoteDeviceObserver(const sptr<IBluetoothRemoteDeviceObserver> &observer)
1713 {
1714 HILOGI("Enter!");
1715 if (observer == nullptr || pimpl == nullptr) {
1716 HILOGE("observer is nullptr!");
1717 return;
1718 }
1719 {
1720 std::lock_guard<std::mutex> lock(pimpl->remoteDeviceObserversMutex);
1721 for (auto iter = pimpl->remoteDeviceObservers_.begin(); iter != pimpl->remoteDeviceObservers_.end(); ++iter) {
1722 if ((*iter)->AsObject() == observer->AsObject()) {
1723 pimpl->remoteObservers_.Deregister(*iter);
1724 pimpl->remoteDeviceObservers_.erase(iter);
1725 break;
1726 }
1727 }
1728 }
1729 pimpl->remoteObserversToken_.Erase(observer->AsObject());
1730 pimpl->remoteObserversPid_.Erase(observer->AsObject());
1731 }
1732
IsBtEnabled()1733 bool BluetoothHostServer::IsBtEnabled()
1734 {
1735 int32_t state = static_cast<int32_t>(BluetoothState::STATE_OFF);
1736 GetBtState(state);
1737 bool isEnabled = (state == static_cast<int32_t>(BluetoothState::STATE_ON)) ? true : false;
1738 HILOGI("%{public}s", isEnabled ? "true" : "false");
1739 return isEnabled;
1740 }
1741
RegisterBleAdapterObserver(const sptr<IBluetoothHostObserver> & observer)1742 void BluetoothHostServer::RegisterBleAdapterObserver(const sptr<IBluetoothHostObserver> &observer)
1743 {
1744 HILOGI("start.");
1745 if (observer == nullptr) {
1746 HILOGE("observer is nullptr!");
1747 return;
1748 }
1749 pimpl->bleObserversToken_.EnsureInsert(observer->AsObject(), IPCSkeleton::GetCallingTokenID());
1750 pimpl->bleObserversPid_.EnsureInsert(observer->AsObject(), IPCSkeleton::GetCallingUid());
1751 auto func = std::bind(&BluetoothHostServer::DeregisterBleAdapterObserver, this, std::placeholders::_1);
1752 pimpl->bleObservers_.Register(observer, func);
1753 std::lock_guard<std::mutex> lock(pimpl->bleAdapterObserversMutex);
1754 pimpl->bleAdapterObservers_.push_back(observer);
1755 }
1756
DeregisterBleAdapterObserver(const sptr<IBluetoothHostObserver> & observer)1757 void BluetoothHostServer::DeregisterBleAdapterObserver(const sptr<IBluetoothHostObserver> &observer)
1758 {
1759 HILOGI("start.");
1760 if (observer == nullptr || pimpl == nullptr) {
1761 HILOGE("observer is nullptr!");
1762 return;
1763 }
1764 {
1765 std::lock_guard<std::mutex> lock(pimpl->bleAdapterObserversMutex);
1766 for (auto iter = pimpl->bleAdapterObservers_.begin(); iter != pimpl->bleAdapterObservers_.end(); ++iter) {
1767 if ((*iter)->AsObject() == observer->AsObject()) {
1768 pimpl->bleObservers_.Deregister(*iter);
1769 pimpl->bleAdapterObservers_.erase(iter);
1770 break;
1771 }
1772 }
1773 }
1774 pimpl->bleObserversToken_.Erase(observer->AsObject());
1775 pimpl->bleObserversPid_.Erase(observer->AsObject());
1776 }
1777
RegisterBlePeripheralCallback(const sptr<IBluetoothBlePeripheralObserver> & observer)1778 void BluetoothHostServer::RegisterBlePeripheralCallback(const sptr<IBluetoothBlePeripheralObserver> &observer)
1779 {
1780 HILOGI("start.");
1781 if (observer == nullptr) {
1782 HILOGE("observer is nullptr!");
1783 return;
1784 }
1785 pimpl->bleRemoteObserversToken_.EnsureInsert(observer->AsObject(), IPCSkeleton::GetCallingTokenID());
1786 auto func = std::bind(&BluetoothHostServer::DeregisterBlePeripheralCallback, this, std::placeholders::_1);
1787 pimpl->bleRemoteObservers_.Register(observer, func);
1788 std::lock_guard<std::mutex> lock(pimpl->blePeripheralObserversMutex);
1789 pimpl->blePeripheralObservers_.push_back(observer);
1790 }
1791
DeregisterBlePeripheralCallback(const sptr<IBluetoothBlePeripheralObserver> & observer)1792 void BluetoothHostServer::DeregisterBlePeripheralCallback(const sptr<IBluetoothBlePeripheralObserver> &observer)
1793 {
1794 HILOGI("start.");
1795 if (observer == nullptr) {
1796 HILOGE("observer is nullptr!");
1797 return;
1798 }
1799 {
1800 std::lock_guard<std::mutex> lock(pimpl->blePeripheralObserversMutex);
1801 for (auto iter = pimpl->blePeripheralObservers_.begin(); iter != pimpl->blePeripheralObservers_.end(); ++iter) {
1802 if ((*iter)->AsObject() == observer->AsObject()) {
1803 if (pimpl != nullptr) {
1804 pimpl->bleRemoteObservers_.Deregister(*iter);
1805 pimpl->blePeripheralObservers_.erase(iter);
1806 break;
1807 }
1808 }
1809 }
1810 }
1811 pimpl->bleRemoteObserversToken_.Erase(observer->AsObject());
1812 }
1813
Dump(int32_t fd,const std::vector<std::u16string> & args)1814 int32_t BluetoothHostServer::Dump(int32_t fd, const std::vector<std::u16string> &args)
1815 {
1816 HILOGI("fd: %{public}d", fd);
1817 std::vector<std::string> argsInStr8;
1818 std::transform(args.begin(), args.end(), std::back_inserter(argsInStr8), [](const std::u16string &arg) {
1819 return Str16ToStr8(arg);
1820 });
1821
1822 std::string result;
1823 BluetoothHostDumper::BluetoothDump(argsInStr8, result);
1824
1825 if (!SaveStringToFd(fd, result)) {
1826 HILOGE("bluetooth dump save string to fd failed!");
1827 return ERR_INVALID_OPERATION;
1828 }
1829 return ERR_OK;
1830 }
1831
SetFastScan(bool isEnable)1832 int32_t BluetoothHostServer::SetFastScan(bool isEnable)
1833 {
1834 return NO_ERROR;
1835 }
1836
GetRandomAddress(const std::string & realAddr,std::string & randomAddr)1837 int32_t BluetoothHostServer::GetRandomAddress(const std::string &realAddr, std::string &randomAddr)
1838 {
1839 return BT_ERR_API_NOT_SUPPORT;
1840 }
1841
SyncRandomAddress(const std::string & realAddr,const std::string & randomAddr)1842 int32_t BluetoothHostServer::SyncRandomAddress(const std::string &realAddr, const std::string &randomAddr)
1843 {
1844 return NO_ERROR;
1845 }
1846
StartCrediblePair(int32_t transport,const std::string & address)1847 int32_t BluetoothHostServer::StartCrediblePair(int32_t transport, const std::string &address)
1848 {
1849 if (!PermissionUtils::CheckSystemHapApp()) {
1850 HILOGE("check system api failed.");
1851 return BT_ERR_SYSTEM_PERMISSION_FAILED;
1852 }
1853 return NO_ERROR;
1854 }
1855
SatelliteControl(int type,int state)1856 int32_t BluetoothHostServer::SatelliteControl(int type, int state)
1857 {
1858 return BT_ERR_API_NOT_SUPPORT;
1859 }
1860
ConnectAllowedProfiles(const std::string & address)1861 int32_t BluetoothHostServer::ConnectAllowedProfiles(const std::string &address)
1862 {
1863 return BT_ERR_API_NOT_SUPPORT;
1864 }
1865
DisconnectAllowedProfiles(const std::string & address)1866 int32_t BluetoothHostServer::DisconnectAllowedProfiles(const std::string &address)
1867 {
1868 return BT_ERR_API_NOT_SUPPORT;
1869 }
1870
SetDeviceCustomType(const std::string & address,int32_t deviceType)1871 int32_t BluetoothHostServer::SetDeviceCustomType(const std::string &address, int32_t deviceType)
1872 {
1873 return BT_ERR_API_NOT_SUPPORT;
1874 }
1875
GetRemoteDeviceInfo(const std::string & address,std::shared_ptr<BluetoothRemoteDeviceInfo> & deviceInfo,int type)1876 int32_t BluetoothHostServer::GetRemoteDeviceInfo(const std::string &address,
1877 std::shared_ptr<BluetoothRemoteDeviceInfo> &deviceInfo, int type)
1878 {
1879 return BT_ERR_API_NOT_SUPPORT;
1880 }
1881
RegisterBtResourceManagerObserver(const sptr<IBluetoothResourceManagerObserver> & observer)1882 void BluetoothHostServer::RegisterBtResourceManagerObserver(const sptr<IBluetoothResourceManagerObserver> &observer)
1883 {}
1884
DeregisterBtResourceManagerObserver(const sptr<IBluetoothResourceManagerObserver> & observer)1885 void BluetoothHostServer::DeregisterBtResourceManagerObserver(const sptr<IBluetoothResourceManagerObserver> &observer)
1886 {}
1887
UpdateVirtualDevice(int32_t action,const std::string & address)1888 void BluetoothHostServer::UpdateVirtualDevice(int32_t action, const std::string &address)
1889 {}
1890
IsSupportVirtualAutoConnect(const std::string & address,bool & outSupport)1891 int32_t BluetoothHostServer::IsSupportVirtualAutoConnect(const std::string &address, bool &outSupport)
1892 {
1893 outSupport = false;
1894 return BT_ERR_API_NOT_SUPPORT;
1895 }
1896
SetVirtualAutoConnectType(const std::string & address,int connType,int businessType)1897 int32_t BluetoothHostServer::SetVirtualAutoConnectType(const std::string &address, int connType, int businessType)
1898 {
1899 return BT_ERR_API_NOT_SUPPORT;
1900 }
1901
SetFastScanLevel(int level)1902 int32_t BluetoothHostServer::SetFastScanLevel(int level)
1903 {
1904 return BT_ERR_API_NOT_SUPPORT;
1905 }
1906
EnableBluetoothToRestrictMode(void)1907 int32_t BluetoothHostServer::EnableBluetoothToRestrictMode(void)
1908 {
1909 return BT_ERR_API_NOT_SUPPORT;
1910 }
1911
ControlDeviceAction(const std::string & deviceId,uint32_t controlType,uint32_t controlTypeVal,uint32_t controlObject)1912 int32_t BluetoothHostServer::ControlDeviceAction(const std::string &deviceId, uint32_t controlType,
1913 uint32_t controlTypeVal, uint32_t controlObject)
1914 {
1915 return BT_ERR_API_NOT_SUPPORT;
1916 }
1917
GetLastConnectionTime(const std::string & address,int64_t & connectionTime)1918 int32_t BluetoothHostServer::GetLastConnectionTime(const std::string &address, int64_t &connectionTime)
1919 {
1920 return BT_ERR_API_NOT_SUPPORT;
1921 }
1922
UpdateCloudBluetoothDevice(std::vector<BluetoothTrustPairDevice> & cloudDevices)1923 int32_t BluetoothHostServer::UpdateCloudBluetoothDevice(std::vector<BluetoothTrustPairDevice> &cloudDevices)
1924 {
1925 return BT_ERR_API_NOT_SUPPORT;
1926 }
1927
GetCloudBondState(const std::string & address,int32_t & cloudBondState)1928 int32_t BluetoothHostServer::GetCloudBondState(const std::string &address, int32_t &cloudBondState)
1929 {
1930 return BT_ERR_API_NOT_SUPPORT;
1931 }
1932
UpdateRefusePolicy(const int32_t pid,const int64_t prohibitedSecondsTime)1933 int32_t BluetoothHostServer::UpdateRefusePolicy(const int32_t pid, const int64_t prohibitedSecondsTime)
1934 {
1935 return BT_ERR_API_NOT_SUPPORT;
1936 }
1937
ProcessRandomDeviceIdCommand(int32_t command,std::vector<std::string> & deviceIdVec,bool & isValid)1938 int32_t BluetoothHostServer::ProcessRandomDeviceIdCommand(
1939 int32_t command, std::vector<std::string> &deviceIdVec, bool &isValid)
1940 {
1941 return BT_ERR_API_NOT_SUPPORT;
1942 }
1943 } // namespace Bluetooth
1944 } // namespace OHOS
1945