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 #ifndef LOG_TAG
16 #define LOG_TAG "bt_fwk_host"
17 #endif
18 
19 #include "bluetooth_host.h"
20 #include <memory>
21 #include <mutex>
22 #include <unistd.h>
23 #include <thread>
24 #include "bluetooth_ble_peripheral_observer_stub.h"
25 #include "bluetooth_host_load_callback.h"
26 #include "bluetooth_host_observer_stub.h"
27 #include "bluetooth_host_proxy.h"
28 #include "bluetooth_profile_manager.h"
29 #include "bluetooth_log.h"
30 #include "bluetooth_utils.h"
31 #include "bluetooth_observer_list.h"
32 #include "bluetooth_remote_device_observer_stub.h"
33 #include "bluetooth_resource_manager_observer_stub.h"
34 #include "iservice_registry.h"
35 #include "parameter.h"
36 #include "system_ability_definition.h"
37 #include "bluetooth_switch_module.h"
38 #include "ffrt_inner.h"
39 #include "common_event.h"
40 #include "common_event_data.h"
41 #include "common_event_manager.h"
42 
43 using namespace OHOS::EventFwk;
44 
45 namespace OHOS {
46 namespace Bluetooth {
47 namespace {
48 constexpr int32_t LOAD_SA_TIMEOUT_MS = 4000;
49 }
50 
51 struct BluetoothHost::impl {
52     impl();
53     ~impl();
54 
55     bool LoadBluetoothHostService();
56     void LoadSystemAbilitySuccess(const sptr<IRemoteObject> &remoteObject);
57     void LoadSystemAbilityFail();
58     int EnableBluetoothAfterFactoryReset(void);
59 
60     // host observer
61     class BluetoothHostObserverImp;
62     sptr<BluetoothHostObserverImp> observerImp_ = nullptr;
63     sptr<BluetoothHostObserverImp> bleObserverImp_ = nullptr;
64 
65     // remote device observer
66     class BluetoothRemoteDeviceObserverImp;
67     sptr<BluetoothRemoteDeviceObserverImp> remoteObserverImp_ = nullptr;
68 
69     // remote device observer
70     class BluetoothBlePeripheralCallbackImp;
71     sptr<BluetoothBlePeripheralCallbackImp> bleRemoteObserverImp_ = nullptr;
72 
73     // bluetooth resource manager observer
74     class BluetoothResourceManagerObserverImp;
75     sptr<BluetoothResourceManagerObserverImp> resourceManagerObserverImp_ = nullptr;
76 
77     // user regist observers
78     BluetoothObserverList<BluetoothHostObserver> observers_;
79 
80     // user regist remote observers
81     BluetoothObserverList<BluetoothRemoteDeviceObserver> remoteObservers_;
82 
83     // user regist resource manager observers
84     BluetoothObserverList<BluetoothResourceManagerObserver> resourceManagerObservers_;
85 
86     void SyncRandomAddrToService(void);
87     int ConvertBluetoothStateToBtStateID(BluetoothState state);
88 
89     std::mutex proxyMutex_;
90     std::string stagingRealAddr_;
91     std::string stagingRandomAddr_;
92     int32_t profileRegisterId = 0;
93     std::atomic_bool isFactoryReseting_ { false };
94 
95     class BluetoothSwitchAction;
96     std::mutex switchModuleMutex_ {};  // used for serial execute enableBluetoothToRestrictMode.
97     std::shared_ptr<BluetoothSwitchModule> switchModule_ { nullptr };
98 
99 private:
100     SaManagerStatus saManagerStatus_ = SaManagerStatus::WAIT_NOTIFY;
101     std::condition_variable proxyConVar_;
102 };
103 
104 class BluetoothHost::impl::BluetoothHostObserverImp : public BluetoothHostObserverStub {
105 public:
BluetoothHostObserverImp(BluetoothHost::impl & host)106     explicit BluetoothHostObserverImp(BluetoothHost::impl &host) : host_(host){};
~BluetoothHostObserverImp()107     ~BluetoothHostObserverImp() override{};
108 
Register(std::shared_ptr<BluetoothHostObserver> & observer)109     void Register(std::shared_ptr<BluetoothHostObserver> &observer)
110     {
111         host_.observers_.Register(observer);
112     }
113 
Deregister(std::shared_ptr<BluetoothHostObserver> & observer)114     void Deregister(std::shared_ptr<BluetoothHostObserver> &observer)
115     {
116         host_.observers_.Deregister(observer);
117     }
118 
OnStateChanged(int32_t transport,int32_t status)119     void OnStateChanged(int32_t transport, int32_t status) override
120     {
121         if (status == BTStateID::STATE_TURN_ON) {
122             host_.SyncRandomAddrToService();
123         }
124         CHECK_AND_RETURN_LOG(!isNeedInterceptSwitchStatus(transport, status), "No Need transform same status");
125         BluetoothProfileManager::GetInstance().NotifyBluetoothStateChange(transport, status);
126         host_.observers_.ForEach([transport, status](std::shared_ptr<BluetoothHostObserver> observer) {
127             observer->OnStateChanged(transport, status);
128         });
129     }
130 
OnBluetoothStateChanged(int32_t state)131     void OnBluetoothStateChanged(int32_t state) override
132     {
133         std::lock_guard<std::mutex> lock(host_.switchModuleMutex_);
134         CHECK_AND_RETURN_LOG(host_.switchModule_, "switchModule is nullptr");
135         if (state == bluetooth::BluetoothSwitchState::STATE_ON) {
136             host_.switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::BLUETOOTH_ON);
137         }
138         if (state == bluetooth::BluetoothSwitchState::STATE_OFF) {
139             host_.switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::BLUETOOTH_OFF);
140         }
141         if (state == bluetooth::BluetoothSwitchState::STATE_HALF) {
142             host_.switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::BLUETOOTH_HALF);
143         }
144     }
145 
OnDiscoveryStateChanged(int32_t status)146     void OnDiscoveryStateChanged(int32_t status) override
147     {
148         HILOGD("enter, status: %{public}d", status);
149         host_.observers_.ForEach(
150             [status](std::shared_ptr<BluetoothHostObserver> observer) { observer->OnDiscoveryStateChanged(status); });
151     }
152 
OnDiscoveryResult(const BluetoothRawAddress & device,int rssi,const std::string deviceName,int deviceClass)153     void OnDiscoveryResult(
154         const BluetoothRawAddress &device, int rssi, const std::string deviceName, int deviceClass) override
155     {
156         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
157         host_.observers_.ForEach([remoteDevice, rssi, deviceName, deviceClass](
158             std::shared_ptr<BluetoothHostObserver> observer) {
159             observer->OnDiscoveryResult(remoteDevice, rssi, deviceName, deviceClass);
160         });
161     }
162 
OnPairRequested(const int32_t transport,const BluetoothRawAddress & device)163     void OnPairRequested(const int32_t transport, const BluetoothRawAddress &device) override
164     {
165         HILOGI("enter, transport: %{public}d, device: %{public}s",
166             transport, GET_ENCRYPT_RAW_ADDR(device));
167         BluetoothRemoteDevice remoteDevice(device.GetAddress(), transport);
168         host_.observers_.ForEach([remoteDevice](std::shared_ptr<BluetoothHostObserver> observer) {
169             observer->OnPairRequested(remoteDevice);
170         });
171     }
172 
OnPairConfirmed(const int32_t transport,const BluetoothRawAddress & device,int reqType,int number)173     void OnPairConfirmed(const int32_t transport, const BluetoothRawAddress &device, int reqType, int number) override
174     {
175         HILOGI("enter, transport: %{public}d, device: %{public}s, reqType: %{public}d, number: %{public}d",
176             transport, GET_ENCRYPT_RAW_ADDR(device), reqType, number);
177         BluetoothRemoteDevice remoteDevice(device.GetAddress(), transport);
178         host_.observers_.ForEach([remoteDevice, reqType, number](std::shared_ptr<BluetoothHostObserver> observer) {
179             observer->OnPairConfirmed(remoteDevice, reqType, number);
180         });
181     }
182 
OnScanModeChanged(int mode)183     void OnScanModeChanged(int mode) override
184     {
185         HILOGI("enter, mode: %{public}d", mode);
186         host_.observers_.ForEach(
187             [mode](std::shared_ptr<BluetoothHostObserver> observer) { observer->OnScanModeChanged(mode); });
188     }
189 
OnDeviceNameChanged(const std::string & deviceName)190     void OnDeviceNameChanged(const std::string &deviceName) override
191     {
192         HILOGI("enter, deviceName: %{public}s", deviceName.c_str());
193         host_.observers_.ForEach([deviceName](std::shared_ptr<BluetoothHostObserver> observer) {
194             observer->OnDeviceNameChanged(deviceName);
195         });
196     }
197 
OnDeviceAddrChanged(const std::string & address)198     void OnDeviceAddrChanged(const std::string &address) override
199     {
200         HILOGD("enter");
201         host_.observers_.ForEach(
202             [address](std::shared_ptr<BluetoothHostObserver> observer) { observer->OnDeviceAddrChanged(address); });
203     }
204 
205 private:
isNeedInterceptSwitchStatus(int32_t transport,int32_t status)206     bool isNeedInterceptSwitchStatus(int32_t transport, int32_t status)
207     {
208         bool isBluetoothSeriviceOn = BluetoothProfileManager::GetInstance().IsBluetoothServiceOn();
209         if (status == BTStateID::STATE_TURN_OFF) {
210             if (transport == BTTransport::ADAPTER_BLE &&
211                 preBleState_ == BTStateID::STATE_TURN_OFF && !isBluetoothSeriviceOn) {
212                 return true;
213             }
214             if (transport == BTTransport::ADAPTER_BREDR &&
215                 preBrState_ == BTStateID::STATE_TURN_OFF && !isBluetoothSeriviceOn) {
216                 return true;
217             }
218         }
219         if (transport == BTTransport::ADAPTER_BREDR) {
220             preBrState_ = status;
221         } else {
222             preBleState_ = status;
223         }
224         return false;
225     }
226     BluetoothHost::impl &host_;
227     const int32_t INVALID_STATE = -1;
228     int32_t preBrState_ = INVALID_STATE;
229     int32_t preBleState_ = INVALID_STATE;
230     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothHostObserverImp);
231 };
232 
233 class BluetoothHost::impl::BluetoothRemoteDeviceObserverImp : public BluetoothRemoteDeviceObserverstub {
234 public:
BluetoothRemoteDeviceObserverImp(BluetoothHost::impl & host)235     explicit BluetoothRemoteDeviceObserverImp(BluetoothHost::impl &host) : host_(host){};
236     ~BluetoothRemoteDeviceObserverImp() override = default;
237 
OnAclStateChanged(const BluetoothRawAddress & device,int32_t state,uint32_t reason)238     void OnAclStateChanged(const BluetoothRawAddress &device, int32_t state, uint32_t reason) override
239     {
240         HILOGD("enter, device: %{public}s, state: %{public}d, reason: %{public}u",
241             GET_ENCRYPT_RAW_ADDR(device), state, reason);
242         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
243         host_.remoteObservers_.ForEach(
244             [remoteDevice, state, reason](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
245                 observer->OnAclStateChanged(remoteDevice, state, reason);
246             });
247     }
248 
OnPairStatusChanged(const int32_t transport,const BluetoothRawAddress & device,int32_t status,int32_t cause)249     void OnPairStatusChanged(const int32_t transport, const BluetoothRawAddress &device,
250         int32_t status, int32_t cause) override
251     {
252         HILOGD("enter, transport: %{public}d, device: %{public}s, status: %{public}d, cause: %{public}d",
253             transport, GET_ENCRYPT_RAW_ADDR(device), status, cause);
254         BluetoothRemoteDevice remoteDevice(device.GetAddress(), transport);
255         host_.remoteObservers_.ForEach(
256             [remoteDevice, status, cause](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
257                 observer->OnPairStatusChanged(remoteDevice, status, cause);
258             });
259     }
260 
OnRemoteUuidChanged(const BluetoothRawAddress & device,const std::vector<bluetooth::Uuid> uuids)261     void OnRemoteUuidChanged(const BluetoothRawAddress &device, const std::vector<bluetooth::Uuid> uuids) override
262     {
263         HILOGD("enter, device: %{public}s", GET_ENCRYPT_RAW_ADDR(device));
264         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
265         host_.remoteObservers_.ForEach(
266             [remoteDevice, uuids](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
267                 std::vector<ParcelUuid> parcelUuids;
268                 for (auto &uuid : uuids) {
269                     ParcelUuid parcelUuid = UUID::ConvertFrom128Bits(uuid.ConvertTo128Bits());
270                     parcelUuids.push_back(parcelUuid);
271                 }
272                 observer->OnRemoteUuidChanged(remoteDevice, parcelUuids);
273             });
274     }
275 
OnRemoteNameChanged(const BluetoothRawAddress & device,const std::string deviceName)276     void OnRemoteNameChanged(const BluetoothRawAddress &device, const std::string deviceName) override
277     {
278         HILOGD("enter, device: %{public}s, deviceName: %{public}s",
279             GET_ENCRYPT_RAW_ADDR(device), deviceName.c_str());
280         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
281         host_.remoteObservers_.ForEach(
282             [remoteDevice, deviceName](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
283                 observer->OnRemoteNameChanged(remoteDevice, deviceName);
284             });
285     }
286 
OnRemoteAliasChanged(const BluetoothRawAddress & device,const std::string alias)287     void OnRemoteAliasChanged(const BluetoothRawAddress &device, const std::string alias) override
288     {
289         HILOGI("enter, device: %{public}s, alias: %{public}s",
290             GET_ENCRYPT_RAW_ADDR(device), alias.c_str());
291         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
292         host_.remoteObservers_.ForEach(
293             [remoteDevice, alias](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
294                 observer->OnRemoteAliasChanged(remoteDevice, alias);
295             });
296     }
297 
OnRemoteCodChanged(const BluetoothRawAddress & device,int32_t cod)298     void OnRemoteCodChanged(const BluetoothRawAddress &device, int32_t cod) override
299     {
300         HILOGD("enter, device: %{public}s, cod: %{public}d", GET_ENCRYPT_RAW_ADDR(device), cod);
301         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
302         BluetoothDeviceClass deviceClass(cod);
303         host_.remoteObservers_.ForEach(
304             [remoteDevice, deviceClass](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
305                 observer->OnRemoteCodChanged(remoteDevice, deviceClass);
306             });
307     }
308 
OnRemoteBatteryChanged(const BluetoothRawAddress & device,const BluetoothBatteryInfo & batteryInfo)309     void OnRemoteBatteryChanged(const BluetoothRawAddress &device, const BluetoothBatteryInfo &batteryInfo) override
310     {
311         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
312         DeviceBatteryInfo info;
313         info.deviceId_ = device.GetAddress();
314         info.batteryLevel_ = batteryInfo.batteryLevel_;
315         info.leftEarBatteryLevel_ = batteryInfo.leftEarBatteryLevel_;
316         info.leftEarChargeState_ = static_cast<DeviceChargeState>(batteryInfo.leftEarChargeState_);
317         info.rightEarBatteryLevel_ = batteryInfo.rightEarBatteryLevel_;
318         info.rightEarChargeState_ = static_cast<DeviceChargeState>(batteryInfo.rightEarChargeState_);
319         info.boxBatteryLevel_ = batteryInfo.boxBatteryLevel_;
320         info.boxChargeState_ = static_cast<DeviceChargeState>(batteryInfo.boxChargeState_);
321         host_.remoteObservers_.ForEach(
322             [remoteDevice, info](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
323                 observer->OnRemoteBatteryChanged(remoteDevice, info);
324             });
325     }
326 
OnRemoteDeviceCommonInfoReport(const BluetoothRawAddress & device,const std::vector<uint8_t> & value)327     void OnRemoteDeviceCommonInfoReport(const BluetoothRawAddress &device, const std::vector<uint8_t> &value) override
328     {
329         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BREDR);
330         host_.remoteObservers_.ForEach(
331             [remoteDevice, value](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
332                 observer->OnRemoteDeviceCommonInfoReport(remoteDevice, value);
333             });
334     }
335 
336 private:
337     BluetoothHost::impl &host_;
338     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothRemoteDeviceObserverImp);
339 };
340 
341 class BluetoothHost::impl::BluetoothBlePeripheralCallbackImp : public BluetoothBlePeripheralObserverStub {
342 public:
BluetoothBlePeripheralCallbackImp(BluetoothHost::impl & host)343     explicit BluetoothBlePeripheralCallbackImp(BluetoothHost::impl &host) : host_(host){};
344     ~BluetoothBlePeripheralCallbackImp() override = default;
345 
OnAclStateChanged(const BluetoothRawAddress & device,int state,unsigned int reason)346     void OnAclStateChanged(const BluetoothRawAddress &device, int state, unsigned int reason) override
347     {
348         HILOGD("enter, device: %{public}s, state: %{public}d, reason: %{public}u",
349             GET_ENCRYPT_RAW_ADDR(device), state, reason);
350         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BLE);
351         host_.remoteObservers_.ForEach(
352             [remoteDevice, state, reason](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
353                 observer->OnAclStateChanged(remoteDevice, state, reason);
354             });
355     }
356 
OnPairStatusChanged(const int32_t transport,const BluetoothRawAddress & device,int status,int cause)357     void OnPairStatusChanged(const int32_t transport, const BluetoothRawAddress &device, int status, int cause) override
358     {
359         HILOGI("enter, transport: %{public}d, device: %{public}s, status: %{public}d, cause: %{public}d",
360             transport, GET_ENCRYPT_RAW_ADDR(device), status, cause);
361         BluetoothRemoteDevice remoteDevice(device.GetAddress(), transport);
362         host_.remoteObservers_.ForEach(
363             [remoteDevice, status, cause](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
364                 observer->OnPairStatusChanged(remoteDevice, status, cause);
365             });
366     }
367 
OnReadRemoteRssiEvent(const BluetoothRawAddress & device,int rssi,int status)368     void OnReadRemoteRssiEvent(const BluetoothRawAddress &device, int rssi, int status) override
369     {
370         HILOGI("enter, device: %{public}s, rssi: %{public}d, status: %{public}d",
371             GET_ENCRYPT_RAW_ADDR(device), rssi, status);
372         BluetoothRemoteDevice remoteDevice(device.GetAddress(), BTTransport::ADAPTER_BLE);
373         host_.remoteObservers_.ForEach(
374             [remoteDevice, rssi, status](std::shared_ptr<BluetoothRemoteDeviceObserver> observer) {
375                 observer->OnReadRemoteRssiEvent(remoteDevice, rssi, status);
376             });
377     }
378 
379 private:
380     BluetoothHost::impl &host_;
381     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothBlePeripheralCallbackImp);
382 };
383 
384 class BluetoothHost::impl::BluetoothResourceManagerObserverImp : public BluetoothResourceManagerObserverStub {
385 public:
BluetoothResourceManagerObserverImp(BluetoothHost::impl & host)386     explicit BluetoothResourceManagerObserverImp(BluetoothHost::impl &host) : host_(host){};
387     ~BluetoothResourceManagerObserverImp() override = default;
388 
OnSensingStateChanged(uint8_t eventId,const BluetoothSensingInfo & info)389     void OnSensingStateChanged(uint8_t eventId, const BluetoothSensingInfo &info) override
390     {
391         HILOGD("enter, eventId: %{public}d", eventId);
392         SensingInfo sensingInfo;
393         sensingInfo.addr_ = info.addr_;
394         sensingInfo.uuid_ = info.uuid_;
395         sensingInfo.resourceId_ = info.resourceId_;
396         sensingInfo.pkgName_ = info.pkgName_;
397         sensingInfo.isServer_ = info.isServer_;
398         sensingInfo.interval_ = info.interval_;
399         host_.resourceManagerObservers_.ForEach(
400             [eventId, sensingInfo](std::shared_ptr<BluetoothResourceManagerObserver> observer) {
401                 observer->OnSensingStateChanged(eventId, sensingInfo);
402             });
403     }
404 
OnBluetoothResourceDecision(uint8_t eventId,const BluetoothSensingInfo & info,uint32_t & result)405     void OnBluetoothResourceDecision(uint8_t eventId, const BluetoothSensingInfo &info, uint32_t &result) override
406     {
407         HILOGD("enter, eventId: %{public}d, result: %{public}d", eventId, result);
408         SensingInfo sensingInfo;
409         sensingInfo.addr_ = info.addr_;
410         sensingInfo.uuid_ = info.uuid_;
411         sensingInfo.resourceId_ = info.resourceId_;
412         sensingInfo.pkgName_ = info.pkgName_;
413         sensingInfo.isServer_ = info.isServer_;
414         sensingInfo.interval_ = info.interval_;
415         host_.resourceManagerObservers_.ForEach(
416             [eventId, sensingInfo, &result](std::shared_ptr<BluetoothResourceManagerObserver> observer) {
417                 observer->OnBluetoothResourceDecision(eventId, sensingInfo, result);
418             });
419     }
420 
421 private:
422     BluetoothHost::impl &host_;
423     BLUETOOTH_DISALLOW_COPY_AND_ASSIGN(BluetoothResourceManagerObserverImp);
424 };
425 
426 class BluetoothHost::impl::BluetoothSwitchAction : public IBluetoothSwitchAction {
427 public:
428     BluetoothSwitchAction() = default;
429     ~BluetoothSwitchAction() override = default;
430 
EnableBluetooth(void)431     int EnableBluetooth(void) override
432     {
433         CHECK_AND_RETURN_LOG_RET(!BluetoothHost::GetDefaultHost().IsBtProhibitedByEdm(),
434             BT_ERR_PROHIBITED_BY_EDM, "bluetooth is prohibited !");
435         CHECK_AND_RETURN_LOG_RET(BluetoothHost::GetDefaultHost().pimpl->LoadBluetoothHostService(),
436             BT_ERR_INTERNAL_ERROR, "pimpl is null or load bluetooth service failed.");
437 
438         sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
439         CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr");
440         return proxy->EnableBle();
441     }
442 
DisableBluetooth(void)443     int DisableBluetooth(void) override
444     {
445         sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
446         CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr");
447         return proxy->DisableBt();
448     }
449 
EnableBluetoothToRestrictMode(void)450     int EnableBluetoothToRestrictMode(void) override
451     {
452         CHECK_AND_RETURN_LOG_RET(!BluetoothHost::GetDefaultHost().IsBtProhibitedByEdm(),
453             BT_ERR_PROHIBITED_BY_EDM, "bluetooth is prohibited !");
454         CHECK_AND_RETURN_LOG_RET(BluetoothHost::GetDefaultHost().pimpl->LoadBluetoothHostService(),
455             BT_ERR_INTERNAL_ERROR, "pimpl is null or load bluetooth service failed.");
456 
457         sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
458         CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr");
459         return proxy->EnableBluetoothToRestrictMode();
460     }
461 };
462 
impl()463 BluetoothHost::impl::impl()
464 {
465     observerImp_ = new BluetoothHostObserverImp(*this);
466     remoteObserverImp_ = new BluetoothRemoteDeviceObserverImp(*this);
467     bleRemoteObserverImp_ = new BluetoothBlePeripheralCallbackImp(*this);
468     bleObserverImp_ = new BluetoothHostObserverImp(*this);
469     resourceManagerObserverImp_ = new BluetoothResourceManagerObserverImp(*this);
470 
471     auto switchActionPtr = std::make_unique<BluetoothSwitchAction>();
472     switchModule_ = std::make_shared<BluetoothSwitchModule>(std::move(switchActionPtr));
473 
474     profileRegisterId = BluetoothProfileManager::GetInstance().RegisterFunc(BLUETOOTH_HOST,
475         [this](sptr<IRemoteObject> remote) {
476         sptr<IBluetoothHost> proxy = iface_cast<IBluetoothHost>(remote);
477         CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is nullptr");
478         proxy->RegisterObserver(observerImp_);
479         proxy->RegisterBleAdapterObserver(bleObserverImp_);
480         proxy->RegisterRemoteDeviceObserver(remoteObserverImp_);
481         proxy->RegisterBlePeripheralCallback(bleRemoteObserverImp_);
482         proxy->RegisterBtResourceManagerObserver(resourceManagerObserverImp_);
483     });
484 }
485 
~impl()486 BluetoothHost::impl::~impl()
487 {
488     HILOGI("starts");
489     BluetoothProfileManager::GetInstance().DeregisterFunc(profileRegisterId);
490     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
491     CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is nullptr");
492     proxy->DeregisterObserver(observerImp_);
493     proxy->DeregisterBleAdapterObserver(bleObserverImp_);
494     proxy->DeregisterRemoteDeviceObserver(remoteObserverImp_);
495     proxy->DeregisterBlePeripheralCallback(bleRemoteObserverImp_);
496     proxy->DeregisterBtResourceManagerObserver(resourceManagerObserverImp_);
497 }
498 
LoadBluetoothHostService()499 bool BluetoothHost::impl::LoadBluetoothHostService()
500 {
501     std::unique_lock<std::mutex> lock(proxyMutex_);
502     auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
503     if (samgrProxy == nullptr) {
504         HILOGE("samgrProxy is nullptr.");
505         return false;
506     }
507     sptr<IRemoteObject> hostRemote = BluetoothProfileManager::GetInstance().GetProfileRemote(BLUETOOTH_HOST);
508     //当蓝牙服务已经起来的时候。这时的hostRemote不为空, 不需要进行后续的从sa拉起蓝牙服务的动作
509     if (hostRemote != nullptr) {
510         return true;
511     }
512 
513     sptr<BluetoothHostLoadCallBack> loadCallback = new BluetoothHostLoadCallBack();
514     if (loadCallback == nullptr) {
515         HILOGE("loadCallback is nullptr.");
516         return false;
517     }
518     int32_t ret = samgrProxy->LoadSystemAbility(BLUETOOTH_HOST_SYS_ABILITY_ID, loadCallback);
519     if (ret != ERR_OK) {
520         HILOGE("Failed to load bluetooth systemAbility");
521         return false;
522     }
523     auto waitStatus = proxyConVar_.wait_for(
524         lock, std::chrono::milliseconds(LOAD_SA_TIMEOUT_MS), [this]() {
525             HILOGI("bluetooth_service load systemAbility finished");
526             sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
527             return proxy != nullptr || saManagerStatus_ == SaManagerStatus::LOAD_FAIL;
528         });
529     if (!waitStatus) {
530         HILOGE("load bluetooth systemAbility timeout");
531         return false;
532     }
533     if (saManagerStatus_ == SaManagerStatus::LOAD_FAIL) {
534         HILOGE("load bluetooth_service fail");
535         saManagerStatus_ = SaManagerStatus::WAIT_NOTIFY;
536         return false;
537     }
538     saManagerStatus_ = SaManagerStatus::WAIT_NOTIFY;
539     return true;
540 }
541 
LoadSystemAbilitySuccess(const sptr<IRemoteObject> & remoteObject)542 void BluetoothHost::impl::LoadSystemAbilitySuccess(const sptr<IRemoteObject> &remoteObject)
543 {
544     HILOGI("LoadSystemAbilitySuccess FinishStart SA");
545     saManagerStatus_ = SaManagerStatus::LOAD_SUCCESS;
546     proxyConVar_.notify_one();
547 }
548 
LoadSystemAbilityFail()549 void BluetoothHost::impl::LoadSystemAbilityFail()
550 {
551     HILOGI("LoadSystemAbilityFail FinishStart SA");
552     saManagerStatus_ = SaManagerStatus::LOAD_FAIL;
553     proxyConVar_.notify_one();
554 }
555 
SyncRandomAddrToService(void)556 void BluetoothHost::impl::SyncRandomAddrToService(void)
557 {
558     if (!IsValidBluetoothAddr(stagingRealAddr_)) {
559         HILOGD("stagingRealAddr_ is invalid.");
560         return;
561     }
562     if (!IsValidBluetoothAddr(stagingRandomAddr_)) {
563         HILOGE("stagingRandomAddr_ is invalid.");
564         return;
565     }
566     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
567     CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is nullptr");
568     proxy->SyncRandomAddress(stagingRealAddr_, stagingRandomAddr_);
569     stagingRealAddr_ = "";
570     stagingRandomAddr_ = "";
571 }
572 
ConvertBluetoothStateToBtStateID(BluetoothState state)573 int BluetoothHost::impl::ConvertBluetoothStateToBtStateID(BluetoothState state)
574 {
575     int ret = BTStateID::STATE_TURN_OFF;
576     switch (state) {
577         case BluetoothState::STATE_ON: ret = BTStateID::STATE_TURN_ON; break;
578         case BluetoothState::STATE_TURNING_ON: ret = BTStateID::STATE_TURNING_ON; break;
579         case BluetoothState::STATE_TURNING_OFF: ret = BTStateID::STATE_TURNING_OFF; break;
580         case BluetoothState::STATE_OFF: ret = BTStateID::STATE_TURN_OFF; break;
581         default: break;
582     }
583     return ret;
584 }
585 
BluetoothHost()586 BluetoothHost::BluetoothHost()
587 {
588     pimpl = std::make_unique<impl>();
589     if (!pimpl) {
590         HILOGE("fails: no pimpl");
591     }
592 }
593 
~BluetoothHost()594 BluetoothHost::~BluetoothHost() {}
595 
GetDefaultHost()596 BluetoothHost &BluetoothHost::GetDefaultHost()
597 {
598 #ifdef DTFUZZ_TEST
599     static BluetoothNoDestructor<BluetoothHost> instance;
600     return *instance;
601 #else
602     // C++11 static local variable initialization is thread-safe.
603     static BluetoothHost hostAdapter;
604     return hostAdapter;
605 #endif
606 }
607 
RegisterObserver(std::shared_ptr<BluetoothHostObserver> observer)608 void BluetoothHost::RegisterObserver(std::shared_ptr<BluetoothHostObserver> observer)
609 {
610     HILOGD("enter");
611     CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null.");
612     pimpl->observers_.Register(observer);
613 }
614 
DeregisterObserver(std::shared_ptr<BluetoothHostObserver> observer)615 void BluetoothHost::DeregisterObserver(std::shared_ptr<BluetoothHostObserver> observer)
616 {
617     HILOGD("enter");
618     CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null.");
619     pimpl->observers_.Deregister(observer);
620 }
621 
EnableBt()622 int BluetoothHost::EnableBt()
623 {
624     HILOGD("enter");
625     CHECK_AND_RETURN_LOG_RET(!IsBtProhibitedByEdm(), BT_ERR_PROHIBITED_BY_EDM, "bluetooth is prohibited");
626     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
627     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr");
628 
629     return proxy->EnableBt();
630 }
631 
DisableBt()632 int BluetoothHost::DisableBt()
633 {
634     HILOGI("enter");
635     std::lock_guard<std::mutex> lock(pimpl->switchModuleMutex_);
636     CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr");
637     return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH);
638 }
639 
PublishBtSwitchRestrictBluetoothEvent(void)640 static void PublishBtSwitchRestrictBluetoothEvent(void)
641 {
642     OHOS::AAFwk::Want want;
643     want.SetAction("usual.event.bluetooth.BT_SWITCH_RESTRICT_BLUETOOTH");
644 
645     OHOS::EventFwk::CommonEventData data;
646     data.SetWant(want);
647 
648     OHOS::EventFwk::CommonEventPublishInfo publishInfo;
649     publishInfo.SetSubscriberPermissions({"ohos.permission.ACCESS_BLUETOOTH"});
650     bool ret = OHOS::EventFwk::CommonEventManager::PublishCommonEvent(data, publishInfo);
651     if (!ret) {
652         HILOGE("Publish usual.event.bluetooth.BT_SWITCH_RESTRICT_BLUETOOTH event failed");
653         return;
654     }
655 }
656 
RestrictBluetooth()657 int BluetoothHost::RestrictBluetooth()
658 {
659     HILOGI("enter");
660     std::lock_guard<std::mutex> lock(pimpl->switchModuleMutex_);
661     PublishBtSwitchRestrictBluetoothEvent();
662     CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr");
663     int ret =  pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::DISABLE_BLUETOOTH);
664     if (ret != BT_NO_ERROR) {
665         return ret;
666     }
667     ret = pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE);
668     return ret;
669 }
670 
SatelliteControl(int type,int state)671 int BluetoothHost::SatelliteControl(int type, int state)
672 {
673     HILOGI("type: %{public}d, state: %{public}d", type, state);
674     if (type == static_cast<int>(SATELLITE_CONTROL_MODE::ANTENNA)) {
675         CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
676     } else if (type == static_cast<int>(SATELLITE_CONTROL_MODE::BLUETOOTH_SWITCH)) {
677         pimpl->LoadBluetoothHostService();
678     } else {
679         HILOGE("Invalid control type: %{public}d", type);
680         return BT_ERR_INVALID_PARAM;
681     }
682     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
683     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr");
684     return proxy->SatelliteControl(type, state);
685 }
686 
UpdateVirtualDevice(int32_t action,const std::string & address)687 void BluetoothHost::UpdateVirtualDevice(int32_t action, const std::string &address)
688 {
689     HILOGD("enter");
690     CHECK_AND_RETURN_LOG(IS_BT_ENABLED(), "bluetooth is off");
691     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
692     CHECK_AND_RETURN_LOG(proxy != nullptr, "proxy is nullptr");
693     proxy->UpdateVirtualDevice(action, address);
694 }
695 
GetBtState() const696 int BluetoothHost::GetBtState() const
697 {
698     BluetoothState state = GetBluetoothState();
699     return pimpl->ConvertBluetoothStateToBtStateID(state);
700 }
701 
GetBtState(int & state) const702 int BluetoothHost::GetBtState(int &state) const
703 {
704     state = GetBtState();
705     return BT_NO_ERROR;
706 }
707 
GetBluetoothState(void) const708 BluetoothState BluetoothHost::GetBluetoothState(void) const
709 {
710     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
711     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BluetoothState::STATE_OFF, "proxy is nullptr");
712     int state = static_cast<int>(BluetoothState::STATE_OFF);
713     proxy->GetBtState(state);
714     return static_cast<BluetoothState>(state);
715 }
716 
EnableBluetoothAfterFactoryReset(void)717 int BluetoothHost::impl::EnableBluetoothAfterFactoryReset(void)
718 {
719     HILOGI("Attempt to enable bluetooth after factory reset");
720     isFactoryReseting_ = false;
721     SetParameter("persist.bluetooth.switch_enable", "2");  // 2 means bluetooth auto enter restricted mode
722     return BT_NO_ERROR;
723 }
724 
BluetoothFactoryReset()725 int BluetoothHost::BluetoothFactoryReset()
726 {
727     HILOGI("enter");
728     constexpr const char* BLUETOOTH_FACTORY_RESET_KEY = "persist.bluetooth.factoryreset";
729     int ret = SetParameter(BLUETOOTH_FACTORY_RESET_KEY, "true");
730     CHECK_AND_RETURN_LOG_RET(ret == 0, BT_ERR_INTERNAL_ERROR, "SetParameter failed");
731 
732     pimpl->isFactoryReseting_ = true;
733 
734     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
735     if (proxy == nullptr) {
736         return pimpl->EnableBluetoothAfterFactoryReset();
737     }
738     CHECK_AND_RETURN_LOG_RET(IS_BLE_ENABLED(), BT_NO_ERROR, "bluetooth is off.");
739     return proxy->BluetoothFactoryReset();
740 }
741 
IsValidBluetoothAddr(const std::string & addr)742 bool BluetoothHost::IsValidBluetoothAddr(const std::string &addr)
743 {
744 #if defined(IOS_PLATFORM)
745     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}$");
746     return regex_match(addr, deviceIdRegex);
747 #elif defined(ANDROID_PLATFORM)
748     const std::regex deviceIdRegex("^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$");
749     return regex_match(addr, deviceIdRegex);
750 #else
751     if (addr.length() != ADDRESS_LENGTH) {
752         HILOGD("invalid address len.");
753         return false;
754     }
755 
756     for (int i = 0; i < ADDRESS_LENGTH; i++) {
757         char c = addr[i];
758         switch (i % ADDRESS_SEPARATOR_UNIT) {
759             case 0:
760             case 1:
761                 if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
762                     break;
763                 }
764                 return false;
765             case ADDRESS_COLON_INDEX:
766             default:
767                 if (c == ':') {
768                     break;
769                 }
770                 return false;
771         }
772     }
773     return true;
774 #endif
775 }
776 
GetRemoteDevice(const std::string & addr,int transport) const777 BluetoothRemoteDevice BluetoothHost::GetRemoteDevice(const std::string &addr, int transport) const
778 {
779     BluetoothRemoteDevice remoteDevice(addr, transport);
780     return remoteDevice;
781 }
782 
EnableBle()783 int BluetoothHost::EnableBle()
784 {
785     HILOGI("enter");
786     std::lock_guard<std::mutex> lock(pimpl->switchModuleMutex_);
787     CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr");
788     return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH);
789 }
790 
DisableBle()791 int BluetoothHost::DisableBle()
792 {
793     HILOGD("enter");
794     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
795     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_INTERNAL_ERROR, "proxy is nullptr");
796 
797     return proxy->DisableBle();
798 }
799 
EnableBluetoothToRestrictMode(void)800 int BluetoothHost::EnableBluetoothToRestrictMode(void)
801 {
802     HILOGI("enter");
803     std::lock_guard<std::mutex> lock(pimpl->switchModuleMutex_);
804     CHECK_AND_RETURN_LOG_RET(pimpl->switchModule_, BT_ERR_INTERNAL_ERROR, "switchModule is nullptr");
805     return pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::ENABLE_BLUETOOTH_TO_RESTRICE_MODE);
806 }
807 
IsBrEnabled() const808 bool BluetoothHost::IsBrEnabled() const
809 {
810     BluetoothState state = GetBluetoothState();
811     return state == BluetoothState::STATE_ON;
812 }
813 
IsBleEnabled() const814 bool BluetoothHost::IsBleEnabled() const
815 {
816     BluetoothState state = GetBluetoothState();
817     return (state == BluetoothState::STATE_ON ||
818         state == BluetoothState::STATE_BLE_ON ||
819         state == BluetoothState::STATE_TURNING_ON ||
820         state == BluetoothState::STATE_TURNING_OFF);
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 
SetFastScanLevel(int level)1177 int BluetoothHost::SetFastScanLevel(int level)
1178 {
1179     CHECK_AND_RETURN_LOG_RET(IS_BT_ENABLED(), BT_ERR_INVALID_STATE, "bluetooth is off.");
1180     sptr<IBluetoothHost> proxy = GetRemoteProxy<IBluetoothHost>(BLUETOOTH_HOST);
1181     CHECK_AND_RETURN_LOG_RET(proxy != nullptr, BT_ERR_UNAVAILABLE_PROXY, "pimpl or bluetooth host is nullptr");
1182     return proxy->SetFastScanLevel(level);
1183 }
1184 
RegisterBtResourceManagerObserver(std::shared_ptr<BluetoothResourceManagerObserver> observer)1185 void BluetoothHost::RegisterBtResourceManagerObserver(std::shared_ptr<BluetoothResourceManagerObserver> observer)
1186 {
1187     CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null.");
1188 
1189     pimpl->resourceManagerObservers_.Register(observer);
1190 }
1191 
DeregisterBtResourceManagerObserver(std::shared_ptr<BluetoothResourceManagerObserver> observer)1192 void BluetoothHost::DeregisterBtResourceManagerObserver(std::shared_ptr<BluetoothResourceManagerObserver> observer)
1193 {
1194     CHECK_AND_RETURN_LOG(pimpl != nullptr, "pimpl is null.");
1195 
1196     pimpl->resourceManagerObservers_.Deregister(observer);
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         // Notify profile manager bluetooth off once.
1234         BluetoothProfileManager::GetInstance().NotifyBluetoothStateChange(
1235             BTTransport::ADAPTER_BLE, BTStateID::STATE_TURN_OFF);
1236     } else if (pimpl->observerImp_ && pimpl->bleObserverImp_) {
1237         HILOGD("bluetooth_servi died and send state off to app");
1238         pimpl->observerImp_->OnStateChanged(BTTransport::ADAPTER_BREDR, BTStateID::STATE_TURN_OFF);
1239         pimpl->bleObserverImp_->OnStateChanged(BTTransport::ADAPTER_BLE, BTStateID::STATE_TURN_OFF);
1240     }
1241     if (pimpl->isFactoryReseting_.load()) {
1242         pimpl->EnableBluetoothAfterFactoryReset();
1243     }
1244     std::lock_guard<std::mutex> lock(pimpl->switchModuleMutex_);
1245     if (pimpl->switchModule_) {
1246         pimpl->switchModule_->ProcessBluetoothSwitchEvent(BluetoothSwitchEvent::BLUETOOTH_OFF);
1247     }
1248 }
1249 
Close(void)1250 void BluetoothHost::Close(void)
1251 {
1252     std::lock_guard<std::mutex> lock(pimpl->switchModuleMutex_);
1253     pimpl->switchModule_ = nullptr;
1254 }
1255 } // namespace Bluetooth
1256 } // namespace OHOS
1257