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