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