• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "nfc_sdk_common.h"
16 
17 #include <algorithm>
18 #include <sstream>
19 #include <securec.h>
20 #include <sys/time.h>
21 #include "bundle_mgr_proxy.h"
22 #include "iservice_registry.h"
23 #include "cJSON.h"
24 #include "file_ex.h"
25 
26 #include "loghelper.h"
27 
28 namespace OHOS {
29 namespace NFC {
30 namespace KITS {
31 
IsLittleEndian()32 bool NfcSdkCommon::IsLittleEndian()
33 {
34     const char LAST_DATA_BYTE = 0x78;
35     union CheckData {
36         int x;
37         char y;
38     };
39 
40     union CheckData data;
41     data.x = 0x12345678;
42     if (data.y == LAST_DATA_BYTE) {
43         return true;
44     }
45     return false;
46 }
47 
BytesVecToHexString(const unsigned char * src,uint32_t length)48 std::string NfcSdkCommon::BytesVecToHexString(const unsigned char* src, uint32_t length)
49 {
50     std::string result = "";
51     if (length <= 0) {
52         return result;
53     }
54     const std::string hexKeys = "0123456789ABCDEF";
55     for (uint32_t i = 0; i < length; i++) {
56         result.push_back(hexKeys[(src[i] & 0xF0) >> HALF_BYTE_BITS]);
57         result.push_back(hexKeys[src[i] & 0x0F]);
58     }
59     return result;
60 }
61 
UnsignedCharToHexString(const unsigned char src)62 std::string NfcSdkCommon::UnsignedCharToHexString(const unsigned char src)
63 {
64     std::string result = "";
65     const std::string hexKeys = "0123456789ABCDEF";
66     result.push_back(hexKeys[(src & 0xF0) >> HALF_BYTE_BITS]);
67     result.push_back(hexKeys[src & 0x0F]);
68     return result;
69 }
70 
HexStringToBytes(const std::string & src,std::vector<unsigned char> & bytes)71 void NfcSdkCommon::HexStringToBytes(const std::string &src, std::vector<unsigned char> &bytes)
72 {
73     if (src.empty()) {
74         return;
75     }
76 
77     uint32_t bytesLen = src.length() / HEX_BYTE_LEN;
78     std::string strByte;
79     unsigned int srcIntValue;
80     for (uint32_t i = 0; i < bytesLen; i++) {
81         strByte = src.substr(i * HEX_BYTE_LEN, HEX_BYTE_LEN);
82         if (sscanf_s(strByte.c_str(), "%x", &srcIntValue) <= 0) {
83             ErrorLog("HexStringToBytes, sscanf_s failed.");
84             bytes.clear();
85             return;
86         }
87         bytes.push_back(static_cast<unsigned char>(srcIntValue & 0xFF));
88     }
89 }
90 
GetHexStrBytesLen(const std::string src)91 uint32_t NfcSdkCommon::GetHexStrBytesLen(const std::string src)
92 {
93     // 2 charactors consist of one byte.
94     if (src.empty()) {
95         return 0;
96     }
97     uint32_t length = src.length();
98     if (length % HEX_BYTE_LEN == 0) {
99         return (length / HEX_BYTE_LEN);
100     } else {
101         return ((length / HEX_BYTE_LEN) + 1);
102     }
103 }
104 
GetByteFromHexStr(const std::string src,uint32_t index)105 unsigned char NfcSdkCommon::GetByteFromHexStr(const std::string src, uint32_t index)
106 {
107     // 2 charactors consist of one byte.
108     if (src.empty() || (src.length() < index * HEX_BYTE_LEN + HEX_BYTE_LEN)) {
109         ErrorLog("GetByteFromHexStr, src length error.");
110         return 0;
111     }
112     std::string strByte = src.substr(index * HEX_BYTE_LEN, HEX_BYTE_LEN);
113     unsigned int srcIntValue;
114     if (sscanf_s(strByte.c_str(), "%x", &srcIntValue) <= 0) {
115         ErrorLog("GetByteFromHexStr, sscanf_s failed.");
116         return 0;
117     }
118     return static_cast<unsigned char>(srcIntValue & 0xFF);
119 }
120 
StringToInt(std::string src,bool bLittleEndian)121 uint32_t NfcSdkCommon::StringToInt(std::string src, bool bLittleEndian)
122 {
123     uint32_t value = 0;
124     if (bLittleEndian) {
125         for (size_t i = SHIFT_TIME; i > 0; i--) {
126             value += static_cast<uint32_t>((src.at(SHIFT_TIME - i)) << (i * SHIFT_SIZE - SHIFT_SIZE));
127         }
128     } else {
129         for (size_t i = 0; i < SHIFT_TIME; i++) {
130             value += static_cast<uint32_t>((src.at(i)) << (i * SHIFT_SIZE));
131         }
132     }
133     return value;
134 }
135 
IntToHexString(uint32_t num)136 std::string NfcSdkCommon::IntToHexString(uint32_t num)
137 {
138     std::stringstream ss;
139     ss << std::hex << num;
140     std::string result = ss.str();
141     transform(result.begin(), result.end(), result.begin(), ::toupper);
142     if (result.length() % HEX_BYTE_LEN > 0) { // expend "0" if string length is odd
143         result = "0" + result;
144     }
145     return result;
146 }
147 
StringToAsciiBytes(const std::string & src,std::vector<unsigned char> & bytes)148 void NfcSdkCommon::StringToAsciiBytes(const std::string &src, std::vector<unsigned char> &bytes)
149 {
150     if (src.empty()) {
151         return;
152     }
153     uint32_t bytesLen = src.length();
154     for (uint32_t i = 0; i < bytesLen; i++) {
155         unsigned int srcAsciiIntVal = static_cast<unsigned int>(src[i]);
156         bytes.push_back(static_cast<unsigned char>(srcAsciiIntVal & 0xFF));
157     }
158 }
159 
StringToHexString(const std::string & src)160 std::string NfcSdkCommon::StringToHexString(const std::string &src)
161 {
162     std::vector<unsigned char> bytes;
163     StringToAsciiBytes(src, bytes);
164     uint32_t len = src.length();
165     std::string result = BytesVecToHexString(&bytes[0], len);
166     return result;
167 }
168 
HexStringToAsciiString(const std::string & src)169 std::string NfcSdkCommon::HexStringToAsciiString(const std::string &src)
170 {
171     if (src.size() % HEX_BYTE_LEN != 0 || src.empty()) {  // 2 is Even number judgement
172         ErrorLog("HexStringToAsciiString length error");
173         return "";
174     }
175     std::string result = "";
176     for (size_t i = 0; i < src.size() / HEX_BYTE_LEN; i++) {
177         unsigned char byteVal = GetByteFromHexStr(src, i);
178         const char minPrintChar = ' ';
179         const char maxPrintChar = '~';
180         /* ' ' to '~' is the printable char range */
181         if (static_cast<char>(byteVal) < minPrintChar || static_cast<char>(byteVal) > maxPrintChar) {
182             return "";
183         }
184         result.push_back(static_cast<char>(byteVal));
185     }
186     return result;
187 }
188 
189 /*
190  * transfer Hex array to String without checking Ascii validation, compatible with Chinese characters
191  */
HexArrayToStringWithoutChecking(const std::string & src)192 std::string NfcSdkCommon::HexArrayToStringWithoutChecking(const std::string &src)
193 {
194     if (src.size() % HEX_BYTE_LEN != 0 || src.empty()) {  // 2 is Even number judgement
195         ErrorLog("HexStringToAsciiString length error");
196         return "";
197     }
198     std::string result = "";
199     for (size_t i = 0; i < src.size() / HEX_BYTE_LEN; i++) {
200         unsigned char byteVal = GetByteFromHexStr(src, i);
201         result.push_back(static_cast<char>(byteVal));
202     }
203     return result;
204 }
205 
GetCurrentTime()206 uint64_t NfcSdkCommon::GetCurrentTime()
207 {
208     // get the time since 1970/1/1
209     constexpr int timeRate = 1000;
210     struct timeval time = {0};
211     gettimeofday(&time, nullptr);
212     return static_cast<uint64_t>(time.tv_sec * timeRate + time.tv_usec / timeRate);
213 }
214 
GetRelativeTime()215 uint64_t NfcSdkCommon::GetRelativeTime()
216 {
217     // get the time since the system was booted
218     constexpr int64_t msPerSecond = 1000;
219     constexpr int64_t nsPerMs = 1000000;
220 
221     struct timespec times = {0};
222     clock_gettime(CLOCK_MONOTONIC, &times);
223     return ((times.tv_sec * msPerSecond) + (times.tv_nsec / nsPerMs));
224 }
225 
CodeMiddlePart(const std::string & src)226 std::string NfcSdkCommon::CodeMiddlePart(const std::string &src)
227 {
228     std::string res = "";
229     if (src.empty()) {
230         return res;
231     }
232     const char code = 'X';
233     const uint32_t maxStrLen = 1024;
234     uint32_t len = src.length();
235     if (len > maxStrLen) {
236         return res;
237     }
238 
239     uint32_t head = (len / 2) / 2; // Divide the string evenly into 2 * 2 parts
240     if (len <= head * 2) {  // The length of the head * 2 is greater than src
241         return src;
242     }
243     for (uint32_t i = 0; i < head; i++) {
244         res.push_back(src[i]);
245     }
246     for (uint32_t i = head; i < (len - head); i++) {
247         res.push_back(code);
248     }
249     for (uint32_t i = (len - head); i < len; i++) {
250         res.push_back(src[i]);
251     }
252     return res;
253 }
254 
SecureStringToInt(const std::string & str,int32_t & value,int base)255 bool NfcSdkCommon::SecureStringToInt(const std::string &str, int32_t &value, int base)
256 {
257     errno = 0;
258     char *endptr = nullptr;
259     const char *ptr = str.c_str();
260     value = std::strtol(str.c_str(), &endptr, base);
261     if (errno == ERANGE || endptr == ptr || *endptr != '\0') { // ERANGE: integer overflow
262         ErrorLog("SecureStringToInt errno str = %{public}s", str.c_str());
263         return false;
264     }
265     return true;
266 }
267 
GetSdkVersion(void)268 int NfcSdkCommon::GetSdkVersion(void)
269 {
270     int version = SDK_VERSION_UNKNOWN;
271 
272     auto systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
273     if (!systemAbilityManager) {
274         ErrorLog("fail to get system ability mgr.");
275         return version;
276     }
277     auto remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
278     if (!remoteObject) {
279         ErrorLog("fail to get bundle manager proxy.");
280         return version;
281     }
282     sptr<AppExecFwk::BundleMgrProxy> bundleMgrProxy = iface_cast<AppExecFwk::BundleMgrProxy>(remoteObject);
283     if (bundleMgrProxy == nullptr) {
284         ErrorLog("failed to get bundle manager proxy.");
285         return version;
286     }
287     AppExecFwk::BundleInfo bundleInfo;
288     auto flags = AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION;
289     auto ret = bundleMgrProxy->GetBundleInfoForSelf(static_cast<int32_t>(flags), bundleInfo);
290     if (ret != ERR_OK) {
291         ErrorLog("GetBundleInfoForSelf: get fail.");
292         return version;
293     }
294 
295     version = static_cast<int>(bundleInfo.targetVersion % 100); // %100 to get the real version
296     return version;
297 }
298 
GetConfigFromJson(const std::string & key,std::string & value)299 bool NfcSdkCommon::GetConfigFromJson(const std::string &key, std::string &value)
300 {
301     std::string content;
302     if (!LoadStringFromFile(NFC_SERVICE_CONFIG_PATH, content) || content.empty()) {
303         ErrorLog("fail to load string from nfc_service_config.json");
304         return false;
305     }
306     cJSON *json = cJSON_Parse(content.c_str());
307     if (json == nullptr) {
308         ErrorLog("json nullptr");
309         return false;
310     }
311     if (!cJSON_IsObject(json)) {
312         ErrorLog("reader is not cJSON object");
313         cJSON_Delete(json);
314         return false;
315     }
316     if (!NFC_SERVICE_CONFIG_KEY_SET.count(key)) {
317         WarnLog("current key[%{public}s] not exists!", key.c_str());
318         cJSON_Delete(json);
319         return false;
320     }
321 
322     cJSON *cJsonObject = cJSON_GetObjectItem(json, key.c_str());
323     if (cJsonObject == nullptr) {
324         ErrorLog("cJsonObject is nullptr.");
325         cJSON_Delete(json);
326         return false;
327     }
328     value = cJSON_GetStringValue(cJsonObject);
329     cJSON_Delete(json);
330     return true;
331 }
332 }  // namespace KITS
333 }  // namespace NFC
334 }  // namespace OHOS
335