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