1 /*
2  * Copyright (C) 2021 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 "classic_adapter_properties.h"
17 
18 #include <string>
19 
20 #include "classic_data_structure.h"
21 #include "classic_data_type_defs.h"
22 #include "classic_defs.h"
23 #include "classic_utils.h"
24 #include "gap_if.h"
25 #include "log_util.h"
26 #include "raw_address.h"
27 #include "securec.h"
28 
29 namespace OHOS {
30 namespace bluetooth {
GetInstance()31 ClassicAdapterProperties &ClassicAdapterProperties::GetInstance()
32 {
33     static ClassicAdapterProperties instance;
34     return instance;
35 }
36 
ClassicAdapterProperties()37 ClassicAdapterProperties::ClassicAdapterProperties() : config_(ClassicConfig::GetInstance())
38 {}
39 
~ClassicAdapterProperties()40 ClassicAdapterProperties::~ClassicAdapterProperties()
41 {}
42 
LoadConfigInfo()43 bool ClassicAdapterProperties::LoadConfigInfo()
44 {
45     if (!config_.LoadConfigFile()) {
46         LOG_ERROR("Load config file failed!");
47         return false;
48     } else {
49         LoadHostInfo();
50     }
51 
52     return true;
53 }
54 
LoadHostInfo()55 void ClassicAdapterProperties::LoadHostInfo()
56 {
57     deviceName_ = config_.GetLocalName();
58     if (deviceName_.empty()) {
59         deviceName_ = DEFAULT_DEVICE_NAME;
60     }
61 
62     cod_ = (config_.GetLocalDeviceClass() & CLASS_OF_DEVICE_RANGE);
63     if (INVALID_VALUE > cod_) {
64         cod_ = DEFAULT_CLASS_OF_DEVICE;
65     }
66 
67     ioCapability_ = config_.GetIoCapability();
68     if ((GAP_IO_DISPLAYONLY > ioCapability_) || (GAP_IO_NOINPUTNOOUTPUT < ioCapability_)) {
69         ioCapability_ = GAP_IO_DISPLAYYESNO;
70     }
71 
72     passkey_ = config_.GetLocalPasskey();
73     if (passkey_.empty()) {
74         passkey_ = DEFAULT_PASSKEY;
75     }
76 
77     securityMode_ = config_.GetSecurityMode();
78     if ((securityMode_ != SEC_MODE_2) && (securityMode_ != SEC_MODE_4)) {
79         securityMode_ = SEC_MODE_2;
80     }
81 
82     LOG_DEBUG("Get Host info:");
83     LOG_DEBUG("Device name is: %{public}s", deviceName_.c_str());
84     LOG_DEBUG("Class of device is: %{public}d", cod_);
85     LOG_DEBUG("IoCapability is: %{public}d", ioCapability_);
86     LOG_DEBUG("Passkey is: %{public}s", passkey_.c_str());
87     LOG_DEBUG("securityMode is: %{public}d", securityMode_);
88 }
89 
GetLocalName() const90 std::string ClassicAdapterProperties::GetLocalName() const
91 {
92     return deviceName_;
93 }
94 
SetLocalName(const std::string & name)95 bool ClassicAdapterProperties::SetLocalName(const std::string &name)
96 {
97     std::lock_guard<std::recursive_mutex> lock(propertiesMutex_);
98 
99     int length = name.length();
100     if (length >= MAX_LOC_BT_NAME_LEN) {
101         length = MAX_LOC_BT_NAME_LEN;
102         deviceName_ = name.substr(0, length);
103     } else {
104         deviceName_ = name;
105     }
106 
107     // Update controller
108     bool ret = (GAPIF_SetLocalName(deviceName_.c_str(), length) == BT_SUCCESS);
109     ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "GAPIF_SetLocalName", ret);
110 
111     // Set EIR
112     ret &= SetEirData();
113     ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "SetEirData", ret);
114 
115     // Update config
116     ret &= UpdateConfig(BT_PROPERTY_BDNAME);
117     ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "UpdateConfig", ret);
118 
119     return ret;
120 }
121 
GetLocalAddress() const122 std::string ClassicAdapterProperties::GetLocalAddress() const
123 {
124     return macAddr_;
125 }
126 
GetLocalDeviceClass() const127 int ClassicAdapterProperties::GetLocalDeviceClass() const
128 {
129     LOG_DEBUG("[ClassicAdapterProperties]::%{public}s cod: %{public}d", __func__, cod_);
130     return cod_;
131 }
132 
SetLocalDeviceClass(int deviceClass)133 bool ClassicAdapterProperties::SetLocalDeviceClass(int deviceClass)
134 {
135     bool ret = false;
136     cod_ = deviceClass;
137 
138     int result = GAPIF_SetClassOfDevice(cod_);
139     if (result != BT_SUCCESS) {
140         LOG_ERROR("ClassicAdapterProperties::%{public}s GAPIF_SetClassOfDevice failed!", __func__);
141         return ret;
142     }
143 
144     ret = UpdateConfig(BT_PROPERTY_CLASS_OF_DEVICE);
145     ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "UpdateConfig", ret);
146 
147     return true;
148 }
149 
GetBondableMode() const150 int ClassicAdapterProperties::GetBondableMode() const
151 {
152     return bondableMode_;
153 }
154 
SetBondableMode(int mode)155 bool ClassicAdapterProperties::SetBondableMode(int mode)
156 {
157     if (mode < BONDABLE_MODE_OFF || mode > BONDABLE_MODE_ON) {
158         LOG_ERROR("ClassicAdapterProperties::%{public}s. Invalid Parameter", __func__);
159         return false;
160     }
161 
162     switch (mode) {
163         case BONDABLE_MODE_OFF:
164             bondableMode_ = GAP_BONDABLE_MODE_NON;
165             break;
166         case BONDABLE_MODE_ON:
167             bondableMode_ = GAP_BONDABLE_MODE;
168             break;
169         default:
170             bondableMode_ = GAP_BONDABLE_MODE_NON;
171             break;
172     }
173     int ret = GAPIF_SetBondableMode(bondableMode_);
174     if (ret != BT_SUCCESS) {
175         return false;
176     }
177 
178     return true;
179 }
180 
GetPasskey() const181 std::string ClassicAdapterProperties::GetPasskey() const
182 {
183     return passkey_;
184 }
185 
GetIoCapability() const186 int ClassicAdapterProperties::GetIoCapability() const
187 {
188     return ioCapability_;
189 }
190 
SetIoCapability(int ioCapability)191 bool ClassicAdapterProperties::SetIoCapability(int ioCapability)
192 {
193     ioCapability_ = ioCapability;
194     return true;
195 }
196 
ConfigProperties()197 bool ClassicAdapterProperties::ConfigProperties()
198 {
199     /// Read MAC Addr from Controller.
200     bool ret = ReadAddrFromController();
201     if (!ret) {
202         return ret;
203     }
204 
205     /// Update MAC Addr to config file.
206     ret &= UpdateConfig(BT_PROPERTY_BDADDR);
207     ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "UpdateConfig", ret);
208 
209     ret &= SetLocalName(deviceName_);
210     ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "SetLocalName", ret);
211 
212     // Set Class of Device.
213     ret &= SetLocalDeviceClass(cod_);
214     ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "SetLocalDeviceClass", ret);
215 
216     return ret;
217 }
218 
InitMode()219 bool ClassicAdapterProperties::InitMode()
220 {
221     /// Set BondMode.
222     bool ret = true;
223     if (bondableMode_ != BONDABLE_MODE_OFF) {
224         ret = SetBondableMode(BONDABLE_MODE_OFF);
225         ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "SetBondableMode", ret);
226     }
227 
228     return ret;
229 }
230 
SetSecurityMode()231 bool ClassicAdapterProperties::SetSecurityMode()
232 {
233     LOG_DEBUG("[ClassicAdapterProperties]::%{public}s", __func__);
234 
235     bool ret = (GAPIF_SetSecurityMode((GAP_SecurityMode)securityMode_) == BT_SUCCESS);
236     ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "GAPIF_SetSecurityMode", ret);
237 
238     return ret;
239 }
240 
GetDiscoverableTimeout() const241 int ClassicAdapterProperties::GetDiscoverableTimeout() const
242 {
243     LOG_DEBUG("[ClassicAdapterProperties]::%{public}s", __func__);
244 
245     return discoverableTimeout_;
246 }
247 
SetDiscoverableTimeout(int time)248 bool ClassicAdapterProperties::SetDiscoverableTimeout(int time)
249 {
250     LOG_DEBUG("[ClassicAdapterProperties]::%{public}s time = %{public}d", __func__, time);
251 
252     bool ret = true;
253     if (discoverableTimeout_ != time) {
254         discoverableTimeout_ = time;
255     } else {
256         LOG_WARN("ClassicAdapterProperties::SetDiscoverableTimeout same value");
257     }
258 
259     return ret;
260 }
261 
ReadAddrFromController()262 bool ClassicAdapterProperties::ReadAddrFromController()
263 {
264     BtAddr btAddr;
265     errno_t result = memset_s(&btAddr, sizeof(BtAddr), 0, sizeof(BtAddr));
266     if (result != EOK) {
267         LOG_ERROR("%{public}s::memset_s failed!", __func__);
268         return false;
269     }
270 
271     bool ret = (GAPIF_GetLocalAddr(&btAddr) == BT_SUCCESS);
272     if (!ret) {
273         return ret;
274     }
275     macAddr_ = RawAddress::ConvertToString(btAddr.addr).GetAddress();
276     HILOGI("GAPIF_GetLocalAddr: %{public}s", GetEncryptAddr(macAddr_).c_str());
277 
278     return ret;
279 }
280 
UpdateConfig(int type)281 bool ClassicAdapterProperties::UpdateConfig(int type)
282 {
283     LOG_DEBUG("[ClassicAdapterProperties]::%{public}s Type: %{public}d", __func__, type);
284 
285     bool ret = false;
286     switch (type) {
287         case BT_PROPERTY_BDNAME: {
288             ret = config_.SetLocalName(deviceName_);
289             if (ret == false) {
290                 LOG_ERROR("UpdateConfig::SetLocalName failed");
291             } else {
292                 SendDeviceNameChanged(deviceName_);
293             }
294             break;
295         }
296         case BT_PROPERTY_BDADDR: {
297             ret = config_.SetLocalAddress(macAddr_);
298             if (ret == false) {
299                 LOG_ERROR("UpdateConfig::SetLocalAddress failed");
300             } else {
301                 SendDeviceAddrChanged(macAddr_);
302             }
303             break;
304         }
305         case BT_PROPERTY_CLASS_OF_DEVICE:
306             ret = config_.SetLocalDeviceClass(cod_);
307             ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "SetLocalDeviceClass", ret);
308             break;
309         case BT_PROPERTY_ADAPTER_DISCOVERABLE_TIMEOUT:
310             ret = config_.SetDiscoverableTimeout(discoverableTimeout_);
311             ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "SetDiscoverableTimeout", ret);
312             break;
313         default:
314             break;
315     }
316 
317     ret = config_.Save();
318     ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "Save", ret);
319 
320     return ret;
321 }
322 
SendDeviceNameChanged(const std::string & deviceName)323 void ClassicAdapterProperties::SendDeviceNameChanged(const std::string &deviceName)
324 {
325     LOG_DEBUG("[ClassicAdapterProperties]::%{public}s", __func__);
326 
327     adapterObservers_.ForEach(
328         [deviceName](IAdapterClassicObserver &observer) { observer.OnDeviceNameChanged(deviceName); });
329 }
330 
SendDeviceAddrChanged(const std::string & address)331 void ClassicAdapterProperties::SendDeviceAddrChanged(const std::string &address)
332 {
333     LOG_DEBUG("[ClassicAdapterProperties]::%{public}s", __func__);
334 
335     adapterObservers_.ForEach([address](IAdapterClassicObserver &observer) { observer.OnDeviceAddrChanged(address); });
336 }
337 
SetEirData()338 bool ClassicAdapterProperties::SetEirData()
339 {
340     LOG_DEBUG("[ClassicAdapterProperties]::%{public}s", __func__);
341 
342     std::lock_guard<std::recursive_mutex> lock(propertiesMutex_);
343     bool ret = true;
344     /// New bluetooth object to make up the eir data.
345     std::unique_ptr<ClassicBluetoothData> eirData = std::make_unique<ClassicBluetoothData>();
346 
347     /// Set data length for eir.
348     eirData->SetDataMaxLength(MAX_EXTEND_INQUIRY_RESPONSE_LEN);
349 
350     /// Set eir name length and eir type.
351     uint8_t nameLen = deviceName_.length() + EXTEND_INQUIRY_RESPONSE_TYPE_SIZE;
352     int nameType = BLUETOOTH_DATA_TYPE_COMPLETE_LOCAL_NAME;
353 
354     uint8_t uuidLen = (UUID16_BYTES_TYPE * uuids_.size()) + EXTEND_INQUIRY_RESPONSE_TYPE_SIZE;
355     if (EXTEND_INQUIRY_RESPONSE_TYPE_SIZE < uuidLen) {
356         int dataLen = nameLen + EXTEND_INQUIRY_RESPONSE_LENGTH_SIZE + uuidLen + EXTEND_INQUIRY_RESPONSE_LENGTH_SIZE;
357         if (dataLen >= MAX_EXTEND_INQUIRY_RESPONSE_LEN) {
358             nameType = BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME;
359             nameLen = MAX_EXTEND_INQUIRY_RESPONSE_LEN - (uuidLen + EXTEND_INQUIRY_RESPONSE_LENGTH_SIZE) -
360                       EXTEND_INQUIRY_RESPONSE_TYPE_SIZE;
361         }
362     } else {
363         if (nameLen >= MAX_EXTEND_INQUIRY_RESPONSE_LEN) {
364             nameType = BLUETOOTH_DATA_TYPE_SHORTENED_LOCAL_NAME;
365             nameLen = MAX_EXTEND_INQUIRY_RESPONSE_LEN - EXTEND_INQUIRY_RESPONSE_TYPE_SIZE;
366         }
367     }
368     std::string subString = deviceName_.substr(0, (nameLen - 1));
369     std::vector<uint8_t> eirName;
370     eirName.assign(subString.begin(), subString.end());
371 
372     /// Construct the eir data
373     ClassicDataStructure nameData(nameLen, nameType, eirName);
374     eirData->AddDataStructure(nameData);
375 
376     if (!uuids_.empty()) {
377         int uuidType = BLUETOOTH_DATA_TYPE_COMPLETE_LIST_OF_16_BIT_SERVICE_CLASS_UUIDS;
378         std::vector<uint8_t> value(uuidLen - EXTEND_INQUIRY_RESPONSE_TYPE_SIZE);
379         int idx = 0;
380         for (auto it = uuids_.begin(); it != uuids_.end(); it++) {
381             uint16_t uuid = (*it).ConvertTo16Bits();
382             value[idx] = (uint8_t)(uuid & 0x00FF);
383             value[idx + 1] = (uint8_t)((uuid & 0xFF00) >> MOVE_ONE_BYTE);
384             idx += sizeof(uint16_t);
385         }
386         ClassicDataStructure uuidData(uuidLen, uuidType, value);
387         eirData->AddDataStructure(uuidData);
388         value.clear();
389     }
390 
391     /// Set eir data to GAP
392     int result = GAPIF_SetExtendedInquiryResponse(eirData->GetClassicBluetoothData().data());
393     if (result != BT_SUCCESS) {
394         LOG_ERROR("ClassicAdapterProperties::GAPIF_SetExtendedInquiryResponse failed, ret = %{public}d", result);
395         ret = false;
396     }
397     return ret;
398 }
399 
RegisterClassicAdapterObserver(IAdapterClassicObserver & observer)400 void ClassicAdapterProperties::RegisterClassicAdapterObserver(IAdapterClassicObserver &observer)
401 {
402     LOG_DEBUG("[ClassicAdapterProperties]::%{public}s", __func__);
403     adapterObservers_.Register(observer);
404 }
405 
DeregisterClassicAdapterObserver(IAdapterClassicObserver & observer)406 void ClassicAdapterProperties::DeregisterClassicAdapterObserver(IAdapterClassicObserver &observer)
407 {
408     LOG_DEBUG("[ClassicAdapterProperties]::%{public}s", __func__);
409     adapterObservers_.Deregister(observer);
410 }
411 
GetPairedAddrList() const412 std::vector<std::string> ClassicAdapterProperties::GetPairedAddrList() const
413 {
414     return config_.GetPairedAddrList();
415 }
416 
SaveConfigFile() const417 void ClassicAdapterProperties::SaveConfigFile() const
418 {
419     LOG_DEBUG("[ClassicAdapterProperties]::%{public}s", __func__);
420     bool ret = config_.Save();
421     LOG_DEBUG("ClassicAdapterProperties::%{public}s result = %{public}d", __func__, ret);
422 }
423 
GetPairedDevice(std::string addr)424 std::shared_ptr<ClassicRemoteDevice> ClassicAdapterProperties::GetPairedDevice(std::string addr)
425 {
426     HILOGI("addr: %{public}s", GetEncryptAddr(addr).c_str());
427 
428     std::shared_ptr<ClassicRemoteDevice> remote = std::make_shared<ClassicRemoteDevice>(addr);
429 
430     std::string name = config_.GetRemoteName(addr);
431     remote->SetRemoteName(name);
432 
433     std::string alias = config_.GetRemoteAlias(addr);
434     remote->SetAliasName(alias);
435 
436     int linkKeyType = config_.GetRemoteLinkkeyType(addr);
437     remote->SetLinkKeyType(linkKeyType);
438 
439     if (linkKeyType != PAIR_INVALID_LINK_KEY_TYPE) {
440         std::string key = config_.GetRemoteLinkkey(addr);
441         LOG_DEBUG("Get linkKey value is %{public}s", key.c_str());
442         std::vector<uint8_t> linkKey;
443         ClassicUtils::ConvertHexStringToInt(key, linkKey);
444         remote->SetLinkKey(linkKey);
445     }
446 
447     int io = config_.GetRemoteDeviceIoCapability(addr);
448     remote->SetIoCapability(io);
449 
450     int cod = config_.GetRemoteDeviceClass(addr);
451     remote->SetDeviceClass(cod);
452 
453     int deviceType = config_.GetRemoteDeviceType(addr);
454     remote->SetDeviceType(deviceType);
455 
456     bool pairFlag = config_.GetRemoteDevicePairFlag(addr);
457     if (pairFlag == true) {
458         remote->SetPairedStatus(PAIR_PAIRED);
459     }
460 
461     bool bondFromLocal = config_.GetRemoteDeviceBondFromLocal(addr);
462     remote->SetBondedFromLocal(bondFromLocal);
463 
464     std::string uuidVal = config_.GetRemoteUuids(addr);
465     std::vector<Uuid> uuids = ClassicUtils::ConvertStringToUuid(uuidVal);
466     if (!uuids.empty()) {
467         remote->SetDeviceUuids(uuids);
468     }
469 
470     return remote;
471 }
472 
SavePairedDeviceInfo(std::shared_ptr<ClassicRemoteDevice> remote)473 void ClassicAdapterProperties::SavePairedDeviceInfo(std::shared_ptr<ClassicRemoteDevice> remote)
474 {
475     HILOGI("addr: %{public}s", GetEncryptAddr(remote->GetAddress()).c_str());
476     std::string addr = remote->GetAddress();
477 
478     std::string name = remote->GetRemoteName();
479     if (!name.empty()) {
480         config_.SetRemoteName(addr, name);
481     }
482 
483     std::string alias = remote->GetAliasName();
484     if (!alias.empty()) {
485         config_.SetRemoteAlias(addr, alias);
486     }
487 
488     int linkKeyType = remote->GetLinkKeyType();
489     config_.SetRemoteLinkkeyType(addr, linkKeyType);
490 
491     if (linkKeyType != PAIR_INVALID_LINK_KEY_TYPE) {
492         std::vector<uint8_t> linkKey = remote->GetLinkKey();
493         std::string key = ClassicUtils::ConvertIntToHexString(linkKey);
494         LOG_DEBUG("Save LinkKey value is %{public}s", key.c_str());
495         config_.SetRemoteLinkkey(addr, key);
496     }
497 
498     int io = remote->GetIoCapability();
499     config_.SetRemoteDeviceIoCapability(addr, io);
500 
501     int cod = remote->GetDeviceClass();
502     config_.SetRemoteDeviceClass(addr, cod);
503 
504     int deviceType = remote->GetDeviceType();
505     config_.SetRemoteDeviceType(addr, deviceType);
506 
507     bool pairFlag = remote->IsPaired();
508     config_.SetRemoteDevicePairFlag(addr, pairFlag);
509 
510     bool bondFromLocal = remote->IsBondedFromLocal();
511     config_.SetRemoteDeviceBondFromLocal(addr, bondFromLocal);
512 
513     std::lock_guard<std::recursive_mutex> lock(propertiesMutex_);
514     std::vector<Uuid> uuids = remote->GetDeviceUuids();
515     if (uuids.empty()) {
516         return;
517     }
518     std::string uuidVal = ClassicUtils::ConvertUuidToString(uuids);
519     if (!uuidVal.empty()) {
520         config_.SetRemoteUuids(addr, uuidVal);
521     }
522 }
523 
RemovePairedDeviceInfo(std::string addr) const524 void ClassicAdapterProperties::RemovePairedDeviceInfo(std::string addr) const
525 {
526     HILOGI("addr: %{public}s", GetEncryptAddr(addr).c_str());
527 
528     bool ret = config_.RemovePairedDevice(addr);
529     if (ret == false) {
530         HILOGI("failed, addr is %{public}s", GetEncryptAddr(addr).c_str());
531     }
532 }
533 
SaveSupportUuids(const std::vector<Uuid> & uuids)534 bool ClassicAdapterProperties::SaveSupportUuids(const std::vector<Uuid> &uuids)
535 {
536     std::lock_guard<std::recursive_mutex> lock(propertiesMutex_);
537 
538     if (uuids.empty()) {
539         LOG_DEBUG("ClassicAdapterProperties::%{public}s input parameter(uuids) is null.", __func__);
540         return false;
541     }
542 
543     if (!uuids_.empty()) {
544         uuids_.clear();
545     }
546     uuids_ = uuids;
547 
548     bool ret = SetEirData();
549     ClassicUtils::CheckReturnValue("ClassicAdapaterProperties", "SetEirData", ret);
550 
551     return ret;
552 }
553 }  // namespace bluetooth
554 }  // namespace OHOS