• 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 
20 #include "accesstoken_kit.h"
21 #include "bundle_mgr_interface.h"
22 #include "bundle_mgr_proxy.h"
23 #include "if_system_ability_manager.h"
24 #include "iservice_registry.h"
25 #include "os_account_manager.h"
26 #include "system_ability_definition.h"
27 #include "tokenid_kit.h"
28 
29 #include "common_utils.h"
30 
31 #include "uri.h"
32 #include "constant_definition.h"
33 #include "location_data_rdb_helper.h"
34 #include "parameter.h"
35 #include "location_sa_load_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 
CheckLocationPermission(uint32_t tokenId,uint32_t firstTokenId)43 bool CommonUtils::CheckLocationPermission(uint32_t tokenId, uint32_t firstTokenId)
44 {
45     return CheckPermission(ACCESS_LOCATION, tokenId, firstTokenId);
46 }
47 
CheckPermission(const std::string & permission,uint32_t callerToken,uint32_t tokenFirstCaller)48 bool CommonUtils::CheckPermission(const std::string &permission, uint32_t callerToken, uint32_t tokenFirstCaller)
49 {
50     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
51     int result = Security::AccessToken::PERMISSION_DENIED;
52     if (tokenFirstCaller == 0) {
53         if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_INVALID) {
54             LBSLOGE(COMMON_UTILS, "tokenid = %{public}d has no permission.permission name=%{public}s",
55                 callerToken, permission.c_str());
56             return false;
57         } else {
58             result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permission);
59         }
60     } else {
61         result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, tokenFirstCaller, permission);
62     }
63     if (result == Security::AccessToken::PERMISSION_GRANTED) {
64         return true;
65     } else {
66         LBSLOGE(COMMON_UTILS, "tokenid = %{public}d has no permission.permission name=%{public}s",
67             callerToken, permission.c_str());
68         return false;
69     }
70 }
71 
CheckRssProcessName(uint32_t tokenId)72 bool CommonUtils::CheckRssProcessName(uint32_t tokenId)
73 {
74     Security::AccessToken::NativeTokenInfo callingTokenInfo;
75     Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, callingTokenInfo);
76     if (callingTokenInfo.processName != RSS_PROCESS_NAME) {
77         LBSLOGE(COMMON_UTILS, "CheckProcess failed, processName=%{public}s", callingTokenInfo.processName.c_str());
78         return false;
79     }
80     return true;
81 }
82 
CheckBackgroundPermission(uint32_t tokenId,uint32_t firstTokenId)83 bool CommonUtils::CheckBackgroundPermission(uint32_t tokenId, uint32_t firstTokenId)
84 {
85     return CheckPermission(ACCESS_BACKGROUND_LOCATION, tokenId, firstTokenId);
86 }
87 
CheckApproximatelyPermission(uint32_t tokenId,uint32_t firstTokenId)88 bool CommonUtils::CheckApproximatelyPermission(uint32_t tokenId, uint32_t firstTokenId)
89 {
90     return CheckPermission(ACCESS_APPROXIMATELY_LOCATION, tokenId, firstTokenId);
91 }
92 
CheckSecureSettings(uint32_t tokenId,uint32_t firstTokenId)93 bool CommonUtils::CheckSecureSettings(uint32_t tokenId, uint32_t firstTokenId)
94 {
95     return CheckPermission(MANAGE_SECURE_SETTINGS, tokenId, firstTokenId);
96 }
97 
CheckCallingPermission(pid_t callingUid,pid_t callingPid,MessageParcel & reply)98 bool CommonUtils::CheckCallingPermission(pid_t callingUid, pid_t callingPid, MessageParcel &reply)
99 {
100     if (callingUid != static_cast<pid_t>(getuid()) || callingPid != getpid()) {
101         LBSLOGE(COMMON_UTILS, "uid pid not match locationhub process.");
102         reply.WriteInt32(ERRCODE_PERMISSION_DENIED);
103         return false;
104     }
105     return true;
106 }
107 
GetPermissionLevel(uint32_t tokenId,uint32_t firstTokenId)108 int CommonUtils::GetPermissionLevel(uint32_t tokenId, uint32_t firstTokenId)
109 {
110     int ret = PERMISSION_INVALID;
111     if (CheckPermission(ACCESS_APPROXIMATELY_LOCATION, tokenId, firstTokenId) &&
112         CheckPermission(ACCESS_LOCATION, tokenId, firstTokenId)) {
113         ret = PERMISSION_ACCURATE;
114     } else if (CheckPermission(ACCESS_APPROXIMATELY_LOCATION, tokenId, firstTokenId) &&
115         !CheckPermission(ACCESS_LOCATION, tokenId, firstTokenId)) {
116         ret = PERMISSION_APPROXIMATELY;
117     } else if (!CheckPermission(ACCESS_APPROXIMATELY_LOCATION, tokenId, firstTokenId) &&
118         CheckPermission(ACCESS_LOCATION, tokenId, firstTokenId)) {
119         ret = PERMISSION_ACCURATE;
120     }  else {
121         ret = PERMISSION_INVALID;
122     }
123     return ret;
124 }
125 
AbilityConvertToId(const std::string ability)126 int CommonUtils::AbilityConvertToId(const std::string ability)
127 {
128     if (GNSS_ABILITY.compare(ability) == 0) {
129         return LOCATION_GNSS_SA_ID;
130     }
131     if (NETWORK_ABILITY.compare(ability) == 0) {
132         return LOCATION_NETWORK_LOCATING_SA_ID;
133     }
134     if (PASSIVE_ABILITY.compare(ability) == 0) {
135         return LOCATION_NOPOWER_LOCATING_SA_ID;
136     }
137     if (GEO_ABILITY.compare(ability) == 0) {
138         return LOCATION_GEO_CONVERT_SA_ID;
139     }
140     return -1;
141 }
142 
GetCapabilityToString(std::string ability,uint32_t capability)143 std::u16string CommonUtils::GetCapabilityToString(std::string ability, uint32_t capability)
144 {
145     std::string value = "{\"Capabilities\":{\"" + ability + "\":" + std::to_string(capability) + "}}";
146     return Str8ToStr16(value);
147 }
148 
GetCapability(std::string ability)149 std::u16string CommonUtils::GetCapability(std::string ability)
150 {
151     uint32_t capability = 0x102;
152     return GetCapabilityToString(ability, capability);
153 }
154 
GetLabel(std::string name)155 OHOS::HiviewDFX::HiLogLabel CommonUtils::GetLabel(std::string name)
156 {
157     if (GNSS_ABILITY.compare(name) == 0) {
158         return GNSS;
159     }
160     if (NETWORK_ABILITY.compare(name) == 0) {
161         return NETWORK;
162     }
163     if (PASSIVE_ABILITY.compare(name) == 0) {
164         return PASSIVE;
165     }
166     if (GEO_ABILITY.compare(name) == 0) {
167         return GEO_CONVERT;
168     }
169     OHOS::HiviewDFX::HiLogLabel label = { LOG_CORE, LOCATOR_LOG_ID, "unknown" };
170     return label;
171 }
172 
GetRemoteObject(int abilityId)173 sptr<IRemoteObject> CommonUtils::GetRemoteObject(int abilityId)
174 {
175     return GetRemoteObject(abilityId, InitDeviceId());
176 }
177 
GetRemoteObject(int abilityId,std::string deviceId)178 sptr<IRemoteObject> CommonUtils::GetRemoteObject(int abilityId, std::string deviceId)
179 {
180     std::unique_lock<std::mutex> lock(g_proxyMutex);
181     auto objectGnss = g_proxyMap->find(abilityId);
182     if (objectGnss == g_proxyMap->end()) {
183         auto manager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
184         if (manager == nullptr) {
185             LBSLOGE(COMMON_UTILS, "GetSystemAbilityManager is null.");
186             return nullptr;
187         }
188         sptr<IRemoteObject> object = manager->GetSystemAbility(abilityId, deviceId);
189         if (object == nullptr) {
190             LBSLOGE(COMMON_UTILS, "GetSystemAbility is null.");
191             return nullptr;
192         }
193         g_proxyMap->insert(std::make_pair(abilityId, object));
194         return object;
195     } else {
196         sptr<IRemoteObject> remoteObject = objectGnss->second;
197         return remoteObject;
198     }
199 }
200 
InitDeviceId()201 std::string CommonUtils::InitDeviceId()
202 {
203     std::string deviceId;
204     return deviceId;
205 }
206 
GetCurrentUserId(int & userId)207 bool CommonUtils::GetCurrentUserId(int &userId)
208 {
209     std::vector<int> activeIds;
210     int ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeIds);
211     if (ret != 0) {
212         LBSLOGE(COMMON_UTILS, "QueryActiveOsAccountIds failed ret:%{public}d", ret);
213         return false;
214     }
215     if (activeIds.empty()) {
216         LBSLOGE(COMMON_UTILS, "QueryActiveOsAccountIds activeIds empty");
217         return false;
218     }
219     userId = activeIds[0];
220     return true;
221 }
222 
Wait(int time)223 void CountDownLatch::Wait(int time)
224 {
225     LBSLOGD(LOCATOR_STANDARD, "enter wait, time = %{public}d", time);
226     std::unique_lock<std::mutex> lock(mutex_);
227     if (count_ == 0) {
228         LBSLOGE(LOCATOR_STANDARD, "count_ = 0");
229         return;
230     }
231     condition_.wait_for(lock, std::chrono::seconds(time / SEC_TO_MILLI_SEC), [&]() {return count_ == 0;});
232 }
233 
CountDown()234 void CountDownLatch::CountDown()
235 {
236     LBSLOGD(LOCATOR_STANDARD, "enter CountDown");
237     std::unique_lock<std::mutex> lock(mutex_);
238     int oldC = count_.load();
239     while (oldC > 0) {
240         if (count_.compare_exchange_strong(oldC, oldC - 1)) {
241             if (oldC == 1) {
242                 LBSLOGD(LOCATOR_STANDARD, "notify_all");
243                 condition_.notify_all();
244             }
245             break;
246         }
247         oldC = count_.load();
248     }
249 }
250 
GetCount()251 int CountDownLatch::GetCount()
252 {
253     std::unique_lock<std::mutex> lock(mutex_);
254     return count_;
255 }
256 
SetCount(int count)257 void CountDownLatch::SetCount(int count)
258 {
259     std::unique_lock<std::mutex> lock(mutex_);
260     count_ = count;
261 }
262 
Str16ToStr8(std::u16string str)263 std::string CommonUtils::Str16ToStr8(std::u16string str)
264 {
265     if (str == DEFAULT_USTRING) {
266         return DEFAULT_STRING;
267     }
268     std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert(DEFAULT_STRING);
269     std::string result = convert.to_bytes(str);
270     return result == DEFAULT_STRING ? "" : result;
271 }
272 
DoubleEqual(double a,double b)273 bool CommonUtils::DoubleEqual(double a, double b)
274 {
275     if (fabs(a - b) < 1e-6) {
276         return true;
277     } else {
278         return false;
279     }
280 }
281 
CalDistance(const double lat1,const double lon1,const double lat2,const double lon2)282 double CommonUtils::CalDistance(const double lat1, const double lon1, const double lat2, const double lon2)
283 {
284     double radLat1 = lat1 * PI / DEGREE_PI;
285     double radLat2 = lat2 * PI / DEGREE_PI;
286     double radLon1 = lon1 * PI / DEGREE_PI;
287     double radLon2 = lon2 * PI / DEGREE_PI;
288 
289     double latDiff = radLat1 - radLat2;
290     double lonDiff = radLon1 - radLon2;
291     double temp = sqrt(pow(sin(latDiff / DIS_FROMLL_PARAMETER), DIS_FROMLL_PARAMETER) +
292         cos(radLat1) * cos(radLat2) * pow(sin(lonDiff / DIS_FROMLL_PARAMETER), DIS_FROMLL_PARAMETER));
293     double disRad = asin(temp) * DIS_FROMLL_PARAMETER;
294     double dis = disRad * EARTH_RADIUS;
295     return dis;
296 }
297 
DoubleRandom(double min,double max)298 double CommonUtils::DoubleRandom(double min, double max)
299 {
300     double param = 0.0;
301     std::random_device rd;
302     static std::uniform_real_distribution<double> u(min, max);
303     static std::default_random_engine e(rd());
304     param = u(e);
305     return param;
306 }
307 
IntRandom(int min,int max)308 int CommonUtils::IntRandom(int min, int max)
309 {
310     int param = 0;
311     std::random_device rd;
312     static std::uniform_int_distribution<int> u(min, max);
313     static std::default_random_engine e(rd());
314     param = u(e);
315     return param;
316 }
317 
CheckSystemPermission(uint32_t callerTokenId,uint64_t callerTokenIdEx)318 bool CommonUtils::CheckSystemPermission(uint32_t callerTokenId, uint64_t callerTokenIdEx)
319 {
320     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerTokenId);
321     if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
322         return true;
323     }
324     if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL ||
325         tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_INVALID) {
326         return false;
327     }
328     bool isSysApp = Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(callerTokenIdEx);
329     return isSysApp;
330 }
331 
GetBundleNameByUid(int32_t uid,std::string & bundleName)332 bool CommonUtils::GetBundleNameByUid(int32_t uid, std::string& bundleName)
333 {
334     sptr<ISystemAbilityManager> smgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
335     if (smgr == nullptr) {
336         LBSLOGE(COMMON_UTILS, "%{public}s Fail to get system ability manager.", __func__);
337         return false;
338     }
339     sptr<IRemoteObject> remoteObject = smgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
340     if (remoteObject == nullptr) {
341         LBSLOGE(COMMON_UTILS, "%{public}s Fail to get sa obj.", __func__);
342         return false;
343     }
344     sptr<AppExecFwk::IBundleMgr> bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(remoteObject);
345     if (bundleMgr == nullptr) {
346         LBSLOGE(COMMON_UTILS, "%{public}s Bundle mgr proxy is nullptr.", __func__);
347         return false;
348     }
349     int32_t error = bundleMgr->GetNameForUid(uid, bundleName);
350     if (error != ERR_OK) {
351         return false;
352     }
353     return true;
354 }
355 
356 /*
357  * Check whether the application is installed by bundleName
358  * @param bundleName
359  * @return true if app is installed
360  * @return false if app is not installed
361  */
CheckAppInstalled(const std::string & bundleName)362 bool CommonUtils::CheckAppInstalled(const std::string& bundleName)
363 {
364     int userId = 0;
365     bool ret = GetCurrentUserId(userId);
366     if (!ret) {
367         LBSLOGE(COMMON_UTILS, "GetCurrentUserId failed");
368         return false;
369     }
370     auto systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
371     if (systemManager == nullptr) {
372         LBSLOGE(COMMON_UTILS, "fail to get system ability manager!");
373         return false;
374     }
375     auto bundleMgrSa = systemManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
376     if (bundleMgrSa == nullptr) {
377         LBSLOGE(COMMON_UTILS, "fail to get bundle manager system ability!");
378         return false;
379     }
380     auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bundleMgrSa);
381     if (bundleMgr == nullptr) {
382         LBSLOGE(COMMON_UTILS, "Bundle mgr is nullptr.");
383         return false;
384     }
385     AppExecFwk::ApplicationInfo info;
386     bundleMgr->GetApplicationInfoV9(bundleName, 0, userId, info);
387     if (info.name.empty() || info.bundleName.empty()) {
388         return false;
389     }
390     return true;
391 }
392 
CheckIfSystemAbilityAvailable(int32_t systemAbilityId)393 bool CommonUtils::CheckIfSystemAbilityAvailable(int32_t systemAbilityId)
394 {
395     sptr<ISystemAbilityManager> samgr =
396         SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
397     if (samgr == nullptr) {
398         LBSLOGE(LOCATOR, "%{public}s: get system ability manager failed!", __func__);
399         return false;
400     }
401     return (samgr->CheckSystemAbility(systemAbilityId) != nullptr);
402 }
403 
QuerySwitchState()404 int CommonUtils::QuerySwitchState()
405 {
406     int32_t state = DISABLED;
407     Uri locationDataEnableUri(LOCATION_DATA_URI);
408     LocationErrCode errCode = DelayedSingleton<LocationDataRdbHelper>::GetInstance()->
409         GetValue(locationDataEnableUri, LOCATION_DATA_COLUMN_ENABLE, state);
410     if (errCode != ERRCODE_SUCCESS) {
411         LBSLOGE(LOCATOR, "%{public}s: can not query state, reset state.", __func__);
412         DelayedSingleton<LocationDataRdbHelper>::GetInstance()->
413             SetValue(locationDataEnableUri, LOCATION_DATA_COLUMN_ENABLE, state);
414     }
415     return state;
416 }
417 
GetCurrentTime()418 int64_t CommonUtils::GetCurrentTime()
419 {
420     struct timespec times = {0, 0};
421     clock_gettime(CLOCK_MONOTONIC, &times);
422     int64_t second = static_cast<int64_t>(times.tv_sec);
423     return second;
424 }
425 
GetCurrentTimeStamp()426 int64_t CommonUtils::GetCurrentTimeStamp()
427 {
428     struct timeval currentTime;
429     gettimeofday(&currentTime, nullptr);
430     return static_cast<int64_t>(currentTime.tv_sec);
431 }
432 
Split(std::string str,std::string pattern)433 std::vector<std::string> CommonUtils::Split(std::string str, std::string pattern)
434 {
435     std::vector<std::string> result;
436     str += pattern;
437     size_t size = str.size();
438     size_t i = 0;
439     while (i < size) {
440         size_t pos = str.find(pattern, i);
441         if (pos != std::string::npos && pos < size) {
442             std::string s = str.substr(i, pos - i);
443             result.push_back(s);
444             i = pos + pattern.size() - 1;
445         }
446         i++;
447     }
448     return result;
449 }
450 
ConvertStringToDigit(std::string str)451 uint8_t CommonUtils::ConvertStringToDigit(std::string str)
452 {
453     uint8_t res = 0;
454     constexpr int bitWidth = 4;
455     constexpr int numDiffForHexAlphabet = 10;
456     for (auto ch : str) {
457         res = res << bitWidth;
458         if (ch >= '0' && ch <= '9') {
459             res += (ch - '0');
460         }
461         if (ch >= 'A' && ch <= 'F') {
462             res += (ch - 'A' + numDiffForHexAlphabet);
463         }
464         if (ch >= 'a' && ch <= 'f') {
465             res += (ch - 'a' + numDiffForHexAlphabet);
466         }
467     }
468     return res;
469 }
470 
GetMacArray(const std::string & strMac,uint8_t mac[MAC_LEN])471 errno_t CommonUtils::GetMacArray(const std::string& strMac, uint8_t mac[MAC_LEN])
472 {
473     std::vector<std::string> strVec = Split(strMac, ":");
474     for (size_t i = 0; i < strVec.size() && i < MAC_LEN; i++) {
475         mac[i] = ConvertStringToDigit(strVec[i]);
476     }
477     return EOK;
478 }
479 
GetStringParameter(const std::string & type,std::string & value)480 bool CommonUtils::GetStringParameter(const std::string& type, std::string& value)
481 {
482     char result[MAX_BUFF_SIZE] = {0};
483     auto res = GetParameter(type.c_str(), "", result, MAX_BUFF_SIZE);
484     if (res <= 0) {
485         LBSLOGE(LOCATOR, "%{public}s get para value failed, res: %{public}d",
486             __func__, res);
487         return false;
488     }
489     value = result;
490     return true;
491 }
492 
GetEdmPolicy(std::string & name)493 bool CommonUtils::GetEdmPolicy(std::string& name)
494 {
495     return GetStringParameter(EDM_POLICY_NAME, name);
496 }
497 
InitLocationSa(int32_t systemAbilityId)498 bool CommonUtils::InitLocationSa(int32_t systemAbilityId)
499 {
500     if (CommonUtils::CheckIfSystemAbilityAvailable(systemAbilityId)) {
501         LBSLOGD(LOCATOR, "sa has been loaded");
502         return true;
503     }
504     auto instance = DelayedSingleton<LocationSaLoadManager>::GetInstance();
505     if (instance == nullptr || instance->LoadLocationSa(systemAbilityId) != ERRCODE_SUCCESS) {
506         LBSLOGE(LOCATOR, "sa load failed.");
507         return false;
508     }
509     return true;
510 }
511 } // namespace Location
512 } // namespace OHOS
513