• 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 "locator_ability.h"
17 
18 #include "accesstoken_kit.h"
19 #include "event_runner.h"
20 #include "ipc_skeleton.h"
21 #include "privacy_kit.h"
22 #include "privacy_error.h"
23 #include "system_ability_definition.h"
24 #include "uri.h"
25 
26 #include "common_event_manager.h"
27 #include "common_hisysevent.h"
28 #include "location_log_event_ids.h"
29 #include "common_utils.h"
30 #include "constant_definition.h"
31 #ifdef FEATURE_GEOCODE_SUPPORT
32 #include "geo_convert_proxy.h"
33 #endif
34 #ifdef FEATURE_GNSS_SUPPORT
35 #include "gnss_ability_proxy.h"
36 #endif
37 #include "hook_utils.h"
38 #include "locator_background_proxy.h"
39 #include "location_config_manager.h"
40 #include "location_data_rdb_helper.h"
41 #include "location_log.h"
42 #include "location_sa_load_manager.h"
43 #include "locator_required_data_manager.h"
44 #include "location_data_rdb_manager.h"
45 #ifdef FEATURE_NETWORK_SUPPORT
46 #include "network_ability_proxy.h"
47 #endif
48 #ifdef FEATURE_PASSIVE_SUPPORT
49 #include "passive_ability_proxy.h"
50 #endif
51 #include "permission_status_change_cb.h"
52 #include "permission_manager.h"
53 #ifdef RES_SCHED_SUPPROT
54 #include "res_type.h"
55 #include "res_sched_client.h"
56 #endif
57 #include "app_mgr_interface.h"
58 #include "app_state_data.h"
59 #include "if_system_ability_manager.h"
60 #include "iservice_registry.h"
61 #include "geo_convert_request.h"
62 #include "parameter.h"
63 #include "self_request_manager.h"
64 #ifdef LOCATION_HICOLLIE_ENABLE
65 #include "xcollie/xcollie.h"
66 #include "xcollie/xcollie_define.h"
67 #endif
68 #include "common_event_helper.h"
69 
70 namespace OHOS {
71 namespace Location {
72 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
73     LocatorAbility::GetInstance());
74 
75 const uint32_t EVENT_UPDATE_SA = 0x0001;
76 const uint32_t EVENT_INIT_REQUEST_MANAGER = 0x0002;
77 const uint32_t EVENT_APPLY_REQUIREMENTS = 0x0003;
78 const uint32_t EVENT_RETRY_REGISTER_ACTION = 0x0004;
79 const uint32_t EVENT_REPORT_LOCATION_MESSAGE = 0x0005;
80 const uint32_t EVENT_SEND_SWITCHSTATE_TO_HIFENCE = 0x0006;
81 const uint32_t EVENT_START_LOCATING = 0x0007;
82 const uint32_t EVENT_STOP_LOCATING = 0x0008;
83 const uint32_t EVENT_UNLOAD_SA = 0x0010;
84 const uint32_t EVENT_GET_CACHED_LOCATION_SUCCESS = 0x0014;
85 const uint32_t EVENT_GET_CACHED_LOCATION_FAILED = 0x0015;
86 const uint32_t EVENT_REG_LOCATION_ERROR = 0x0011;
87 const uint32_t EVENT_UNREG_LOCATION_ERROR = 0x0012;
88 const uint32_t EVENT_REPORT_LOCATION_ERROR = 0x0013;
89 const uint32_t EVENT_PERIODIC_CHECK = 0x0016;
90 const uint32_t EVENT_SYNC_LOCATION_STATUS = 0x0017;
91 const uint32_t EVENT_SYNC_STILL_MOVEMENT_STATE = 0x0018;
92 const uint32_t EVENT_SYNC_IDLE_STATE = 0x0019;
93 const uint32_t EVENT_INIT_MSDP_MONITOR_MANAGER = 0x0020;
94 const uint32_t EVENT_IS_STAND_BY = 0x0021;
95 const uint32_t EVENT_SET_LOCATION_WORKING_STATE = 0x0022;
96 const uint32_t EVENT_SEND_GEOREQUEST = 0x0023;
97 const uint32_t EVENT_SET_SWITCH_STATE_TO_DB = 0x0024;
98 const uint32_t EVENT_WATCH_SWITCH_PARAMETER = 0x0025;
99 const uint32_t EVENT_SET_SWITCH_STATE_TO_DB_BY_USERID = 0x0026;
100 const uint32_t EVENT_START_SCAN_BLUETOOTH_DEVICE = 0x0027;
101 const uint32_t EVENT_STOP_SCAN_BLUETOOTH_DEVICE = 0x0028;
102 
103 const uint32_t RETRY_INTERVAL_UNITE = 1000;
104 const uint32_t RETRY_INTERVAL_OF_INIT_REQUEST_MANAGER = 5 * RETRY_INTERVAL_UNITE;
105 #ifdef FEATURE_DYNAMIC_OFFLOAD
106 const uint32_t RETRY_INTERVAL_OF_UNLOAD_SA = 4 * 60 * RETRY_INTERVAL_UNITE;
107 #else
108 const uint32_t RETRY_INTERVAL_OF_UNLOAD_SA = 30 * 60 * RETRY_INTERVAL_UNITE;
109 #endif // FEATURE_DYNAMIC_OFFLOAD
110 const int COMMON_SA_ID = 4353;
111 const int COMMON_SWITCH_STATE_ID = 30;
112 const std::u16string COMMON_DESCRIPTION = u"location.IHifenceAbility";
113 const std::string UNLOAD_TASK = "locatior_sa_unload";
114 const std::string WIFI_SCAN_STATE_CHANGE = "wifiScanStateChange";
115 const uint32_t SET_ENABLE = 3;
116 const uint32_t EVENT_PERIODIC_INTERVAL = 3 * 60 * 1000;
117 const uint32_t REQUEST_DEFAULT_TIMEOUT_SECOUND = 5 * 60;
118 const int LOCATIONHUB_STATE_UNLOAD = 0;
119 const int LOCATIONHUB_STATE_LOAD = 1;
120 const int MAX_SIZE = 100;
121 const int TIMEOUT_WATCHDOG = 60; // s
122 const int INVALID_REQUESTS_SIZE = 20;
123 const int MAX_PERMISSION_NUM = 1000;
124 const int MAX_SWITCH_CALLBACKS_NUM = 1000;
125 const int LOCATION_SWITCH_IGNORED_STATE_VALID_TIME = 2 * 60 * 1000; // 2min
126 const int DEFAULT_USERID = 100;
127 
GetInstance()128 LocatorAbility* LocatorAbility::GetInstance()
129 {
130     static LocatorAbility data;
131     return &data;
132 }
133 
LocatorAbility()134 LocatorAbility::LocatorAbility() : SystemAbility(LOCATION_LOCATOR_SA_ID, true)
135 {
136 #ifndef TDD_CASES_ENABLED
137     locatorHandler_ = std::make_shared<LocatorHandler>(AppExecFwk::EventRunner::Create(true,
138         AppExecFwk::ThreadMode::FFRT));
139 #endif
140     requests_ = std::make_shared<std::map<std::string, std::list<std::shared_ptr<Request>>>>();
141     receivers_ = std::make_shared<std::map<sptr<IRemoteObject>, std::list<std::shared_ptr<Request>>>>();
142     proxyMap_ = std::make_shared<std::map<std::string, sptr<IRemoteObject>>>();
143     loadedSaMap_ = std::make_shared<std::map<std::string, sptr<IRemoteObject>>>();
144     permissionMap_ = std::make_shared<std::map<uint32_t, std::shared_ptr<PermissionStatusChangeCb>>>();
145     InitRequestManagerMap();
146     reportManager_ = ReportManager::GetInstance();
147     deviceId_ = CommonUtils::InitDeviceId();
148 #ifdef MOVEMENT_CLIENT_ENABLE
149 #ifndef TDD_CASES_ENABLED
150     if (locatorHandler_ != nullptr) {
151         locatorHandler_->SendHighPriorityEvent(EVENT_INIT_MSDP_MONITOR_MANAGER, 0, 0);
152     }
153 #endif
154 #endif
155     requestManager_ = RequestManager::GetInstance();
156 #ifndef TDD_CASES_ENABLED
157     if (locatorHandler_ != nullptr) {
158         locatorHandler_->SendHighPriorityEvent(EVENT_IS_STAND_BY, 0, 0);
159     }
160 #endif
161     LBSLOGI(LOCATOR, "LocatorAbility constructed.");
162 }
163 
~LocatorAbility()164 LocatorAbility::~LocatorAbility() {}
165 
OnStart()166 void LocatorAbility::OnStart()
167 {
168     if (state_ == ServiceRunningState::STATE_RUNNING) {
169         LBSLOGI(LOCATOR, "LocatorAbility has already started.");
170         return;
171     }
172     if (!Init()) {
173         LBSLOGE(LOCATOR, "failed to init LocatorAbility");
174         OnStop();
175         return;
176     }
177     state_ = ServiceRunningState::STATE_RUNNING;
178     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
179     if (locatorHandler_ != nullptr) {
180         locatorHandler_->SendHighPriorityEvent(EVENT_SET_LOCATION_WORKING_STATE, 0, 0);
181         locatorHandler_->SendHighPriorityEvent(EVENT_SYNC_LOCATION_STATUS, 0, 0);
182         locatorHandler_->SendHighPriorityEvent(EVENT_WATCH_SWITCH_PARAMETER, 0, 0);
183     }
184     LBSLOGW(LOCATOR, "LocatorAbility::OnStart start ability success.");
185 }
186 
OnStop()187 void LocatorAbility::OnStop()
188 {
189     state_ = ServiceRunningState::STATE_NOT_START;
190     registerToAbility_ = false;
191     if (!LocationDataRdbManager::SetLocationWorkingState(0)) {
192         LBSLOGD(LOCATOR, "LocatorAbility::reset LocationWorkingState failed.");
193     }
194     SetLocationhubStateToSyspara(LOCATIONHUB_STATE_UNLOAD);
195     LocatorRequiredDataManager::GetInstance()->UnregisterWifiCallBack();
196     LBSLOGW(LOCATOR, "LocatorAbility::OnStop ability stopped.");
197 }
198 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)199 void LocatorAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
200 {
201     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
202         RegisterAction();
203         RegisterLocationPrivacyAction();
204     }
205 }
206 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)207 void LocatorAbility::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
208 {
209     if (systemAbilityId != COMMON_EVENT_SERVICE_ID) {
210         LBSLOGE(LOCATOR, "systemAbilityId is not COMMON_EVENT_SERVICE_ID");
211         return;
212     }
213 
214     if (locationPrivacyEventSubscriber_ != nullptr) {
215         bool ret = OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(locationPrivacyEventSubscriber_);
216         locationPrivacyEventSubscriber_ = nullptr;
217         isLocationPrivacyActionRegistered_ = false;
218         LBSLOGI(LOCATOR, "UnSubscribeCommonEvent locationPrivacyEventSubscriber_ result = %{public}d", ret);
219         return;
220     }
221 
222     if (locatorEventSubscriber_ == nullptr) {
223         LBSLOGE(LOCATOR, "OnRemoveSystemAbility subscribeer is nullptr");
224         return;
225     }
226     bool result = OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(locatorEventSubscriber_);
227     isActionRegistered = false;
228     LBSLOGI(LOCATOR, "UnSubscribeCommonEvent locatorEventSubscriber_ result = %{public}d", result);
229 }
230 
Init()231 bool LocatorAbility::Init()
232 {
233     if (registerToAbility_) {
234         return true;
235     }
236     LBSLOGI(LOCATOR, "LocatorAbility Init.");
237     bool ret = Publish(AsObject());
238     if (!ret) {
239         LBSLOGE(LOCATOR, "Init add system ability failed!");
240         return false;
241     }
242     UpdateSaAbility();
243     if (locatorHandler_ != nullptr) {
244         locatorHandler_->SendHighPriorityEvent(EVENT_INIT_REQUEST_MANAGER, 0, RETRY_INTERVAL_OF_INIT_REQUEST_MANAGER);
245         locatorHandler_->SendHighPriorityEvent(EVENT_PERIODIC_CHECK, 0, EVENT_PERIODIC_INTERVAL);
246     }
247     SetLocationhubStateToSyspara(LOCATIONHUB_STATE_LOAD);
248     registerToAbility_ = true;
249     return registerToAbility_;
250 }
251 
InitRequestManagerMap()252 void LocatorAbility::InitRequestManagerMap()
253 {
254     std::unique_lock<ffrt::mutex> lock(requestsMutex_);
255     if (requests_ != nullptr) {
256 #ifdef FEATURE_GNSS_SUPPORT
257         std::list<std::shared_ptr<Request>> gnssList;
258         requests_->insert(make_pair(GNSS_ABILITY, gnssList));
259 #endif
260 #ifdef FEATURE_NETWORK_SUPPORT
261         std::list<std::shared_ptr<Request>> networkList;
262         requests_->insert(make_pair(NETWORK_ABILITY, networkList));
263 #endif
264 #ifdef FEATURE_PASSIVE_SUPPORT
265         std::list<std::shared_ptr<Request>> passiveList;
266         requests_->insert(make_pair(PASSIVE_ABILITY, passiveList));
267 #endif
268     }
269 }
270 
GetRequests()271 std::shared_ptr<std::map<std::string, std::list<std::shared_ptr<Request>>>> LocatorAbility::GetRequests()
272 {
273     std::unique_lock<ffrt::mutex> lock(requestsMutex_);
274     return requests_;
275 }
276 
GetActiveRequestNum()277 int LocatorAbility::GetActiveRequestNum()
278 {
279     std::unique_lock<ffrt::mutex> lock(requestsMutex_);
280     int num = 0;
281 #ifdef FEATURE_GNSS_SUPPORT
282     auto gpsListIter = requests_->find(GNSS_ABILITY);
283     if (gpsListIter != requests_->end()) {
284         auto list = &(gpsListIter->second);
285         num += static_cast<int>(list->size());
286     }
287 #endif
288 #ifdef FEATURE_NETWORK_SUPPORT
289     auto networkListIter = requests_->find(NETWORK_ABILITY);
290     if (networkListIter != requests_->end()) {
291         auto list = &(networkListIter->second);
292         num += static_cast<int>(list->size());
293     }
294 #endif
295     return num;
296 }
297 
GetReceivers()298 std::shared_ptr<std::map<sptr<IRemoteObject>, std::list<std::shared_ptr<Request>>>> LocatorAbility::GetReceivers()
299 {
300     std::unique_lock<ffrt::mutex> lock(receiversMutex_);
301     return receivers_;
302 }
303 
GetProxyMap()304 std::shared_ptr<std::map<std::string, sptr<IRemoteObject>>> LocatorAbility::GetProxyMap()
305 {
306     std::unique_lock<std::mutex> lock(proxyMapMutex_);
307     return proxyMap_;
308 }
309 
ApplyRequests(int delay)310 void LocatorAbility::ApplyRequests(int delay)
311 {
312     if (locatorHandler_ != nullptr) {
313         locatorHandler_->SendHighPriorityEvent(EVENT_APPLY_REQUIREMENTS, 0, delay * RETRY_INTERVAL_UNITE);
314     }
315 }
316 
InitSaAbility()317 void LocatorAbility::InitSaAbility()
318 {
319     LBSLOGI(LOCATOR, "initSaAbility start");
320     if (proxyMap_ == nullptr) {
321         return;
322     }
323     UpdateSaAbilityHandler();
324 }
325 
CheckSaValid()326 bool LocatorAbility::CheckSaValid()
327 {
328     std::unique_lock<std::mutex> lock(proxyMapMutex_);
329 #ifdef FEATURE_GNSS_SUPPORT
330     auto objectGnss = proxyMap_->find(GNSS_ABILITY);
331     if (objectGnss == proxyMap_->end()) {
332         LBSLOGI(LOCATOR, "gnss sa is null");
333         return false;
334     }
335 #endif
336 #ifdef FEATURE_NETWORK_SUPPORT
337     auto objectNetwork = proxyMap_->find(NETWORK_ABILITY);
338     if (objectNetwork == proxyMap_->end()) {
339         LBSLOGI(LOCATOR, "network sa is null");
340         return false;
341     }
342 #endif
343 #ifdef FEATURE_PASSIVE_SUPPORT
344     auto objectPassive = proxyMap_->find(PASSIVE_ABILITY);
345     if (objectPassive == proxyMap_->end()) {
346         LBSLOGI(LOCATOR, "passive sa is null");
347         return false;
348     }
349 #endif
350     return true;
351 }
352 
SetLocationhubStateToSyspara(int value)353 bool LocatorAbility::SetLocationhubStateToSyspara(int value)
354 {
355     char valueArray[MAX_SIZE] = {0};
356     (void)sprintf_s(valueArray, sizeof(valueArray), "%d", value);
357     int res = SetParameter(LOCATION_LOCATIONHUB_STATE, valueArray);
358     if (res != 0) {
359         LBSLOGE(LOCATOR, "%{public}s failed, res: %{public}d", __func__, res);
360         return false;
361     }
362     return true;
363 }
364 
UpdateSaAbility()365 LocationErrCode LocatorAbility::UpdateSaAbility()
366 {
367     auto event = AppExecFwk::InnerEvent::Get(EVENT_UPDATE_SA, 0);
368     if (locatorHandler_ != nullptr) {
369         locatorHandler_->SendHighPriorityEvent(event);
370     }
371     return ERRCODE_SUCCESS;
372 }
373 
UpdateSaAbilityHandler()374 void LocatorAbility::UpdateSaAbilityHandler()
375 {
376     int state = LocationDataRdbManager::QuerySwitchState();
377     LBSLOGI(LOCATOR, "update location subability enable state, switch state=%{public}d, action registered=%{public}d",
378         state, isActionRegistered);
379     if (state == DEFAULT_SWITCH_STATE) {
380         return;
381     }
382     bool isEnabled = (state == ENABLED);
383     auto locatorBackgroundProxy = LocatorBackgroundProxy::GetInstance();
384     locatorBackgroundProxy->OnSaStateChange(isEnabled);
385     UpdateLoadedSaMap();
386     std::string callingIdentity = IPCSkeleton::ResetCallingIdentity();
387     std::unique_lock<ffrt::mutex> lock(loadedSaMapMutex_);
388     for (auto iter = loadedSaMap_->begin(); iter != loadedSaMap_->end(); iter++) {
389         sptr<IRemoteObject> remoteObject = iter->second;
390         MessageParcel data;
391         if (iter->first == GNSS_ABILITY) {
392 #ifdef FEATURE_GNSS_SUPPORT
393             data.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor());
394 #endif
395         } else if (iter->first == NETWORK_ABILITY) {
396 #ifdef FEATURE_NETWORK_SUPPORT
397             data.WriteInterfaceToken(NetworkAbilityProxy::GetDescriptor());
398 #endif
399         } else if (iter->first == PASSIVE_ABILITY) {
400 #ifdef FEATURE_PASSIVE_SUPPORT
401             data.WriteInterfaceToken(PassiveAbilityProxy::GetDescriptor());
402 #endif
403         }
404         data.WriteBool(isEnabled);
405 
406         MessageParcel reply;
407         MessageOption option;
408         int error = remoteObject->SendRequest(SET_ENABLE, data, reply, option);
409         if (error != ERR_OK) {
410             LBSLOGI(LOCATOR, "enable %{public}s ability, remote result %{public}d", (iter->first).c_str(), error);
411         }
412     }
413     SendSwitchState(isEnabled ? 1 : 0);
414     IPCSkeleton::SetCallingIdentity(callingIdentity);
415 }
416 
CallbackEnter(uint32_t code)417 int32_t LocatorAbility::CallbackEnter(uint32_t code)
418 {
419     CancelIdleState(code);
420     RemoveUnloadTask(code);
421     return ERRCODE_SUCCESS;
422 }
423 
CallbackExit(uint32_t code,int32_t result)424 int32_t LocatorAbility::CallbackExit(uint32_t code, int32_t result)
425 {
426     PostUnloadTask(code);
427     return ERRCODE_SUCCESS;
428 }
429 
CheckRequestAvailable(LocatorInterfaceCode code,AppIdentity & identity)430 bool LocatorAbility::CheckRequestAvailable(LocatorInterfaceCode code, AppIdentity &identity)
431 {
432     LBSLOGI(LOCATOR, "OnReceived cmd = %{public}u, identity= [%{public}s], timestamp = %{public}s",
433             code, identity.ToString().c_str(), std::to_string(CommonUtils::GetCurrentTimeStamp()).c_str());
434     if (code == LocatorInterfaceCode::UNREG_SWITCH_CALLBACK ||
435         code == LocatorInterfaceCode::STOP_LOCATING ||
436         code == LocatorInterfaceCode::STOP_LOCATING ||
437         code == LocatorInterfaceCode::DISABLE_LOCATION_MOCK ||
438         code == LocatorInterfaceCode::UNREG_LOCATION_ERROR ||
439         code == LocatorInterfaceCode::UNREG_LOCATING_REQUIRED_DATA_CALLBACK) {
440         return true;
441     }
442     int currentUserId = LocatorBackgroundProxy::GetInstance()->getCurrentUserId();
443     if (CommonUtils::IsAppBelongCurrentAccount(identity, currentUserId)) {
444         return true;
445     }
446     LBSLOGD(LOCATOR, "CheckRequestAvailable fail uid:%{public}d", identity.GetUid());
447     return false;
448 }
449 
CancelIdleState(uint32_t code)450 bool LocatorAbility::CancelIdleState(uint32_t code)
451 {
452     if (code == static_cast<uint16_t>(LocatorInterfaceCode::PROXY_PID_FOR_FREEZE) ||
453         code == static_cast<uint16_t>(LocatorInterfaceCode::RESET_ALL_PROXY)) {
454         return true;
455     }
456     SystemAbilityState state = GetAbilityState();
457     if (state != SystemAbilityState::IDLE) {
458         return true;
459     }
460     bool ret = CancelIdle();
461     if (!ret) {
462         LBSLOGE(LOCATOR, "%{public}s cancel idle failed!", __func__);
463         return false;
464     }
465     return true;
466 }
467 
RemoveUnloadTask(uint32_t code)468 void LocatorAbility::RemoveUnloadTask(uint32_t code)
469 {
470     if (locatorHandler_ == nullptr) {
471         LBSLOGE(LOCATOR, "%{public}s locatorHandler is nullptr", __func__);
472         return;
473     }
474     if (code == static_cast<uint16_t>(LocatorInterfaceCode::PROXY_PID_FOR_FREEZE) ||
475         code == static_cast<uint16_t>(LocatorInterfaceCode::RESET_ALL_PROXY)) {
476         return;
477     }
478     locatorHandler_->RemoveTask(UNLOAD_TASK);
479 }
480 
PostUnloadTask(uint32_t code)481 void LocatorAbility::PostUnloadTask(uint32_t code)
482 {
483     if (code == static_cast<uint16_t>(LocatorInterfaceCode::PROXY_PID_FOR_FREEZE) ||
484         code == static_cast<uint16_t>(LocatorInterfaceCode::RESET_ALL_PROXY)) {
485         return;
486     }
487     auto task = [this]() {
488         if (CheckIfLocatorConnecting()) {
489             return;
490         }
491         SaLoadWithStatistic::UnInitLocationSa(LOCATION_LOCATOR_SA_ID);
492     };
493     if (locatorHandler_ != nullptr) {
494         locatorHandler_->PostTask(task, UNLOAD_TASK, RETRY_INTERVAL_OF_UNLOAD_SA);
495     }
496 }
497 
SendSwitchState(const int state)498 void LocatorAbility::SendSwitchState(const int state)
499 {
500     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
501         Get(EVENT_SEND_SWITCHSTATE_TO_HIFENCE, state);
502     if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
503         LBSLOGD(LOCATOR, "%{public}s: EVENT_SEND_SWITCHSTATE_TO_HIFENCE Send Success", __func__);
504     }
505 }
506 
CheckIfLocatorConnecting()507 bool LocatorAbility::CheckIfLocatorConnecting()
508 {
509     return LocatorRequiredDataManager::GetInstance()->IsWifiConnecting() ||
510         LocatorRequiredDataManager::GetInstance()->IsBluetoothConnecting() || GetActiveRequestNum() > 0;
511 }
512 
EnableAbility(bool isEnabled)513 ErrCode LocatorAbility::EnableAbility(bool isEnabled)
514 {
515     LBSLOGI(LOCATOR, "EnableAbility %{public}d", isEnabled);
516     AppIdentity identity;
517     GetAppIdentityInfo(identity);
518     if (!CheckRequestAvailable(LocatorInterfaceCode::ENABLE_ABILITY, identity)) {
519         return LOCATION_ERRCODE_PERMISSION_DENIED;
520     }
521     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
522         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
523         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
524     }
525     if (!PermissionManager::CheckSecureSettings(identity.GetTokenId(), identity.GetFirstTokenId())) {
526         LBSLOGE(LOCATOR, "CheckSecureSettings return false, [%{public}s]", identity.ToString().c_str());
527         return LOCATION_ERRCODE_PERMISSION_DENIED;
528     }
529     bool privacyState = false;
530     LocationErrCode code =
531         LocationConfigManager::GetInstance()->GetPrivacyTypeState(PRIVACY_TYPE_STARTUP, privacyState);
532     if (code == ERRCODE_SUCCESS && isEnabled && !privacyState && identity.GetBundleName() == "com.ohos.sceneboard") {
533         LocationConfigManager::GetInstance()->OpenPrivacyDialog();
534         LBSLOGE(LOCATOR, "OpenPrivacyDialog");
535         return ERRCODE_SERVICE_UNAVAILABLE;
536     }
537     int userId = 0;
538     if (!CommonUtils::GetCurrentUserId(userId)) {
539         userId = DEFAULT_USERID;
540     }
541     if (!HookUtils::ExecuteHookEnableAbility(
542         identity.GetBundleName().size() == 0 ? std::to_string(identity.GetUid()) : identity.GetBundleName(),
543         isEnabled, userId)) {
544         return ERRCODE_SUCCESS;
545     }
546     LocationErrCode errCode = SetSwitchState(isEnabled);
547     std::string bundleName;
548     bool result = LocationConfigManager::GetInstance()->GetSettingsBundleName(bundleName);
549     // settings first enable location, need to update privacy state
550     if (code == ERRCODE_SUCCESS && errCode == ERRCODE_SUCCESS && isEnabled && !privacyState &&
551         result && !bundleName.empty() && identity.GetBundleName() == bundleName) {
552         LocationConfigManager::GetInstance()->SetPrivacyTypeState(PRIVACY_TYPE_STARTUP, true);
553     }
554     return ERRCODE_SUCCESS;
555 }
556 
EnableAbilityForUser(bool isEnabled,int32_t userId)557 ErrCode LocatorAbility::EnableAbilityForUser(bool isEnabled, int32_t userId)
558 {
559     LBSLOGI(LOCATOR, "EnableAbilityForUser %{public}d, UserId %{public}d", isEnabled, userId);
560     AppIdentity identity;
561     GetAppIdentityInfo(identity);
562     if (!CheckRequestAvailable(LocatorInterfaceCode::ENABLE_ABILITY_BY_USERID, identity)) {
563         return LOCATION_ERRCODE_PERMISSION_DENIED;
564     }
565     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
566         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
567         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
568     }
569     if (!PermissionManager::CheckSecureSettings(identity.GetTokenId(), identity.GetFirstTokenId())) {
570         LBSLOGE(LOCATOR, "CheckSecureSettings return false, [%{public}s]", identity.ToString().c_str());
571         return LOCATION_ERRCODE_PERMISSION_DENIED;
572     }
573     bool privacyState = false;
574     int currentUserId = 0;
575     LocationErrCode code =
576         LocationConfigManager::GetInstance()->GetPrivacyTypeState(PRIVACY_TYPE_STARTUP, privacyState);
577     if (code == ERRCODE_SUCCESS && isEnabled && !privacyState && identity.GetBundleName() == "com.ohos.sceneboard" &&
578         (CommonUtils::GetCurrentUserId(currentUserId) && userId == currentUserId)) {
579         LocationConfigManager::GetInstance()->OpenPrivacyDialog();
580         LBSLOGE(LOCATOR, "OpenPrivacyDialog");
581         return ERRCODE_SERVICE_UNAVAILABLE;
582     }
583     if (!HookUtils::ExecuteHookEnableAbility(
584         identity.GetBundleName().size() == 0 ? std::to_string(identity.GetUid()) : identity.GetBundleName(),
585         isEnabled, userId)) {
586         return ERRCODE_SUCCESS;
587     }
588     SetSwitchStateForUser(isEnabled, userId);
589     std::string bundleName;
590     bool result = LocationConfigManager::GetInstance()->GetSettingsBundleName(bundleName);
591     // settings first enable location, need to update privacy state
592     if (code == ERRCODE_SUCCESS && isEnabled && !privacyState &&
593         result && !bundleName.empty() && identity.GetBundleName() == bundleName &&
594         (CommonUtils::GetCurrentUserId(currentUserId) && userId == currentUserId)) {
595         LocationConfigManager::GetInstance()->SetPrivacyTypeState(PRIVACY_TYPE_STARTUP, true);
596     }
597     return ERRCODE_SUCCESS;
598 }
599 
GetSwitchState(int32_t & state)600 ErrCode LocatorAbility::GetSwitchState(int32_t& state)
601 {
602     state = DEFAULT_SWITCH_STATE;
603     state = LocationDataRdbManager::QuerySwitchState();
604     return ERRCODE_SUCCESS;
605 }
606 
IsLocationPrivacyConfirmed(int32_t type,bool & state)607 ErrCode LocatorAbility::IsLocationPrivacyConfirmed(int32_t type, bool& state)
608 {
609     state = false;
610     AppIdentity identity;
611     GetAppIdentityInfo(identity);
612     if (!CheckRequestAvailable(LocatorInterfaceCode::IS_PRIVACY_COMFIRMED, identity)) {
613         return LOCATION_ERRCODE_PERMISSION_DENIED;
614     }
615     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
616         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
617         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
618     }
619     return LocationConfigManager::GetInstance()->GetPrivacyTypeState(type, state);
620 }
621 
SetLocationPrivacyConfirmStatus(int32_t type,bool isConfirmed)622 ErrCode LocatorAbility::SetLocationPrivacyConfirmStatus(int32_t type, bool isConfirmed)
623 {
624     AppIdentity identity;
625     GetAppIdentityInfo(identity);
626     if (!CheckRequestAvailable(LocatorInterfaceCode::SET_PRIVACY_COMFIRM_STATUS, identity)) {
627         return LOCATION_ERRCODE_PERMISSION_DENIED;
628     }
629     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
630         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
631         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
632     }
633     if (!PermissionManager::CheckSecureSettings(identity.GetTokenId(), identity.GetFirstTokenId())) {
634         LBSLOGE(LOCATOR, "CheckSecureSettings return false, [%{public}s]", identity.ToString().c_str());
635         return LOCATION_ERRCODE_PERMISSION_DENIED;
636     }
637     return LocationConfigManager::GetInstance()->SetPrivacyTypeState(type, isConfirmed);
638 }
639 
640 #ifdef FEATURE_GNSS_SUPPORT
SendGnssRequest(int type,MessageParcel & data,MessageParcel & reply)641 LocationErrCode LocatorAbility::SendGnssRequest(int type, MessageParcel &data, MessageParcel &reply)
642 {
643     if (!SaLoadWithStatistic::InitLocationSa(LOCATION_GNSS_SA_ID)) {
644         return ERRCODE_SERVICE_UNAVAILABLE;
645     }
646     sptr<IRemoteObject> objectGnss =
647             CommonUtils::GetRemoteObject(LOCATION_GNSS_SA_ID, CommonUtils::InitDeviceId());
648     if (objectGnss == nullptr) {
649         return ERRCODE_SERVICE_UNAVAILABLE;
650     }
651     std::string callingIdentity = IPCSkeleton::ResetCallingIdentity();
652     MessageOption option;
653     objectGnss->SendRequest(type, data, reply, option);
654     IPCSkeleton::SetCallingIdentity(callingIdentity);
655     return LocationErrCode(reply.ReadInt32());
656 }
657 #endif
658 
RegisterGnssStatusCallback(const sptr<IRemoteObject> & cb)659 ErrCode LocatorAbility::RegisterGnssStatusCallback(const sptr<IRemoteObject>& cb)
660 {
661 #ifdef FEATURE_GNSS_SUPPORT
662     AppIdentity identity;
663     GetAppIdentityInfo(identity);
664     if (!CheckRequestAvailable(LocatorInterfaceCode::REG_LOCATING_REQUIRED_DATA_CALLBACK, identity)) {
665         return LOCATION_ERRCODE_PERMISSION_DENIED;
666     }
667     if (!CheckLocationSwitchState()) {
668         return ERRCODE_SWITCH_OFF;
669     }
670     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
671         return LOCATION_ERRCODE_PERMISSION_DENIED;
672     }
673     MessageParcel dataToStub;
674     MessageParcel replyToStub;
675     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
676         return ERRCODE_SERVICE_UNAVAILABLE;
677     }
678     identity.Marshalling(dataToStub);
679     dataToStub.WriteRemoteObject(cb);
680     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::REG_GNSS_STATUS), dataToStub, replyToStub);
681 #else
682     return ERRCODE_SERVICE_UNAVAILABLE;
683 #endif
684 }
685 
UnregisterGnssStatusCallback(const sptr<IRemoteObject> & cb)686 ErrCode LocatorAbility::UnregisterGnssStatusCallback(const sptr<IRemoteObject>& cb)
687 {
688 #ifdef FEATURE_GNSS_SUPPORT
689     AppIdentity identity;
690     GetAppIdentityInfo(identity);
691     if (!CheckRequestAvailable(LocatorInterfaceCode::UNREG_LOCATING_REQUIRED_DATA_CALLBACK, identity)) {
692         return LOCATION_ERRCODE_PERMISSION_DENIED;
693     }
694     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
695         return LOCATION_ERRCODE_PERMISSION_DENIED;
696     }
697     MessageParcel dataToStub;
698     MessageParcel replyToStub;
699     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
700         return ERRCODE_SERVICE_UNAVAILABLE;
701     }
702     dataToStub.WriteRemoteObject(cb);
703     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::UNREG_GNSS_STATUS), dataToStub, replyToStub);
704 #else
705     return ERRCODE_SERVICE_UNAVAILABLE;
706 #endif
707 }
708 
RegisterNmeaMessageCallback(const sptr<IRemoteObject> & cb)709 ErrCode LocatorAbility::RegisterNmeaMessageCallback(const sptr<IRemoteObject>& cb)
710 {
711 #ifdef FEATURE_GNSS_SUPPORT
712     AppIdentity identity;
713     GetAppIdentityInfo(identity);
714     if (!CheckRequestAvailable(LocatorInterfaceCode::REG_NMEA_CALLBACK_V9, identity)) {
715         return LOCATION_ERRCODE_PERMISSION_DENIED;
716     }
717     if (!CheckLocationSwitchState()) {
718         return ERRCODE_SWITCH_OFF;
719     }
720     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
721         return LOCATION_ERRCODE_PERMISSION_DENIED;
722     }
723     MessageParcel dataToStub;
724     MessageParcel replyToStub;
725     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
726         return ERRCODE_SERVICE_UNAVAILABLE;
727     }
728     identity.Marshalling(dataToStub);
729     dataToStub.WriteRemoteObject(cb);
730     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::REG_NMEA), dataToStub, replyToStub);
731 #else
732     return ERRCODE_SERVICE_UNAVAILABLE;
733 #endif
734 }
735 
UnregisterNmeaMessageCallback(const sptr<IRemoteObject> & cb)736 ErrCode LocatorAbility::UnregisterNmeaMessageCallback(const sptr<IRemoteObject>& cb)
737 {
738 #ifdef FEATURE_GNSS_SUPPORT
739     AppIdentity identity;
740     GetAppIdentityInfo(identity);
741     if (!CheckRequestAvailable(LocatorInterfaceCode::UNREG_NMEA_CALLBACK_V9, identity)) {
742         return LOCATION_ERRCODE_PERMISSION_DENIED;
743     }
744     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
745         return LOCATION_ERRCODE_PERMISSION_DENIED;
746     }
747     MessageParcel dataToStub;
748     MessageParcel replyToStub;
749     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
750         return ERRCODE_SERVICE_UNAVAILABLE;
751     }
752     dataToStub.WriteRemoteObject(cb);
753     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::UNREG_NMEA), dataToStub, replyToStub);
754 #else
755     return ERRCODE_SERVICE_UNAVAILABLE;
756 #endif
757 }
758 
RegisterCachedLocationCallback(int32_t reportingPeriodSec,bool wakeUpCacheQueueFull,const sptr<ICachedLocationsCallback> & cb,const std::string & bundleName)759 ErrCode LocatorAbility::RegisterCachedLocationCallback(int32_t reportingPeriodSec, bool wakeUpCacheQueueFull,
760     const sptr<ICachedLocationsCallback>& cb, const std::string& bundleName)
761 {
762 #ifdef FEATURE_GNSS_SUPPORT
763     AppIdentity identity;
764     GetAppIdentityInfo(identity);
765     if (!CheckRequestAvailable(LocatorInterfaceCode::REG_CACHED_CALLBACK, identity)) {
766         return LOCATION_ERRCODE_PERMISSION_DENIED;
767     }
768     if (!CheckLocationSwitchState()) {
769         return ERRCODE_SWITCH_OFF;
770     }
771     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
772         return LOCATION_ERRCODE_PERMISSION_DENIED;
773     }
774     if (cb == nullptr) {
775         LBSLOGE(LOCATOR, "ParseDataAndStartCacheLocating remote object nullptr");
776         return ERRCODE_SERVICE_UNAVAILABLE;
777     }
778     if (bundleName.empty()) {
779         LBSLOGE(LOCATOR, "ParseDataAndStartCacheLocating get empty bundle name");
780         return LOCATION_ERRCODE_INVALID_PARAM;
781     }
782     MessageParcel dataToStub;
783     MessageParcel replyToStub;
784     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
785         return ERRCODE_SERVICE_UNAVAILABLE;
786     }
787     dataToStub.WriteInt32(reportingPeriodSec);
788     dataToStub.WriteBool(wakeUpCacheQueueFull);
789     dataToStub.WriteRemoteObject(cb->AsObject());
790     dataToStub.WriteString16(Str8ToStr16(bundleName));
791     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::REG_CACHED), dataToStub, replyToStub);
792 #else
793     return ERRCODE_SERVICE_UNAVAILABLE;
794 #endif
795 }
796 
UnregisterCachedLocationCallback(const sptr<ICachedLocationsCallback> & cb)797 ErrCode LocatorAbility::UnregisterCachedLocationCallback(const sptr<ICachedLocationsCallback>& cb)
798 {
799 #ifdef FEATURE_GNSS_SUPPORT
800     AppIdentity identity;
801     GetAppIdentityInfo(identity);
802     if (!CheckRequestAvailable(LocatorInterfaceCode::UNREG_CACHED_CALLBACK, identity)) {
803         return LOCATION_ERRCODE_PERMISSION_DENIED;
804     }
805     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
806         return LOCATION_ERRCODE_PERMISSION_DENIED;
807     }
808     if (cb == nullptr) {
809         LBSLOGE(LOCATOR, "LocatorAbility::ParseDataAndStopCacheLocating remote object nullptr");
810         return ERRCODE_SERVICE_UNAVAILABLE;
811     }
812     MessageParcel dataToStub;
813     MessageParcel replyToStub;
814     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
815         return ERRCODE_SERVICE_UNAVAILABLE;
816     }
817     dataToStub.WriteRemoteObject(cb->AsObject());
818     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::UNREG_CACHED), dataToStub, replyToStub);
819 #else
820     return ERRCODE_SERVICE_UNAVAILABLE;
821 #endif
822 }
823 
GetCachedGnssLocationsSize(int32_t & size)824 ErrCode LocatorAbility::GetCachedGnssLocationsSize(int32_t& size)
825 {
826 #ifdef FEATURE_GNSS_SUPPORT
827     AppIdentity identity;
828     GetAppIdentityInfo(identity);
829     if (!CheckRequestAvailable(LocatorInterfaceCode::GET_CACHED_LOCATION_SIZE, identity)) {
830         return LOCATION_ERRCODE_PERMISSION_DENIED;
831     }
832     if (!CheckLocationSwitchState()) {
833         return ERRCODE_SWITCH_OFF;
834     }
835     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
836         return LOCATION_ERRCODE_PERMISSION_DENIED;
837     }
838     size = -1;
839     MessageParcel dataToStub;
840     MessageParcel replyToStub;
841     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
842         return ERRCODE_SERVICE_UNAVAILABLE;
843     }
844     LocationErrCode errorCode =
845         SendGnssRequest(static_cast<int>(GnssInterfaceCode::GET_CACHED_SIZE), dataToStub, replyToStub);
846     if (errorCode == ERRCODE_SUCCESS) {
847         size = replyToStub.ReadInt32();
848     }
849     return errorCode;
850 #else
851     return ERRCODE_SERVICE_UNAVAILABLE;
852 #endif
853 }
854 
FlushCachedGnssLocations()855 ErrCode LocatorAbility::FlushCachedGnssLocations()
856 {
857 #ifdef FEATURE_GNSS_SUPPORT
858     AppIdentity identity;
859     GetAppIdentityInfo(identity);
860     if (!CheckRequestAvailable(LocatorInterfaceCode::FLUSH_CACHED_LOCATIONS, identity)) {
861         return LOCATION_ERRCODE_PERMISSION_DENIED;
862     }
863     if (!CheckLocationSwitchState()) {
864         return ERRCODE_SWITCH_OFF;
865     }
866     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
867         return LOCATION_ERRCODE_PERMISSION_DENIED;
868     }
869     MessageParcel dataToStub;
870     MessageParcel replyToStub;
871     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
872         return ERRCODE_SERVICE_UNAVAILABLE;
873     }
874     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::FLUSH_CACHED), dataToStub, replyToStub);
875 #else
876     return ERRCODE_SERVICE_UNAVAILABLE;
877 #endif
878 }
879 
SendCommand(int32_t scenario,const std::string & command)880 ErrCode LocatorAbility::SendCommand(int32_t scenario, const std::string& command)
881 {
882 #ifdef FEATURE_GNSS_SUPPORT
883     AppIdentity identity;
884     GetAppIdentityInfo(identity);
885     if (!CheckRequestAvailable(LocatorInterfaceCode::SEND_COMMAND, identity)) {
886         return LOCATION_ERRCODE_PERMISSION_DENIED;
887     }
888     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
889         return LOCATION_ERRCODE_PERMISSION_DENIED;
890     }
891     MessageParcel dataToStub;
892     MessageParcel replyToStub;
893     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
894         return ERRCODE_SERVICE_UNAVAILABLE;
895     }
896     dataToStub.WriteInt32(scenario);
897     dataToStub.WriteString16(Str8ToStr16(command));
898     LocationErrCode errorCode =
899         SendGnssRequest(static_cast<int>(GnssInterfaceCode::SEND_COMMANDS), dataToStub, replyToStub);
900     CommandStruct commandStruct;
901     commandStruct.packageName = identity.GetBundleName();
902     commandStruct.command = command;
903     commandStruct.result = true;
904     HookUtils::ExecuteHook(LocationProcessStage::LOCATOR_SA_COMMAND_PROCESS, (void *)&commandStruct, nullptr);
905     return errorCode;
906 #else
907     return ERRCODE_SERVICE_UNAVAILABLE;
908 #endif
909 }
910 
AddFence(const GeofenceRequest & request)911 ErrCode LocatorAbility::AddFence(const GeofenceRequest& request)
912 {
913 #ifdef FEATURE_GNSS_SUPPORT
914     AppIdentity identity;
915     GetAppIdentityInfo(identity);
916     if (!CheckRequestAvailable(LocatorInterfaceCode::ADD_FENCE, identity)) {
917         return LOCATION_ERRCODE_PERMISSION_DENIED;
918     }
919     if (!CheckLocationSwitchState()) {
920         return ERRCODE_SWITCH_OFF;
921     }
922     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
923         return LOCATION_ERRCODE_PERMISSION_DENIED;
924     }
925     MessageParcel dataToStub;
926     MessageParcel replyToStub;
927     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
928         return ERRCODE_SERVICE_UNAVAILABLE;
929     }
930     request.Marshalling(dataToStub);
931     return SendGnssRequest(
932         static_cast<int>(GnssInterfaceCode::ADD_FENCE_INFO), dataToStub, replyToStub);
933 #else
934     return ERRCODE_SERVICE_UNAVAILABLE;
935 #endif
936 }
937 
RemoveFence(const GeofenceRequest & request)938 ErrCode LocatorAbility::RemoveFence(const GeofenceRequest& request)
939 {
940 #ifdef FEATURE_GNSS_SUPPORT
941     AppIdentity identity;
942     GetAppIdentityInfo(identity);
943     if (!CheckRequestAvailable(LocatorInterfaceCode::REMOVE_FENCE, identity)) {
944         return LOCATION_ERRCODE_PERMISSION_DENIED;
945     }
946     if (!CheckLocationSwitchState()) {
947         return ERRCODE_SWITCH_OFF;
948     }
949     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
950         return LOCATION_ERRCODE_PERMISSION_DENIED;
951     }
952     MessageParcel dataToStub;
953     MessageParcel replyToStub;
954     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
955         return ERRCODE_SERVICE_UNAVAILABLE;
956     }
957     request.Marshalling(dataToStub);
958     return SendGnssRequest(
959         static_cast<int>(GnssInterfaceCode::REMOVE_FENCE_INFO), dataToStub, replyToStub);
960 #else
961     return ERRCODE_SERVICE_UNAVAILABLE;
962 #endif
963 }
964 
AddGnssGeofence(const GeofenceRequest & request)965 ErrCode LocatorAbility::AddGnssGeofence(const GeofenceRequest& request)
966 {
967 #ifdef FEATURE_GNSS_SUPPORT
968     AppIdentity identity;
969     GetAppIdentityInfo(identity);
970     if (!CheckRequestAvailable(LocatorInterfaceCode::ADD_GNSS_GEOFENCE, identity)) {
971         return LOCATION_ERRCODE_PERMISSION_DENIED;
972     }
973     if (!CheckLocationSwitchState()) {
974         return ERRCODE_SWITCH_OFF;
975     }
976     if (!CheckPreciseLocationPermissions(identity.GetTokenId(), identity.GetFirstTokenId())) {
977         return LOCATION_ERRCODE_PERMISSION_DENIED;
978     }
979     std::shared_ptr<GeofenceRequest> geofenceRequest =
980         std::make_shared<GeofenceRequest>(const_cast<GeofenceRequest&>(request));
981     geofenceRequest->SetBundleName(identity.GetBundleName());
982     geofenceRequest->SetUid(identity.GetUid());
983     MessageParcel dataToStub;
984     MessageParcel replyToStub;
985     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
986         return ERRCODE_SERVICE_UNAVAILABLE;
987     }
988     geofenceRequest->Marshalling(dataToStub);
989     return SendGnssRequest(
990         static_cast<int>(GnssInterfaceCode::ADD_GNSS_GEOFENCE), dataToStub, replyToStub);
991 #else
992     return ERRCODE_SERVICE_UNAVAILABLE;
993 #endif
994 }
995 
RemoveGnssGeofence(int32_t fenceId)996 ErrCode LocatorAbility::RemoveGnssGeofence(int32_t fenceId)
997 {
998 #ifdef FEATURE_GNSS_SUPPORT
999     AppIdentity identity;
1000     GetAppIdentityInfo(identity);
1001     if (!CheckRequestAvailable(LocatorInterfaceCode::REMOVE_GNSS_GEOFENCE, identity)) {
1002         return LOCATION_ERRCODE_PERMISSION_DENIED;
1003     }
1004     if (!CheckLocationSwitchState()) {
1005         return ERRCODE_SWITCH_OFF;
1006     }
1007     if (!CheckPreciseLocationPermissions(identity.GetTokenId(), identity.GetFirstTokenId())) {
1008         return LOCATION_ERRCODE_PERMISSION_DENIED;
1009     }
1010     MessageParcel dataToStub;
1011     MessageParcel replyToStub;
1012     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
1013         return ERRCODE_SERVICE_UNAVAILABLE;
1014     }
1015     dataToStub.WriteInt32(fenceId);
1016     dataToStub.WriteString(identity.GetBundleName());
1017     return SendGnssRequest(
1018         static_cast<int>(GnssInterfaceCode::REMOVE_GNSS_GEOFENCE), dataToStub, replyToStub);
1019 #else
1020     return ERRCODE_SERVICE_UNAVAILABLE;
1021 #endif
1022 }
1023 
SendLocationMockMsgToGnssSa(const sptr<IRemoteObject> obj,const int timeInterval,const std::vector<std::shared_ptr<Location>> & location,int msgId)1024 LocationErrCode LocatorAbility::SendLocationMockMsgToGnssSa(const sptr<IRemoteObject> obj,
1025     const int timeInterval, const std::vector<std::shared_ptr<Location>> &location, int msgId)
1026 {
1027 #ifdef FEATURE_GNSS_SUPPORT
1028     if (obj == nullptr) {
1029         LBSLOGE(LOCATOR, "SendLocationMockMsgToGnssSa obj is nullptr");
1030         return ERRCODE_SERVICE_UNAVAILABLE;
1031     }
1032     std::unique_ptr<GnssAbilityProxy> gnssProxy = std::make_unique<GnssAbilityProxy>(obj);
1033     LocationErrCode errorCode = LOCATION_ERRCODE_NOT_SUPPORTED;
1034     if (msgId == static_cast<int>(LocatorInterfaceCode::ENABLE_LOCATION_MOCK)) {
1035         errorCode = gnssProxy->EnableMock();
1036     } else if (msgId == static_cast<int>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK)) {
1037         errorCode = gnssProxy->DisableMock();
1038     } else if (msgId == static_cast<int>(LocatorInterfaceCode::SET_MOCKED_LOCATIONS)) {
1039         errorCode = gnssProxy->SetMocked(timeInterval, location);
1040     }
1041     return errorCode;
1042 #else
1043     return ERRCODE_SERVICE_UNAVAILABLE;
1044 #endif
1045 }
1046 
SendLocationMockMsgToNetworkSa(const sptr<IRemoteObject> obj,const int timeInterval,const std::vector<std::shared_ptr<Location>> & location,int msgId)1047 LocationErrCode LocatorAbility::SendLocationMockMsgToNetworkSa(const sptr<IRemoteObject> obj,
1048     const int timeInterval, const std::vector<std::shared_ptr<Location>> &location, int msgId)
1049 {
1050 #ifdef FEATURE_NETWORK_SUPPORT
1051     if (obj == nullptr) {
1052         LBSLOGE(LOCATOR, "SendLocationMockMsgToNetworkSa obj is nullptr");
1053         return ERRCODE_SERVICE_UNAVAILABLE;
1054     }
1055     std::unique_ptr<NetworkAbilityProxy> networkProxy =
1056         std::make_unique<NetworkAbilityProxy>(obj);
1057     LocationErrCode errorCode = LOCATION_ERRCODE_NOT_SUPPORTED;
1058     if (msgId == static_cast<int>(LocatorInterfaceCode::ENABLE_LOCATION_MOCK)) {
1059         errorCode = networkProxy->EnableMock();
1060     } else if (msgId == static_cast<int>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK)) {
1061         errorCode = networkProxy->DisableMock();
1062     } else if (msgId == static_cast<int>(LocatorInterfaceCode::SET_MOCKED_LOCATIONS)) {
1063         errorCode = networkProxy->SetMocked(timeInterval, location);
1064     }
1065     return errorCode;
1066 #else
1067     return ERRCODE_SERVICE_UNAVAILABLE;
1068 #endif
1069 }
1070 
SendLocationMockMsgToPassiveSa(const sptr<IRemoteObject> obj,const int timeInterval,const std::vector<std::shared_ptr<Location>> & location,int msgId)1071 LocationErrCode LocatorAbility::SendLocationMockMsgToPassiveSa(const sptr<IRemoteObject> obj,
1072     const int timeInterval, const std::vector<std::shared_ptr<Location>> &location, int msgId)
1073 {
1074 #ifdef FEATURE_PASSIVE_SUPPORT
1075     if (obj == nullptr) {
1076         LBSLOGE(LOCATOR, "SendLocationMockMsgToNetworkSa obj is nullptr");
1077         return ERRCODE_SERVICE_UNAVAILABLE;
1078     }
1079     std::unique_ptr<PassiveAbilityProxy> passiveProxy =
1080         std::make_unique<PassiveAbilityProxy>(obj);
1081     LocationErrCode errorCode = LOCATION_ERRCODE_NOT_SUPPORTED;
1082     if (msgId == static_cast<int>(LocatorInterfaceCode::ENABLE_LOCATION_MOCK)) {
1083         errorCode = passiveProxy->EnableMock();
1084     } else if (msgId == static_cast<int>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK)) {
1085         errorCode = passiveProxy->DisableMock();
1086     } else if (msgId == static_cast<int>(LocatorInterfaceCode::SET_MOCKED_LOCATIONS)) {
1087         errorCode = passiveProxy->SetMocked(timeInterval, location);
1088     }
1089     return errorCode;
1090 #else
1091     return ERRCODE_SERVICE_UNAVAILABLE;
1092 #endif
1093 }
1094 
ProcessLocationMockMsg(const int timeInterval,const std::vector<std::shared_ptr<Location>> & location,int msgId)1095 LocationErrCode LocatorAbility::ProcessLocationMockMsg(
1096     const int timeInterval, const std::vector<std::shared_ptr<Location>> &location, int msgId)
1097 {
1098 #if !defined(FEATURE_GNSS_SUPPORT) && !defined(FEATURE_NETWORK_SUPPORT) && !defined(FEATURE_PASSIVE_SUPPORT)
1099     LBSLOGE(LOCATOR, "%{public}s: mock service unavailable", __func__);
1100     return LOCATION_ERRCODE_NOT_SUPPORTED;
1101 #endif
1102     if (!CheckSaValid()) {
1103         UpdateProxyMap();
1104     }
1105 
1106     std::unique_lock<std::mutex> lock(proxyMapMutex_);
1107     std::string callingIdentity = IPCSkeleton::ResetCallingIdentity();
1108     for (auto iter = proxyMap_->begin(); iter != proxyMap_->end(); iter++) {
1109         auto obj = iter->second;
1110         if (iter->first == GNSS_ABILITY) {
1111 #ifdef FEATURE_GNSS_SUPPORT
1112             SendLocationMockMsgToGnssSa(obj, timeInterval, location, msgId);
1113 #endif
1114         } else if (iter->first == NETWORK_ABILITY) {
1115 #ifdef FEATURE_NETWORK_SUPPORT
1116             SendLocationMockMsgToNetworkSa(obj, timeInterval, location, msgId);
1117 #endif
1118         } else if (iter->first == PASSIVE_ABILITY) {
1119 #ifdef FEATURE_PASSIVE_SUPPORT
1120             SendLocationMockMsgToPassiveSa(obj, timeInterval, location, msgId);
1121 #endif
1122         }
1123     }
1124     IPCSkeleton::SetCallingIdentity(callingIdentity);
1125     return ERRCODE_SUCCESS;
1126 }
1127 
UpdateLoadedSaMap()1128 void LocatorAbility::UpdateLoadedSaMap()
1129 {
1130     std::unique_lock<ffrt::mutex> lock(loadedSaMapMutex_);
1131     loadedSaMap_->clear();
1132     if (LocationSaLoadManager::CheckIfSystemAbilityAvailable(LOCATION_GNSS_SA_ID)) {
1133         sptr<IRemoteObject> objectGnss =
1134             CommonUtils::GetRemoteObject(LOCATION_GNSS_SA_ID, CommonUtils::InitDeviceId());
1135         loadedSaMap_->insert(make_pair(GNSS_ABILITY, objectGnss));
1136     }
1137     if (LocationSaLoadManager::CheckIfSystemAbilityAvailable(LOCATION_NETWORK_LOCATING_SA_ID)) {
1138         sptr<IRemoteObject> objectNetwork =
1139             CommonUtils::GetRemoteObject(LOCATION_NETWORK_LOCATING_SA_ID, CommonUtils::InitDeviceId());
1140         loadedSaMap_->insert(make_pair(NETWORK_ABILITY, objectNetwork));
1141     }
1142     if (LocationSaLoadManager::CheckIfSystemAbilityAvailable(LOCATION_NOPOWER_LOCATING_SA_ID)) {
1143         sptr<IRemoteObject> objectPassive =
1144             CommonUtils::GetRemoteObject(LOCATION_NOPOWER_LOCATING_SA_ID, CommonUtils::InitDeviceId());
1145         loadedSaMap_->insert(make_pair(PASSIVE_ABILITY, objectPassive));
1146     }
1147 }
1148 
UpdateProxyMap()1149 void LocatorAbility::UpdateProxyMap()
1150 {
1151     std::unique_lock<std::mutex> lock(proxyMapMutex_);
1152 #ifdef FEATURE_GNSS_SUPPORT
1153     // init gnss ability sa
1154     if (!SaLoadWithStatistic::InitLocationSa(LOCATION_GNSS_SA_ID)) {
1155         return;
1156     }
1157     sptr<IRemoteObject> objectGnss = CommonUtils::GetRemoteObject(LOCATION_GNSS_SA_ID, CommonUtils::InitDeviceId());
1158     if (objectGnss != nullptr) {
1159         proxyMap_->insert(make_pair(GNSS_ABILITY, objectGnss));
1160     } else {
1161         LBSLOGE(LOCATOR, "GetRemoteObject gnss sa is null");
1162     }
1163 #endif
1164 #ifdef FEATURE_NETWORK_SUPPORT
1165     // init network ability sa
1166     if (!SaLoadWithStatistic::InitLocationSa(LOCATION_NETWORK_LOCATING_SA_ID)) {
1167         return;
1168     }
1169     sptr<IRemoteObject> objectNetwork = CommonUtils::GetRemoteObject(LOCATION_NETWORK_LOCATING_SA_ID,
1170         CommonUtils::InitDeviceId());
1171     if (objectNetwork != nullptr) {
1172         proxyMap_->insert(make_pair(NETWORK_ABILITY, objectNetwork));
1173     } else {
1174         LBSLOGE(LOCATOR, "GetRemoteObject network sa is null");
1175     }
1176 #endif
1177 #ifdef FEATURE_PASSIVE_SUPPORT
1178     // init passive ability sa
1179     if (!SaLoadWithStatistic::InitLocationSa(LOCATION_NOPOWER_LOCATING_SA_ID)) {
1180         return;
1181     }
1182     sptr<IRemoteObject> objectPassive = CommonUtils::GetRemoteObject(LOCATION_NOPOWER_LOCATING_SA_ID,
1183         CommonUtils::InitDeviceId());
1184     if (objectPassive != nullptr) {
1185         proxyMap_->insert(make_pair(PASSIVE_ABILITY, objectPassive));
1186     } else {
1187         LBSLOGE(LOCATOR, "GetRemoteObject passive sa is null");
1188     }
1189 #endif
1190 }
1191 
EnableLocationMock()1192 ErrCode LocatorAbility::EnableLocationMock()
1193 {
1194     AppIdentity identity;
1195     GetAppIdentityInfo(identity);
1196     if (!CheckRequestAvailable(LocatorInterfaceCode::ENABLE_LOCATION_MOCK, identity)) {
1197         return LOCATION_ERRCODE_PERMISSION_DENIED;
1198     }
1199     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
1200         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
1201         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
1202     }
1203     if (!PermissionManager::CheckMockLocationPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
1204         LBSLOGE(LOCATOR, "CheckMockLocationPermission return false, [%{public}s]", identity.ToString().c_str());
1205         return LOCATION_ERRCODE_PERMISSION_DENIED;
1206     }
1207     int timeInterval = 0;
1208     std::vector<std::shared_ptr<Location>> location;
1209     return ProcessLocationMockMsg(timeInterval, location,
1210         static_cast<int>(LocatorInterfaceCode::ENABLE_LOCATION_MOCK));
1211 }
1212 
DisableLocationMock()1213 ErrCode LocatorAbility::DisableLocationMock()
1214 {
1215     AppIdentity identity;
1216     GetAppIdentityInfo(identity);
1217     if (!CheckRequestAvailable(LocatorInterfaceCode::DISABLE_LOCATION_MOCK, identity)) {
1218         return LOCATION_ERRCODE_PERMISSION_DENIED;
1219     }
1220     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
1221         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
1222         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
1223     }
1224     if (!PermissionManager::CheckMockLocationPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
1225         LBSLOGE(LOCATOR, "CheckMockLocationPermission return false, [%{public}s]", identity.ToString().c_str());
1226         return LOCATION_ERRCODE_PERMISSION_DENIED;
1227     }
1228     int timeInterval = 0;
1229     std::vector<std::shared_ptr<Location>> location;
1230     return ProcessLocationMockMsg(timeInterval, location,
1231         static_cast<int>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK));
1232 }
1233 
SetMockedLocations(int32_t timeInterval,const std::vector<Location> & locations)1234 ErrCode LocatorAbility::SetMockedLocations(int32_t timeInterval, const std::vector<Location>& locations)
1235 {
1236     AppIdentity identity;
1237     GetAppIdentityInfo(identity);
1238     if (!CheckRequestAvailable(LocatorInterfaceCode::SET_MOCKED_LOCATIONS, identity)) {
1239         return LOCATION_ERRCODE_PERMISSION_DENIED;
1240     }
1241     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
1242         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
1243         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
1244     }
1245     if (!PermissionManager::CheckMockLocationPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
1246         LBSLOGE(LOCATOR, "CheckMockLocationPermission return false, [%{public}s]", identity.ToString().c_str());
1247         return LOCATION_ERRCODE_PERMISSION_DENIED;
1248     }
1249     timeInterval = timeInterval < 0 ? 1 : timeInterval;
1250     auto locationSize = locations.size();
1251     locationSize = locationSize > INPUT_ARRAY_LEN_MAX ? INPUT_ARRAY_LEN_MAX : locationSize;
1252     std::vector<std::shared_ptr<Location>> sharedLocations;
1253     for (size_t i = 0; i < locationSize; i++) {
1254         sharedLocations.push_back(std::make_shared<Location>(locations[i]));
1255     }
1256     return ProcessLocationMockMsg(timeInterval, sharedLocations,
1257         static_cast<int>(LocatorInterfaceCode::SET_MOCKED_LOCATIONS));
1258 }
1259 
StartLocating(const RequestConfig & requestConfig,const sptr<ILocatorCallback> & cb)1260 ErrCode LocatorAbility::StartLocating(const RequestConfig& requestConfig, const sptr<ILocatorCallback>& cb)
1261 {
1262     AppIdentity identity;
1263     GetAppIdentityInfo(identity);
1264     if (!CheckRequestAvailable(LocatorInterfaceCode::START_LOCATING, identity)) {
1265         return LOCATION_ERRCODE_PERMISSION_DENIED;
1266     }
1267     if (!GetLocationSwitchIgnoredFlag(identity.GetTokenId()) && !CheckLocationSwitchState()) {
1268         return ERRCODE_SWITCH_OFF;
1269     }
1270     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
1271         WriteLocationInnerEvent(LBS_REQUEST_FAIL_DETAIL, {"REQ_APP_NAME", identity.GetBundleName(),
1272             "NETWORK_FAIL_CODE", std::to_string(ERRCODE_PERMISSION_DENIED)});
1273         return LOCATION_ERRCODE_PERMISSION_DENIED;
1274     }
1275     bool res = HookUtils::ExecuteHookWhenPreStartLocating(identity.GetBundleName());
1276     auto reportManager = ReportManager::GetInstance();
1277     if (reportManager != nullptr && res) {
1278         if (reportManager->IsAppBackground(identity.GetBundleName(), identity.GetTokenId(),
1279             identity.GetTokenIdEx(), identity.GetUid(), identity.GetPid()) &&
1280             !PermissionManager::CheckBackgroundPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
1281             WriteLocationInnerEvent(LBS_REQUEST_FAIL_DETAIL, {"REQ_APP_NAME", identity.GetBundleName(),
1282                 "NETWORK_FAIL_CODE", std::to_string(LOCATION_ERRCODE_BACKGROUND_PERMISSION_DENIED)});
1283             return LOCATION_ERRCODE_PERMISSION_DENIED;
1284         }
1285     }
1286     return StartLocatingProcess(requestConfig, cb, identity);
1287 }
1288 
IsCacheVaildScenario(const sptr<RequestConfig> & requestConfig)1289 bool LocatorAbility::IsCacheVaildScenario(const sptr<RequestConfig>& requestConfig)
1290 {
1291     if ((requestConfig->GetPriority() == LOCATION_PRIORITY_LOCATING_SPEED) ||
1292         (requestConfig->GetScenario() == SCENE_DAILY_LIFE_SERVICE) ||
1293         (requestConfig->GetScenario() == LOCATION_SCENE_DAILY_LIFE_SERVICE) ||
1294         (requestConfig->GetScenario() == LOCATION_SCENE_LOW_POWER_CONSUMPTION) ||
1295         ((requestConfig->GetScenario() == SCENE_UNSET) && (requestConfig->GetPriority() == PRIORITY_FAST_FIRST_FIX)) ||
1296         ((requestConfig->GetScenario() == SCENE_UNSET) && (requestConfig->GetPriority() == PRIORITY_LOW_POWER))) {
1297         return true;
1298     }
1299     return false;
1300 }
1301 
IsSingleRequest(const sptr<RequestConfig> & requestConfig)1302 bool LocatorAbility::IsSingleRequest(const sptr<RequestConfig>& requestConfig)
1303 {
1304     if (requestConfig->GetFixNumber() == 1) {
1305         return true;
1306     }
1307     return false;
1308 }
1309 
UpdatePermissionUsedRecord(uint32_t tokenId,std::string permissionName,int permUsedType,int succCnt,int failCnt)1310 int LocatorAbility::UpdatePermissionUsedRecord(uint32_t tokenId, std::string permissionName,
1311     int permUsedType, int succCnt, int failCnt)
1312 {
1313     // permUsedType is invalid, no need to call AddPermissionUsedRecord
1314     if (permUsedType == -1) {
1315         return 0;
1316     }
1317     Security::AccessToken::AddPermParamInfo info;
1318     info.tokenId = tokenId;
1319     info.permissionName = permissionName;
1320     info.successCount = succCnt;
1321     info.failCount = failCnt;
1322     info.type = static_cast<OHOS::Security::AccessToken::PermissionUsedType>(permUsedType);
1323     int ret = Security::AccessToken::PrivacyKit::AddPermissionUsedRecord(info);
1324     return ret;
1325 }
1326 
NeedReportCacheLocation(const std::shared_ptr<Request> & request,const sptr<ILocatorCallback> & callback)1327 bool LocatorAbility::NeedReportCacheLocation(const std::shared_ptr<Request>& request,
1328     const sptr<ILocatorCallback>& callback)
1329 {
1330     if (reportManager_ == nullptr || requestManager_ == nullptr || request == nullptr || callback == nullptr ||
1331         !IsCacheVaildScenario(request->GetRequestConfig())) {
1332         return false;
1333     }
1334     uint32_t tokenId = request->GetTokenId();
1335     uint32_t firstTokenId = request->GetFirstTokenId();
1336     if (!PermissionManager::CheckLocationPermission(tokenId, firstTokenId) &&
1337         !PermissionManager::CheckApproximatelyPermission(tokenId, firstTokenId)) {
1338         RequestManager::GetInstance()->ReportLocationError(LOCATING_FAILED_LOCATION_PERMISSION_DENIED, request);
1339         LBSLOGI(LOCATOR, "CheckLocationPermission return false, tokenId=%{public}d", tokenId);
1340         return false;
1341     }
1342     std::string bundleName = request->GetPackageName();
1343     pid_t uid = request->GetUid();
1344     pid_t pid = request->GetPid();
1345     auto reportManager = ReportManager::GetInstance();
1346     if (reportManager != nullptr) {
1347         if (reportManager->IsAppBackground(bundleName, tokenId, request->GetTokenIdEx(), uid, pid) &&
1348             !PermissionManager::CheckBackgroundPermission(tokenId, firstTokenId)) {
1349             RequestManager::GetInstance()->ReportLocationError(LOCATING_FAILED_BACKGROUND_PERMISSION_DENIED, request);
1350             LBSLOGE(REPORT_MANAGER, "CheckBackgroundPermission return false, Id=%{public}d", tokenId);
1351             return false;
1352         }
1353     }
1354     // report cache location
1355     auto cacheLocation = reportManager_->GetCacheLocation(request);
1356     if (cacheLocation == nullptr) {
1357         return false;
1358     }
1359     if (IsSingleRequest(request->GetRequestConfig())) {
1360         return ReportSingleCacheLocation(request, callback, cacheLocation);
1361     } else {
1362         return ReportCacheLocation(request, callback, cacheLocation);
1363     }
1364 }
1365 
ReportSingleCacheLocation(const std::shared_ptr<Request> & request,const sptr<ILocatorCallback> & callback,std::unique_ptr<Location> & cacheLocation)1366 bool LocatorAbility::ReportSingleCacheLocation(const std::shared_ptr<Request>& request,
1367     const sptr<ILocatorCallback>& callback, std::unique_ptr<Location>& cacheLocation)
1368 {
1369     requestManager_->IncreaseWorkingPidsCount(request->GetPid());
1370     if (requestManager_->IsNeedStartUsingPermission(request->GetPid())) {
1371         int ret = PrivacyKit::StartUsingPermission(
1372             request->GetTokenId(), ACCESS_APPROXIMATELY_LOCATION, request->GetPid());
1373         if (ret != ERRCODE_SUCCESS && ret != Security::AccessToken::ERR_PERMISSION_ALREADY_START_USING &&
1374             IsHapCaller(request->GetTokenId())) {
1375             requestManager_->DecreaseWorkingPidsCount(request->GetPid());
1376             LBSLOGE(LOCATOR, "StartUsingPermission failed ret=%{public}d", ret);
1377             return false;
1378         }
1379     }
1380     // add location permission using record
1381     int recordResult = UpdatePermissionUsedRecord(request->GetTokenId(), ACCESS_APPROXIMATELY_LOCATION,
1382         request->GetPermUsedType(), 1, 0);
1383     if (recordResult != ERRCODE_SUCCESS && IsHapCaller(request->GetTokenId())) {
1384         requestManager_->DecreaseWorkingPidsCount(request->GetPid());
1385         LBSLOGE(LOCATOR, "UpdatePermissionUsedRecord failed ret=%{public}d", recordResult);
1386         return false;
1387     }
1388     LBSLOGI(LOCATOR, "report cache location to %{public}s, uuid: %{public}s",
1389         request->GetPackageName().c_str(), request->GetUuid().c_str());
1390     callback->OnLocationReport(cacheLocation);
1391     requestManager_->DecreaseWorkingPidsCount(request->GetPid());
1392     if (requestManager_->IsNeedStopUsingPermission(request->GetPid())) {
1393         PrivacyKit::StopUsingPermission(request->GetTokenId(), ACCESS_APPROXIMATELY_LOCATION, request->GetPid());
1394     }
1395     return true;
1396 }
1397 
ReportCacheLocation(const std::shared_ptr<Request> & request,const sptr<ILocatorCallback> & callback,std::unique_ptr<Location> & cacheLocation)1398 bool LocatorAbility::ReportCacheLocation(const std::shared_ptr<Request>& request,
1399     const sptr<ILocatorCallback>& callback, std::unique_ptr<Location>& cacheLocation)
1400 {
1401     // add location permission using record
1402     int ret = UpdatePermissionUsedRecord(request->GetTokenId(), ACCESS_APPROXIMATELY_LOCATION,
1403         request->GetPermUsedType(), 1, 0);
1404     if (ret != ERRCODE_SUCCESS && IsHapCaller(request->GetTokenId())) {
1405         LBSLOGE(LOCATOR, "UpdatePermissionUsedRecord failed ret=%{public}d", ret);
1406         return false;
1407     }
1408     LBSLOGI(LOCATOR, "report cache location to %{public}s, uuid: %{public}s",
1409         request->GetPackageName().c_str(), request->GetUuid().c_str());
1410     callback->OnLocationReport(cacheLocation);
1411     return false;
1412 }
1413 
HandleStartLocating(const std::shared_ptr<Request> & request,const sptr<ILocatorCallback> & callback)1414 void LocatorAbility::HandleStartLocating(const std::shared_ptr<Request>& request,
1415     const sptr<ILocatorCallback>& callback)
1416 {
1417     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::Get(EVENT_START_LOCATING, request);
1418     if (locatorHandler_ != nullptr) {
1419         locatorHandler_->SendEvent(event);
1420     }
1421     if (callback != nullptr) {
1422         ReportLocationStatus(callback, SESSION_START);
1423     }
1424 }
1425 
StopLocating(const sptr<ILocatorCallback> & cb)1426 ErrCode LocatorAbility::StopLocating(const sptr<ILocatorCallback>& cb)
1427 {
1428     AppIdentity identity;
1429     GetAppIdentityInfo(identity);
1430     if (!CheckRequestAvailable(LocatorInterfaceCode::STOP_LOCATING, identity)) {
1431         return LOCATION_ERRCODE_PERMISSION_DENIED;
1432     }
1433     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
1434         return LOCATION_ERRCODE_PERMISSION_DENIED;
1435     }
1436     if (cb == nullptr) {
1437         LBSLOGE(LOCATOR, "LocatorAbility::StopLocating remote object nullptr");
1438         return ERRCODE_SERVICE_UNAVAILABLE;
1439     }
1440 #if !defined(FEATURE_GNSS_SUPPORT) && !defined(FEATURE_NETWORK_SUPPORT) && !defined(FEATURE_PASSIVE_SUPPORT)
1441     LBSLOGE(LOCATOR, "%{public}s: service unavailable", __func__);
1442     return LOCATION_ERRCODE_NOT_SUPPORTED;
1443 #endif
1444     if (requestManager_ == nullptr) {
1445         return ERRCODE_SERVICE_UNAVAILABLE;
1446     }
1447     std::unique_ptr<LocatorCallbackMessage> callbackMessage = std::make_unique<LocatorCallbackMessage>();
1448     callbackMessage->SetCallback(cb);
1449     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::Get(EVENT_STOP_LOCATING, callbackMessage);
1450     if (locatorHandler_ != nullptr) {
1451         locatorHandler_->SendEvent(event);
1452     }
1453     ReportLocationStatus(cb, SESSION_STOP);
1454     return ERRCODE_SUCCESS;
1455 }
1456 
GetCacheLocation(Location & location)1457 ErrCode LocatorAbility::GetCacheLocation(Location& location)
1458 {
1459     AppIdentity identity;
1460     GetAppIdentityInfo(identity);
1461     if (!CheckRequestAvailable(LocatorInterfaceCode::GET_CACHE_LOCATION, identity)) {
1462         return LOCATION_ERRCODE_PERMISSION_DENIED;
1463     }
1464     if (!GetLocationSwitchIgnoredFlag(identity.GetTokenId()) && !CheckLocationSwitchState()) {
1465         return ERRCODE_SWITCH_OFF;
1466     }
1467     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
1468         return LOCATION_ERRCODE_PERMISSION_DENIED;
1469     }
1470     if (locatorHandler_ == nullptr) {
1471         return ERRCODE_SERVICE_UNAVAILABLE;
1472     }
1473     auto lastLocation = reportManager_->GetLastLocation();
1474     std::unique_ptr<RequestConfig> requestConfig = std::make_unique<RequestConfig>();
1475     sptr<ILocatorCallback> callback;
1476     std::shared_ptr<Request> request = std::make_shared<Request>(requestConfig, callback, identity);
1477     std::unique_ptr<Location> loc = reportManager_->GetPermittedLocation(request, lastLocation);
1478     std::shared_ptr<AppIdentity> identityInfo = std::make_shared<AppIdentity>(identity);
1479     if (loc == nullptr) {
1480         locatorHandler_->SendHighPriorityEvent(EVENT_GET_CACHED_LOCATION_FAILED, identityInfo, 0);
1481         return ERRCODE_LOCATING_CACHE_FAIL;
1482     }
1483     reportManager_->UpdateLocationByRequest(identity.GetTokenId(), identity.GetTokenIdEx(), loc);
1484     location = *loc;
1485     requestManager_->IncreaseWorkingPidsCount(identity.GetPid());
1486     if (requestManager_->IsNeedStartUsingPermission(identity.GetPid())) {
1487         int ret = PrivacyKit::StartUsingPermission(
1488             identity.GetTokenId(), ACCESS_APPROXIMATELY_LOCATION, identity.GetPid());
1489         if (ret != ERRCODE_SUCCESS && ret != Security::AccessToken::ERR_PERMISSION_ALREADY_START_USING &&
1490             IsHapCaller(request->GetTokenId())) {
1491             LBSLOGE(LOCATOR, "StartUsingPermission failed ret=%{public}d", ret);
1492             locatorHandler_->SendHighPriorityEvent(EVENT_GET_CACHED_LOCATION_FAILED, identityInfo, 0);
1493             return ERRCODE_LOCATING_FAIL;
1494         }
1495     }
1496     // add location permission using record
1497     LBSLOGW(REPORT_MANAGER, "report last location to %{public}d, TimeSinceBoot : %{public}s, SourceType : %{public}d",
1498             identity.GetTokenId(), std::to_string(loc->GetTimeSinceBoot()).c_str(),
1499             loc->GetLocationSourceType());
1500     locatorHandler_->SendHighPriorityEvent(EVENT_GET_CACHED_LOCATION_SUCCESS, identityInfo, 0);
1501     return ERRCODE_SUCCESS;
1502 }
1503 
ReportLocation(const std::string & abilityName,const Location & location)1504 ErrCode LocatorAbility::ReportLocation(const std::string& abilityName, const Location& location)
1505 {
1506     AppIdentity identity;
1507     GetAppIdentityInfo(identity);
1508     if (!CheckRequestAvailable(LocatorInterfaceCode::REPORT_LOCATION, identity)) {
1509         return LOCATION_ERRCODE_PERMISSION_DENIED;
1510     }
1511     if (identity.GetUid() != static_cast<pid_t>(getuid()) || identity.GetPid() != getpid()) {
1512         LBSLOGE(LOCATOR, "check system permission failed, [%{public}s]", identity.ToString().c_str());
1513         return LOCATION_ERRCODE_PERMISSION_DENIED;
1514     }
1515     if (requests_ == nullptr) {
1516         return ERRCODE_SERVICE_UNAVAILABLE;
1517     }
1518     std::unique_ptr<LocationMessage> locationMessage = std::make_unique<LocationMessage>();
1519     locationMessage->SetAbilityName(abilityName);
1520     auto loc = std::make_unique<OHOS::Location::Location>(location);
1521     locationMessage->SetLocation(loc);
1522     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1523         Get(EVENT_REPORT_LOCATION_MESSAGE, locationMessage);
1524     if (locatorHandler_ == nullptr || !locatorHandler_->SendEvent(event)) {
1525         return ERRCODE_SERVICE_UNAVAILABLE;
1526     }
1527 #ifdef FEATURE_GNSS_SUPPORT
1528     if (abilityName == NETWORK_ABILITY) {
1529         SendNetworkLocation(loc);
1530     }
1531 #endif
1532     return ERRCODE_SUCCESS;
1533 }
1534 
ReportLocationStatus(const sptr<ILocatorCallback> & callback,int result)1535 ErrCode LocatorAbility::ReportLocationStatus(const sptr<ILocatorCallback>& callback, int result)
1536 {
1537     int state = DISABLED;
1538     ErrCode errorCode = GetSwitchState(state);
1539     if (errorCode != ERRCODE_SUCCESS) {
1540         return errorCode;
1541     }
1542     if (state == DISABLED) {
1543         LBSLOGE(LOCATOR, "%{public}s line:%{public}d location switch is off", __func__, __LINE__);
1544         return ERRCODE_SWITCH_OFF;
1545     }
1546     if (reportManager_->ReportRemoteCallback(callback, ILocatorCallback::RECEIVE_LOCATION_STATUS_EVENT, result)) {
1547         return ERRCODE_SUCCESS;
1548     }
1549     return ERRCODE_SERVICE_UNAVAILABLE;
1550 }
1551 
ReportErrorStatus(const sptr<ILocatorCallback> & callback,int result)1552 ErrCode LocatorAbility::ReportErrorStatus(const sptr<ILocatorCallback>& callback, int result)
1553 {
1554     int state = DISABLED;
1555     ErrCode errorCode = GetSwitchState(state);
1556     if (errorCode != ERRCODE_SUCCESS) {
1557         return errorCode;
1558     }
1559     if (state == DISABLED) {
1560         LBSLOGE(LOCATOR, "%{public}s line:%{public}d location switch is off", __func__, __LINE__);
1561         return ERRCODE_SWITCH_OFF;
1562     }
1563     if (reportManager_->ReportRemoteCallback(callback, ILocatorCallback::RECEIVE_ERROR_INFO_EVENT, result)) {
1564         return ERRCODE_SUCCESS;
1565     }
1566     return ERRCODE_SERVICE_UNAVAILABLE;
1567 }
1568 
RegisterAction()1569 void LocatorAbility::RegisterAction()
1570 {
1571     if (isActionRegistered) {
1572         LBSLOGI(LOCATOR, "action has already registered");
1573         return;
1574     }
1575     OHOS::EventFwk::MatchingSkills matchingSkills;
1576     matchingSkills.AddEvent(MODE_CHANGED_EVENT);
1577     matchingSkills.AddEvent(OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED);
1578     matchingSkills.AddEvent(OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_SIM_STATE_CHANGED);
1579     matchingSkills.AddEvent(LOCATION_CUST_CONFIG_POLICY_CHANGE);
1580     matchingSkills.AddEvent(PACKAGE_REMOVED_EVENT);
1581     OHOS::EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills);
1582     locatorEventSubscriber_ = std::make_shared<LocatorEventSubscriber>(subscriberInfo);
1583 
1584     bool result = OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(locatorEventSubscriber_);
1585     if (!result) {
1586         LBSLOGE(LOCATOR, "Failed to subscriber locator event, result = %{public}d", result);
1587         isActionRegistered = false;
1588     } else {
1589         LBSLOGI(LOCATOR, "success to subscriber locator event, result = %{public}d", result);
1590         isActionRegistered = true;
1591     }
1592 }
1593 
RegisterLocationPrivacyAction()1594 void LocatorAbility::RegisterLocationPrivacyAction()
1595 {
1596     if (isLocationPrivacyActionRegistered_) {
1597         LBSLOGI(LOCATOR, "location privacy action has already registered");
1598         return;
1599     }
1600     OHOS::EventFwk::MatchingSkills matchingSkills;
1601     matchingSkills.AddEvent(LOCATION_PRIVACY_ACCEPT_EVENT);
1602     matchingSkills.AddEvent(LOCATION_PRIVACY_REJECT_EVENT);
1603     OHOS::EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills);
1604     subscriberInfo.SetPermission("ohos.permission.PUBLISH_LOCATION_EVENT");
1605     locationPrivacyEventSubscriber_ = std::make_shared<LocatorEventSubscriber>(subscriberInfo);
1606 
1607     bool result = OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(locationPrivacyEventSubscriber_);
1608     if (!result) {
1609         LBSLOGE(LOCATOR, "Failed to subscriber location privacy event, result = %{public}d", result);
1610         isLocationPrivacyActionRegistered_ = false;
1611     } else {
1612         LBSLOGI(LOCATOR, "success to subscriber location privacy event, result = %{public}d", result);
1613         isLocationPrivacyActionRegistered_ = true;
1614     }
1615 }
1616 
IsGeoConvertAvailable(bool & isAvailable)1617 ErrCode LocatorAbility::IsGeoConvertAvailable(bool& isAvailable)
1618 {
1619 #ifdef FEATURE_GEOCODE_SUPPORT
1620     MessageParcel dataParcel;
1621     MessageParcel replyParcel;
1622     if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1623         isAvailable = false;
1624         return ERRCODE_SERVICE_UNAVAILABLE;
1625     }
1626     SendGeoRequest(static_cast<int>(LocatorInterfaceCode::GEO_IS_AVAILABLE), dataParcel, replyParcel);
1627     LocationErrCode errorCode = LocationErrCode(replyParcel.ReadInt32());
1628     if (errorCode == ERRCODE_SUCCESS) {
1629         isAvailable = replyParcel.ReadBool();
1630     } else {
1631         isAvailable = false;
1632     }
1633     return errorCode;
1634 #else
1635     return ERRCODE_SERVICE_UNAVAILABLE;
1636 #endif
1637 }
1638 
GetAddressByCoordinate(const sptr<IRemoteObject> & cb,const GeocodeConvertLocationRequest & request)1639 ErrCode LocatorAbility::GetAddressByCoordinate(const sptr<IRemoteObject>& cb,
1640     const GeocodeConvertLocationRequest& request)
1641 {
1642 #ifdef FEATURE_GEOCODE_SUPPORT
1643     AppIdentity identity;
1644     GetAppIdentityInfo(identity);
1645     if (!CheckRequestAvailable(LocatorInterfaceCode::GET_FROM_COORDINATE, identity)) {
1646         return LOCATION_ERRCODE_PERMISSION_DENIED;
1647     }
1648     std::string bundleName =
1649         identity.GetBundleName().size() > 0 ? identity.GetBundleName() : std::to_string(identity.GetUid());
1650     MessageParcel data;
1651     request.Marshalling(data);
1652     data.WriteRemoteObject(cb);
1653     MessageParcel dataParcel;
1654     auto requestTime = CommonUtils::GetCurrentTimeStamp();
1655     GeoCodeType requestType = GeoCodeType::REQUEST_REVERSE_GEOCODE;
1656     GeoConvertRequest::OrderParcel(data, dataParcel, cb, requestType, bundleName);
1657     auto geoConvertRequest = GeoConvertRequest::Unmarshalling(dataParcel, requestType);
1658     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1659         Get(EVENT_SEND_GEOREQUEST, geoConvertRequest);
1660     if (locatorHandler_ != nullptr) {
1661         locatorHandler_->SendEvent(event);
1662     }
1663     HookUtils::ExecuteHookWhenGetAddressFromLocation(bundleName);
1664     return ERRCODE_SUCCESS;
1665 #else
1666     return ERRCODE_SERVICE_UNAVAILABLE;
1667 #endif
1668 }
1669 
GetAddressByLocationName(const sptr<IRemoteObject> & cb,const GeocodeConvertAddressRequest & request)1670 ErrCode LocatorAbility::GetAddressByLocationName(const sptr<IRemoteObject>& cb,
1671     const GeocodeConvertAddressRequest& request)
1672 {
1673 #ifdef FEATURE_GEOCODE_SUPPORT
1674     AppIdentity identity;
1675     GetAppIdentityInfo(identity);
1676     if (!CheckRequestAvailable(LocatorInterfaceCode::GET_FROM_LOCATION_NAME, identity)) {
1677         return LOCATION_ERRCODE_PERMISSION_DENIED;
1678     }
1679     std::string bundleName =
1680         identity.GetBundleName().size() > 0 ? identity.GetBundleName() : std::to_string(identity.GetUid());
1681     MessageParcel data;
1682     request.Marshalling(data);
1683     data.WriteRemoteObject(cb);
1684     MessageParcel dataParcel;
1685     auto requestTime = CommonUtils::GetCurrentTimeStamp();
1686     GeoCodeType requestType = GeoCodeType::REQUEST_GEOCODE;
1687     GeoConvertRequest::OrderParcel(data, dataParcel, cb, requestType, bundleName);
1688     auto geoConvertRequest = GeoConvertRequest::Unmarshalling(dataParcel, requestType);
1689     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1690         Get(EVENT_SEND_GEOREQUEST, geoConvertRequest);
1691     if (locatorHandler_ != nullptr) {
1692         locatorHandler_->SendEvent(event);
1693     }
1694     HookUtils::ExecuteHookWhenGetAddressFromLocationName(bundleName);
1695     return ERRCODE_SUCCESS;
1696 #else
1697     return ERRCODE_SERVICE_UNAVAILABLE;
1698 #endif
1699 }
1700 
SendGeoRequest(int type,MessageParcel & data,MessageParcel & reply)1701 LocationErrCode LocatorAbility::SendGeoRequest(int type, MessageParcel &data, MessageParcel &reply)
1702 {
1703 #ifdef FEATURE_GEOCODE_SUPPORT
1704     if (!SaLoadWithStatistic::InitLocationSa(LOCATION_GEO_CONVERT_SA_ID)) {
1705         reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
1706         return ERRCODE_SERVICE_UNAVAILABLE;
1707     }
1708     sptr<IRemoteObject> remoteObject = CommonUtils::GetRemoteObject(LOCATION_GEO_CONVERT_SA_ID,
1709         CommonUtils::InitDeviceId());
1710     if (remoteObject == nullptr) {
1711         reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
1712         return ERRCODE_SERVICE_UNAVAILABLE;
1713     }
1714     std::string callingIdentity = IPCSkeleton::ResetCallingIdentity();
1715     MessageOption option;
1716     remoteObject->SendRequest(type, data, reply, option);
1717     IPCSkeleton::SetCallingIdentity(callingIdentity);
1718     return ERRCODE_SUCCESS;
1719 #else
1720     return ERRCODE_SERVICE_UNAVAILABLE;
1721 #endif
1722 }
1723 
EnableReverseGeocodingMock()1724 ErrCode LocatorAbility::EnableReverseGeocodingMock()
1725 {
1726 #ifdef FEATURE_GEOCODE_SUPPORT
1727     AppIdentity identity;
1728     GetAppIdentityInfo(identity);
1729     if (!CheckRequestAvailable(LocatorInterfaceCode::ENABLE_REVERSE_GEOCODE_MOCK, identity)) {
1730         return LOCATION_ERRCODE_PERMISSION_DENIED;
1731     }
1732     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
1733         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
1734         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
1735     }
1736     if (!PermissionManager::CheckMockLocationPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
1737         LBSLOGE(LOCATOR, "CheckMockLocationPermission return false, [%{public}s]", identity.ToString().c_str());
1738         return LOCATION_ERRCODE_PERMISSION_DENIED;
1739     }
1740     MessageParcel dataParcel;
1741     MessageParcel replyParcel;
1742     if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1743         return ERRCODE_SERVICE_UNAVAILABLE;
1744     }
1745     SendGeoRequest(static_cast<int>(LocatorInterfaceCode::ENABLE_REVERSE_GEOCODE_MOCK), dataParcel, replyParcel);
1746     return replyParcel.ReadInt32();
1747 #else
1748     return ERRCODE_SERVICE_UNAVAILABLE;
1749 #endif
1750 }
1751 
DisableReverseGeocodingMock()1752 ErrCode LocatorAbility::DisableReverseGeocodingMock()
1753 {
1754 #ifdef FEATURE_GEOCODE_SUPPORT
1755     AppIdentity identity;
1756     GetAppIdentityInfo(identity);
1757     if (!CheckRequestAvailable(LocatorInterfaceCode::DISABLE_REVERSE_GEOCODE_MOCK, identity)) {
1758         return LOCATION_ERRCODE_PERMISSION_DENIED;
1759     }
1760     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
1761         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
1762         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
1763     }
1764     if (!PermissionManager::CheckMockLocationPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
1765         LBSLOGE(LOCATOR, "CheckMockLocationPermission return false, [%{public}s]", identity.ToString().c_str());
1766         return LOCATION_ERRCODE_PERMISSION_DENIED;
1767     }
1768     MessageParcel dataParcel;
1769     MessageParcel replyParcel;
1770     if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1771         return ERRCODE_SERVICE_UNAVAILABLE;
1772     }
1773     SendGeoRequest(static_cast<int>(LocatorInterfaceCode::DISABLE_REVERSE_GEOCODE_MOCK), dataParcel, replyParcel);
1774     return replyParcel.ReadInt32();
1775 #else
1776     return ERRCODE_SERVICE_UNAVAILABLE;
1777 #endif
1778 }
1779 
SetReverseGeocodingMockInfo(const std::vector<GeocodingMockInfo> & geocodingMockInfo)1780 ErrCode LocatorAbility::SetReverseGeocodingMockInfo(const std::vector<GeocodingMockInfo>& geocodingMockInfo)
1781 {
1782 #ifdef FEATURE_GEOCODE_SUPPORT
1783     AppIdentity identity;
1784     GetAppIdentityInfo(identity);
1785     if (!CheckRequestAvailable(LocatorInterfaceCode::SET_REVERSE_GEOCODE_MOCKINFO, identity)) {
1786         return LOCATION_ERRCODE_PERMISSION_DENIED;
1787     }
1788     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
1789         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
1790         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
1791     }
1792     if (!PermissionManager::CheckMockLocationPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
1793         LBSLOGE(LOCATOR, "CheckMockLocationPermission return false, [%{public}s]", identity.ToString().c_str());
1794         return LOCATION_ERRCODE_PERMISSION_DENIED;
1795     }
1796     size_t arraySize = geocodingMockInfo.size();
1797     arraySize = arraySize > INPUT_ARRAY_LEN_MAX ? INPUT_ARRAY_LEN_MAX : arraySize;
1798     std::vector<std::shared_ptr<GeocodingMockInfo>> mockInfo;
1799     for (size_t i = 0; i < arraySize; i++) {
1800         std::shared_ptr<GeocodingMockInfo> info = std::make_shared<GeocodingMockInfo>(geocodingMockInfo[i]);
1801         mockInfo.push_back(info);
1802     }
1803     MessageParcel dataParcel;
1804     MessageParcel replyParcel;
1805     if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1806         return ERRCODE_SERVICE_UNAVAILABLE;
1807     }
1808     dataParcel.WriteInt32(mockInfo.size());
1809     for (size_t i = 0; i < mockInfo.size(); i++) {
1810         mockInfo[i]->Marshalling(dataParcel);
1811     }
1812     SendGeoRequest(static_cast<int>(LocatorInterfaceCode::SET_REVERSE_GEOCODE_MOCKINFO), dataParcel, replyParcel);
1813     return LocationErrCode(replyParcel.ReadInt32());
1814 #else
1815     return ERRCODE_SERVICE_UNAVAILABLE;
1816 #endif
1817 }
1818 
ProxyForFreeze(const std::vector<int32_t> & pidList,bool isProxy)1819 ErrCode LocatorAbility::ProxyForFreeze(const std::vector<int32_t>& pidList, bool isProxy)
1820 {
1821     AppIdentity identity;
1822     GetAppIdentityInfo(identity);
1823     if (!PermissionManager::CheckRssProcessName(identity.GetTokenId())) {
1824         return LOCATION_ERRCODE_PERMISSION_DENIED;
1825     }
1826     ProxyFreezeManager::GetInstance()->ProxyForFreeze(pidList, isProxy);
1827     if (GetActiveRequestNum() <= 0) {
1828         LBSLOGD(LOCATOR, "no active request, do not refresh.");
1829         return ERRCODE_SUCCESS;
1830     }
1831     // for proxy uid update, should send message to refresh requests
1832     ApplyRequests(0);
1833     return ERRCODE_SUCCESS;
1834 }
1835 
ResetAllProxy()1836 ErrCode LocatorAbility::ResetAllProxy()
1837 {
1838     LBSLOGI(LOCATOR, "Start locator ResetAllProxy");
1839     AppIdentity identity;
1840     GetAppIdentityInfo(identity);
1841     if (!PermissionManager::CheckRssProcessName(identity.GetTokenId())) {
1842         return LOCATION_ERRCODE_PERMISSION_DENIED;
1843     }
1844     ProxyFreezeManager::GetInstance()->ResetAllProxy();
1845     if (GetActiveRequestNum() <= 0) {
1846         LBSLOGD(LOCATOR, "no active request, do not refresh.");
1847         return ERRCODE_SUCCESS;
1848     }
1849     // for proxy uid update, should send message to refresh requests
1850     ApplyRequests(0);
1851     return ERRCODE_SUCCESS;
1852 }
1853 
RegisterPermissionCallback(const uint32_t callingTokenId,const std::vector<std::string> & permissionNameList)1854 void LocatorAbility::RegisterPermissionCallback(const uint32_t callingTokenId,
1855     const std::vector<std::string>& permissionNameList)
1856 {
1857     std::unique_lock<ffrt::mutex> lock(permissionMapMutex_);
1858     if (permissionMap_ == nullptr) {
1859         LBSLOGE(LOCATOR, "permissionMap is null.");
1860         return;
1861     }
1862     PermStateChangeScope scopeInfo;
1863     scopeInfo.permList = permissionNameList;
1864     scopeInfo.tokenIDs = {callingTokenId};
1865     auto callbackPtr = std::make_shared<PermissionStatusChangeCb>(scopeInfo);
1866     permissionMap_->erase(callingTokenId);
1867     if (permissionMap_->size() <= MAX_PERMISSION_NUM) {
1868         permissionMap_->insert(std::make_pair(callingTokenId, callbackPtr));
1869     } else {
1870         LBSLOGE(LOCATOR, "RegisterPermissionCallback num max");
1871         return;
1872     }
1873     LBSLOGD(LOCATOR, "after Id:%{public}d register, permission callback size:%{public}s",
1874         callingTokenId, std::to_string(permissionMap_->size()).c_str());
1875     int32_t res = AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr);
1876     if (res != SUCCESS) {
1877         LBSLOGE(LOCATOR, "RegisterPermStateChangeCallback failed.");
1878     }
1879 }
1880 
UnregisterPermissionCallback(const uint32_t callingTokenId)1881 void LocatorAbility::UnregisterPermissionCallback(const uint32_t callingTokenId)
1882 {
1883     std::unique_lock<ffrt::mutex> lock(permissionMapMutex_);
1884     if (permissionMap_ == nullptr) {
1885         LBSLOGE(LOCATOR, "permissionMap is null.");
1886         return;
1887     }
1888     auto iter = permissionMap_->find(callingTokenId);
1889     if (iter != permissionMap_->end()) {
1890         auto callbackPtr = iter->second;
1891         int32_t res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr);
1892         if (res != SUCCESS) {
1893             LBSLOGE(LOCATOR, "UnRegisterPermStateChangeCallback failed.");
1894         }
1895     }
1896     permissionMap_->erase(callingTokenId);
1897     LBSLOGD(LOCATOR, "after Id:%{public}d unregister, permission callback size:%{public}s",
1898         callingTokenId, std::to_string(permissionMap_->size()).c_str());
1899 }
1900 
ReportDataToResSched(std::string state)1901 void LocatorAbility::ReportDataToResSched(std::string state)
1902 {
1903 #ifdef RES_SCHED_SUPPROT
1904     std::unordered_map<std::string, std::string> payload;
1905     payload["state"] = state;
1906     uint32_t type = ResourceSchedule::ResType::RES_TYPE_LOCATION_STATUS_CHANGE;
1907     int64_t value =  ResourceSchedule::ResType::LocationStatus::LOCATION_SWTICH_CHANGE;
1908     ResourceSchedule::ResSchedClient::GetInstance().ReportData(type, value, payload);
1909 #endif
1910 }
1911 
QuerySupportCoordinateSystemType(std::vector<CoordinateType> & coordinateTypes)1912 ErrCode LocatorAbility::QuerySupportCoordinateSystemType(std::vector<CoordinateType>& coordinateTypes)
1913 {
1914 #ifdef FEATURE_GNSS_SUPPORT
1915     MessageParcel dataToStub;
1916     MessageParcel replyToStub;
1917     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
1918         return ERRCODE_SERVICE_UNAVAILABLE;
1919     }
1920     auto errCode = SendGnssRequest(
1921         static_cast<int>(GnssInterfaceCode::GET_GEOFENCE_SUPPORT_COORDINATE_SYSTEM_TYPE),
1922         dataToStub, replyToStub);
1923     if (errCode == ERRCODE_SUCCESS) {
1924         int size = replyToStub.ReadInt32();
1925         size = size > COORDINATE_SYSTEM_TYPE_SIZE ? COORDINATE_SYSTEM_TYPE_SIZE : size;
1926         for (int i = 0; i < size; i++) {
1927             int coordinateSystemType = replyToStub.ReadInt32();
1928             coordinateTypes.push_back(static_cast<CoordinateType>(coordinateSystemType));
1929         }
1930     }
1931     return errCode;
1932 #else
1933     return ERRCODE_SERVICE_UNAVAILABLE;
1934 #endif
1935 }
1936 
SendNetworkLocation(const std::unique_ptr<Location> & location)1937 LocationErrCode LocatorAbility::SendNetworkLocation(const std::unique_ptr<Location>& location)
1938 {
1939 #ifdef FEATURE_GNSS_SUPPORT
1940     LBSLOGD(LOCATOR, "%{public}s: send network location", __func__);
1941     int64_t time = location->GetTimeStamp();
1942     int64_t timeSinceBoot = location->GetTimeSinceBoot();
1943     double acc = location->GetAccuracy();
1944     LBSLOGI(LOCATOR,
1945         "receive network location: [ time=%{public}s timeSinceBoot=%{public}s acc=%{public}f]",
1946         std::to_string(time).c_str(), std::to_string(timeSinceBoot).c_str(), acc);
1947     MessageParcel dataToStub;
1948     MessageParcel replyToStub;
1949     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
1950         return ERRCODE_SERVICE_UNAVAILABLE;
1951     }
1952     location->Marshalling(dataToStub);
1953     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::SEND_NETWORK_LOCATION), dataToStub, replyToStub);
1954 #else
1955     return ERRCODE_SERVICE_UNAVAILABLE;
1956 #endif
1957 }
1958 
SubscribeBluetoothScanResultChange(const sptr<IBluetoothScanResultCallback> & cb)1959 ErrCode LocatorAbility::SubscribeBluetoothScanResultChange(
1960     const sptr<IBluetoothScanResultCallback>& cb)
1961 {
1962     AppIdentity identity;
1963     GetAppIdentityInfo(identity);
1964     if (!CheckRequestAvailable(LocatorInterfaceCode::START_SCAN_BLUETOOTH_DEVICE, identity)) {
1965         return LOCATION_ERRCODE_PERMISSION_DENIED;
1966     }
1967     if (!CheckLocationSwitchState()) {
1968         return ERRCODE_SWITCH_OFF;
1969     }
1970     if (!PermissionManager::CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
1971         return LOCATION_ERRCODE_PERMISSION_DENIED;
1972     }
1973     if (cb == nullptr) {
1974         LBSLOGE(LOCATOR, "%{public}s.callback == nullptr", __func__);
1975         return ERRCODE_SERVICE_UNAVAILABLE;
1976     }
1977     std::unique_ptr<BluetoothScanResultCallbackMessage> callbackMessage =
1978         std::make_unique<BluetoothScanResultCallbackMessage>();
1979     callbackMessage->SetCallback(cb);
1980     callbackMessage->SetAppIdentity(identity);
1981     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1982         Get(EVENT_START_SCAN_BLUETOOTH_DEVICE, callbackMessage);
1983     if (locatorHandler_ != nullptr) {
1984         locatorHandler_->SendEvent(event);
1985     }
1986     return ERRCODE_SUCCESS;
1987 }
1988 
UnSubscribeBluetoothScanResultChange(const sptr<IBluetoothScanResultCallback> & cb)1989 ErrCode LocatorAbility::UnSubscribeBluetoothScanResultChange(
1990     const sptr<IBluetoothScanResultCallback>& cb)
1991 {
1992     AppIdentity identity;
1993     GetAppIdentityInfo(identity);
1994     if (!CheckRequestAvailable(LocatorInterfaceCode::STOP_SCAN_BLUETOOTH_DEVICE, identity)) {
1995         return LOCATION_ERRCODE_PERMISSION_DENIED;
1996     }
1997     if (!PermissionManager::CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
1998         return LOCATION_ERRCODE_PERMISSION_DENIED;
1999     }
2000     if (cb == nullptr) {
2001         LBSLOGE(LOCATOR, "%{public}s.callback == nullptr", __func__);
2002         return ERRCODE_SERVICE_UNAVAILABLE;
2003     }
2004     std::unique_ptr<BluetoothScanResultCallbackMessage> callbackMessage =
2005         std::make_unique<BluetoothScanResultCallbackMessage>();
2006     callbackMessage->SetCallback(cb);
2007     callbackMessage->SetAppIdentity(identity);
2008     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
2009         Get(EVENT_STOP_SCAN_BLUETOOTH_DEVICE, callbackMessage);
2010     if (locatorHandler_ != nullptr) {
2011         locatorHandler_->SendEvent(event);
2012     }
2013     return ERRCODE_SUCCESS;
2014 }
2015 
RegisterLocationError(const sptr<ILocatorCallback> & callback,AppIdentity & identity)2016 LocationErrCode LocatorAbility::RegisterLocationError(const sptr<ILocatorCallback>& callback, AppIdentity &identity)
2017 {
2018     std::unique_ptr<LocatorCallbackMessage> callbackMessage = std::make_unique<LocatorCallbackMessage>();
2019     callbackMessage->SetCallback(callback);
2020     callbackMessage->SetAppIdentity(identity);
2021     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
2022         Get(EVENT_REG_LOCATION_ERROR, callbackMessage);
2023     if (locatorHandler_ != nullptr) {
2024         locatorHandler_->SendEvent(event);
2025     }
2026     return ERRCODE_SUCCESS;
2027 }
2028 
UnregisterLocationError(const sptr<ILocatorCallback> & callback,AppIdentity & identity)2029 LocationErrCode LocatorAbility::UnregisterLocationError(const sptr<ILocatorCallback>& callback, AppIdentity &identity)
2030 {
2031     std::unique_ptr<LocatorCallbackMessage> callbackMessage = std::make_unique<LocatorCallbackMessage>();
2032     callbackMessage->SetCallback(callback);
2033     callbackMessage->SetAppIdentity(identity);
2034     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
2035         Get(EVENT_UNREG_LOCATION_ERROR, callbackMessage);
2036     if (locatorHandler_ != nullptr) {
2037         locatorHandler_->SendEvent(event);
2038     }
2039     return ERRCODE_SUCCESS;
2040 }
2041 
SetLocationSwitchIgnored(bool isEnabled)2042 ErrCode LocatorAbility::SetLocationSwitchIgnored(bool isEnabled)
2043 {
2044     LBSLOGI(LOCATOR, "SetLocationSwitchIgnored %{public}d", isEnabled);
2045     AppIdentity identity;
2046     GetAppIdentityInfo(identity);
2047     if (!CheckRequestAvailable(LocatorInterfaceCode::SET_LOCATION_SETTINGS_IGNORED, identity)) {
2048         return LOCATION_ERRCODE_PERMISSION_DENIED;
2049     }
2050     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
2051         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
2052         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
2053     }
2054     if (!PermissionManager::CheckLocationSwitchIgnoredPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
2055         LBSLOGE(LOCATOR, "CheckLocationSwitchIgnoredPermission return false, [%{public}s]",
2056             identity.ToString().c_str());
2057         return LOCATION_ERRCODE_PERMISSION_DENIED;
2058     }
2059     SetLocationSwitchIgnoredFlag(identity.GetTokenId(), isEnabled);
2060     return ERRCODE_SUCCESS;
2061 }
2062 
AddBeaconFence(const BeaconFenceRequest & request)2063 ErrCode LocatorAbility::AddBeaconFence(const BeaconFenceRequest& request)
2064 {
2065     AppIdentity identity;
2066     GetAppIdentityInfo(identity);
2067     if (!CheckRequestAvailable(LocatorInterfaceCode::ADD_BEACON_FENCE, identity)) {
2068         return LOCATION_ERRCODE_PERMISSION_DENIED;
2069     }
2070     if (!CheckLocationSwitchState()) {
2071         return ERRCODE_BEACONFENCE_LOCATION_SWITCH_OFF;
2072     }
2073     if (!CheckBluetoothSwitchState()) {
2074         return ERRCODE_BEACONFENCE_BLUETOOTH_SWITCH_OFF;
2075     }
2076     if (!PermissionManager::CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
2077         return LOCATION_ERRCODE_PERMISSION_DENIED;
2078     }
2079     std::shared_ptr<BeaconFenceRequest> beaconFenceRequest =
2080         std::make_shared<BeaconFenceRequest>(const_cast<BeaconFenceRequest&>(request));
2081     beaconFenceRequest->SetBundleName(identity.GetBundleName());
2082     ErrCode locationErrCode = BeaconFenceManager::GetInstance()->AddBeaconFence(beaconFenceRequest, identity);
2083     return locationErrCode;
2084 }
2085 
RemoveBeaconFence(const BeaconFence & beaconFence)2086 ErrCode LocatorAbility::RemoveBeaconFence(const BeaconFence& beaconFence)
2087 {
2088     AppIdentity identity;
2089     GetAppIdentityInfo(identity);
2090     if (!CheckRequestAvailable(LocatorInterfaceCode::REMOVE_BEACON_FENCE, identity)) {
2091         return LOCATION_ERRCODE_PERMISSION_DENIED;
2092     }
2093     if (!CheckLocationSwitchState()) {
2094         return ERRCODE_SWITCH_OFF;
2095     }
2096     if (!PermissionManager::CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
2097         return LOCATION_ERRCODE_PERMISSION_DENIED;
2098     }
2099     std::shared_ptr<BeaconFence> beacon =
2100         std::make_shared<BeaconFence>(const_cast<BeaconFence&>(beaconFence));
2101     ErrCode locationErrCode = BeaconFenceManager::GetInstance()->RemoveBeaconFence(beacon);
2102     return locationErrCode;
2103 }
2104 
ReportLocationError(int32_t errCodeNum,const std::string & errMsg,const std::string & uuid)2105 ErrCode LocatorAbility::ReportLocationError(int32_t errCodeNum, const std::string& errMsg, const std::string& uuid)
2106 {
2107     AppIdentity identity;
2108     GetAppIdentityInfo(identity);
2109     if (!CheckRequestAvailable(LocatorInterfaceCode::REPORT_LOCATION_ERROR, identity)) {
2110         return LOCATION_ERRCODE_PERMISSION_DENIED;
2111     }
2112     if (identity.GetUid() != static_cast<pid_t>(getuid()) || identity.GetPid() != getpid()) {
2113         LBSLOGE(LOCATOR, "check system permission failed, [%{public}s]", identity.ToString().c_str());
2114         return LOCATION_ERRCODE_PERMISSION_DENIED;
2115     }
2116     std::unique_ptr<LocatorErrorMessage> locatorErrorMessage = std::make_unique<LocatorErrorMessage>();
2117     locatorErrorMessage->SetUuid(uuid);
2118     locatorErrorMessage->SetErrCode(errCodeNum);
2119     locatorErrorMessage->SetErrMsg(errMsg);
2120     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
2121         Get(EVENT_REPORT_LOCATION_ERROR, locatorErrorMessage);
2122     if (locatorHandler_ != nullptr) {
2123         locatorHandler_->SendEvent(event);
2124     }
2125     return ERRCODE_SUCCESS;
2126 }
2127 
RemoveInvalidRequests()2128 LocationErrCode LocatorAbility::RemoveInvalidRequests()
2129 {
2130     std::list<std::shared_ptr<Request>> invalidRequestList;
2131     int32_t requestNum = 0;
2132     int32_t invalidRequestNum = 0;
2133     {
2134         std::unique_lock<ffrt::mutex> lock(requestsMutex_);
2135 #ifdef FEATURE_GNSS_SUPPORT
2136         auto gpsListIter = requests_->find(GNSS_ABILITY);
2137         if (gpsListIter != requests_->end()) {
2138             auto list = &(gpsListIter->second);
2139             requestNum += static_cast<int>(list->size());
2140             for (auto& item : *list) {
2141                 if (IsInvalidRequest(item)) {
2142                     invalidRequestList.push_back(item);
2143                     invalidRequestNum++;
2144                 }
2145             }
2146         }
2147 #endif
2148 #ifdef FEATURE_NETWORK_SUPPORT
2149         auto networkListIter = requests_->find(NETWORK_ABILITY);
2150         if (networkListIter != requests_->end()) {
2151             auto list = &(networkListIter->second);
2152             requestNum += static_cast<int>(list->size());
2153             for (auto& item : *list) {
2154                 if (IsInvalidRequest(item)) {
2155                     invalidRequestList.push_back(item);
2156                     invalidRequestNum++;
2157                 }
2158             }
2159         }
2160 #endif
2161     }
2162     LBSLOGI(LOCATOR, "request num : %{public}d, invalid request num: %{public}d", requestNum, invalidRequestNum);
2163     if (invalidRequestList.size() > INVALID_REQUESTS_SIZE) {
2164         return ERRCODE_SUCCESS;
2165     }
2166     for (auto& item : invalidRequestList) {
2167         sptr<ILocatorCallback> callback = item->GetLocatorCallBack();
2168         StopLocating(callback);
2169     }
2170     return ERRCODE_SUCCESS;
2171 }
2172 
IsInvalidRequest(std::shared_ptr<Request> & request)2173 bool LocatorAbility::IsInvalidRequest(std::shared_ptr<Request>& request)
2174 {
2175     LBSLOGI(LOCATOR, "request : %{public}s %{public}s", request->GetPackageName().c_str(),
2176         request->GetRequestConfig()->ToString().c_str());
2177     int64_t timeDiff = fabs(CommonUtils::GetCurrentTime() - request->GetRequestConfig()->GetTimeStamp());
2178     if (request->GetRequestConfig()->GetFixNumber() == 1 &&
2179         timeDiff > (request->GetRequestConfig()->GetTimeOut() / MILLI_PER_SEC)) {
2180         LBSLOGI(LOCATOR, "once request is timeout");
2181         return true;
2182     }
2183 
2184     if (timeDiff > REQUEST_DEFAULT_TIMEOUT_SECOUND && !IsProcessRunning(request->GetPid(), request->GetTokenId())) {
2185         LBSLOGI(LOCATOR, "request process is not running");
2186         return true;
2187     }
2188     return false;
2189 }
2190 
IsProcessRunning(pid_t pid,const uint32_t tokenId)2191 bool LocatorAbility::IsProcessRunning(pid_t pid, const uint32_t tokenId)
2192 {
2193     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
2194     if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
2195         return true;
2196     }
2197     sptr<ISystemAbilityManager> samgrClient = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2198     if (samgrClient == nullptr) {
2199         LBSLOGE(LOCATOR, "Get system ability manager failed.");
2200         return true;
2201     }
2202     sptr<AppExecFwk::IAppMgr> iAppManager =
2203         iface_cast<AppExecFwk::IAppMgr>(samgrClient->GetSystemAbility(APP_MGR_SERVICE_ID));
2204     if (iAppManager == nullptr) {
2205         LBSLOGE(LOCATOR, "Failed to get ability manager service.");
2206         return true;
2207     }
2208     std::vector<AppExecFwk::RunningProcessInfo> runningProcessList;
2209     int32_t res = iAppManager->GetAllRunningProcesses(runningProcessList);
2210     if (res != ERR_OK) {
2211         LBSLOGE(LOCATOR, "Failed to get all running process.");
2212         return true;
2213     }
2214     auto it = std::find_if(runningProcessList.begin(), runningProcessList.end(), [pid] (auto runningProcessInfo) {
2215         return pid == runningProcessInfo.pid_;
2216     });
2217     if (it != runningProcessList.end()) {
2218         LBSLOGD(LOCATOR, "process : %{public}d is found.", pid);
2219         return true;
2220     }
2221     return false;
2222 }
2223 
SyncStillMovementState(bool state)2224 void LocatorAbility::SyncStillMovementState(bool state)
2225 {
2226     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
2227         Get(EVENT_SYNC_STILL_MOVEMENT_STATE, state);
2228     if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
2229         LBSLOGD(LOCATOR, "%{public}s: EVENT_SYNC_MOVEMENT_STATE Send Success", __func__);
2230     }
2231 }
2232 
IsHapCaller(const uint32_t tokenId)2233 bool LocatorAbility::IsHapCaller(const uint32_t tokenId)
2234 {
2235     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
2236     if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) {
2237         return true;
2238     }
2239     return false;
2240 }
2241 
SyncIdleState(bool state)2242 void LocatorAbility::SyncIdleState(bool state)
2243 {
2244     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
2245         Get(EVENT_SYNC_IDLE_STATE, state);
2246     if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
2247         LBSLOGD(LOCATOR, "%{public}s: EVENT_SYNC_IDLE_STATE Send Success", __func__);
2248     }
2249 }
2250 
SetLocationSwitchIgnoredFlag(uint32_t tokenId,bool enable)2251 void LocatorAbility::SetLocationSwitchIgnoredFlag(uint32_t tokenId, bool enable)
2252 {
2253     std::unique_lock<std::mutex> lock(LocationSwitchIgnoredFlagMutex_);
2254     LBSLOGD(LOCATOR, "SetLocationSwitchIgnoredFlag enable = %{public}d", enable);
2255     AppSwitchIgnoredState appSwitchIgnoredState;
2256     appSwitchIgnoredState.state = enable;
2257     appSwitchIgnoredState.timeSinceBoot = CommonUtils::GetSinceBootTime();
2258     if (enable) {
2259         locationSettingsIgnoredFlagMap_[tokenId] = appSwitchIgnoredState;
2260         ApplyRequests(LOCATION_SWITCH_IGNORED_STATE_VALID_TIME / MILLI_PER_SEC);
2261     } else {
2262         auto iter = locationSettingsIgnoredFlagMap_.find(tokenId);
2263         if (iter != locationSettingsIgnoredFlagMap_.end()) {
2264             locationSettingsIgnoredFlagMap_.erase(iter);
2265             ApplyRequests(0);
2266         }
2267     }
2268 }
2269 
GetLocationSwitchIgnoredFlag(uint32_t tokenId)2270 bool LocatorAbility::GetLocationSwitchIgnoredFlag(uint32_t tokenId)
2271 {
2272     std::unique_lock<std::mutex> lock(LocationSwitchIgnoredFlagMutex_);
2273     auto iter = locationSettingsIgnoredFlagMap_.find(tokenId);
2274     if (iter == locationSettingsIgnoredFlagMap_.end()) {
2275         return false;
2276     }
2277     AppSwitchIgnoredState appSwitchIgnoredState = iter->second;
2278     if ((CommonUtils::GetSinceBootTime()- appSwitchIgnoredState.timeSinceBoot) / NANOS_PER_MICRO / MICRO_PER_MILLI >
2279         LOCATION_SWITCH_IGNORED_STATE_VALID_TIME) {
2280         locationSettingsIgnoredFlagMap_.erase(iter);
2281         return false;
2282     }
2283     LBSLOGD(LOCATOR, "GetLocationSwitchIgnoredFlag enable = %{public}d", appSwitchIgnoredState.state);
2284     return appSwitchIgnoredState.state;
2285 }
2286 
RegisterLocatingRequiredDataCallback(const LocatingRequiredDataConfig & dataConfig,const sptr<ILocatingRequiredDataCallback> & cb)2287 ErrCode LocatorAbility::RegisterLocatingRequiredDataCallback(const LocatingRequiredDataConfig& dataConfig,
2288     const sptr<ILocatingRequiredDataCallback>& cb)
2289 {
2290     AppIdentity identity;
2291     GetAppIdentityInfo(identity);
2292     if (!CheckRequestAvailable(LocatorInterfaceCode::REG_LOCATING_REQUIRED_DATA_CALLBACK, identity)) {
2293         return LOCATION_ERRCODE_PERMISSION_DENIED;
2294     }
2295     if (!CheckPreciseLocationPermissions(identity.GetTokenId(), identity.GetFirstTokenId())) {
2296         return LOCATION_ERRCODE_PERMISSION_DENIED;
2297     }
2298     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
2299         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
2300         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
2301     }
2302     if (cb == nullptr) {
2303         LBSLOGE(LOCATOR, "%{public}s: callback is nullptr.", __func__);
2304         return ERRCODE_SERVICE_UNAVAILABLE;
2305     }
2306     auto dataConfigShared =
2307         std::make_shared<LocatingRequiredDataConfig>(const_cast<LocatingRequiredDataConfig&>(dataConfig));
2308     auto locatorDataManager = LocatorRequiredDataManager::GetInstance();
2309     cb->AsObject()->AddDeathRecipient(scanRecipient_);
2310     return locatorDataManager->RegisterCallback(identity, dataConfigShared, cb->AsObject());
2311 }
2312 
UnRegisterLocatingRequiredDataCallback(const sptr<ILocatingRequiredDataCallback> & cb)2313 ErrCode LocatorAbility::UnRegisterLocatingRequiredDataCallback(const sptr<ILocatingRequiredDataCallback>& cb)
2314 {
2315     AppIdentity identity;
2316     GetAppIdentityInfo(identity);
2317     if (!CheckRequestAvailable(LocatorInterfaceCode::UNREG_LOCATING_REQUIRED_DATA_CALLBACK, identity)) {
2318         return LOCATION_ERRCODE_PERMISSION_DENIED;
2319     }
2320     if (!CheckPreciseLocationPermissions(identity.GetTokenId(), identity.GetFirstTokenId())) {
2321         return LOCATION_ERRCODE_PERMISSION_DENIED;
2322     }
2323     if (!PermissionManager::CheckSystemPermission(identity.GetTokenId(), identity.GetTokenIdEx())) {
2324         LBSLOGE(LOCATOR, "CheckSystemPermission return false, [%{public}s]", identity.ToString().c_str());
2325         return LOCATION_ERRCODE_SYSTEM_PERMISSION_DENIED;
2326     }
2327     if (cb == nullptr) {
2328         LBSLOGE(LOCATOR, "%{public}s: callback is nullptr.", __func__);
2329         return ERRCODE_SERVICE_UNAVAILABLE;
2330     }
2331     auto locatorDataManager = LocatorRequiredDataManager::GetInstance();
2332     cb->AsObject()->RemoveDeathRecipient(scanRecipient_);
2333     return locatorDataManager->UnregisterCallback(cb->AsObject());
2334 }
2335 
SubscribeLocationError(const sptr<ILocatorCallback> & cb)2336 ErrCode LocatorAbility::SubscribeLocationError(const sptr<ILocatorCallback>& cb)
2337 {
2338     AppIdentity identity;
2339     GetAppIdentityInfo(identity);
2340     if (!CheckRequestAvailable(LocatorInterfaceCode::REG_LOCATION_ERROR, identity)) {
2341         return LOCATION_ERRCODE_PERMISSION_DENIED;
2342     }
2343     if (!CheckLocationSwitchState()) {
2344         return ERRCODE_SWITCH_OFF;
2345     }
2346     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
2347         return LOCATION_ERRCODE_PERMISSION_DENIED;
2348     }
2349     if (cb == nullptr) {
2350         LBSLOGE(LOCATOR, "StartLocating remote object nullptr");
2351         return ERRCODE_SERVICE_UNAVAILABLE;
2352     }
2353     return RegisterLocationError(cb, identity);
2354 }
2355 
UnSubscribeLocationError(const sptr<ILocatorCallback> & cb)2356 ErrCode LocatorAbility::UnSubscribeLocationError(const sptr<ILocatorCallback>& cb)
2357 {
2358     AppIdentity identity;
2359     GetAppIdentityInfo(identity);
2360     if (!CheckRequestAvailable(LocatorInterfaceCode::UNREG_LOCATION_ERROR, identity)) {
2361         return LOCATION_ERRCODE_PERMISSION_DENIED;
2362     }
2363     if (!CheckLocationPermission(identity.GetTokenId(), identity.GetFirstTokenId())) {
2364         return LOCATION_ERRCODE_PERMISSION_DENIED;
2365     }
2366     if (cb == nullptr) {
2367         LBSLOGE(LOCATOR, "LocatorAbility::StopLocating remote object nullptr");
2368         return ERRCODE_SERVICE_UNAVAILABLE;
2369     }
2370     return UnregisterLocationError(cb, identity);
2371 }
2372 
GetCurrentWifiBssidForLocating(std::string & bssid)2373 ErrCode LocatorAbility::GetCurrentWifiBssidForLocating(std::string& bssid)
2374 {
2375     AppIdentity identity;
2376     GetAppIdentityInfo(identity);
2377     if (!CheckRequestAvailable(LocatorInterfaceCode::GET_CURRENT_WIFI_BSSID_FOR_LOCATING, identity)) {
2378         return LOCATION_ERRCODE_PERMISSION_DENIED;
2379     }
2380     if (!CheckLocationSwitchState()) {
2381         return ERRCODE_SWITCH_OFF;
2382     }
2383     if (!CheckPreciseLocationPermissions(identity.GetTokenId(), identity.GetFirstTokenId())) {
2384         return LOCATION_ERRCODE_PERMISSION_DENIED;
2385     }
2386     auto locatorDataManager = LocatorRequiredDataManager::GetInstance();
2387     return locatorDataManager->GetCurrentWifiBssidForLocating(bssid);
2388 }
2389 
IsPoiServiceSupported(bool & poiServiceSupportState)2390 ErrCode LocatorAbility::IsPoiServiceSupported(bool& poiServiceSupportState)
2391 {
2392     LBSLOGI(LOCATOR, "IsPoiServiceSupported enter");
2393     std::string serviceName;
2394     bool result = LocationConfigManager::GetInstance()->GetNlpServiceName(serviceName);
2395     if (!result || serviceName.empty()) {
2396         LBSLOGE(LOCATOR, "get service name failed!");
2397         poiServiceSupportState = false;
2398         return ERRCODE_SUCCESS;
2399     }
2400     if (!CommonUtils::CheckAppInstalled(serviceName)) { // app is not installed
2401         poiServiceSupportState = false;
2402     } else {
2403         poiServiceSupportState = true;
2404     }
2405     return ERRCODE_SUCCESS;
2406 }
2407 
SetSwitchState(bool isEnabled)2408 LocationErrCode LocatorAbility::SetSwitchState(bool isEnabled)
2409 {
2410     int modeValue = isEnabled ? ENABLED : DISABLED;
2411     int currentSwitchState = LocationDataRdbManager::QuerySwitchState();
2412     if (modeValue == currentSwitchState) {
2413         LBSLOGD(LOCATOR, "no need to set location ability, enable:%{public}d", modeValue);
2414         return ERRCODE_SUCCESS;
2415     }
2416     if (LocationDataRdbManager::SetSwitchStateToSysparaForCurrentUser(modeValue)) {
2417         int userId = 0;
2418         if (!CommonUtils::GetCurrentUserId(userId)) {
2419             userId = DEFAULT_USERID;
2420         }
2421         CommonEventHelper::PublishLocationModeChangeCommonEventAsUser(modeValue, userId);
2422     }
2423     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::Get(EVENT_SET_SWITCH_STATE_TO_DB, modeValue);
2424     if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
2425         LBSLOGD(LOCATOR, "%{public}s: EVENT_SET_SWITCH_STATE_TO_DB Send Success", __func__);
2426     }
2427     return ERRCODE_SUCCESS;
2428 }
2429 
SetSwitchStateForUser(bool isEnabled,int32_t userId)2430 LocationErrCode LocatorAbility::SetSwitchStateForUser(bool isEnabled, int32_t userId)
2431 {
2432     int modeValue = isEnabled ? ENABLED : DISABLED;
2433     std::unique_ptr<LocatorSwitchMessage> locatorSwitchMessage = std::make_unique<LocatorSwitchMessage>();
2434     locatorSwitchMessage->SetModeValue(modeValue);
2435     locatorSwitchMessage->SetUserId(userId);
2436     if (LocationDataRdbManager::SetSwitchStateToSysparaForUser(modeValue, userId)) {
2437         CommonEventHelper::PublishLocationModeChangeCommonEventAsUser(modeValue, userId);
2438     }
2439     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
2440         Get(EVENT_SET_SWITCH_STATE_TO_DB_BY_USERID, locatorSwitchMessage);
2441     if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
2442         LBSLOGD(LOCATOR, "%{public}s: EVENT_SET_SWITCH_STATE_TO_DB_BY_USERID Send Success", __func__);
2443     }
2444     return ERRCODE_SUCCESS;
2445 }
2446 
CheckLocationSwitchState()2447 bool LocatorAbility::CheckLocationSwitchState()
2448 {
2449     int state = DISABLED;
2450     ErrCode errorCode = GetSwitchState(state);
2451     if (errorCode != ERRCODE_SUCCESS) {
2452         LBSLOGE(LOCATOR, "GetSwitchState failed errCode = %{public}d.", errorCode);
2453     }
2454     if (state != ENABLED) {
2455         LBSLOGE(LOCATOR, "switch state is off.");
2456         return false;
2457     }
2458     return true;
2459 }
2460 
CheckBluetoothSwitchState()2461 bool LocatorAbility::CheckBluetoothSwitchState()
2462 {
2463     Bluetooth::BluetoothState state = Bluetooth::BluetoothHost::GetDefaultHost().GetBluetoothState();
2464     if (state != Bluetooth::BluetoothState::STATE_ON) {
2465         return false;
2466     }
2467     return true;
2468 }
2469 
CheckLocationPermission(uint32_t callingTokenId,uint32_t callingFirstTokenid)2470 bool LocatorAbility::CheckLocationPermission(uint32_t callingTokenId, uint32_t callingFirstTokenid)
2471 {
2472     if (!PermissionManager::CheckLocationPermission(callingTokenId, callingFirstTokenid) &&
2473         !PermissionManager::CheckApproximatelyPermission(callingTokenId, callingFirstTokenid)) {
2474         LBSLOGE(LOCATOR, "%{public}d %{public}s failed", callingTokenId, __func__);
2475         return false;
2476     } else {
2477         return true;
2478     }
2479 }
2480 
CheckPreciseLocationPermissions(uint32_t callingTokenId,uint32_t callingFirstTokenid)2481 bool LocatorAbility::CheckPreciseLocationPermissions(uint32_t callingTokenId, uint32_t callingFirstTokenid)
2482 {
2483     if (!PermissionManager::CheckLocationPermission(callingTokenId, callingFirstTokenid) ||
2484         !PermissionManager::CheckApproximatelyPermission(callingTokenId, callingFirstTokenid)) {
2485         LBSLOGE(LOCATOR, "%{public}d %{public}s failed", callingTokenId, __func__);
2486         return false;
2487     } else {
2488         return true;
2489     }
2490 }
2491 
StartLocatingProcess(const RequestConfig & requestConfig,const sptr<ILocatorCallback> & cb,AppIdentity & identity)2492 ErrCode LocatorAbility::StartLocatingProcess(const RequestConfig& requestConfig,
2493     const sptr<ILocatorCallback>& cb, AppIdentity& identity)
2494 {
2495     if (cb == nullptr) {
2496         LBSLOGE(LOCATOR, "StartLocating remote object nullptr");
2497         return ERRCODE_SERVICE_UNAVAILABLE;
2498     }
2499 #if !defined(FEATURE_GNSS_SUPPORT) && !defined(FEATURE_NETWORK_SUPPORT) && !defined(FEATURE_PASSIVE_SUPPORT)
2500     LBSLOGE(LOCATOR, "%{public}s: service unavailable", __func__);
2501     return LOCATION_ERRCODE_NOT_SUPPORTED;
2502 #endif
2503     if (LocationDataRdbManager::QuerySwitchState() != ENABLED && !GetLocationSwitchIgnoredFlag(identity.GetTokenId())) {
2504         ReportErrorStatus(cb, ERROR_SWITCH_UNOPEN);
2505     }
2506     // update offset before add request
2507     if (reportManager_ == nullptr || requestManager_ == nullptr) {
2508         return ERRCODE_SERVICE_UNAVAILABLE;
2509     }
2510     reportManager_->UpdateRandom();
2511     std::unique_ptr<RequestConfig> requestConfigUnique = std::make_unique<RequestConfig>(requestConfig);
2512     std::shared_ptr<Request> request = std::make_shared<Request>(requestConfigUnique, cb, identity);
2513     sptr<IRemoteObject::DeathRecipient> death(new (std::nothrow) LocatorCallbackDeathRecipient(identity.GetTokenId()));
2514     cb->AsObject()->AddDeathRecipient(death);
2515     request->SetLocatorCallbackRecipient(death);
2516     OHOS::Security::AccessToken::PermUsedTypeEnum type =
2517         Security::AccessToken::AccessTokenKit::GetPermissionUsedType(request->GetTokenId(),
2518         ACCESS_APPROXIMATELY_LOCATION);
2519     request->SetPermUsedType(static_cast<int>(type));
2520     if (requestConfigUnique->GetScenario() != SCENE_NO_POWER &&
2521         requestConfigUnique->GetScenario() != LOCATION_SCENE_NO_POWER_CONSUMPTION &&
2522         !reportManager_->IsCacheGnssLocationValid()) {
2523         LocatorRequiredDataManager::GetInstance()->SendWifiScanEvent();
2524     }
2525 #ifdef EMULATOR_ENABLED
2526     // for emulator, report cache location is unnecessary
2527     HandleStartLocating(request, cb);
2528 #else
2529     if (NeedReportCacheLocation(request, cb)) {
2530         LBSLOGI(LOCATOR, "report cache location to %{public}s", identity.GetBundleName().c_str());
2531         if (requestConfigUnique->GetScenario() != SCENE_NO_POWER &&
2532             requestConfigUnique->GetScenario() != LOCATION_SCENE_NO_POWER_CONSUMPTION) {
2533             SelfRequestManager::GetInstance()->StartSelfRequest(request);
2534         }
2535         cb->AsObject()->RemoveDeathRecipient(death);
2536     } else {
2537         HandleStartLocating(request, cb);
2538     }
2539 #endif
2540     return ERRCODE_SUCCESS;
2541 }
2542 
GetAppIdentityInfo(AppIdentity & identity)2543 void LocatorAbility::GetAppIdentityInfo(AppIdentity& identity)
2544 {
2545     identity.SetPid(IPCSkeleton::GetCallingPid());
2546     identity.SetUid(IPCSkeleton::GetCallingUid());
2547     identity.SetTokenId(IPCSkeleton::GetCallingTokenID());
2548     identity.SetTokenIdEx(IPCSkeleton::GetCallingFullTokenID());
2549     identity.SetFirstTokenId(IPCSkeleton::GetFirstTokenID());
2550     if (identity.GetUid() == static_cast<pid_t>(identity.GetFirstTokenId()) &&
2551         identity.GetUid() == static_cast<pid_t>(getuid()) && identity.GetPid() == getpid()) {
2552         identity.SetFirstTokenId(0);
2553     }
2554     std::string bundleName = "";
2555     if (!CommonUtils::GetBundleNameByUid(identity.GetUid(), bundleName)) {
2556         LBSLOGD(LOCATOR, "Fail to Get bundle name: uid = %{public}d.", identity.GetUid());
2557     }
2558     identity.SetBundleName(bundleName);
2559 }
2560 
SetAbilityName(std::string abilityName)2561 void LocationMessage::SetAbilityName(std::string abilityName)
2562 {
2563     abilityName_ = abilityName;
2564 }
2565 
GetAbilityName()2566 std::string LocationMessage::GetAbilityName()
2567 {
2568     return abilityName_;
2569 }
2570 
SetLocation(const std::unique_ptr<Location> & location)2571 void LocationMessage::SetLocation(const std::unique_ptr<Location>& location)
2572 {
2573     if (location != nullptr) {
2574         location_ = std::make_unique<Location>(*location);
2575     }
2576 }
2577 
GetLocation()2578 std::unique_ptr<Location> LocationMessage::GetLocation()
2579 {
2580     if (location_ != nullptr) {
2581         return std::make_unique<Location>(*location_);
2582     } else {
2583         return nullptr;
2584     }
2585 }
2586 
SetCallback(const sptr<ILocatorCallback> & callback)2587 void LocatorCallbackMessage::SetCallback(const sptr<ILocatorCallback>& callback)
2588 {
2589     callback_ = callback;
2590 }
2591 
GetCallback()2592 sptr<ILocatorCallback> LocatorCallbackMessage::GetCallback()
2593 {
2594     return callback_;
2595 }
2596 
SetAppIdentity(AppIdentity & appIdentity)2597 void LocatorCallbackMessage::SetAppIdentity(AppIdentity& appIdentity)
2598 {
2599     appIdentity_ = appIdentity;
2600 }
2601 
GetAppIdentity()2602 AppIdentity LocatorCallbackMessage::GetAppIdentity()
2603 {
2604     return appIdentity_;
2605 }
2606 
SetCallback(const sptr<IBluetoothScanResultCallback> & callback)2607 void BluetoothScanResultCallbackMessage::SetCallback(const sptr<IBluetoothScanResultCallback>& callback)
2608 {
2609     callback_ = callback;
2610 }
2611 
GetCallback()2612 sptr<IBluetoothScanResultCallback> BluetoothScanResultCallbackMessage::GetCallback()
2613 {
2614     return callback_;
2615 }
2616 
SetAppIdentity(AppIdentity & appIdentity)2617 void BluetoothScanResultCallbackMessage::SetAppIdentity(AppIdentity& appIdentity)
2618 {
2619     appIdentity_ = appIdentity;
2620 }
2621 
GetAppIdentity()2622 AppIdentity BluetoothScanResultCallbackMessage::GetAppIdentity()
2623 {
2624     return appIdentity_;
2625 }
2626 
SetUuid(std::string uuid)2627 void LocatorErrorMessage::SetUuid(std::string uuid)
2628 {
2629     uuid_ = uuid;
2630 }
2631 
GetUuid()2632 std::string LocatorErrorMessage::GetUuid()
2633 {
2634     return uuid_;
2635 }
2636 
SetErrCode(int32_t errCode)2637 void LocatorErrorMessage::SetErrCode(int32_t errCode)
2638 {
2639     errCode_ = errCode;
2640 }
2641 
GetErrCode()2642 int32_t LocatorErrorMessage::GetErrCode()
2643 {
2644     return errCode_;
2645 }
2646 
SetNetErrCode(int32_t netErrCode)2647 void LocatorErrorMessage::SetNetErrCode(int32_t netErrCode)
2648 {
2649     netErrCode_ = netErrCode;
2650 }
2651 
GetNetErrCode()2652 int32_t LocatorErrorMessage::GetNetErrCode()
2653 {
2654     return netErrCode_;
2655 }
2656 
SetErrMsg(std::string errMsg)2657 void LocatorErrorMessage::SetErrMsg(std::string errMsg)
2658 {
2659     errMsg_ = errMsg;
2660 }
2661 
GetErrMsg()2662 std::string LocatorErrorMessage::GetErrMsg()
2663 {
2664     return errMsg_;
2665 }
2666 
SetUserId(int32_t userId)2667 void LocatorSwitchMessage::SetUserId(int32_t userId)
2668 {
2669     userId_ = userId;
2670 }
2671 
GetUserId()2672 int32_t LocatorSwitchMessage::GetUserId()
2673 {
2674     return userId_;
2675 }
2676 
SetModeValue(int32_t modeValue)2677 void LocatorSwitchMessage::SetModeValue(int32_t modeValue)
2678 {
2679     modeValue_ = modeValue;
2680 }
2681 
GetModeValue()2682 int32_t LocatorSwitchMessage::GetModeValue()
2683 {
2684     return modeValue_;
2685 }
2686 
LocatorHandler(const std::shared_ptr<AppExecFwk::EventRunner> & runner)2687 LocatorHandler::LocatorHandler(const std::shared_ptr<AppExecFwk::EventRunner>& runner) : EventHandler(runner)
2688 {
2689     InitLocatorHandlerEventMap();
2690 }
2691 
~LocatorHandler()2692 LocatorHandler::~LocatorHandler() {}
2693 
InitLocatorHandlerEventMap()2694 void LocatorHandler::InitLocatorHandlerEventMap()
2695 {
2696     if (locatorHandlerEventMap_.size() != 0) {
2697         return;
2698     }
2699     locatorHandlerEventMap_[EVENT_UPDATE_SA] =
2700         [this](const AppExecFwk::InnerEvent::Pointer& event) { UpdateSaEvent(event); };
2701     locatorHandlerEventMap_[EVENT_INIT_REQUEST_MANAGER] =
2702         [this](const AppExecFwk::InnerEvent::Pointer& event) { InitRequestManagerEvent(event); };
2703     locatorHandlerEventMap_[EVENT_APPLY_REQUIREMENTS] =
2704         [this](const AppExecFwk::InnerEvent::Pointer& event) { ApplyRequirementsEvent(event); };
2705     locatorHandlerEventMap_[EVENT_RETRY_REGISTER_ACTION] =
2706         [this](const AppExecFwk::InnerEvent::Pointer& event) { RetryRegisterActionEvent(event); };
2707     locatorHandlerEventMap_[EVENT_REPORT_LOCATION_MESSAGE] =
2708         [this](const AppExecFwk::InnerEvent::Pointer& event) { ReportLocationMessageEvent(event); };
2709     locatorHandlerEventMap_[EVENT_SEND_SWITCHSTATE_TO_HIFENCE] =
2710         [this](const AppExecFwk::InnerEvent::Pointer& event) { SendSwitchStateToHifenceEvent(event); };
2711     locatorHandlerEventMap_[EVENT_START_LOCATING] =
2712         [this](const AppExecFwk::InnerEvent::Pointer& event) { StartLocatingEvent(event); };
2713     locatorHandlerEventMap_[EVENT_STOP_LOCATING] =
2714         [this](const AppExecFwk::InnerEvent::Pointer& event) { StopLocatingEvent(event); };
2715     locatorHandlerEventMap_[EVENT_UNLOAD_SA] =
2716         [this](const AppExecFwk::InnerEvent::Pointer& event) { UnloadSaEvent(event); };
2717     locatorHandlerEventMap_[EVENT_GET_CACHED_LOCATION_SUCCESS] =
2718         [this](const AppExecFwk::InnerEvent::Pointer& event) { GetCachedLocationSuccess(event); };
2719     locatorHandlerEventMap_[EVENT_GET_CACHED_LOCATION_FAILED] =
2720         [this](const AppExecFwk::InnerEvent::Pointer& event) { GetCachedLocationFailed(event); };
2721     locatorHandlerEventMap_[EVENT_REG_LOCATION_ERROR] =
2722         [this](const AppExecFwk::InnerEvent::Pointer& event) { RegLocationErrorEvent(event); };
2723     locatorHandlerEventMap_[EVENT_UNREG_LOCATION_ERROR] =
2724         [this](const AppExecFwk::InnerEvent::Pointer& event) { UnRegLocationErrorEvent(event); };
2725     locatorHandlerEventMap_[EVENT_REPORT_LOCATION_ERROR] =
2726         [this](const AppExecFwk::InnerEvent::Pointer& event) { ReportNetworkLocatingErrorEvent(event); };
2727     locatorHandlerEventMap_[EVENT_PERIODIC_CHECK] =
2728         [this](const AppExecFwk::InnerEvent::Pointer& event) { RequestCheckEvent(event); };
2729     locatorHandlerEventMap_[EVENT_SYNC_LOCATION_STATUS] =
2730         [this](const AppExecFwk::InnerEvent::Pointer& event) { SyncSwitchStatus(event); };
2731     locatorHandlerEventMap_[EVENT_SYNC_STILL_MOVEMENT_STATE] =
2732         [this](const AppExecFwk::InnerEvent::Pointer& event) { SyncStillMovementState(event); };
2733     locatorHandlerEventMap_[EVENT_SYNC_IDLE_STATE] =
2734         [this](const AppExecFwk::InnerEvent::Pointer& event) { SyncIdleState(event); };
2735     locatorHandlerEventMap_[EVENT_INIT_MSDP_MONITOR_MANAGER] =
2736         [this](const AppExecFwk::InnerEvent::Pointer& event) { InitMonitorManagerEvent(event); };
2737     locatorHandlerEventMap_[EVENT_IS_STAND_BY] =
2738         [this](const AppExecFwk::InnerEvent::Pointer& event) { IsStandByEvent(event); };
2739     ConstructDbHandleMap();
2740     ConstructGeocodeHandleMap();
2741     ConstructBluetoothScanHandleMap();
2742 }
2743 
ConstructGeocodeHandleMap()2744 void LocatorHandler::ConstructGeocodeHandleMap()
2745 {
2746     locatorHandlerEventMap_[EVENT_SEND_GEOREQUEST] =
2747         [this](const AppExecFwk::InnerEvent::Pointer& event) { SendGeoRequestEvent(event); };
2748 }
2749 
ConstructDbHandleMap()2750 void LocatorHandler::ConstructDbHandleMap()
2751 {
2752     locatorHandlerEventMap_[EVENT_SET_LOCATION_WORKING_STATE] =
2753         [this](const AppExecFwk::InnerEvent::Pointer& event) { SetLocationWorkingStateEvent(event); };
2754     locatorHandlerEventMap_[EVENT_SET_SWITCH_STATE_TO_DB] =
2755         [this](const AppExecFwk::InnerEvent::Pointer& event) { SetSwitchStateToDbEvent(event); };
2756     locatorHandlerEventMap_[EVENT_SET_SWITCH_STATE_TO_DB_BY_USERID] =
2757         [this](const AppExecFwk::InnerEvent::Pointer& event) { SetSwitchStateToDbForUserEvent(event); };
2758     locatorHandlerEventMap_[EVENT_WATCH_SWITCH_PARAMETER] =
2759         [this](const AppExecFwk::InnerEvent::Pointer& event) { WatchSwitchParameter(event); };
2760 }
2761 
ConstructBluetoothScanHandleMap()2762 void LocatorHandler::ConstructBluetoothScanHandleMap()
2763 {
2764     locatorHandlerEventMap_[EVENT_START_SCAN_BLUETOOTH_DEVICE] =
2765         [this](const AppExecFwk::InnerEvent::Pointer& event) { StartScanBluetoothDeviceEvent(event); };
2766     locatorHandlerEventMap_[EVENT_STOP_SCAN_BLUETOOTH_DEVICE] =
2767         [this](const AppExecFwk::InnerEvent::Pointer& event) { StopScanBluetoothDeviceEvent(event); };
2768 }
2769 
GetCachedLocationSuccess(const AppExecFwk::InnerEvent::Pointer & event)2770 void LocatorHandler::GetCachedLocationSuccess(const AppExecFwk::InnerEvent::Pointer& event)
2771 {
2772     std::shared_ptr<AppIdentity> identity = event->GetSharedObject<AppIdentity>();
2773     if (identity == nullptr) {
2774         LBSLOGE(LOCATOR, "%{public}s get identity failed", __func__);
2775         return;
2776     }
2777     int64_t tokenId = identity->GetTokenId();
2778     OHOS::Security::AccessToken::PermUsedTypeEnum type =
2779         Security::AccessToken::AccessTokenKit::GetPermissionUsedType(tokenId, ACCESS_APPROXIMATELY_LOCATION);
2780     auto locatorAbility = LocatorAbility::GetInstance();
2781     int ret;
2782     if (locatorAbility != nullptr) {
2783         ret = locatorAbility->UpdatePermissionUsedRecord(tokenId, ACCESS_APPROXIMATELY_LOCATION,
2784             static_cast<int>(type), 1, 0);
2785         LBSLOGD(LOCATOR, "UpdatePermissionUsedRecord, ret=%{public}d", ret);
2786     }
2787     auto requestManager = RequestManager::GetInstance();
2788     requestManager->DecreaseWorkingPidsCount(identity->GetPid());
2789     if (requestManager->IsNeedStopUsingPermission(identity->GetPid())) {
2790         ret = PrivacyKit::StopUsingPermission(tokenId, ACCESS_APPROXIMATELY_LOCATION, identity->GetPid());
2791         LBSLOGD(LOCATOR, "StopUsingPermission, ret=%{public}d", ret);
2792     }
2793 }
2794 
GetCachedLocationFailed(const AppExecFwk::InnerEvent::Pointer & event)2795 void LocatorHandler::GetCachedLocationFailed(const AppExecFwk::InnerEvent::Pointer& event)
2796 {
2797     std::shared_ptr<AppIdentity> identity = event->GetSharedObject<AppIdentity>();
2798     if (identity == nullptr) {
2799         LBSLOGE(LOCATOR, "%{public}s get identity failed", __func__);
2800         return;
2801     }
2802     int64_t tokenId = identity->GetTokenId();
2803     OHOS::Security::AccessToken::PermUsedTypeEnum type =
2804         Security::AccessToken::AccessTokenKit::GetPermissionUsedType(tokenId, ACCESS_APPROXIMATELY_LOCATION);
2805     auto locatorAbility = LocatorAbility::GetInstance();
2806     int ret;
2807     if (locatorAbility != nullptr) {
2808         ret = locatorAbility->UpdatePermissionUsedRecord(tokenId, ACCESS_APPROXIMATELY_LOCATION,
2809             static_cast<int>(type), 0, 1);
2810         LBSLOGD(LOCATOR, "UpdatePermissionUsedRecord, ret=%{public}d", ret);
2811     }
2812     auto requestManager = RequestManager::GetInstance();
2813     requestManager->DecreaseWorkingPidsCount(identity->GetPid());
2814     if (requestManager->IsNeedStopUsingPermission(identity->GetPid())) {
2815         ret = PrivacyKit::StopUsingPermission(tokenId, ACCESS_APPROXIMATELY_LOCATION, identity->GetPid());
2816         LBSLOGD(LOCATOR, "StopUsingPermission, ret=%{public}d", ret);
2817     }
2818 }
2819 
UpdateSaEvent(const AppExecFwk::InnerEvent::Pointer & event)2820 void LocatorHandler::UpdateSaEvent(const AppExecFwk::InnerEvent::Pointer& event)
2821 {
2822     auto locatorAbility = LocatorAbility::GetInstance();
2823     if (locatorAbility != nullptr) {
2824         locatorAbility->UpdateSaAbilityHandler();
2825     }
2826 }
2827 
InitRequestManagerEvent(const AppExecFwk::InnerEvent::Pointer & event)2828 void LocatorHandler::InitRequestManagerEvent(const AppExecFwk::InnerEvent::Pointer& event)
2829 {
2830     auto requestManager = RequestManager::GetInstance();
2831     if (!requestManager->InitSystemListeners()) {
2832         LBSLOGE(LOCATOR, "InitSystemListeners failed");
2833     }
2834 }
2835 
ApplyRequirementsEvent(const AppExecFwk::InnerEvent::Pointer & event)2836 void LocatorHandler::ApplyRequirementsEvent(const AppExecFwk::InnerEvent::Pointer& event)
2837 {
2838     auto requestManager = RequestManager::GetInstance();
2839     if (requestManager != nullptr) {
2840         requestManager->HandleRequest();
2841     }
2842 }
2843 
RetryRegisterActionEvent(const AppExecFwk::InnerEvent::Pointer & event)2844 void LocatorHandler::RetryRegisterActionEvent(const AppExecFwk::InnerEvent::Pointer& event)
2845 {
2846     auto locatorAbility = LocatorAbility::GetInstance();
2847     if (locatorAbility != nullptr) {
2848         locatorAbility->RegisterAction();
2849         locatorAbility->RegisterLocationPrivacyAction();
2850     }
2851 }
2852 
ReportLocationMessageEvent(const AppExecFwk::InnerEvent::Pointer & event)2853 void LocatorHandler::ReportLocationMessageEvent(const AppExecFwk::InnerEvent::Pointer& event)
2854 {
2855     auto reportManager = ReportManager::GetInstance();
2856     if (reportManager != nullptr) {
2857         std::unique_ptr<LocationMessage> locationMessage = event->GetUniqueObject<LocationMessage>();
2858         if (locationMessage == nullptr) {
2859             return;
2860         }
2861         std::unique_ptr<Location> location = locationMessage->GetLocation();
2862         std::string abilityName = locationMessage->GetAbilityName();
2863         int64_t time = location->GetTimeStamp();
2864         int64_t timeSinceBoot = location->GetTimeSinceBoot();
2865         double acc = location->GetAccuracy();
2866         LBSLOGW(LOCATOR,
2867             "receive location: [%{public}s time=%{public}s timeSinceBoot=%{public}s acc=%{public}f]",
2868             abilityName.c_str(), std::to_string(time).c_str(), std::to_string(timeSinceBoot).c_str(), acc);
2869         reportManager->OnReportLocation(location, abilityName);
2870         if (abilityName == NETWORK_ABILITY || abilityName == GNSS_ABILITY) {
2871             reportManager->OnReportLocation(location, PASSIVE_ABILITY);
2872         }
2873     }
2874 }
2875 
SendSwitchStateToHifenceEvent(const AppExecFwk::InnerEvent::Pointer & event)2876 void LocatorHandler::SendSwitchStateToHifenceEvent(const AppExecFwk::InnerEvent::Pointer& event)
2877 {
2878     auto locatorAbility = LocatorAbility::GetInstance();
2879     if (locatorAbility != nullptr) {
2880         int state = event->GetParam();
2881         if (!SaLoadWithStatistic::InitLocationSa(COMMON_SA_ID)) {
2882             return;
2883         }
2884         MessageParcel data;
2885         MessageParcel reply;
2886         MessageOption option;
2887         if (!data.WriteInterfaceToken(COMMON_DESCRIPTION)) {
2888             return;
2889         }
2890         data.WriteInt32(state);
2891         sptr<IRemoteObject> object =
2892                 CommonUtils::GetRemoteObject(COMMON_SA_ID, CommonUtils::InitDeviceId());
2893         if (object == nullptr) {
2894             return;
2895         }
2896         std::string callingIdentity = IPCSkeleton::ResetCallingIdentity();
2897         object->SendRequest(COMMON_SWITCH_STATE_ID, data, reply, option);
2898         IPCSkeleton::SetCallingIdentity(callingIdentity);
2899     }
2900 }
2901 
StartLocatingEvent(const AppExecFwk::InnerEvent::Pointer & event)2902 void LocatorHandler::StartLocatingEvent(const AppExecFwk::InnerEvent::Pointer& event)
2903 {
2904     auto requestManager = RequestManager::GetInstance();
2905     std::shared_ptr<Request> request = event->GetSharedObject<Request>();
2906     if (request == nullptr) {
2907         return;
2908     }
2909     if (requestManager != nullptr) {
2910         HookUtils::ExecuteHookWhenStartLocation(request);
2911         requestManager->HandleStartLocating(request);
2912     }
2913 }
2914 
StopLocatingEvent(const AppExecFwk::InnerEvent::Pointer & event)2915 void LocatorHandler::StopLocatingEvent(const AppExecFwk::InnerEvent::Pointer& event)
2916 {
2917     auto requestManager = RequestManager::GetInstance();
2918     std::unique_ptr<LocatorCallbackMessage> callbackMessage = event->GetUniqueObject<LocatorCallbackMessage>();
2919     if (callbackMessage == nullptr) {
2920         return;
2921     }
2922     if (requestManager != nullptr) {
2923         requestManager->HandleStopLocating(callbackMessage->GetCallback());
2924     }
2925 }
2926 
UnloadSaEvent(const AppExecFwk::InnerEvent::Pointer & event)2927 void LocatorHandler::UnloadSaEvent(const AppExecFwk::InnerEvent::Pointer& event)
2928 {
2929     auto locationSaLoadManager = LocationSaLoadManager::GetInstance();
2930     if (locationSaLoadManager != nullptr) {
2931         locationSaLoadManager->UnloadLocationSa(LOCATION_LOCATOR_SA_ID);
2932     }
2933 }
2934 
StartScanBluetoothDeviceEvent(const AppExecFwk::InnerEvent::Pointer & event)2935 void LocatorHandler::StartScanBluetoothDeviceEvent(const AppExecFwk::InnerEvent::Pointer& event)
2936 {
2937     std::unique_ptr<BluetoothScanResultCallbackMessage> callbackMessage =
2938         event->GetUniqueObject<BluetoothScanResultCallbackMessage>();
2939     if (callbackMessage == nullptr) {
2940         return;
2941     }
2942     LocatorRequiredDataManager::GetInstance()->StartScanBluetoothDevice(
2943         callbackMessage->GetCallback(), callbackMessage->GetAppIdentity());
2944 }
2945 
StopScanBluetoothDeviceEvent(const AppExecFwk::InnerEvent::Pointer & event)2946 void LocatorHandler::StopScanBluetoothDeviceEvent(const AppExecFwk::InnerEvent::Pointer& event)
2947 {
2948     std::unique_ptr<BluetoothScanResultCallbackMessage> callbackMessage =
2949         event->GetUniqueObject<BluetoothScanResultCallbackMessage>();
2950     if (callbackMessage == nullptr) {
2951         return;
2952     }
2953     LocatorRequiredDataManager::GetInstance()->StopScanBluetoothDevice(callbackMessage->GetCallback()->AsObject());
2954 }
2955 
RegLocationErrorEvent(const AppExecFwk::InnerEvent::Pointer & event)2956 void LocatorHandler::RegLocationErrorEvent(const AppExecFwk::InnerEvent::Pointer& event)
2957 {
2958     auto requestManager = RequestManager::GetInstance();
2959     std::unique_ptr<LocatorCallbackMessage> callbackMessage = event->GetUniqueObject<LocatorCallbackMessage>();
2960     if (callbackMessage == nullptr) {
2961         return;
2962     }
2963     if (requestManager != nullptr) {
2964         requestManager->RegisterLocationErrorCallback(callbackMessage->GetCallback(),
2965             callbackMessage->GetAppIdentity());
2966     }
2967 }
2968 
UnRegLocationErrorEvent(const AppExecFwk::InnerEvent::Pointer & event)2969 void LocatorHandler::UnRegLocationErrorEvent(const AppExecFwk::InnerEvent::Pointer& event)
2970 {
2971     auto requestManager = RequestManager::GetInstance();
2972     std::unique_ptr<LocatorCallbackMessage> callbackMessage = event->GetUniqueObject<LocatorCallbackMessage>();
2973     if (callbackMessage == nullptr) {
2974         return;
2975     }
2976     if (requestManager != nullptr) {
2977         requestManager->UnRegisterLocationErrorCallback(callbackMessage->GetCallback());
2978     }
2979 }
2980 
ReportNetworkLocatingErrorEvent(const AppExecFwk::InnerEvent::Pointer & event)2981 void LocatorHandler::ReportNetworkLocatingErrorEvent(const AppExecFwk::InnerEvent::Pointer& event)
2982 {
2983     std::unique_ptr<LocatorErrorMessage> locatorErrorMessage = event->GetUniqueObject<LocatorErrorMessage>();
2984     if (locatorErrorMessage == nullptr) {
2985         return;
2986     }
2987     auto uuid = locatorErrorMessage->GetUuid();
2988     auto errCode = locatorErrorMessage->GetErrCode();
2989     auto errMsg = locatorErrorMessage->GetErrMsg();
2990     auto requestMap = LocatorAbility::GetInstance()->GetRequests();
2991     if (requestMap == nullptr || requestMap->empty()) {
2992         LBSLOGE(REQUEST_MANAGER, "requests map is empty");
2993         return;
2994     }
2995     auto requestListIter = requestMap->find(NETWORK_ABILITY);
2996     if (requestListIter == requestMap->end()) {
2997         return;
2998     }
2999     auto requestList = requestListIter->second;
3000     for (auto iter = requestList.begin(); iter != requestList.end(); iter++) {
3001         auto request = *iter;
3002         if (uuid.compare(request->GetUuid()) == 0) {
3003             std::string requestInfo = "";
3004             if (request->GetRequestConfig() != nullptr) {
3005                 requestInfo = request->GetRequestConfig()->ToString();
3006             }
3007             RequestManager::GetInstance()->ReportLocationError(errCode, request);
3008             WriteLocationInnerEvent(LBS_REQUEST_FAIL_DETAIL, {"REQ_APP_NAME", request->GetPackageName(),
3009                 "TRANS_ID", request->GetUuid(), "ERR_CODE", std::to_string(errCode), "NETWORK_FAIL_CODE_MSG", errMsg});
3010             break;
3011         }
3012     }
3013 }
3014 
SyncSwitchStatus(const AppExecFwk::InnerEvent::Pointer & event)3015 void LocatorHandler::SyncSwitchStatus(const AppExecFwk::InnerEvent::Pointer& event)
3016 {
3017     LocationDataRdbManager::SyncSwitchStatus();
3018 }
3019 
IsSwitchObserverReg()3020 bool LocatorHandler::IsSwitchObserverReg()
3021 {
3022     std::unique_lock<ffrt::mutex> lock(isSwitchObserverRegMutex_);
3023     return isSwitchObserverReg_;
3024 }
3025 
SetIsSwitchObserverReg(bool isSwitchObserverReg)3026 void LocatorHandler::SetIsSwitchObserverReg(bool isSwitchObserverReg)
3027 {
3028     std::unique_lock<ffrt::mutex> lock(isSwitchObserverRegMutex_);
3029     isSwitchObserverReg_ = isSwitchObserverReg;
3030 }
3031 
WatchSwitchParameter(const AppExecFwk::InnerEvent::Pointer & event)3032 void LocatorHandler::WatchSwitchParameter(const AppExecFwk::InnerEvent::Pointer& event)
3033 {
3034     if (IsSwitchObserverReg()) {
3035         return;
3036     }
3037     auto eventCallback = [](const char *key, const char *value, void *context) {
3038         LocationDataRdbManager::SyncSwitchStatus();
3039     };
3040 
3041     int ret = WatchParameter(LOCATION_SWITCH_MODE, eventCallback, nullptr);
3042     if (ret != SUCCESS) {
3043         LBSLOGE(LOCATOR, "WatchParameter fail");
3044         return;
3045     }
3046     SetIsSwitchObserverReg(true);
3047 }
3048 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)3049 void LocatorHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event)
3050 {
3051     uint32_t eventId = event->GetInnerEventId();
3052     LBSLOGD(LOCATOR, "ProcessEvent event:%{public}d, timestamp = %{public}s",
3053         eventId, std::to_string(CommonUtils::GetCurrentTimeStamp()).c_str());
3054     auto handleFunc = locatorHandlerEventMap_.find(eventId);
3055     if (handleFunc != locatorHandlerEventMap_.end() && handleFunc->second != nullptr) {
3056         auto memberFunc = handleFunc->second;
3057 #ifdef LOCATION_HICOLLIE_ENABLE
3058         int tid = gettid();
3059         std::string moduleName = "LocatorHandler";
3060         XCollieCallback callbackFunc = [moduleName, eventId, tid](void *) {
3061             LBSLOGE(LOCATOR, "TimeoutCallback tid:%{public}d moduleName:%{public}s excute eventId:%{public}u timeout.",
3062                 tid, moduleName.c_str(), eventId);
3063         };
3064         std::string dfxInfo = moduleName + "_" + std::to_string(eventId) + "_" + std::to_string(tid);
3065         int timerId = HiviewDFX::XCollie::GetInstance().SetTimer(dfxInfo, TIMEOUT_WATCHDOG, callbackFunc, nullptr,
3066             HiviewDFX::XCOLLIE_FLAG_LOG|HiviewDFX::XCOLLIE_FLAG_RECOVERY);
3067         memberFunc(event);
3068         HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
3069 #else
3070         memberFunc(event);
3071 #endif
3072     } else {
3073         LBSLOGE(LOCATOR, "ProcessEvent event:%{public}d, unsupport service.", eventId);
3074     }
3075 }
3076 
RequestCheckEvent(const AppExecFwk::InnerEvent::Pointer & event)3077 void LocatorHandler::RequestCheckEvent(const AppExecFwk::InnerEvent::Pointer& event)
3078 {
3079     auto locatorAbility = LocatorAbility::GetInstance();
3080     if (locatorAbility != nullptr) {
3081         locatorAbility->RemoveInvalidRequests();
3082     }
3083     SendHighPriorityEvent(EVENT_PERIODIC_CHECK, 0, EVENT_PERIODIC_INTERVAL);
3084 }
3085 
SyncStillMovementState(const AppExecFwk::InnerEvent::Pointer & event)3086 void LocatorHandler::SyncStillMovementState(const AppExecFwk::InnerEvent::Pointer& event)
3087 {
3088     bool state = event->GetParam();
3089     RequestManager::GetInstance()->SyncStillMovementState(state);
3090     LocatorRequiredDataManager::GetInstance()->SyncStillMovementState(state);
3091 }
3092 
SyncIdleState(const AppExecFwk::InnerEvent::Pointer & event)3093 void LocatorHandler::SyncIdleState(const AppExecFwk::InnerEvent::Pointer& event)
3094 {
3095     auto requestManager = RequestManager::GetInstance();
3096     if (requestManager != nullptr) {
3097         bool state = event->GetParam();
3098         requestManager->SyncIdleState(state);
3099     }
3100 }
3101 
SendGeoRequestEvent(const AppExecFwk::InnerEvent::Pointer & event)3102 void LocatorHandler::SendGeoRequestEvent(const AppExecFwk::InnerEvent::Pointer& event)
3103 {
3104     auto locatorAbility = LocatorAbility::GetInstance();
3105     if (locatorAbility != nullptr) {
3106         std::unique_ptr<GeoConvertRequest> geoConvertRequest = event->GetUniqueObject<GeoConvertRequest>();
3107         if (geoConvertRequest == nullptr) {
3108             return;
3109         }
3110         MessageParcel dataParcel;
3111         MessageParcel replyParcel;
3112         if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
3113             return;
3114         }
3115         geoConvertRequest->Marshalling(dataParcel);
3116         locatorAbility->SendGeoRequest(
3117             geoConvertRequest->GetRequestType() == GeoCodeType::REQUEST_GEOCODE ?
3118             static_cast<int>(LocatorInterfaceCode::GET_FROM_LOCATION_NAME) :
3119             static_cast<int>(LocatorInterfaceCode::GET_FROM_COORDINATE),
3120             dataParcel, replyParcel);
3121     }
3122 }
3123 
InitMonitorManagerEvent(const AppExecFwk::InnerEvent::Pointer & event)3124 void LocatorHandler::InitMonitorManagerEvent(const AppExecFwk::InnerEvent::Pointer& event)
3125 {
3126 #ifdef MOVEMENT_CLIENT_ENABLE
3127     LocatorMsdpMonitorManager::GetInstance();
3128 #endif
3129 }
3130 
IsStandByEvent(const AppExecFwk::InnerEvent::Pointer & event)3131 void LocatorHandler::IsStandByEvent(const AppExecFwk::InnerEvent::Pointer& event)
3132 {
3133     auto requestManager = RequestManager::GetInstance();
3134     if (requestManager != nullptr) {
3135         requestManager->IsStandby();
3136     }
3137 }
3138 
SetLocationWorkingStateEvent(const AppExecFwk::InnerEvent::Pointer & event)3139 void LocatorHandler::SetLocationWorkingStateEvent(const AppExecFwk::InnerEvent::Pointer& event)
3140 {
3141     if (!LocationDataRdbManager::SetLocationWorkingState(0)) {
3142         LBSLOGD(LOCATOR, "LocatorAbility::reset LocationWorkingState failed.");
3143     }
3144 }
3145 
SetSwitchStateToDbEvent(const AppExecFwk::InnerEvent::Pointer & event)3146 void LocatorHandler::SetSwitchStateToDbEvent(const AppExecFwk::InnerEvent::Pointer& event)
3147 {
3148     int modeValue = event->GetParam();
3149     if (LocationDataRdbManager::SetSwitchStateToDb(modeValue) != ERRCODE_SUCCESS) {
3150         LBSLOGE(LOCATOR, "%{public}s: can not set state to db", __func__);
3151         return;
3152     }
3153     auto locatorAbility = LocatorAbility::GetInstance();
3154     if (locatorAbility != nullptr) {
3155         locatorAbility->UpdateSaAbility();
3156         locatorAbility->ApplyRequests(0);
3157         bool isEnabled = (modeValue == ENABLED);
3158         std::string state = isEnabled ? "enable" : "disable";
3159         locatorAbility->ReportDataToResSched(state);
3160         WriteLocationSwitchStateEvent(state);
3161     }
3162 }
3163 
SetSwitchStateToDbForUserEvent(const AppExecFwk::InnerEvent::Pointer & event)3164 void LocatorHandler::SetSwitchStateToDbForUserEvent(const AppExecFwk::InnerEvent::Pointer& event)
3165 {
3166     std::unique_ptr<LocatorSwitchMessage> locatorSwitchMessage = event->GetUniqueObject<LocatorSwitchMessage>();
3167     if (locatorSwitchMessage == nullptr) {
3168         return;
3169     }
3170     auto modeValue = locatorSwitchMessage->GetModeValue();
3171     auto userId = locatorSwitchMessage->GetUserId();
3172     if (LocationDataRdbManager::SetSwitchStateToDbForUser(modeValue, userId) != ERRCODE_SUCCESS) {
3173         LBSLOGE(LOCATOR, "%{public}s: can not set state to db", __func__);
3174         return;
3175     }
3176     LocatorAbility::GetInstance()->UpdateSaAbility();
3177     LocatorAbility::GetInstance()->ApplyRequests(0);
3178     int currentUserId = 0;
3179     if (CommonUtils::GetCurrentUserId(currentUserId) && userId != currentUserId) {
3180         return;
3181     }
3182     bool isEnabled = (modeValue == ENABLED);
3183     std::string state = isEnabled ? "enable" : "disable";
3184     // background task only check the current user switch state
3185     LocatorAbility::GetInstance()->ReportDataToResSched(state);
3186     WriteLocationSwitchStateEvent(state);
3187 }
3188 
LocatorCallbackDeathRecipient(int32_t tokenId)3189 LocatorCallbackDeathRecipient::LocatorCallbackDeathRecipient(int32_t tokenId)
3190 {
3191     tokenId_ = tokenId;
3192 }
3193 
~LocatorCallbackDeathRecipient()3194 LocatorCallbackDeathRecipient::~LocatorCallbackDeathRecipient()
3195 {
3196 }
3197 
OnRemoteDied(const wptr<IRemoteObject> & remote)3198 void LocatorCallbackDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
3199 {
3200     sptr<ILocatorCallback> callback = iface_cast<ILocatorCallback>(remote.promote());
3201     auto locatorAbility = LocatorAbility::GetInstance();
3202     if (locatorAbility != nullptr) {
3203         locatorAbility->RemoveUnloadTask(DEFAULT_CODE);
3204         locatorAbility->StopLocating(callback);
3205         locatorAbility->PostUnloadTask(DEFAULT_CODE);
3206         LBSLOGI(LOCATOR, "locator callback OnRemoteDied Id = %{public}d", tokenId_);
3207     }
3208 }
3209 
ScanCallbackDeathRecipient()3210 ScanCallbackDeathRecipient::ScanCallbackDeathRecipient()
3211 {
3212 }
3213 
~ScanCallbackDeathRecipient()3214 ScanCallbackDeathRecipient::~ScanCallbackDeathRecipient()
3215 {
3216 }
3217 
OnRemoteDied(const wptr<IRemoteObject> & remote)3218 void ScanCallbackDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
3219 {
3220     auto locatorDataManager = LocatorRequiredDataManager::GetInstance();
3221     if (locatorDataManager != nullptr) {
3222         locatorDataManager->UnregisterCallback(remote.promote());
3223         LBSLOGI(LOCATOR, "scan callback OnRemoteDied");
3224     }
3225 }
3226 } // namespace Location
3227 } // namespace OHOS
3228