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;
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         LBSLOGI(COMMON_UTILS, "GetCurrentUserId failed ret:%{public}d", ret);
135         return false;
136     }
137     if (activeIds.empty()) {
138         LBSLOGE(COMMON_UTILS, "QueryActiveOsAccountIds activeIds empty");
139         return false;
140     }
141     userId = activeIds[0];
142     return true;
143 }
144 
GetAllUserId(std::vector<int> & activeIds)145 bool CommonUtils::GetAllUserId(std::vector<int>& activeIds)
146 {
147     std::vector<AccountSA::OsAccountInfo> accountInfos;
148     int ret = AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(accountInfos);
149     if (ret != 0) {
150         LBSLOGE(COMMON_UTILS, "GetAllUserId failed ret:%{public}d", ret);
151         return false;
152     }
153     for (auto &info : accountInfos) {
154         activeIds.push_back(info.GetLocalId());
155     }
156     if (activeIds.empty()) {
157         LBSLOGE(COMMON_UTILS, "QueryActiveOsAccountIds activeIds empty");
158         return false;
159     }
160     return true;
161 }
162 
Wait(int time)163 void CountDownLatch::Wait(int time)
164 {
165     LBSLOGD(LOCATOR_STANDARD, "enter wait, time = %{public}d", time);
166     std::unique_lock<std::mutex> lock(mutex_);
167     if (count_ == 0) {
168         LBSLOGE(LOCATOR_STANDARD, "count_ = 0");
169         return;
170     }
171     condition_.wait_for(lock, std::chrono::seconds(time / MILLI_PER_SEC), [&]() {return count_ == 0;});
172 }
173 
CountDown()174 void CountDownLatch::CountDown()
175 {
176     LBSLOGD(LOCATOR_STANDARD, "enter CountDown");
177     std::unique_lock<std::mutex> lock(mutex_);
178     int oldC = count_.load();
179     while (oldC > 0) {
180         if (count_.compare_exchange_strong(oldC, oldC - 1)) {
181             if (oldC == 1) {
182                 LBSLOGD(LOCATOR_STANDARD, "notify_all");
183                 condition_.notify_all();
184             }
185             break;
186         }
187         oldC = count_.load();
188     }
189 }
190 
GetCount()191 int CountDownLatch::GetCount()
192 {
193     std::unique_lock<std::mutex> lock(mutex_);
194     return count_;
195 }
196 
SetCount(int count)197 void CountDownLatch::SetCount(int count)
198 {
199     std::unique_lock<std::mutex> lock(mutex_);
200     count_ = count;
201 }
202 
Str16ToStr8(std::u16string str)203 std::string CommonUtils::Str16ToStr8(std::u16string str)
204 {
205     if (str == DEFAULT_USTRING) {
206         return DEFAULT_STRING;
207     }
208     std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert(DEFAULT_STRING);
209     std::string result = convert.to_bytes(str);
210     return result == DEFAULT_STRING ? "" : result;
211 }
212 
DoubleEqual(double a,double b)213 bool CommonUtils::DoubleEqual(double a, double b)
214 {
215     if (fabs(a - b) < 1e-6) {
216         return true;
217     } else {
218         return false;
219     }
220 }
221 
CalDistance(const double lat1,const double lon1,const double lat2,const double lon2)222 double CommonUtils::CalDistance(const double lat1, const double lon1, const double lat2, const double lon2)
223 {
224     double radLat1 = lat1 * PI / DEGREE_PI;
225     double radLat2 = lat2 * PI / DEGREE_PI;
226     double radLon1 = lon1 * PI / DEGREE_PI;
227     double radLon2 = lon2 * PI / DEGREE_PI;
228 
229     double latDiff = radLat1 - radLat2;
230     double lonDiff = radLon1 - radLon2;
231     double temp = sqrt(pow(sin(latDiff / DIS_FROMLL_PARAMETER), DIS_FROMLL_PARAMETER) +
232         cos(radLat1) * cos(radLat2) * pow(sin(lonDiff / DIS_FROMLL_PARAMETER), DIS_FROMLL_PARAMETER));
233     double disRad = asin(temp) * DIS_FROMLL_PARAMETER;
234     double dis = disRad * EARTH_RADIUS;
235     return dis;
236 }
237 
DoubleRandom(double min,double max)238 double CommonUtils::DoubleRandom(double min, double max)
239 {
240     double param = 0.0;
241     std::random_device rd;
242     static std::uniform_real_distribution<double> u(min, max);
243     static std::default_random_engine e(rd());
244     param = u(e);
245     return param;
246 }
247 
IntRandom(int min,int max)248 int CommonUtils::IntRandom(int min, int max)
249 {
250     int param = 0;
251     std::random_device rd;
252     static std::uniform_int_distribution<int> u(min, max);
253     static std::default_random_engine e(rd());
254     param = u(e);
255     return param;
256 }
257 
GetBundleNameByUid(int32_t uid,std::string & bundleName)258 bool CommonUtils::GetBundleNameByUid(int32_t uid, std::string& bundleName)
259 {
260     sptr<ISystemAbilityManager> smgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
261     if (smgr == nullptr) {
262         LBSLOGE(COMMON_UTILS, "%{public}s Fail to get system ability manager.", __func__);
263         return false;
264     }
265     sptr<IRemoteObject> remoteObject = smgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
266     if (remoteObject == nullptr) {
267         LBSLOGE(COMMON_UTILS, "%{public}s Fail to get sa obj.", __func__);
268         return false;
269     }
270     sptr<AppExecFwk::IBundleMgr> bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
271     if (bundleMgr == nullptr) {
272         LBSLOGE(COMMON_UTILS, "%{public}s Bundle mgr proxy is nullptr.", __func__);
273         return false;
274     }
275     int32_t error = bundleMgr->GetNameForUid(uid, bundleName);
276     if (error != ERR_OK) {
277         return false;
278     }
279     return true;
280 }
281 
282 /*
283  * Check whether the application is installed by bundleName
284  * @param bundleName
285  * @return true if app is installed
286  * @return false if app is not installed
287  */
CheckAppInstalled(const std::string & bundleName)288 bool CommonUtils::CheckAppInstalled(const std::string& bundleName)
289 {
290     int userId = 0;
291     bool ret = GetCurrentUserId(userId);
292     if (!ret) {
293         LBSLOGE(COMMON_UTILS, "GetCurrentUserId failed");
294         return false;
295     }
296     auto systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
297     if (systemManager == nullptr) {
298         LBSLOGE(COMMON_UTILS, "fail to get system ability manager!");
299         return false;
300     }
301     auto bundleMgrSa = systemManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
302     if (bundleMgrSa == nullptr) {
303         LBSLOGE(COMMON_UTILS, "fail to get bundle manager system ability!");
304         return false;
305     }
306     auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bundleMgrSa);
307     if (bundleMgr == nullptr) {
308         LBSLOGE(COMMON_UTILS, "Bundle mgr is nullptr.");
309         return false;
310     }
311     AppExecFwk::ApplicationInfo info;
312     bundleMgr->GetApplicationInfoV9(bundleName, 0, userId, info);
313     if (info.name.empty() || info.bundleName.empty()) {
314         return false;
315     }
316     return true;
317 }
318 
GetCurrentTime()319 int64_t CommonUtils::GetCurrentTime()
320 {
321     struct timespec times = {0, 0};
322     clock_gettime(CLOCK_MONOTONIC, &times);
323     int64_t second = static_cast<int64_t>(times.tv_sec);
324     return second;
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 
GetMacArray(const std::string & strMac,uint8_t mac[MAC_LEN])372 errno_t CommonUtils::GetMacArray(const std::string& strMac, uint8_t mac[MAC_LEN])
373 {
374     std::vector<std::string> strVec = Split(strMac, ":");
375     for (size_t i = 0; i < strVec.size() && i < MAC_LEN; i++) {
376         mac[i] = ConvertStringToDigit(strVec[i]);
377     }
378     return EOK;
379 }
380 
GetStringParameter(const std::string & type,std::string & value)381 bool CommonUtils::GetStringParameter(const std::string& type, std::string& value)
382 {
383     char result[MAX_BUFF_SIZE] = {0};
384     auto res = GetParameter(type.c_str(), "", result, MAX_BUFF_SIZE);
385     if (res <= 0) {
386         LBSLOGE(COMMON_UTILS, "%{public}s get para value failed, res: %{public}d",
387             __func__, res);
388         return false;
389     }
390     value = result;
391     return true;
392 }
393 
GetEdmPolicy(std::string & name)394 bool CommonUtils::GetEdmPolicy(std::string& name)
395 {
396     return GetStringParameter(EDM_POLICY_NAME, name);
397 }
398 
GenerateUuid()399 std::string CommonUtils::GenerateUuid()
400 {
401     std::stringstream ss;
402     int i;
403     ss << std::hex;
404     for (i = 0; i < 8; i++) {  // first group 8 bit for UUID
405         ss << g_dis(g_gen);
406     }
407     ss << "-";
408     for (i = 0; i < 4; i++) {  // second group 4 bit for UUID
409         ss << g_dis(g_gen);
410     }
411     ss << "-4";
412     for (i = 0; i < 3; i++) {  // third group 3 bit for UUID
413         ss << g_dis(g_gen);
414     }
415     ss << "-";
416     ss << g_dis2(g_gen);
417     for (i = 0; i < 3; i++) {  // fourth group 3 bit for UUID
418         ss << g_dis(g_gen);
419     }
420     ss << "-";
421     for (i = 0; i < 12; i++) {  // fifth group 12 bit for UUID
422         ss << g_dis(g_gen);
423     };
424     return ss.str();
425 }
426 
CheckAppForUser(int32_t uid)427 bool CommonUtils::CheckAppForUser(int32_t uid)
428 {
429     std::string bundleName = "";
430     if (CommonUtils::GetBundleNameByUid(uid, bundleName)) {
431         if (HookUtils::ExecuteHookWhenCheckAppForUser(bundleName)) {
432             return true;
433         }
434     }
435     int currentUserId = 0;
436     int userId = 0;
437     if (!GetCurrentUserId(currentUserId)) {
438         currentUserId = DEFAULT_USERID;
439     }
440     auto result = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId);
441     if (result != ERR_OK) {
442         LBSLOGE(COMMON_UTILS, "CheckAppForUser GetOsAccountLocalIdFromUid fail");
443         return false;
444     }
445     if (userId != 0 && userId != currentUserId) {
446         return false;
447     }
448     return true;
449 }
450 
GetSinceBootTime()451 int64_t CommonUtils::GetSinceBootTime()
452 {
453     int result;
454     struct timespec ts;
455     result = clock_gettime(CLOCK_BOOTTIME, &ts);
456     if (result == 0) {
457         return ts.tv_sec * SEC_TO_NANO + ts.tv_nsec;
458     } else {
459         return 0;
460     }
461 }
462 
IsAppBelongCurrentAccount(AppIdentity & identity)463 bool CommonUtils::IsAppBelongCurrentAccount(AppIdentity &identity)
464 {
465     if (PermissionManager::CheckIsSystemSa(identity.GetTokenId())) {
466         return true;
467     }
468     if (CommonUtils::CheckAppForUser(identity.GetUid())) {
469         return true;
470     }
471     return false;
472 }
473 } // namespace Location
474 } // namespace OHOS
475