1 /*
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "bluetooth_address.h"
17 #include <cerrno>
18 #include <cstdio>
19 #include <cstring>
20 #include <fcntl.h>
21 #include <hdf_log.h>
22 #include <unistd.h>
23 #include <dlfcn.h>
24 #include "securec.h"
25 
26 #ifdef LOG_DOMAIN
27 #undef LOG_DOMAIN
28 #endif
29 #define LOG_DOMAIN 0xD000105
30 
31 namespace OHOS {
32 namespace HDI {
33 namespace Bluetooth {
34 namespace Hci {
35 namespace {
36 constexpr int ADDRESS_STR_LEN = 17;
37 constexpr int ADDRESS_SIZE = 6;
38 }  // namespace
39 
BluetoothAddress()40 BluetoothAddress::BluetoothAddress()
41 {
42     address_.resize(ADDRESS_SIZE);
43 }
44 
45 constexpr int START_POS = 6;
46 constexpr int END_POS = 13;
47 constexpr int ADDR_BYTE = 18;
GetEncryptAddr(std::string addr)48 std::string GetEncryptAddr(std::string addr)
49 {
50     if (addr.empty() || addr.length() != ADDRESS_STR_LEN) {
51         HDF_LOGE("addr is invalid.");
52         return std::string("");
53     }
54     std::string tmp = "**:**:**:**:**:**";
55     std::string out = addr;
56     for (int i = START_POS; i <= END_POS; i++) {
57         out[i] = tmp[i];
58     }
59     return out;
60 }
61 
ParseAddressToString(std::vector<uint8_t> & address,std::string & outString)62 void BluetoothAddress::ParseAddressToString(std::vector<uint8_t> &address, std::string &outString)
63 {
64     char temp[ADDR_BYTE] = {0};
65     int ret = sprintf_s(temp, sizeof(temp), "%02X:%02X:%02X:%02X:%02X:%02X",
66         address[0], address[1], address[2], address[3], address[4], address[5]);
67     if (ret == -1) {
68         HDF_LOGE("ConvertAddr sprintf_s return error, ret -1");
69     }
70     outString = temp;
71 }
72 
ParseAddressFromString(const std::string & string) const73 int BluetoothAddress::ParseAddressFromString(const std::string &string) const
74 {
75     size_t offset = 0;
76     int bytesIndex = 0;
77     int readCount = 0;
78     for (bytesIndex = 0; bytesIndex < ADDRESS_SIZE && offset < string.size(); bytesIndex++) {
79         readCount = 0;
80         if (sscanf_s(&string[offset], "%02hhx:%n", &address_[bytesIndex], &readCount) > 0) {
81             if (readCount == 0 && bytesIndex != ADDRESS_SIZE - 1) {
82                 return bytesIndex;
83             }
84             offset += readCount;
85         } else {
86             break;
87         }
88     }
89 
90     return bytesIndex;
91 }
92 
GetConstantAddress(char * address,int len)93 bool BluetoothAddress::GetConstantAddress(char *address, int len)
94 {
95     if (address == nullptr || len < ADDRESS_STR_LEN + 1) {
96         HDF_LOGE("GetConstantAddress buf error");
97         return false;
98     }
99 
100     void *libMac = dlopen(BT_MAC_LIB, RTLD_LAZY);
101     if (libMac == nullptr) {
102         HDF_LOGI("GetConstantAddress no mac lib ready for dlopen");
103         return false;
104     }
105 
106     using GetMacFun = int (*)(unsigned int, char*, int);
107     GetMacFun getMac = reinterpret_cast<GetMacFun>(dlsym(libMac, GET_BT_MAC_SYMBOL_NAME));
108     if (getMac == nullptr) {
109         HDF_LOGE("GetConstantAddress dlsym error");
110         dlclose(libMac);
111         return false;
112     }
113 
114     int ret = getMac(MAC_TYPE_BLUETOOTH, address, len);
115     HDF_LOGI("GetConstantAddress ret: %{public}d", ret);
116     dlclose(libMac);
117     return (ret == 0);
118 }
119 
GetDeviceAddress(const std::string & path)120 std::shared_ptr<BluetoothAddress> BluetoothAddress::GetDeviceAddress(const std::string &path)
121 {
122     const int bufsize = 256;
123     char buf[bufsize] = {0};
124     int addrFd = open(path.c_str(), O_RDONLY);
125     if (addrFd < 0) {
126         HDF_LOGI("GetDeviceAddress open %{public}s.", path.c_str());
127         int newFd = open(path.c_str(), O_RDWR | O_CREAT, 00644);
128         HDF_LOGI("GetDeviceAddress open newFd %{public}d.", newFd);
129         char addressStr[ADDRESS_STR_LEN + 1] = {"00:11:22:33:44:55"};
130         if (!GetConstantAddress(addressStr, ADDRESS_STR_LEN + 1)) {
131             auto tmpPtr = GenerateDeviceAddress();
132             std::string strAddress;
133             ParseAddressToString(tmpPtr->address_, strAddress);
134             HDF_LOGI("device mac addr: %{public}s", GetEncryptAddr(strAddress).c_str());
135             int ret = strcpy_s(addressStr, ADDRESS_STR_LEN + 1, strAddress.c_str());
136             if (ret != 0) {
137                 HDF_LOGI("ParseAddressToString strcpy_s err!");
138             }
139         }
140 
141         if (newFd >= 0) {
142             int fdRet = write(newFd, addressStr, ADDRESS_STR_LEN);
143             if (fdRet < 0) {
144                 strerror_r(errno, buf, sizeof(buf));
145                 HDF_LOGI("GetDeviceAddress addr write failed, err:%{public}s.", buf);
146             }
147             close(newFd);
148         }
149         auto ptr = std::make_shared<BluetoothAddress>();
150         if (ptr->ParseAddressFromString(addressStr) != ADDRESS_SIZE) {
151             return nullptr;
152         }
153         return ptr;
154     }
155 
156     char addressStr[ADDRESS_STR_LEN + 1] = {0};
157     if (read(addrFd, addressStr, ADDRESS_STR_LEN) != ADDRESS_STR_LEN) {
158         HDF_LOGE("read %{public}s failed.", path.c_str());
159         close(addrFd);
160         return nullptr;
161     }
162     close(addrFd);
163 
164     auto ptr = std::make_shared<BluetoothAddress>();
165     if (ptr->ParseAddressFromString(addressStr) != ADDRESS_SIZE) {
166         return nullptr;
167     }
168 
169     return ptr;
170 }
171 
GenerateDeviceAddress(const std::string & prefix)172 std::shared_ptr<BluetoothAddress> BluetoothAddress::GenerateDeviceAddress(const std::string &prefix)
173 {
174     const int bufsize = 256;
175     char buf[bufsize] = {0};
176     auto ptr = std::make_shared<BluetoothAddress>();
177     char addressStr[ADDRESS_STR_LEN + 1] = {"00:11:22:33:44:55"};
178     ptr->ParseAddressFromString(addressStr);
179     int prefixCount = ptr->ParseAddressFromString(prefix);
180     if (prefixCount < ADDRESS_SIZE) {
181         int fd = open("/dev/urandom", O_RDONLY);
182         if (fd < 0) {
183             strerror_r(errno, buf, sizeof(buf));
184             HDF_LOGE("open /dev/urandom failed err:%{public}s.", buf);
185             return ptr;
186         }
187         if (read(fd, &ptr->address_[prefixCount], ADDRESS_SIZE - prefixCount) != ADDRESS_SIZE - prefixCount) {
188             strerror_r(errno, buf, sizeof(buf));
189             HDF_LOGE("read /dev/urandom failed err:%{public}s.", buf);
190         }
191         close(fd);
192     }
193     return ptr;
194 }
195 
ReadAddress(std::vector<uint8_t> & address) const196 void BluetoothAddress::ReadAddress(std::vector<uint8_t> &address) const
197 {
198     address = address_;
199 }
200 
ReadAddress(std::string & address) const201 void BluetoothAddress::ReadAddress(std::string &address) const
202 {
203     address.resize(ADDRESS_STR_LEN + 1);
204 
205     int offset = 0;
206     for (int ii = 0; ii < ADDRESS_SIZE; ii++) {
207         int ret = snprintf_s(
208             &address[offset], (ADDRESS_STR_LEN + 1) - offset, ADDRESS_STR_LEN - offset, "%02x:", address_[ii]);
209         if (ret < 0) {
210             break;
211         }
212         offset += ret;
213     }
214 }
215 }  // namespace Hci
216 }  // namespace Bluetooth
217 }  // namespace HDI
218 }  // namespace OHOS
219