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 "bluetooth_host.h"
17 #include <memory>
18 #include <mutex>
19 #include <unistd.h>
20 #include <thread>
21 #include "bluetooth_ble_peripheral_observer_stub.h"
22 #include "bluetooth_host_load_callback.h"
23 #include "bluetooth_host_observer_stub.h"
24 #include "bluetooth_host_proxy.h"
25 #include "bluetooth_profile_manager.h"
26 #include "bluetooth_log.h"
27 #include "bluetooth_utils.h"
28 #include "bluetooth_observer_list.h"
29 #include "bluetooth_remote_device_observer_stub.h"
30 #include "bluetooth_resource_manager_observer_stub.h"
31 #include "iservice_registry.h"
32 #include "parameter.h"
33 #include "system_ability_definition.h"
34 #include "bluetooth_switch_module.h"
35 #include "ffrt_inner.h"
36 #include "common_event.h"
37 #include "common_event_data.h"
38 #include "common_event_manager.h"
39 
40 using namespace OHOS::EventFwk;
41 
42 namespace OHOS {
43 namespace Bluetooth {
44 namespace {
45 constexpr int32_t LOAD_SA_TIMEOUT_MS = 4000;
46 }
47 
48 struct BluetoothHost::impl {
49     impl();
50     ~impl();
51 
52     bool LoadBluetoothHostService();
53     void LoadSystemAbilitySuccess(const sptr<IRemoteObject> &remoteObject);
54     void LoadSystemAbilityFail();
55     int EnableBluetoothAfterFactoryReset(void);
56 
57     // host observer
58     class BluetoothHostObserverImp;
59     sptr<BluetoothHostObserverImp> observerImp_ = nullptr;
60     sptr<BluetoothHostObserverImp> bleObserverImp_ = nullptr;
61 
62     // remote device observer
63     class BluetoothRemoteDeviceObserverImp;
64     sptr<BluetoothRemoteDeviceObserverImp> remoteObserverImp_ = nullptr;
65 
66     // remote device observer
67     class BluetoothBlePeripheralCallbackImp;
68     sptr<BluetoothBlePeripheralCallbackImp> bleRemoteObserverImp_ = nullptr;
69 
70     // bluetooth resource manager observer
71     class BluetoothResourceManagerObserverImp;
72     sptr<BluetoothResourceManagerObserverImp> resourceManagerObserverImp_ = nullptr;
73 
74     // user regist observers
75     BluetoothObserverList<BluetoothHostObserver> observers_;
76 
77     // user regist remote observers
78     BluetoothObserverList<BluetoothRemoteDeviceObserver> remoteObservers_;
79 
80     // user regist resource manager observers
81     BluetoothObserverList<BluetoothResourceManagerObserver> resourceManagerObservers_;
82 
83     void SyncRandomAddrToService(void);
84 
85     std::mutex proxyMutex_;
86     std::string stagingRealAddr_;
87     std::string stagingRandomAddr_;
88     int32_t profileRegisterId = 0;
89     std::atomic_bool isFactoryReseting_ { false };
90 
91     class BluetoothSwitchAction;
92     std::mutex switchModuleMutex_ {};  // used for serial execute enableBluetoothToRestrictMode.
93     std::shared_ptr<BluetoothSwitchModule> switchModule_ { nullptr };
94 
95 private:
96     SaManagerStatus saManagerStatus_ = SaManagerStatus::WAIT_NOTIFY;
97     std::condition_variable proxyConVar_;
98 };
99 
100 class BluetoothHost::impl::BluetoothHostObserverImp : public BluetoothHostObserverStub {
101 public:
BluetoothHostObserverImp(BluetoothHost::impl &host)102     explicit BluetoothHostObserverImp(BluetoothHost::impl &host) : host_(host){};
103     ~BluetoothHostObserverImp() override{};
104 
Register(std::shared_ptr<BluetoothHostObserver> &observer)105     void Register(std::shared_ptr<BluetoothHostObserver> &observer)
106     {
107         host_.observers_.Register(observer);
108     }
109 
Deregister(std::shared_ptr<BluetoothHostObserver> &observer)110     void Deregister(std::shared_ptr<BluetoothHostObserver> &observer)
111     {
112         host_.observers_.Deregister(observer);
113     }
114 
115     void OnStateChanged(int32_t transport, int32_t status) override
116     {
117         if (status == BTStateID::STATE_TURN_ON) {
118             host_.SyncRandomAddrToService();
119         }
120         CHECK_AND_RETURN_LOG(!isNeedInterceptSwitchStatus(transport, status), "No Need transform same status");
121         BluetoothProfileManager::GetInstance().NotifyBluetoothStateChange(transport, status);
122         host_.observers_.ForEach([transport, status](std::shared_ptr<BluetoothHostObserver> observer) {
123             observer->OnStateChanged(transport, status);
124         });
125     }
126 
127     void OnBluetoothStateChanged(int32_t state) override
128     {
129         std::lock_guard<std::mutex> lock(host_.switchModuleMutex_);
130         CHECK_AND_RETURN_LOG(host_.switchModule_, "switchModule is nullptr");
131         if (state == bluetooth::BluetoothSwitchState::STATE_ON) {
132             host_.switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::BLUETOOTH_ON);
133         }
134         if (state == bluetooth::BluetoothSwitchState::STATE_OFF) {
135             host_.switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::BLUETOOTH_OFF);
136         }
137         if (state == bluetooth::BluetoothSwitchState::STATE_HALF) {
138             host_.switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::BLUETOOTH_HALF);
139         }
140     }
141 
142     void OnDiscoveryStateChanged(int32_t status) override
143     {
144         HILOGD("enter, status: %{public}d", status);
145         host_.observers_.ForEach(
146             [status](std::shared_ptr<BluetoothHostObserver> observer) { observer->OnDiscoveryStateChanged(status); });
147     }
148 
149     void OnDiscoveryResult(
150         const BluetoothRawAddress &device, int rssi, const std::string deviceName, int deviceClass) override
151     {
152         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
153         host_.observers_.ForEach([remoteDevice, rssi, deviceName, deviceClass](
154             std::shared_ptr<BluetoothHostObserver> observer) {
155             observer->OnDiscoveryResult(remoteDevice, rssi, deviceName, deviceClass);
156         });
157     }
158 
159     void OnPairRequested(const int32_t transport, const BluetoothRawAddress &device) override
160     {
161         HILOGI("enter, transport: %{public}d, device: %{public}s",
162             transport, GET_ENCRYPT_RAW_ADDR(device));
163         BluetoothRemoteDevice remoteDevice(device.GetAddress(), transport);
164         host_.observers_.ForEach([remoteDevice](std::shared_ptr<BluetoothHostObserver> observer) {
165             observer->OnPairRequested(remoteDevice);
166         });
167     }
168 
169     void OnPairConfirmed(const int32_t transport, const BluetoothRawAddress &device, int reqType, int number) override
170     {
171         HILOGI("enter, transport: %{public}d, device: %{public}s, reqType: %{public}d, number: %{public}d",
172             transport, GET_ENCRYPT_RAW_ADDR(device), reqType, number);
173         BluetoothRemoteDevice remoteDevice(device.GetAddress(), transport);
174         host_.observers_.ForEach([remoteDevice, reqType, number](std::shared_ptr<BluetoothHostObserver> observer) {
175             observer->OnPairConfirmed(remoteDevice, reqType, number);
176         });
177     }
178 
179     void OnScanModeChanged(int mode) override
180     {
181         HILOGI("enter, mode: %{public}d", mode);
182         host_.observers_.ForEach(
183             [mode](std::shared_ptr<BluetoothHostObserver> observer) { observer->OnScanModeChanged(mode); });
184     }
185 
186     void OnDeviceNameChanged(const std::string &deviceName) override
187     {
188         HILOGI("enter, deviceName: %{public}s", deviceName.c_str());
189         host_.observers_.ForEach([deviceName](std::shared_ptr<BluetoothHostObserver> observer) {
190             observer->OnDeviceNameChanged(deviceName);
191         });
192     }
193 
194     void OnDeviceAddrChanged(const std::string &address) override
195     {
196         HILOGD("enter");
197         host_.observers_.ForEach(
198             [address](std::shared_ptr<BluetoothHostObserver> observer) { observer->OnDeviceAddrChanged(address); });
199     }
200 
201 private:
isNeedInterceptSwitchStatus(int32_t transport, int32_t status)202     bool isNeedInterceptSwitchStatus(int32_t transport, int32_t status)
203     {
204         bool isBluetoothSeriviceOn = BluetoothProfileManager::GetInstance().IsBluetoothServiceOn();
205         if (status == BTStateID::STATE_TURN_OFF) {
206             if (transport == BTTransport::ADAPTER_BLE &&
207                 preBleState_ == BTStateID::STATE_TURN_OFF && !isBluetoothSeriviceOn) {
208                 return true;
209             }
210             if (transport == BTTransport::ADAPTER_BREDR &&
211                 preBrState_ == BTStateID::STATE_TURN_OFF && !isBluetoothSeriviceOn) {
212                 return true;
213             }
214         }
215         if (transport == BTTransport::ADAPTER_BREDR) {
216             preBrState_ = status;
217         } else {
218             preBleState_ = status;
219         }
220         return false;
221     }
222     BluetoothHost::impl &host_;
223     const int32_t INVALID_STATE = -1;
224     int32_t preBrState_ = INVALID_STATE;
225     int32_t preBleState_ = INVALID_STATE;
226     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothHostObserverImp);
227 };
228 
229 class BluetoothHost::impl::BluetoothRemoteDeviceObserverImp : public BluetoothRemoteDeviceObserverstub {
230 public:
BluetoothRemoteDeviceObserverImp(BluetoothHost::impl &host)231     explicit BluetoothRemoteDeviceObserverImp(BluetoothHost::impl &host) : host_(host){};
232     ~BluetoothRemoteDeviceObserverImp() override = default;
233 
234     void OnAclStateChanged(const BluetoothRawAddress &device, int32_t state, uint32_t reason) override
235     {
236         HILOGD("enter, device: %{public}s, state: %{public}d, reason: %{public}u",
237             GET_ENCRYPT_RAW_ADDR(device), state, reason);
238         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
239         host_.remoteObservers_.ForEach(
240             [remoteDevice, state, reason](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
241                 observer->OnAclStateChanged(remoteDevice, state, reason);
242             });
243     }
244 
245     void OnPairStatusChanged(const int32_t transport, const BluetoothRawAddress &device,
246         int32_t status, int32_t cause) override
247     {
248         HILOGD("enter, transport: %{public}d, device: %{public}s, status: %{public}d, cause: %{public}d",
249             transport, GET_ENCRYPT_RAW_ADDR(device), status, cause);
250         BluetoothRemoteDevice remoteDevice(device.GetAddress(), transport);
251         host_.remoteObservers_.ForEach(
252             [remoteDevice, status, cause](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
253                 observer->OnPairStatusChanged(remoteDevice, status, cause);
254             });
255     }
256 
257     void OnRemoteUuidChanged(const BluetoothRawAddress &device, const std::vector<bluetooth::Uuid> uuids) override
258     {
259         HILOGD("enter, device: %{public}s", GET_ENCRYPT_RAW_ADDR(device));
260         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
261         host_.remoteObservers_.ForEach(
262             [remoteDevice, uuids](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
263                 std::vector<ParcelUuid> parcelUuids;
264                 for (auto &uuid : uuids) {
265                     ParcelUuid parcelUuid = UUID::ConvertFrom128Bits(uuid.ConvertTo128Bits());
266                     parcelUuids.push_back(parcelUuid);
267                 }
268                 observer->OnRemoteUuidChanged(remoteDevice, parcelUuids);
269             });
270     }
271 
272     void OnRemoteNameChanged(const BluetoothRawAddress &device, const std::string deviceName) override
273     {
274         HILOGD("enter, device: %{public}s, deviceName: %{public}s",
275             GET_ENCRYPT_RAW_ADDR(device), deviceName.c_str());
276         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
277         host_.remoteObservers_.ForEach(
278             [remoteDevice, deviceName](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
279                 observer->OnRemoteNameChanged(remoteDevice, deviceName);
280             });
281     }
282 
283     void OnRemoteAliasChanged(const BluetoothRawAddress &device, const std::string alias) override
284     {
285         HILOGI("enter, device: %{public}s, alias: %{public}s",
286             GET_ENCRYPT_RAW_ADDR(device), alias.c_str());
287         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
288         host_.remoteObservers_.ForEach(
289             [remoteDevice, alias](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
290                 observer->OnRemoteAliasChanged(remoteDevice, alias);
291             });
292     }
293 
294     void OnRemoteCodChanged(const BluetoothRawAddress &device, int32_t cod) override
295     {
296         HILOGD("enter, device: %{public}s, cod: %{public}d", GET_ENCRYPT_RAW_ADDR(device), cod);
297         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
298         BluetoothDeviceClass deviceClass(cod);
299         host_.remoteObservers_.ForEach(
300             [remoteDevice, deviceClass](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
301                 observer->OnRemoteCodChanged(remoteDevice, deviceClass);
302             });
303     }
304 
305     void OnRemoteBatteryChanged(const BluetoothRawAddress &device, const BluetoothBatteryInfo &batteryInfo) override
306     {
307         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
308         DeviceBatteryInfo info;
309         info.deviceId_ = device.GetAddress();
310         info.batteryLevel_ = batteryInfo.batteryLevel_;
311         info.leftEarBatteryLevel_ = batteryInfo.leftEarBatteryLevel_;
312         info.leftEarChargeState_ = static_cast<DeviceChargeState>(batteryInfo.leftEarChargeState_);
313         info.rightEarBatteryLevel_ = batteryInfo.rightEarBatteryLevel_;
314         info.rightEarChargeState_ = static_cast<DeviceChargeState>(batteryInfo.rightEarChargeState_);
315         info.boxBatteryLevel_ = batteryInfo.boxBatteryLevel_;
316         info.boxChargeState_ = static_cast<DeviceChargeState>(batteryInfo.boxChargeState_);
317         host_.remoteObservers_.ForEach(
318             [remoteDevice, info](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
319                 observer->OnRemoteBatteryChanged(remoteDevice, info);
320             });
321     }
322 
323     void OnRemoteDeviceCommonInfoReport(const BluetoothRawAddress &device, const std::vector<uint8_t> &value) override
324     {
325         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
326         host_.remoteObservers_.ForEach(
327             [remoteDevice, value](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
328                 observer->OnRemoteDeviceCommonInfoReport(remoteDevice, value);
329             });
330     }
331 
332 private:
333     BluetoothHost::impl &host_;
334     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothRemoteDeviceObserverImp);
335 };
336 
337 class BluetoothHost::impl::BluetoothBlePeripheralCallbackImp : public BluetoothBlePeripheralObserverStub {
338 public:
BluetoothBlePeripheralCallbackImp(BluetoothHost::impl &host)339     explicit BluetoothBlePeripheralCallbackImp(BluetoothHost::impl &host) : host_(host){};
340     ~BluetoothBlePeripheralCallbackImp() override = default;
341 
342     void OnAclStateChanged(const BluetoothRawAddress &device, int state, unsigned int reason) override
343     {
344         HILOGD("enter, device: %{public}s, state: %{public}d, reason: %{public}u",
345             GET_ENCRYPT_RAW_ADDR(device), state, reason);
346         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BLE);
347         host_.remoteObservers_.ForEach(
348             [remoteDevice, state, reason](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
349                 observer->OnAclStateChanged(remoteDevice, state, reason);
350             });
351     }
352 
353     void OnPairStatusChanged(const int32_t transport, const BluetoothRawAddress &device, int status, int cause) override
354     {
355         HILOGI("enter, transport: %{public}d, device: %{public}s, status: %{public}d, cause: %{public}d",
356             transport, GET_ENCRYPT_RAW_ADDR(device), status, cause);
357         BluetoothRemoteDevice remoteDevice(device.GetAddress(), transport);
358         host_.remoteObservers_.ForEach(
359             [remoteDevice, status, cause](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
360                 observer->OnPairStatusChanged(remoteDevice, status, cause);
361             });
362     }
363 
364     void OnReadRemoteRssiEvent(const BluetoothRawAddress &device, int rssi, int status) override
365     {
366         HILOGI("enter, device: %{public}s, rssi: %{public}d, status: %{public}d",
367             GET_ENCRYPT_RAW_ADDR(device), rssi, status);
368         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BLE);
369         host_.remoteObservers_.ForEach(
370             [remoteDevice, rssi, status](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
371                 observer->OnReadRemoteRssiEvent(remoteDevice, rssi, status);
372             });
373     }
374 
375 private:
376     BluetoothHost::impl &host_;
377     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothBlePeripheralCallbackImp);
378 };
379 
380 class BluetoothHost::impl::BluetoothResourceManagerObserverImp : public BluetoothResourceManagerObserverStub {
381 public:
BluetoothResourceManagerObserverImp(BluetoothHost::impl &host)382     explicit BluetoothResourceManagerObserverImp(BluetoothHost::impl &host) : host_(host){};
383     ~BluetoothResourceManagerObserverImp() override = default;
384 
385     void OnSensingStateChanged(uint8_t eventId, const BluetoothSensingInfo &info) override
386     {
387         HILOGD("enter, eventId: %{public}d", eventId);
388         SensingInfo sensingInfo;
389         sensingInfo.addr_ = info.addr_;
390         sensingInfo.uuid_ = info.uuid_;
391         sensingInfo.resourceId_ = info.resourceId_;
392         sensingInfo.pkgName_ = info.pkgName_;
393         sensingInfo.isServer_ = info.isServer_;
394         sensingInfo.interval_ = info.interval_;
395         host_.resourceManagerObservers_.ForEach(
396             [eventId, sensingInfo](std::shared_ptr<BluetoothResourceManagerObserver> observer) {
397                 observer->OnSensingStateChanged(eventId, sensingInfo);
398             });
399     }
400 
401     void OnBluetoothResourceDecision(uint8_t eventId, const BluetoothSensingInfo &info, uint32_t &result) override
402     {
403         HILOGD("enter, eventId: %{public}d, result: %{public}d", eventId, result);
404         SensingInfo sensingInfo;
405         sensingInfo.addr_ = info.addr_;
406         sensingInfo.uuid_ = info.uuid_;
407         sensingInfo.resourceId_ = info.resourceId_;
408         sensingInfo.pkgName_ = info.pkgName_;
409         sensingInfo.isServer_ = info.isServer_;
410         sensingInfo.interval_ = info.interval_;
411         host_.resourceManagerObservers_.ForEach(
412             [eventId, sensingInfo, &result](std::shared_ptr<BluetoothResourceManagerObserver> observer) {
413                 observer->OnBluetoothResourceDecision(eventId, sensingInfo, result);
414             });
415     }
416 
417 private:
418     BluetoothHost::impl &host_;
419     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothResourceManagerObserverImp);
420 };
421 
422 class BluetoothHost::impl::BluetoothSwitchAction : public IBluetoothSwitchAction {
423 public:
424     BluetoothSwitchAction() = default;
425     ~BluetoothSwitchAction() override = default;
426 
427     int EnableBluetooth(void) override
428     {
429         CHECK_AND_RETURN_LOG_RET(!BluetoothHost::GetDefaultHost().IsBtProhibitedByEdm(),
430             BT_ERR_PROHIBITED_BY_EDM, "bluetooth is prohibited !");
431         CHECK_AND_RETURN_LOG_RET(BluetoothHost::GetDefaultHost().pimpl->LoadBluetoothHostService(),
432             BT_ERR_INTERNAL_ERROR, "pimpl is null or load bluetooth service failed.");
433 
434         sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
435         CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr");
436         return proxy->EnableBle();
437     }
438 
439     int DisableBluetooth(void) override
440     {
441         sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
442         CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr");
443         return proxy->DisableBt();
444     }
445 
446     int EnableBluetoothToRestrictMode(void) override
447     {
448         CHECK_AND_RETURN_LOG_RET(!BluetoothHost::GetDefaultHost().IsBtProhibitedByEdm(),
449             BT_ERR_PROHIBITED_BY_EDM, "bluetooth is prohibited !");
450         CHECK_AND_RETURN_LOG_RET(BluetoothHost::GetDefaultHost().pimpl->LoadBluetoothHostService(),
451             BT_ERR_INTERNAL_ERROR, "pimpl is null or load bluetooth service failed.");
452 
453         sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
454         CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr");
455         return proxy->EnableBluetoothToRestrictMode();
456     }
457 };
458 
impl()459 BluetoothHost::impl::impl()
460 {
461     observerImp_ = new BluetoothHostObserverImp(*this);
462     remoteObserverImp_ = new BluetoothRemoteDeviceObserverImp(*this);
463     bleRemoteObserverImp_ = new BluetoothBlePeripheralCallbackImp(*this);
464     bleObserverImp_ = new BluetoothHostObserverImp(*this);
465     resourceManagerObserverImp_ = new BluetoothResourceManagerObserverImp(*this);
466 
467     auto switchActionPtr = std::make_unique<BluetoothSwitchAction>();
468     switchModule_ = std::make_shared<BluetoothSwitchModule>(std::move(switchActionPtr));
469 
470     profileRegisterId = BluetoothProfileManager::GetInstance().RegisterFunc(BLUETOOTH_HOST,
471         [this](sptr<IRemoteObject> remote) {
472         sptr<IBluetoothHost> proxy = iface_cast<IBluetoothHost>(remote);
473         CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is nullptr");
474         proxy->RegisterObserver(observerImp_);
475         proxy->RegisterBleAdapterObserver(bleObserverImp_);
476         proxy->RegisterRemoteDeviceObserver(remoteObserverImp_);
477         proxy->RegisterBlePeripheralCallback(bleRemoteObserverImp_);
478         proxy->RegisterBtResourceManagerObserver(resourceManagerObserverImp_);
479     });
480 }
481 
~impl()482 BluetoothHost::impl::~impl()
483 {
484     HILOGI("starts");
485     BluetoothProfileManager::GetInstance().DeregisterFunc(profileRegisterId);
486     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
487     CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is nullptr");
488     proxy->DeregisterObserver(observerImp_);
489     proxy->DeregisterBleAdapterObserver(bleObserverImp_);
490     proxy->DeregisterRemoteDeviceObserver(remoteObserverImp_);
491     proxy->DeregisterBlePeripheralCallback(bleRemoteObserverImp_);
492     proxy->DeregisterBtResourceManagerObserver(resourceManagerObserverImp_);
493 }
494 
LoadBluetoothHostService()495 bool BluetoothHost::impl::LoadBluetoothHostService()
496 {
497     std::unique_lock<std::mutex> lock(proxyMutex_);
498     auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
499     if (samgrProxy == nullptr) {
500         HILOGE("samgrProxy is nullptr.");
501         return false;
502     }
503     sptr<IRemoteObject> hostRemote = BluetoothProfileManager::GetInstance().GetProfileRemote(BLUETOOTH_HOST);
504     //当蓝牙服务已经起来的时候。这时的hostRemote不为空, 不需要进行后续的从sa拉起蓝牙服务的动作
505     if (hostRemote != nullptr) {
506         return true;
507     }
508 
509     sptr<BluetoothHostLoadCallBack> loadCallback = new BluetoothHostLoadCallBack();
510     if (loadCallback == nullptr) {
511         HILOGE("loadCallback is nullptr.");
512         return false;
513     }
514     int32_t ret = samgrProxy->LoadSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID, loadCallback);
515     if (ret != ERR_OK) {
516         HILOGE("Failed to load bluetooth systemAbility");
517         return false;
518     }
519     auto waitStatus = proxyConVar_.wait_for(
520         lock, std::chrono::milliseconds(LOAD_SA_TIMEOUT_MS), [this]() {
521             HILOGI("bluetooth_service load systemAbility finished");
522             sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
523             return proxy != nullptr || saManagerStatus_ == SaManagerStatus::LOAD_FAIL;
524         });
525     if (!waitStatus) {
526         HILOGE("load bluetooth systemAbility timeout");
527         return false;
528     }
529     if (saManagerStatus_ == SaManagerStatus::LOAD_FAIL) {
530         HILOGE("load bluetooth_service fail");
531         saManagerStatus_ = SaManagerStatus::WAIT_NOTIFY;
532         return false;
533     }
534     saManagerStatus_ = SaManagerStatus::WAIT_NOTIFY;
535     return true;
536 }
537 
LoadSystemAbilitySuccess(const sptr<IRemoteObject> &remoteObject)538 void BluetoothHost::impl::LoadSystemAbilitySuccess(const sptr<IRemoteObject> &remoteObject)
539 {
540     HILOGI("LoadSystemAbilitySuccess FinishStart SA");
541     saManagerStatus_ = SaManagerStatus::LOAD_SUCCESS;
542     proxyConVar_.notify_one();
543 }
544 
LoadSystemAbilityFail()545 void BluetoothHost::impl::LoadSystemAbilityFail()
546 {
547     HILOGI("LoadSystemAbilityFail FinishStart SA");
548     saManagerStatus_ = SaManagerStatus::LOAD_FAIL;
549     proxyConVar_.notify_one();
550 }
551 
SyncRandomAddrToService(void)552 void BluetoothHost::impl::SyncRandomAddrToService(void)
553 {
554     if (!IsValidBluetoothAddr(stagingRealAddr_)) {
555         HILOGD("stagingRealAddr_ is invalid.");
556         return;
557     }
558     if (!IsValidBluetoothAddr(stagingRandomAddr_)) {
559         HILOGE("stagingRandomAddr_ is invalid.");
560         return;
561     }
562     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
563     CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is nullptr");
564     proxy->SyncRandomAddress(stagingRealAddr_, stagingRandomAddr_);
565     stagingRealAddr_ = "";
566     stagingRandomAddr_ = "";
567 }
568 
BluetoothHost()569 BluetoothHost::BluetoothHost()
570 {
571     pimpl = std::make_unique<impl>();
572     if (!pimpl) {
573         HILOGE("fails: no pimpl");
574     }
575 }
576 
~BluetoothHost()577 BluetoothHost::~BluetoothHost() {}
578 
GetDefaultHost()579 BluetoothHost &BluetoothHost::GetDefaultHost()
580 {
581 #ifdef DTFUZZ_TEST
582     static BluetoothNoDestructor<BluetoothHost> instance;
583     return *instance;
584 #else
585     // C++11 static local variable initialization is thread-safe.
586     static BluetoothHost hostAdapter;
587     return hostAdapter;
588 #endif
589 }
590 
RegisterObserver(std::shared_ptr<BluetoothHostObserver> observer)591 void BluetoothHost::RegisterObserver(std::shared_ptr<BluetoothHostObserver> observer)
592 {
593     HILOGD("enter");
594     CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null.");
595     pimpl->observers_.Register(observer);
596 }
597 
DeregisterObserver(std::shared_ptr<BluetoothHostObserver> observer)598 void BluetoothHost::DeregisterObserver(std::shared_ptr<BluetoothHostObserver> observer)
599 {
600     HILOGD("enter");
601     CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null.");
602     pimpl->observers_.Deregister(observer);
603 }
604 
EnableBt()605 int BluetoothHost::EnableBt()
606 {
607     HILOGD("enter");
608     CHECK_AND_RETURN_LOG_RET(!IsBtProhibitedByEdm(), BT_ERR_PROHIBITED_BY_EDM, "bluetooth is prohibited");
609     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
610     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr");
611 
612     return proxy->EnableBt();
613 }
614 
DisableBt()615 int BluetoothHost::DisableBt()
616 {
617     HILOGI("enter");
618     std::lock_guard<std::mutex> lock(pimpl->switchModuleMutex_);
619     CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr");
620     return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH);
621 }
622 
PublishBtSwitchRestrictBluetoothEvent(void)623 static void PublishBtSwitchRestrictBluetoothEvent(void)
624 {
625     OHOS::AAFwk::Want want;
626     want.SetAction("usual.event.bluetooth.BT_SWITCH_RESTRICT_BLUETOOTH");
627 
628     OHOS::EventFwk::CommonEventData data;
629     data.SetWant(want);
630 
631     OHOS::EventFwk::CommonEventPublishInfo publishInfo;
632     publishInfo.SetSubscriberPermissions({"ohos.permission.ACCESS_BLUETOOTH"});
633     bool ret = OHOS::EventFwk::CommonEventManager::PublishCommonEvent(data, publishInfo);
634     if (!ret) {
635         HILOGE("Publish usual.event.bluetooth.BT_SWITCH_RESTRICT_BLUETOOTH event failed");
636         return;
637     }
638 }
639 
RestrictBluetooth()640 int BluetoothHost::RestrictBluetooth()
641 {
642     HILOGI("enter");
643     std::lock_guard<std::mutex> lock(pimpl->switchModuleMutex_);
644     PublishBtSwitchRestrictBluetoothEvent();
645     CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr");
646     int ret =  pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH);
647     if (ret != BT_NO_ERROR) {
648         return ret;
649     }
650     ret = pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE);
651     return ret;
652 }
653 
UpdateVirtualDevice(int32_t action, const std::string &address)654 void BluetoothHost::UpdateVirtualDevice(int32_t action, const std::string &address)
655 {
656     HILOGD("enter");
657     CHECK_AND_RETURN_LOG(IS_BT_ENABLED(), "bluetooth is off");
658     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
659     CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is nullptr");
660     proxy->UpdateVirtualDevice(action, address);
661 }
662 
SatelliteControl(int type, int state)663 int BluetoothHost::SatelliteControl(int type, int state)
664 {
665     HILOGI("type: %{public}d, state: %{public}d", type, state);
666     if (type == static_cast<int>(SATELLITE_CONTROL_MODE::ANTENNA)) {
667         CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
668     } else if (type == static_cast<int>(SATELLITE_CONTROL_MODE::BLUETOOTH_SWITCH)) {
669         pimpl->LoadBluetoothHostService();
670     } else {
671         HILOGE("Invalid control type: %{public}d", type);
672         return BT_ERR_INVALID_PARAM;
673     }
674 
675     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
676     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr");
677     return proxy->SatelliteControl(type, state);
678 }
679 
GetBtState() const680 int BluetoothHost::GetBtState() const
681 {
682     HILOGD("enter");
683     if (!IS_BT_ENABLED()) {
684         HILOGD("bluetooth is off.");
685         return BTStateID::STATE_TURN_OFF;
686     }
687     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
688     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BTStateID::STATE_TURN_OFF, "proxy is nullptr");
689 
690     int state = BTStateID::STATE_TURN_OFF;
691     proxy->GetBtState(state);
692     HILOGD("state: %{public}d", state);
693     return state;
694 }
695 
GetBtState(int &state) const696 int BluetoothHost::GetBtState(int &state) const
697 {
698     HILOGD("enter");
699     state = BTStateID::STATE_TURN_OFF;
700     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_NO_ERROR, "bluetooth is off.");
701 
702     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
703     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INVALID_STATE, "proxy is nullptr");
704 
705     int ret = proxy->GetBtState(state);
706     HILOGI("state: %{public}d", state);
707     return ret;
708 }
709 
EnableBluetoothAfterFactoryReset(void)710 int BluetoothHost::impl::EnableBluetoothAfterFactoryReset(void)
711 {
712     HILOGI("Attempt to enable bluetooth after factory reset");
713     isFactoryReseting_ = false;
714     SetParameter("persist.bluetooth.switch_enable", "2");  // 2 means bluetooth auto enter restricted mode
715     return BT_NO_ERROR;
716 }
717 
BluetoothFactoryReset()718 int BluetoothHost::BluetoothFactoryReset()
719 {
720     HILOGI("enter");
721     constexpr const char* BLUETOOTH_FACTORY_RESET_KEY = "persist.bluetooth.factoryreset";
722     int ret = SetParameter(BLUETOOTH_FACTORY_RESET_KEY, "true");
723     CHECK_AND_RETURN_LOG_RET(ret == 0, BT_ERR_INTERNAL_ERROR, "SetParameter failed");
724 
725     pimpl->isFactoryReseting_ = true;
726 
727     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
728     if (proxy == nullptr) {
729         return pimpl->EnableBluetoothAfterFactoryReset();
730     }
731     CHECK_AND_RETURN_LOG_RET(IS_BLE_ENABLED(), BT_NO_ERROR, "bluetooth is off.");
732     return proxy->BluetoothFactoryReset();
733 }
734 
IsValidBluetoothAddr(const std::string &addr)735 bool BluetoothHost::IsValidBluetoothAddr(const std::string &addr)
736 {
737 #if defined(IOS_PLATFORM)
738     const std::regex deviceIdRegex("^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$");
739     return regex_match(addr, deviceIdRegex);
740 #elif defined(ANDROID_PLATFORM)
741     const std::regex deviceIdRegex("^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$");
742     return regex_match(addr, deviceIdRegex);
743 #else
744     if (addr.length() != ADDRESS_LENGTH) {
745         HILOGD("invalid address len.");
746         return false;
747     }
748 
749     for (int i = 0; i < ADDRESS_LENGTH; i++) {
750         char c = addr[i];
751         switch (i % ADDRESS_SEPARATOR_UNIT) {
752             case 0:
753             case 1:
754                 if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
755                     break;
756                 }
757                 return false;
758             case ADDRESS_COLON_INDEX:
759             default:
760                 if (c == ':') {
761                     break;
762                 }
763                 return false;
764         }
765     }
766     return true;
767 #endif
768 }
769 
GetRemoteDevice(const std::string &addr, int transport) const770 BluetoothRemoteDevice BluetoothHost::GetRemoteDevice(const std::string &addr, int transport) const
771 {
772     BluetoothRemoteDevice remoteDevice(addr, transport);
773     return remoteDevice;
774 }
775 
EnableBle()776 int BluetoothHost::EnableBle()
777 {
778     HILOGI("enter");
779     std::lock_guard<std::mutex> lock(pimpl->switchModuleMutex_);
780     CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr");
781     return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH);
782 }
783 
DisableBle()784 int BluetoothHost::DisableBle()
785 {
786     HILOGD("enter");
787     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
788     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr");
789 
790     return proxy->DisableBle();
791 }
792 
EnableBluetoothToRestrictMode(void)793 int BluetoothHost::EnableBluetoothToRestrictMode(void)
794 {
795     HILOGI("enter");
796     std::lock_guard<std::mutex> lock(pimpl->switchModuleMutex_);
797     CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr");
798     return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE);
799 }
800 
IsBrEnabled() const801 bool BluetoothHost::IsBrEnabled() const
802 {
803     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
804     if (proxy == nullptr) {
805         HILOGD("proxy is nullptr");
806         return false;
807     }
808 
809     return proxy->IsBrEnabled();
810 }
811 
IsBleEnabled() const812 bool BluetoothHost::IsBleEnabled() const
813 {
814     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
815     if (proxy == nullptr) {
816         HILOGD("proxy is nullptr");
817         return false;
818     }
819 
820     return proxy->IsBleEnabled();
821 }
822 
GetLocalAddress(std::string &addr) const823 int BluetoothHost::GetLocalAddress(std::string &addr) const
824 {
825     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
826     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "failed: no proxy");
827 
828     return proxy->GetLocalAddress(addr);
829 }
830 
GetProfileList() const831 std::vector<uint32_t> BluetoothHost::GetProfileList() const
832 {
833     HILOGD("enter");
834     std::vector<uint32_t> profileList;
835     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
836     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, profileList, "proxy is nullptr");
837 
838     profileList = proxy->GetProfileList();
839     return profileList;
840 }
841 
GetMaxNumConnectedAudioDevices() const842 int BluetoothHost::GetMaxNumConnectedAudioDevices() const
843 {
844     HILOGD("enter");
845     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
846     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, INVALID_VALUE, "proxy is nullptr");
847 
848     return proxy->GetMaxNumConnectedAudioDevices();
849 }
850 
GetBtConnectionState() const851 int BluetoothHost::GetBtConnectionState() const
852 {
853     HILOGD("enter");
854     int state = static_cast<int>(BTConnectState::DISCONNECTED);
855     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), state, "bluetooth is off.");
856 
857     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
858     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, state, "proxy is nullptr");
859 
860     proxy->GetBtConnectionState(state);
861     HILOGI("state: %{public}d", state);
862     return state;
863 }
864 
GetBtConnectionState(int &state) const865 int BluetoothHost::GetBtConnectionState(int &state) const
866 {
867     HILOGD("enter");
868     state = static_cast<int>(BTConnectState::DISCONNECTED);
869     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
870 
871     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
872     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr");
873 
874     int ret = proxy->GetBtConnectionState(state);
875     HILOGI("state: %{public}d", state);
876     return ret;
877 }
878 
GetBtProfileConnState(uint32_t profileId, int &state) const879 int BluetoothHost::GetBtProfileConnState(uint32_t profileId, int &state) const
880 {
881     HILOGI("profileId: %{public}d", profileId);
882     state = static_cast<int>(BTConnectState::DISCONNECTED);
883     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
884 
885     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
886     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr");
887 
888     return proxy->GetBtProfileConnState(profileId, state);
889 }
890 
GetLocalSupportedUuids(std::vector<ParcelUuid> &uuids)891 void BluetoothHost::GetLocalSupportedUuids(std::vector<ParcelUuid> &uuids)
892 {
893     HILOGD("enter");
894     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
895     CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is nullptr");
896 
897     std::vector<std::string> stringUuids;
898     proxy->GetLocalSupportedUuids(stringUuids);
899 
900     for (auto uuid : stringUuids) {
901         uuids.push_back(UUID::FromString(uuid));
902     }
903 }
904 
Start()905 bool BluetoothHost::Start()
906 {
907     // / This function only used for passthrough, so this is empty.
908     return true;
909 }
910 
Stop()911 void BluetoothHost::Stop()
912 {
913     // / This function only used for passthrough, so this is empty.
914 }
915 
GetLocalDeviceClass() const916 BluetoothDeviceClass BluetoothHost::GetLocalDeviceClass() const
917 {
918     HILOGD("enter");
919     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
920     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BluetoothDeviceClass(0), "proxy is nullptr");
921 
922     int LocalDeviceClass = proxy->GetLocalDeviceClass();
923     return BluetoothDeviceClass(LocalDeviceClass);
924 }
925 
SetLocalDeviceClass(const BluetoothDeviceClass &deviceClass)926 bool BluetoothHost::SetLocalDeviceClass(const BluetoothDeviceClass &deviceClass)
927 {
928     HILOGD("enter");
929     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
930     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, false, "proxy is nullptr");
931 
932     int cod = deviceClass.GetClassOfDevice();
933     return proxy->SetLocalDeviceClass(cod);
934 }
935 
GetLocalName() const936 std::string BluetoothHost::GetLocalName() const
937 {
938     HILOGD("enter");
939     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
940     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, std::string(), "proxy is nullptr");
941 
942     std::string name = INVALID_NAME;
943     proxy->GetLocalName(name);
944     return name;
945 }
946 
GetLocalName(std::string &name) const947 int BluetoothHost::GetLocalName(std::string &name) const
948 {
949     HILOGD("enter");
950     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
951     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr");
952 
953     return proxy->GetLocalName(name);
954 }
955 
SetLocalName(const std::string &name)956 int BluetoothHost::SetLocalName(const std::string &name)
957 {
958     HILOGD("enter");
959     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
960 
961     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
962     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr");
963 
964     return proxy->SetLocalName(name);
965 }
966 
GetBtScanMode(int32_t &scanMode) const967 int BluetoothHost::GetBtScanMode(int32_t &scanMode) const
968 {
969     HILOGD("enter");
970     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
971 
972     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
973     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr");
974 
975     return proxy->GetBtScanMode(scanMode);
976 }
977 
SetBtScanMode(int mode, int duration)978 int BluetoothHost::SetBtScanMode(int mode, int duration)
979 {
980     HILOGD("mode: %{public}d, duration: %{public}d", mode, duration);
981     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
982 
983     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
984     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr");
985 
986     return proxy->SetBtScanMode(mode, duration);
987 }
988 
GetBondableMode(int transport) const989 int BluetoothHost::GetBondableMode(int transport) const
990 {
991     HILOGI("transport: %{public}d", transport);
992     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
993     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, INVALID_VALUE, "proxy is nullptr");
994 
995     return proxy->GetBondableMode(transport);
996 }
997 
SetBondableMode(int transport, int mode)998 bool BluetoothHost::SetBondableMode(int transport, int mode)
999 {
1000     HILOGD("transport: %{public}d, mode: %{public}d", transport, mode);
1001     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1002     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, false, "proxy is nullptr");
1003 
1004     return proxy->SetBondableMode(transport, mode);
1005 }
1006 
StartBtDiscovery()1007 int BluetoothHost::StartBtDiscovery()
1008 {
1009     HILOGD("enter");
1010     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
1011 
1012     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1013     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr");
1014 
1015     return proxy->StartBtDiscovery();
1016 }
1017 
CancelBtDiscovery()1018 int BluetoothHost::CancelBtDiscovery()
1019 {
1020     HILOGD("enter");
1021     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
1022 
1023     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1024     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr");
1025 
1026     return proxy->CancelBtDiscovery();
1027 }
1028 
IsBtDiscovering(bool &isDiscovering, int transport) const1029 int32_t BluetoothHost::IsBtDiscovering(bool &isDiscovering, int transport) const
1030 {
1031     HILOGI("transport: %{public}d", transport);
1032     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
1033 
1034     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1035     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INVALID_STATE, "proxy is nullptr");
1036 
1037     return proxy->IsBtDiscovering(isDiscovering, transport);
1038 }
1039 
GetBtDiscoveryEndMillis() const1040 long BluetoothHost::GetBtDiscoveryEndMillis() const
1041 {
1042     HILOGD("enter");
1043     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), 0, "bluetooth is off.");
1044 
1045     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1046     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, 0, "proxy is nullptr");
1047 
1048     return proxy->GetBtDiscoveryEndMillis();
1049 }
1050 
GetPairedDevices(int transport, std::vector<BluetoothRemoteDevice> &pairedDevices) const1051 int32_t BluetoothHost::GetPairedDevices(int transport, std::vector<BluetoothRemoteDevice> &pairedDevices) const
1052 {
1053     HILOGI("transport: %{public}d", transport);
1054     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
1055 
1056     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1057     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr");
1058 
1059     std::vector<BluetoothRawAddress> pairedAddr;
1060     int32_t ret = proxy->GetPairedDevices(pairedAddr);
1061 
1062     for (auto it = pairedAddr.begin(); it != pairedAddr.end(); it++) {
1063         BluetoothRemoteDevice device((*it).GetAddress(), transport);
1064         pairedDevices.emplace_back(device);
1065     }
1066     return ret;
1067 }
1068 
RemovePair(const BluetoothRemoteDevice &device)1069 int32_t BluetoothHost::RemovePair(const BluetoothRemoteDevice &device)
1070 {
1071     HILOGI("device: %{public}s", GET_ENCRYPT_ADDR(device));
1072     CHECK_AND_RETURN_LOG_RET(device.IsValidBluetoothRemoteDevice(), BT_ERR_INTERNAL_ERROR, "Invalid remote device.");
1073 
1074     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1075     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr");
1076 
1077     sptr<BluetoothRawAddress> rawAddrSptr = new BluetoothRawAddress(device.GetDeviceAddr());
1078     return proxy->RemovePair(device.GetTransportType(), rawAddrSptr);
1079 }
1080 
RemoveAllPairs()1081 bool BluetoothHost::RemoveAllPairs()
1082 {
1083     HILOGD("enter");
1084     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1085     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, false, "proxy is nullptr");
1086 
1087     return proxy->RemoveAllPairs();
1088 }
1089 
RegisterRemoteDeviceObserver(std::shared_ptr<BluetoothRemoteDeviceObserver> observer)1090 void BluetoothHost::RegisterRemoteDeviceObserver(std::shared_ptr<BluetoothRemoteDeviceObserver> observer)
1091 {
1092     HILOGD("enter");
1093     CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null.");
1094 
1095     pimpl->remoteObservers_.Register(observer);
1096 }
1097 
DeregisterRemoteDeviceObserver(std::shared_ptr<BluetoothRemoteDeviceObserver> observer)1098 void BluetoothHost::DeregisterRemoteDeviceObserver(std::shared_ptr<BluetoothRemoteDeviceObserver> observer)
1099 {
1100     HILOGD("enter");
1101     CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null.");
1102 
1103     pimpl->remoteObservers_.Deregister(observer);
1104 }
1105 
GetBleMaxAdvertisingDataLength() const1106 int BluetoothHost::GetBleMaxAdvertisingDataLength() const
1107 {
1108     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1109     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, INVALID_VALUE, "proxy is nullptr");
1110 
1111     return proxy->GetBleMaxAdvertisingDataLength();
1112 }
1113 
LoadSystemAbilitySuccess(const sptr<IRemoteObject> &remoteObject)1114 void BluetoothHost::LoadSystemAbilitySuccess(const sptr<IRemoteObject> &remoteObject)
1115 {
1116     CHECK_AND_RETURN_LOG(pimpl, "pimpl is null.");
1117 
1118     pimpl->LoadSystemAbilitySuccess(remoteObject);
1119 }
1120 
LoadSystemAbilityFail()1121 void BluetoothHost::LoadSystemAbilityFail()
1122 {
1123     CHECK_AND_RETURN_LOG(pimpl, "pimpl is null.");
1124 
1125     pimpl->LoadSystemAbilityFail();
1126 }
1127 
GetLocalProfileUuids(std::vector<std::string> &uuids)1128 int32_t BluetoothHost::GetLocalProfileUuids(std::vector<std::string> &uuids)
1129 {
1130     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INTERNAL_ERROR, "bluetooth is off.");
1131 
1132     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1133     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr");
1134 
1135     return proxy->GetLocalProfileUuids(uuids);
1136 }
1137 
SetFastScan(bool isEnable)1138 int BluetoothHost::SetFastScan(bool isEnable)
1139 {
1140     HILOGI("isEnable: %{public}d", isEnable);
1141     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
1142 
1143     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1144     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "proxy is nullptr");
1145 
1146     return proxy->SetFastScan(isEnable);
1147 }
1148 
GetRandomAddress(const std::string &realAddr, std::string &randomAddr) const1149 int BluetoothHost::GetRandomAddress(const std::string &realAddr, std::string &randomAddr) const
1150 {
1151     randomAddr = realAddr;
1152     return BT_NO_ERROR;
1153 }
1154 
ConnectAllowedProfiles(const std::string &remoteAddr) const1155 int BluetoothHost::ConnectAllowedProfiles(const std::string &remoteAddr) const
1156 {
1157     HILOGI("enter");
1158     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
1159 
1160     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1161     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "pimpl or bluetooth host is nullptr");
1162 
1163     return proxy->ConnectAllowedProfiles(remoteAddr);
1164 }
1165 
DisconnectAllowedProfiles(const std::string &remoteAddr) const1166 int BluetoothHost::DisconnectAllowedProfiles(const std::string &remoteAddr) const
1167 {
1168     HILOGI("enter");
1169     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
1170 
1171     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1172     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "pimpl or bluetooth host is nullptr");
1173 
1174     return proxy->DisconnectAllowedProfiles(remoteAddr);
1175 }
1176 
RegisterBtResourceManagerObserver(std::shared_ptr<BluetoothResourceManagerObserver> observer)1177 void BluetoothHost::RegisterBtResourceManagerObserver(std::shared_ptr<BluetoothResourceManagerObserver> observer)
1178 {
1179     CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null.");
1180 
1181     pimpl->resourceManagerObservers_.Register(observer);
1182 }
1183 
DeregisterBtResourceManagerObserver(std::shared_ptr<BluetoothResourceManagerObserver> observer)1184 void BluetoothHost::DeregisterBtResourceManagerObserver(std::shared_ptr<BluetoothResourceManagerObserver> observer)
1185 {
1186     CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null.");
1187 
1188     pimpl->resourceManagerObservers_.Deregister(observer);
1189 }
1190 
SetFastScanLevel(int level)1191 int BluetoothHost::SetFastScanLevel(int level)
1192 {
1193     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
1194     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1195     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "pimpl or bluetooth host is nullptr");
1196     return proxy->SetFastScanLevel(level);
1197 }
1198 
IsBtProhibitedByEdm(void)1199 bool BluetoothHost::IsBtProhibitedByEdm(void)
1200 {
1201     constexpr const char* BLUETOOTH_EDM_KEY = "persist.edm.prohibit_bluetooth";
1202     constexpr const uint32_t PARAM_TRUE_LEN = 4; // "true" 4bytes
1203     constexpr const uint32_t PARAM_FALSE_LEN = 5; // "false" 5bytes
1204     constexpr const char* PARAM_TRUE = "true";
1205     constexpr const char* PARAM_FALSE = "false";
1206 
1207     char result[PARAM_FALSE_LEN + 1] = {0};
1208     //  Returns the number of bytes of the system parameter if the operation is successful.
1209     int len = GetParameter(BLUETOOTH_EDM_KEY, PARAM_FALSE, result, PARAM_FALSE_LEN + 1);
1210     CHECK_AND_RETURN_LOG_RET(len == PARAM_FALSE_LEN || len == PARAM_TRUE_LEN, false, "GetParameter len is invalid.");
1211 
1212     if (strncmp(result, PARAM_TRUE, PARAM_TRUE_LEN) == 0) {
1213         HILOGW("bluetooth is prohibited by EDM. You won't be able to turn on bluetooth !");
1214         return true;
1215     }
1216     return false;
1217 }
1218 
IsBluetoothSystemAbilityOn(void)1219 static bool IsBluetoothSystemAbilityOn(void)
1220 {
1221     auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1222     CHECK_AND_RETURN_LOG_RET(samgrProxy != nullptr, false, "samgrProxy is nullptr");
1223     auto object = samgrProxy->CheckSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID);
1224     return object != nullptr;
1225 }
1226 
OnRemoveBluetoothSystemAbility()1227 void BluetoothHost::OnRemoveBluetoothSystemAbility()
1228 {
1229     // Notify the upper layer that bluetooth is disabled.
1230     bool isBluetoothSystemAbilityOn = IsBluetoothSystemAbilityOn();
1231     if (isBluetoothSystemAbilityOn) {
1232         HILOGW("Bluetooth SA is started, the hap application may be freezed by rss");
1233     }
1234     bool isNeedNotifyBluetoothOffState = pimpl->observerImp_ && pimpl->bleObserverImp_ && !isBluetoothSystemAbilityOn;
1235     if (isNeedNotifyBluetoothOffState) {
1236         HILOGD("bluetooth_servi died and send state off to app");
1237         pimpl->observerImp_->OnStateChanged(BTTransport::ADAPTER_BREDR, BTStateID::STATE_TURN_OFF);
1238         pimpl->bleObserverImp_->OnStateChanged(BTTransport::ADAPTER_BLE, BTStateID::STATE_TURN_OFF);
1239     }
1240     if (pimpl->isFactoryReseting_.load()) {
1241         pimpl->EnableBluetoothAfterFactoryReset();
1242     }
1243     std::lock_guard<std::mutex> lock(pimpl->switchModuleMutex_);
1244     if (pimpl->switchModule_) {
1245         pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::BLUETOOTH_OFF);
1246     }
1247 }
1248 
Close(void)1249 void BluetoothHost::Close(void)
1250 {
1251     std::lock_guard<std::mutex> lock(pimpl->switchModuleMutex_);
1252     pimpl->switchModule_ = nullptr;
1253 }
1254 } // namespace Bluetooth
1255 } // namespace OHOS
1256