1 /*
2 * Copyright (C) 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 <map>
17 #include <random>
18 #include <sys/time.h>
19 #include <sstream>
20
21 #include "common_utils.h"
22
23 #include "bundle_mgr_interface.h"
24 #include "bundle_mgr_proxy.h"
25 #include "if_system_ability_manager.h"
26 #include "iservice_registry.h"
27 #include "system_ability_definition.h"
28 #include "constant_definition.h"
29 #include "parameter.h"
30 #include "location_sa_load_manager.h"
31 #include "hook_utils.h"
32 #include "accesstoken_kit.h"
33 #include "os_account_manager.h"
34 #include "os_account_info.h"
35 #include "permission_manager.h"
36
37 namespace OHOS {
38 namespace Location {
39 static std::shared_ptr<std::map<int, sptr<IRemoteObject>>> g_proxyMap =
40 std::make_shared<std::map<int, sptr<IRemoteObject>>>();
41 std::mutex g_proxyMutex;
42 static std::random_device g_randomDevice;
43 static std::mt19937 g_gen(g_randomDevice());
44 static std::uniform_int_distribution<> g_dis(0, 15); // random between 0 and 15
45 static std::uniform_int_distribution<> g_dis2(8, 11); // random between 8 and 11
46 const int64_t SEC_TO_NANO = 1000 * 1000 * 1000;
AbilityConvertToId(const std::string ability)47 int CommonUtils::AbilityConvertToId(const std::string ability)
48 {
49 if (GNSS_ABILITY.compare(ability) == 0) {
50 return LOCATION_GNSS_SA_ID;
51 }
52 if (NETWORK_ABILITY.compare(ability) == 0) {
53 return LOCATION_NETWORK_LOCATING_SA_ID;
54 }
55 if (PASSIVE_ABILITY.compare(ability) == 0) {
56 return LOCATION_NOPOWER_LOCATING_SA_ID;
57 }
58 if (GEO_ABILITY.compare(ability) == 0) {
59 return LOCATION_GEO_CONVERT_SA_ID;
60 }
61 return -1;
62 }
63
GetCapabilityToString(std::string ability,uint32_t capability)64 std::u16string CommonUtils::GetCapabilityToString(std::string ability, uint32_t capability)
65 {
66 std::string value = "{\"Capabilities\":{\"" + ability + "\":" + std::to_string(capability) + "}}";
67 return Str8ToStr16(value);
68 }
69
GetCapability(std::string ability)70 std::u16string CommonUtils::GetCapability(std::string ability)
71 {
72 uint32_t capability = 0x102;
73 return GetCapabilityToString(ability, capability);
74 }
75
GetLabel(std::string name)76 OHOS::HiviewDFX::HiLogLabel CommonUtils::GetLabel(std::string name)
77 {
78 if (GNSS_ABILITY.compare(name) == 0) {
79 return GNSS;
80 }
81 if (NETWORK_ABILITY.compare(name) == 0) {
82 return NETWORK;
83 }
84 if (PASSIVE_ABILITY.compare(name) == 0) {
85 return PASSIVE;
86 }
87 if (GEO_ABILITY.compare(name) == 0) {
88 return GEO_CONVERT;
89 }
90 OHOS::HiviewDFX::HiLogLabel label = { LOG_CORE, LOCATION_LOG_DOMAIN, "unknown" };
91 return label;
92 }
93
GetRemoteObject(int abilityId)94 sptr<IRemoteObject> CommonUtils::GetRemoteObject(int abilityId)
95 {
96 return GetRemoteObject(abilityId, InitDeviceId());
97 }
98
GetRemoteObject(int abilityId,std::string deviceId)99 sptr<IRemoteObject> CommonUtils::GetRemoteObject(int abilityId, std::string deviceId)
100 {
101 std::unique_lock<std::mutex> lock(g_proxyMutex);
102 auto objectGnss = g_proxyMap->find(abilityId);
103 if (objectGnss == g_proxyMap->end()) {
104 auto manager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
105 if (manager == nullptr) {
106 LBSLOGE(COMMON_UTILS, "GetSystemAbilityManager is null.");
107 return nullptr;
108 }
109 sptr<IRemoteObject> object = manager->GetSystemAbility(abilityId, deviceId);
110 if (object == nullptr) {
111 LBSLOGE(COMMON_UTILS, "GetSystemAbility is null.");
112 return nullptr;
113 }
114 g_proxyMap->insert(std::make_pair(abilityId, object));
115 return object;
116 } else {
117 sptr<IRemoteObject> remoteObject = objectGnss->second;
118 return remoteObject;
119 }
120 }
121
InitDeviceId()122 std::string CommonUtils::InitDeviceId()
123 {
124 std::string deviceId;
125 return deviceId;
126 }
127
GetCurrentUserId(int & userId)128 bool CommonUtils::GetCurrentUserId(int &userId)
129 {
130 std::vector<int> activeIds;
131 int ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeIds);
132 if (ret != 0) {
133 LBSLOGI(COMMON_UTILS, "GetCurrentUserId failed ret:%{public}d", ret);
134 return false;
135 }
136 if (activeIds.empty()) {
137 LBSLOGE(COMMON_UTILS, "QueryActiveOsAccountIds activeIds empty");
138 return false;
139 }
140 userId = activeIds[0];
141 return true;
142 }
143
GetAllUserId(std::vector<int> & activeIds)144 bool CommonUtils::GetAllUserId(std::vector<int>& activeIds)
145 {
146 std::vector<AccountSA::OsAccountInfo> accountInfos;
147 int ret = AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(accountInfos);
148 if (ret != 0) {
149 LBSLOGE(COMMON_UTILS, "GetAllUserId failed ret:%{public}d", ret);
150 return false;
151 }
152 for (auto &info : accountInfos) {
153 activeIds.push_back(info.GetLocalId());
154 }
155 if (activeIds.empty()) {
156 LBSLOGE(COMMON_UTILS, "QueryActiveOsAccountIds activeIds empty");
157 return false;
158 }
159 return true;
160 }
161
Wait(int time)162 void CountDownLatch::Wait(int time)
163 {
164 LBSLOGD(LOCATOR_STANDARD, "enter wait, time = %{public}d", time);
165 std::unique_lock<std::mutex> lock(mutex_);
166 if (count_ == 0) {
167 LBSLOGE(LOCATOR_STANDARD, "count_ = 0");
168 return;
169 }
170 condition_.wait_for(lock, std::chrono::seconds(time / MILLI_PER_SEC), [&]() {return count_ == 0;});
171 }
172
CountDown()173 void CountDownLatch::CountDown()
174 {
175 LBSLOGD(LOCATOR_STANDARD, "enter CountDown");
176 std::unique_lock<std::mutex> lock(mutex_);
177 int oldC = count_.load();
178 while (oldC > 0) {
179 if (count_.compare_exchange_strong(oldC, oldC - 1)) {
180 if (oldC == 1) {
181 LBSLOGD(LOCATOR_STANDARD, "notify_all");
182 condition_.notify_all();
183 }
184 break;
185 }
186 oldC = count_.load();
187 }
188 }
189
GetCount()190 int CountDownLatch::GetCount()
191 {
192 std::unique_lock<std::mutex> lock(mutex_);
193 return count_;
194 }
195
SetCount(int count)196 void CountDownLatch::SetCount(int count)
197 {
198 std::unique_lock<std::mutex> lock(mutex_);
199 count_ = count;
200 }
201
Str16ToStr8(std::u16string str)202 std::string CommonUtils::Str16ToStr8(std::u16string str)
203 {
204 if (str == DEFAULT_USTRING) {
205 return DEFAULT_STRING;
206 }
207 std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert(DEFAULT_STRING);
208 std::string result = convert.to_bytes(str);
209 return result == DEFAULT_STRING ? "" : result;
210 }
211
DoubleEqual(double a,double b)212 bool CommonUtils::DoubleEqual(double a, double b)
213 {
214 if (fabs(a - b) < 1e-6) {
215 return true;
216 } else {
217 return false;
218 }
219 }
220
CalDistance(const double lat1,const double lon1,const double lat2,const double lon2)221 double CommonUtils::CalDistance(const double lat1, const double lon1, const double lat2, const double lon2)
222 {
223 double radLat1 = lat1 * PI / DEGREE_PI;
224 double radLat2 = lat2 * PI / DEGREE_PI;
225 double radLon1 = lon1 * PI / DEGREE_PI;
226 double radLon2 = lon2 * PI / DEGREE_PI;
227
228 double latDiff = radLat1 - radLat2;
229 double lonDiff = radLon1 - radLon2;
230 double temp = sqrt(pow(sin(latDiff / DIS_FROMLL_PARAMETER), DIS_FROMLL_PARAMETER) +
231 cos(radLat1) * cos(radLat2) * pow(sin(lonDiff / DIS_FROMLL_PARAMETER), DIS_FROMLL_PARAMETER));
232 double disRad = asin(temp) * DIS_FROMLL_PARAMETER;
233 double dis = disRad * EARTH_RADIUS;
234 return dis;
235 }
236
DoubleRandom(double min,double max)237 double CommonUtils::DoubleRandom(double min, double max)
238 {
239 double param = 0.0;
240 std::random_device rd;
241 static std::uniform_real_distribution<double> u(min, max);
242 static std::default_random_engine e(rd());
243 param = u(e);
244 return param;
245 }
246
IntRandom(int min,int max)247 int CommonUtils::IntRandom(int min, int max)
248 {
249 int param = 0;
250 std::random_device rd;
251 static std::uniform_int_distribution<int> u(min, max);
252 static std::default_random_engine e(rd());
253 param = u(e);
254 return param;
255 }
256
GetBundleNameByUid(int32_t uid,std::string & bundleName)257 bool CommonUtils::GetBundleNameByUid(int32_t uid, std::string& bundleName)
258 {
259 sptr<ISystemAbilityManager> smgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
260 if (smgr == nullptr) {
261 LBSLOGE(COMMON_UTILS, "%{public}s Fail to get system ability manager.", __func__);
262 return false;
263 }
264 sptr<IRemoteObject> remoteObject = smgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
265 if (remoteObject == nullptr) {
266 LBSLOGE(COMMON_UTILS, "%{public}s Fail to get sa obj.", __func__);
267 return false;
268 }
269 sptr<AppExecFwk::IBundleMgr> bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
270 if (bundleMgr == nullptr) {
271 LBSLOGE(COMMON_UTILS, "%{public}s Bundle mgr proxy is nullptr.", __func__);
272 return false;
273 }
274 int32_t error = bundleMgr->GetNameForUid(uid, bundleName);
275 if (error != ERR_OK) {
276 return false;
277 }
278 return true;
279 }
280
281 /*
282 * Check whether the application is installed by bundleName
283 * @param bundleName
284 * @return true if app is installed
285 * @return false if app is not installed
286 */
CheckAppInstalled(const std::string & bundleName)287 bool CommonUtils::CheckAppInstalled(const std::string& bundleName)
288 {
289 int userId = 0;
290 bool ret = GetCurrentUserId(userId);
291 if (!ret) {
292 LBSLOGE(COMMON_UTILS, "GetCurrentUserId failed");
293 return false;
294 }
295 auto systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
296 if (systemManager == nullptr) {
297 LBSLOGE(COMMON_UTILS, "fail to get system ability manager!");
298 return false;
299 }
300 auto bundleMgrSa = systemManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
301 if (bundleMgrSa == nullptr) {
302 LBSLOGE(COMMON_UTILS, "fail to get bundle manager system ability!");
303 return false;
304 }
305 auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bundleMgrSa);
306 if (bundleMgr == nullptr) {
307 LBSLOGE(COMMON_UTILS, "Bundle mgr is nullptr.");
308 return false;
309 }
310 AppExecFwk::ApplicationInfo info;
311 bundleMgr->GetApplicationInfoV9(bundleName, 0, userId, info);
312 if (info.name.empty() || info.bundleName.empty()) {
313 return false;
314 }
315 return true;
316 }
317
GetCurrentTime()318 int64_t CommonUtils::GetCurrentTime()
319 {
320 struct timespec times = {0, 0};
321 clock_gettime(CLOCK_MONOTONIC, ×);
322 int64_t second = static_cast<int64_t>(times.tv_sec);
323 return second;
324 }
325
GetCurrentTimeStamp()326 int64_t CommonUtils::GetCurrentTimeStamp()
327 {
328 struct timeval currentTime;
329 gettimeofday(¤tTime, nullptr);
330 return static_cast<int64_t>(currentTime.tv_sec);
331 }
332
Split(std::string str,std::string pattern)333 std::vector<std::string> CommonUtils::Split(std::string str, std::string pattern)
334 {
335 std::vector<std::string> result;
336 str += pattern;
337 size_t size = str.size();
338 size_t i = 0;
339 while (i < size) {
340 size_t pos = str.find(pattern, i);
341 if (pos != std::string::npos && pos < size) {
342 std::string s = str.substr(i, pos - i);
343 result.push_back(s);
344 i = pos + pattern.size() - 1;
345 }
346 i++;
347 }
348 return result;
349 }
350
ConvertStringToDigit(std::string str)351 uint8_t CommonUtils::ConvertStringToDigit(std::string str)
352 {
353 uint8_t res = 0;
354 constexpr int bitWidth = 4;
355 constexpr int numDiffForHexAlphabet = 10;
356 for (auto ch : str) {
357 res = res << bitWidth;
358 if (ch >= '0' && ch <= '9') {
359 res += (ch - '0');
360 }
361 if (ch >= 'A' && ch <= 'F') {
362 res += (ch - 'A' + numDiffForHexAlphabet);
363 }
364 if (ch >= 'a' && ch <= 'f') {
365 res += (ch - 'a' + numDiffForHexAlphabet);
366 }
367 }
368 return res;
369 }
370
GetMacArray(const std::string & strMac,uint8_t mac[MAC_LEN])371 errno_t CommonUtils::GetMacArray(const std::string& strMac, uint8_t mac[MAC_LEN])
372 {
373 std::vector<std::string> strVec = Split(strMac, ":");
374 for (size_t i = 0; i < strVec.size() && i < MAC_LEN; i++) {
375 mac[i] = ConvertStringToDigit(strVec[i]);
376 }
377 return EOK;
378 }
379
GetStringParameter(const std::string & type,std::string & value)380 bool CommonUtils::GetStringParameter(const std::string& type, std::string& value)
381 {
382 char result[MAX_BUFF_SIZE] = {0};
383 auto res = GetParameter(type.c_str(), "", result, MAX_BUFF_SIZE);
384 if (res <= 0) {
385 LBSLOGE(COMMON_UTILS, "%{public}s get para value failed, res: %{public}d",
386 __func__, res);
387 return false;
388 }
389 value = result;
390 return true;
391 }
392
GetEdmPolicy(std::string & name)393 bool CommonUtils::GetEdmPolicy(std::string& name)
394 {
395 return GetStringParameter(EDM_POLICY_NAME, name);
396 }
397
GenerateUuid()398 std::string CommonUtils::GenerateUuid()
399 {
400 std::stringstream ss;
401 int i;
402 ss << std::hex;
403 for (i = 0; i < 8; i++) { // first group 8 bit for UUID
404 ss << g_dis(g_gen);
405 }
406 ss << "-";
407 for (i = 0; i < 4; i++) { // second group 4 bit for UUID
408 ss << g_dis(g_gen);
409 }
410 ss << "-4";
411 for (i = 0; i < 3; i++) { // third group 3 bit for UUID
412 ss << g_dis(g_gen);
413 }
414 ss << "-";
415 ss << g_dis2(g_gen);
416 for (i = 0; i < 3; i++) { // fourth group 3 bit for UUID
417 ss << g_dis(g_gen);
418 }
419 ss << "-";
420 for (i = 0; i < 12; i++) { // fifth group 12 bit for UUID
421 ss << g_dis(g_gen);
422 };
423 return ss.str();
424 }
425
CheckAppForUser(int32_t uid)426 bool CommonUtils::CheckAppForUser(int32_t uid)
427 {
428 int currentUserId = 0;
429 int userId = 0;
430 bool ret = GetCurrentUserId(currentUserId);
431 if (!ret) {
432 return true;
433 }
434 auto result = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
435 if (result != ERR_OK) {
436 return true;
437 }
438 if (userId != 0 && userId != currentUserId) {
439 return false;
440 }
441 return true;
442 }
443
GetSinceBootTime()444 int64_t CommonUtils::GetSinceBootTime()
445 {
446 int result;
447 struct timespec ts;
448 result = clock_gettime(CLOCK_BOOTTIME, &ts);
449 if (result == 0) {
450 return ts.tv_sec * SEC_TO_NANO + ts.tv_nsec;
451 } else {
452 return 0;
453 }
454 }
455 } // namespace Location
456 } // namespace OHOS
457