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