• 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 
19 #include "accesstoken_kit.h"
20 #include "bundle_mgr_interface.h"
21 #include "bundle_mgr_proxy.h"
22 #include "if_system_ability_manager.h"
23 #include "iservice_registry.h"
24 #include "os_account_manager.h"
25 #include "system_ability_definition.h"
26 
27 #include "common_utils.h"
28 #include "constant_definition.h"
29 
30 namespace OHOS {
31 namespace Location {
32 static std::shared_ptr<std::map<int, sptr<IRemoteObject>>> g_proxyMap =
33     std::make_shared<std::map<int, sptr<IRemoteObject>>>();
34 std::mutex g_proxyMutex;
35 
CheckLocationPermission(uint32_t tokenId,uint32_t firstTokenId)36 bool CommonUtils::CheckLocationPermission(uint32_t tokenId, uint32_t firstTokenId)
37 {
38     return CheckPermission(ACCESS_LOCATION, tokenId, firstTokenId);
39 }
40 
CheckPermission(const std::string & permission,uint32_t callerToken,uint32_t tokenFirstCaller)41 bool CommonUtils::CheckPermission(const std::string &permission, uint32_t callerToken, uint32_t tokenFirstCaller)
42 {
43     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken);
44     int result = Security::AccessToken::PERMISSION_DENIED;
45     if (tokenFirstCaller == 0) {
46         if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_INVALID) {
47             LBSLOGD(COMMON_UTILS, "has no permission.permission name=%{public}s", permission.c_str());
48             return false;
49         } else {
50             result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permission);
51         }
52     } else {
53         result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, tokenFirstCaller, permission);
54     }
55     if (result == Security::AccessToken::PERMISSION_GRANTED) {
56         return true;
57     } else {
58         LBSLOGD(COMMON_UTILS, "has no permission.permission name=%{public}s", permission.c_str());
59         return false;
60     }
61 }
62 
CheckBackgroundPermission(uint32_t tokenId,uint32_t firstTokenId)63 bool CommonUtils::CheckBackgroundPermission(uint32_t tokenId, uint32_t firstTokenId)
64 {
65     return CheckPermission(ACCESS_BACKGROUND_LOCATION, tokenId, firstTokenId);
66 }
67 
CheckApproximatelyPermission(uint32_t tokenId,uint32_t firstTokenId)68 bool CommonUtils::CheckApproximatelyPermission(uint32_t tokenId, uint32_t firstTokenId)
69 {
70     return CheckPermission(ACCESS_APPROXIMATELY_LOCATION, tokenId, firstTokenId);
71 }
72 
CheckSecureSettings(uint32_t tokenId,uint32_t firstTokenId)73 bool CommonUtils::CheckSecureSettings(uint32_t tokenId, uint32_t firstTokenId)
74 {
75     return CheckPermission(MANAGE_SECURE_SETTINGS, tokenId, firstTokenId);
76 }
77 
CheckCallingPermission(pid_t callingUid,pid_t callingPid,MessageParcel & reply)78 bool CommonUtils::CheckCallingPermission(pid_t callingUid, pid_t callingPid, MessageParcel &reply)
79 {
80     if (callingUid != static_cast<pid_t>(getuid()) || callingPid != getpid()) {
81         LBSLOGE(COMMON_UTILS, "uid pid not match locationhub process.");
82         reply.WriteInt32(ERRCODE_PERMISSION_DENIED);
83         return false;
84     }
85     return true;
86 }
87 
GetPermissionLevel(uint32_t tokenId,uint32_t firstTokenId)88 int CommonUtils::GetPermissionLevel(uint32_t tokenId, uint32_t firstTokenId)
89 {
90     int ret = PERMISSION_INVALID;
91     if (CheckPermission(ACCESS_APPROXIMATELY_LOCATION, tokenId, firstTokenId) &&
92         CheckPermission(ACCESS_LOCATION, tokenId, firstTokenId)) {
93         ret = PERMISSION_ACCURATE;
94     } else if (CheckPermission(ACCESS_APPROXIMATELY_LOCATION, tokenId, firstTokenId) &&
95         !CheckPermission(ACCESS_LOCATION, tokenId, firstTokenId)) {
96         ret = PERMISSION_APPROXIMATELY;
97     } else if (!CheckPermission(ACCESS_APPROXIMATELY_LOCATION, tokenId, firstTokenId) &&
98         CheckPermission(ACCESS_LOCATION, tokenId, firstTokenId)) {
99         ret = PERMISSION_ACCURATE;
100     }  else {
101         ret = PERMISSION_INVALID;
102     }
103     return ret;
104 }
105 
AbilityConvertToId(const std::string ability)106 int CommonUtils::AbilityConvertToId(const std::string ability)
107 {
108     if (GNSS_ABILITY.compare(ability) == 0) {
109         return LOCATION_GNSS_SA_ID;
110     }
111     if (NETWORK_ABILITY.compare(ability) == 0) {
112         return LOCATION_NETWORK_LOCATING_SA_ID;
113     }
114     if (PASSIVE_ABILITY.compare(ability) == 0) {
115         return LOCATION_NOPOWER_LOCATING_SA_ID;
116     }
117     if (GEO_ABILITY.compare(ability) == 0) {
118         return LOCATION_GEO_CONVERT_SA_ID;
119     }
120     return -1;
121 }
122 
GetCapabilityToString(std::string ability,uint32_t capability)123 std::u16string CommonUtils::GetCapabilityToString(std::string ability, uint32_t capability)
124 {
125     std::string value = "{\"Capabilities\":{\"" + ability + "\":" + std::to_string(capability) + "}}";
126     return Str8ToStr16(value);
127 }
128 
GetCapability(std::string ability)129 std::u16string CommonUtils::GetCapability(std::string ability)
130 {
131     uint32_t capability = 0x102;
132     return GetCapabilityToString(ability, capability);
133 }
134 
GetLabel(std::string name)135 OHOS::HiviewDFX::HiLogLabel CommonUtils::GetLabel(std::string name)
136 {
137     if (GNSS_ABILITY.compare(name) == 0) {
138         return GNSS;
139     }
140     if (NETWORK_ABILITY.compare(name) == 0) {
141         return NETWORK;
142     }
143     if (PASSIVE_ABILITY.compare(name) == 0) {
144         return PASSIVE;
145     }
146     if (GEO_ABILITY.compare(name) == 0) {
147         return GEO_CONVERT;
148     }
149     OHOS::HiviewDFX::HiLogLabel label = { LOG_CORE, LOCATOR_LOG_ID, "unknown" };
150     return label;
151 }
152 
GetRemoteObject(int abilityId)153 sptr<IRemoteObject> CommonUtils::GetRemoteObject(int abilityId)
154 {
155     return GetRemoteObject(abilityId, InitDeviceId());
156 }
157 
GetRemoteObject(int abilityId,std::string deviceId)158 sptr<IRemoteObject> CommonUtils::GetRemoteObject(int abilityId, std::string deviceId)
159 {
160     std::lock_guard<std::mutex> lock(g_proxyMutex);
161     auto objectGnss = g_proxyMap->find(abilityId);
162     if (objectGnss == g_proxyMap->end()) {
163         auto manager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
164         if (manager == nullptr) {
165             LBSLOGE(COMMON_UTILS, "GetSystemAbilityManager is null.");
166             return nullptr;
167         }
168         sptr<IRemoteObject> object = manager->GetSystemAbility(abilityId, deviceId);
169         if (object == nullptr) {
170             LBSLOGE(COMMON_UTILS, "GetSystemAbility is null.");
171             return nullptr;
172         }
173         g_proxyMap->insert(std::make_pair(abilityId, object));
174         return object;
175     } else {
176         sptr<IRemoteObject> remoteObject = objectGnss->second;
177         return remoteObject;
178     }
179 }
180 
InitDeviceId()181 std::string CommonUtils::InitDeviceId()
182 {
183     std::string deviceId;
184     return deviceId;
185 }
186 
GetCurrentUserId(int & userId)187 bool CommonUtils::GetCurrentUserId(int &userId)
188 {
189     std::vector<int> activeIds;
190     int ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeIds);
191     if (ret != 0) {
192         LBSLOGE(COMMON_UTILS, "QueryActiveOsAccountIds failed ret:%{public}d", ret);
193         return false;
194     }
195     if (activeIds.empty()) {
196         LBSLOGE(COMMON_UTILS, "QueryActiveOsAccountIds activeIds empty");
197         return false;
198     }
199     userId = activeIds[0];
200     return true;
201 }
202 
Wait(int time)203 void CountDownLatch::Wait(int time)
204 {
205     LBSLOGD(LOCATOR_STANDARD, "enter wait, time = %{public}d", time);
206     std::unique_lock<std::mutex> lock(mutex_);
207     if (count_ == 0) {
208         LBSLOGE(LOCATOR_STANDARD, "count_ = 0");
209         return;
210     }
211     condition_.wait_for(lock, std::chrono::seconds(time / SEC_TO_MILLI_SEC), [&]() {return count_ == 0;});
212 }
213 
CountDown()214 void CountDownLatch::CountDown()
215 {
216     LBSLOGD(LOCATOR_STANDARD, "enter CountDown");
217     std::unique_lock<std::mutex> lock(mutex_);
218     int oldC = count_.load();
219     while (oldC > 0) {
220         if (count_.compare_exchange_strong(oldC, oldC - 1)) {
221             if (oldC == 1) {
222                 LBSLOGD(LOCATOR_STANDARD, "notify_all");
223                 condition_.notify_all();
224             }
225             break;
226         }
227         oldC = count_.load();
228     }
229 }
230 
GetCount()231 int CountDownLatch::GetCount()
232 {
233     std::unique_lock<std::mutex> lock(mutex_);
234     return count_;
235 }
236 
SetCount(int count)237 void CountDownLatch::SetCount(int count)
238 {
239     std::unique_lock<std::mutex> lock(mutex_);
240     count_ = count;
241 }
242 
Str16ToStr8(std::u16string str)243 std::string CommonUtils::Str16ToStr8(std::u16string str)
244 {
245     if (str == DEFAULT_USTRING) {
246         return DEFAULT_STRING;
247     }
248     std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert(DEFAULT_STRING);
249     std::string result = convert.to_bytes(str);
250     return result == DEFAULT_STRING ? "" : result;
251 }
252 
DoubleEqual(double a,double b)253 bool CommonUtils::DoubleEqual(double a, double b)
254 {
255     if (fabs(a - b) < 1e-6) {
256         return true;
257     } else {
258         return false;
259     }
260 }
261 
CalDistance(const double lat1,const double lon1,const double lat2,const double lon2)262 double CommonUtils::CalDistance(const double lat1, const double lon1, const double lat2, const double lon2)
263 {
264     double radLat1 = lat1 * PI / DEGREE_PI;
265     double radLat2 = lat2 * PI / DEGREE_PI;
266     double radLon1 = lon1 * PI / DEGREE_PI;
267     double radLon2 = lon2 * PI / DEGREE_PI;
268 
269     double latDiff = radLat1 - radLat2;
270     double lonDiff = radLon1 - radLon2;
271     double temp = sqrt(pow(sin(latDiff / DIS_FROMLL_PARAMETER), DIS_FROMLL_PARAMETER) +
272         cos(radLat1) * cos(radLat2) * pow(sin(lonDiff / DIS_FROMLL_PARAMETER), DIS_FROMLL_PARAMETER));
273     double disRad = asin(temp) * DIS_FROMLL_PARAMETER;
274     double dis = disRad * EARTH_RADIUS;
275     return dis;
276 }
277 
DoubleRandom(double min,double max)278 double CommonUtils::DoubleRandom(double min, double max)
279 {
280     double param = 0.0;
281     std::random_device rd;
282     static std::uniform_real_distribution<double> u(min, max);
283     static std::default_random_engine e(rd());
284     param = u(e);
285     return param;
286 }
287 
IntRandom(int min,int max)288 int CommonUtils::IntRandom(int min, int max)
289 {
290     int param = 0;
291     std::random_device rd;
292     static std::uniform_int_distribution<int> u(min, max);
293     static std::default_random_engine e(rd());
294     param = u(e);
295     return param;
296 }
297 
CheckSystemPermission(pid_t uid,uint32_t callerTokenId)298 bool CommonUtils::CheckSystemPermission(pid_t uid, uint32_t callerTokenId)
299 {
300     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerTokenId);
301     if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
302         return true;
303     }
304     if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL ||
305         tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_INVALID) {
306         return false;
307     }
308     auto systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
309     if (systemManager == nullptr) {
310         LBSLOGE(COMMON_UTILS, "Get system ability manager failed!");
311         return false;
312     }
313     auto bundleMgrSa = systemManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
314     if (bundleMgrSa == nullptr) {
315         LBSLOGE(COMMON_UTILS, "GetSystemAbility return nullptr!");
316         return false;
317     }
318     auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bundleMgrSa);
319     if (bundleMgr == nullptr) {
320         LBSLOGE(COMMON_UTILS, "iface_cast return nullptr!");
321         return false;
322     }
323     bool isSysApp = bundleMgr->CheckIsSystemAppByUid(uid);
324     LBSLOGD(COMMON_UTILS, "Is system App uid[%{public}d]: %{public}d", uid, isSysApp);
325     return isSysApp;
326 }
327 
GetBundleNameByUid(int32_t uid,std::string & bundleName)328 bool CommonUtils::GetBundleNameByUid(int32_t uid, std::string& bundleName)
329 {
330     sptr<ISystemAbilityManager> smgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
331     if (smgr == nullptr) {
332         LBSLOGE(COMMON_UTILS, "GetBundleNameByUid Fail to get system ability manager.");
333         return false;
334     }
335     sptr<IRemoteObject> remoteObject = smgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
336     if (remoteObject == nullptr) {
337         LBSLOGE(COMMON_UTILS, "GetBundleNameByUid Fail to get system ability manager.");
338         return false;
339     }
340     sptr<AppExecFwk::IBundleMgr> bundleMgrProxy(new AppExecFwk::BundleMgrProxy(remoteObject));
341     if (bundleMgrProxy == nullptr) {
342         LBSLOGE(COMMON_UTILS, "GetBundleNameByUid Bundle mgr proxy is nullptr.");
343         return false;
344     }
345     return bundleMgrProxy->GetBundleNameForUid(uid, bundleName);
346 }
347 
348 /*
349  * Check whether the application is installed by bundleName
350  * @param bundleName
351  * @return true if app is installed
352  * @return false if app is not installed
353  */
CheckAppInstalled(const std::string & bundleName)354 bool CommonUtils::CheckAppInstalled(const std::string& bundleName)
355 {
356     int userId = 0;
357     bool ret = GetCurrentUserId(userId);
358     if (!ret) {
359         LBSLOGE(COMMON_UTILS, "GetCurrentUserId failed");
360         return false;
361     }
362     auto systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
363     if (systemManager == nullptr) {
364         LBSLOGE(COMMON_UTILS, "fail to get system ability manager!");
365         return false;
366     }
367     auto bundleMgrSa = systemManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
368     if (bundleMgrSa == nullptr) {
369         LBSLOGE(COMMON_UTILS, "fail to get bundle manager system ability!");
370         return false;
371     }
372     auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bundleMgrSa);
373     if (bundleMgr == nullptr) {
374         LBSLOGE(COMMON_UTILS, "Bundle mgr is nullptr.");
375         return false;
376     }
377     AppExecFwk::ApplicationInfo info;
378     bundleMgr->GetApplicationInfoV9(bundleName, 0, userId, info);
379     if (info.name.empty() || info.bundleName.empty()) {
380         return false;
381     }
382     return true;
383 }
384 } // namespace Location
385 } // namespace OHOS
386