• 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 "privacy_kit.h"
21 #include "privacy_error.h"
22 #include "system_ability_definition.h"
23 #include "uri.h"
24 
25 #include "common_event_manager.h"
26 #include "common_hisysevent.h"
27 #include "location_log_event_ids.h"
28 #include "common_utils.h"
29 #include "constant_definition.h"
30 #ifdef FEATURE_GEOCODE_SUPPORT
31 #include "geo_convert_proxy.h"
32 #endif
33 #ifdef FEATURE_GNSS_SUPPORT
34 #include "gnss_ability_proxy.h"
35 #endif
36 #include "hook_utils.h"
37 #include "locator_background_proxy.h"
38 #include "location_config_manager.h"
39 #include "location_data_rdb_helper.h"
40 #include "location_log.h"
41 #include "location_sa_load_manager.h"
42 #include "locationhub_ipc_interface_code.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 
69 namespace OHOS {
70 namespace Location {
71 const bool REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(
72     LocatorAbility::GetInstance());
73 
74 const uint32_t EVENT_UPDATE_SA = 0x0001;
75 const uint32_t EVENT_INIT_REQUEST_MANAGER = 0x0002;
76 const uint32_t EVENT_APPLY_REQUIREMENTS = 0x0003;
77 const uint32_t EVENT_RETRY_REGISTER_ACTION = 0x0004;
78 const uint32_t EVENT_REPORT_LOCATION_MESSAGE = 0x0005;
79 const uint32_t EVENT_SEND_SWITCHSTATE_TO_HIFENCE = 0x0006;
80 const uint32_t EVENT_START_LOCATING = 0x0007;
81 const uint32_t EVENT_STOP_LOCATING = 0x0008;
82 const uint32_t EVENT_UNLOAD_SA = 0x0010;
83 const uint32_t EVENT_GET_CACHED_LOCATION_SUCCESS = 0x0014;
84 const uint32_t EVENT_GET_CACHED_LOCATION_FAILED = 0x0015;
85 const uint32_t EVENT_REG_LOCATION_ERROR = 0x0011;
86 const uint32_t EVENT_UNREG_LOCATION_ERROR = 0x0012;
87 const uint32_t EVENT_REPORT_LOCATION_ERROR = 0x0013;
88 const uint32_t EVENT_PERIODIC_CHECK = 0x0016;
89 const uint32_t EVENT_SYNC_LOCATION_STATUS = 0x0017;
90 const uint32_t EVENT_SYNC_STILL_MOVEMENT_STATE = 0x0018;
91 const uint32_t EVENT_SYNC_IDLE_STATE = 0x0019;
92 const uint32_t EVENT_INIT_MSDP_MONITOR_MANAGER = 0x0020;
93 const uint32_t EVENT_IS_STAND_BY = 0x0021;
94 const uint32_t EVENT_SET_LOCATION_WORKING_STATE = 0x0022;
95 const uint32_t EVENT_SEND_GEOREQUEST = 0x0023;
96 const uint32_t EVENT_SET_SWITCH_STATE_TO_DB = 0x0024;
97 const uint32_t EVENT_WATCH_SWITCH_PARAMETER = 0x0025;
98 const uint32_t EVENT_SET_SWITCH_STATE_TO_DB_BY_USERID = 0x0026;
99 const uint32_t EVENT_START_SCAN_BLUETOOH_DEVICE = 0x0027;
100 const uint32_t EVENT_STOP_SCAN_BLUETOOH_DEVICE = 0x0028;
101 
102 const uint32_t RETRY_INTERVAL_UNITE = 1000;
103 const uint32_t RETRY_INTERVAL_OF_INIT_REQUEST_MANAGER = 5 * RETRY_INTERVAL_UNITE;
104 #ifdef FEATURE_DYNAMIC_OFFLOAD
105 const uint32_t RETRY_INTERVAL_OF_UNLOAD_SA = 4 * 60 * RETRY_INTERVAL_UNITE;
106 #else
107 const uint32_t RETRY_INTERVAL_OF_UNLOAD_SA = 30 * 60 * RETRY_INTERVAL_UNITE;
108 #endif // FEATURE_DYNAMIC_OFFLOAD
109 const int COMMON_SA_ID = 4353;
110 const int COMMON_SWITCH_STATE_ID = 30;
111 const std::u16string COMMON_DESCRIPTION = u"location.IHifenceAbility";
112 const std::string UNLOAD_TASK = "locatior_sa_unload";
113 const std::string WIFI_SCAN_STATE_CHANGE = "wifiScanStateChange";
114 const uint32_t SET_ENABLE = 3;
115 const uint32_t EVENT_PERIODIC_INTERVAL = 3 * 60 * 1000;
116 const uint32_t REQUEST_DEFAULT_TIMEOUT_SECOUND = 5 * 60;
117 const int LOCATIONHUB_STATE_UNLOAD = 0;
118 const int LOCATIONHUB_STATE_LOAD = 1;
119 const int MAX_SIZE = 100;
120 const int TIMEOUT_WATCHDOG = 60; // s
121 const int INVALID_REQUESTS_SIZE = 20;
122 const int MAX_PERMISSION_NUM = 1000;
123 const int MAX_SWITCH_CALLBACKS_NUM = 1000;
124 const int LOCATION_SWITCH_IGNORED_STATE_VALID_TIME = 2 * 60 * 1000; // 2min
125 
GetInstance()126 LocatorAbility* LocatorAbility::GetInstance()
127 {
128     static LocatorAbility data;
129     return &data;
130 }
131 
LocatorAbility()132 LocatorAbility::LocatorAbility() : SystemAbility(LOCATION_LOCATOR_SA_ID, true)
133 {
134     locatorHandler_ = std::make_shared<LocatorHandler>(AppExecFwk::EventRunner::Create(true,
135         AppExecFwk::ThreadMode::FFRT));
136     switchCallbacks_ = std::make_unique<std::map<pid_t, sptr<ISwitchCallback>>>();
137     requests_ = std::make_shared<std::map<std::string, std::list<std::shared_ptr<Request>>>>();
138     receivers_ = std::make_shared<std::map<sptr<IRemoteObject>, std::list<std::shared_ptr<Request>>>>();
139     proxyMap_ = std::make_shared<std::map<std::string, sptr<IRemoteObject>>>();
140     loadedSaMap_ = std::make_shared<std::map<std::string, sptr<IRemoteObject>>>();
141     permissionMap_ = std::make_shared<std::map<uint32_t, std::shared_ptr<PermissionStatusChangeCb>>>();
142     InitRequestManagerMap();
143     reportManager_ = ReportManager::GetInstance();
144     deviceId_ = CommonUtils::InitDeviceId();
145 #ifdef MOVEMENT_CLIENT_ENABLE
146     if (locatorHandler_ != nullptr) {
147         locatorHandler_->SendHighPriorityEvent(EVENT_INIT_MSDP_MONITOR_MANAGER, 0, 0);
148     }
149 #endif
150     requestManager_ = RequestManager::GetInstance();
151     if (locatorHandler_ != nullptr) {
152         locatorHandler_->SendHighPriorityEvent(EVENT_IS_STAND_BY, 0, 0);
153     }
154     LBSLOGI(LOCATOR, "LocatorAbility constructed.");
155 }
156 
~LocatorAbility()157 LocatorAbility::~LocatorAbility() {}
158 
OnStart()159 void LocatorAbility::OnStart()
160 {
161     if (state_ == ServiceRunningState::STATE_RUNNING) {
162         LBSLOGI(LOCATOR, "LocatorAbility has already started.");
163         return;
164     }
165     if (!Init()) {
166         LBSLOGE(LOCATOR, "failed to init LocatorAbility");
167         OnStop();
168         return;
169     }
170     state_ = ServiceRunningState::STATE_RUNNING;
171     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
172     if (locatorHandler_ != nullptr) {
173         locatorHandler_->SendHighPriorityEvent(EVENT_SET_LOCATION_WORKING_STATE, 0, 0);
174         locatorHandler_->SendHighPriorityEvent(EVENT_SYNC_LOCATION_STATUS, 0, 0);
175         locatorHandler_->SendHighPriorityEvent(EVENT_WATCH_SWITCH_PARAMETER, 0, 0);
176     }
177     LBSLOGW(LOCATOR, "LocatorAbility::OnStart start ability success.");
178 }
179 
OnStop()180 void LocatorAbility::OnStop()
181 {
182     state_ = ServiceRunningState::STATE_NOT_START;
183     registerToAbility_ = false;
184     if (!LocationDataRdbManager::SetLocationWorkingState(0)) {
185         LBSLOGD(LOCATOR, "LocatorAbility::reset LocationWorkingState failed.");
186     }
187     SetLocationhubStateToSyspara(LOCATIONHUB_STATE_UNLOAD);
188     LocatorRequiredDataManager::GetInstance()->UnregisterWifiCallBack();
189     LBSLOGW(LOCATOR, "LocatorAbility::OnStop ability stopped.");
190 }
191 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)192 void LocatorAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId)
193 {
194     if (systemAbilityId == COMMON_EVENT_SERVICE_ID) {
195         RegisterAction();
196         RegisterLocationPrivacyAction();
197     }
198 }
199 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)200 void LocatorAbility::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
201 {
202     if (systemAbilityId != COMMON_EVENT_SERVICE_ID) {
203         LBSLOGE(LOCATOR, "systemAbilityId is not COMMON_EVENT_SERVICE_ID");
204         return;
205     }
206 
207     if (locationPrivacyEventSubscriber_ != nullptr) {
208         bool ret = OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(locationPrivacyEventSubscriber_);
209         locationPrivacyEventSubscriber_ = nullptr;
210         isLocationPrivacyActionRegistered_ = false;
211         LBSLOGI(LOCATOR, "UnSubscribeCommonEvent locationPrivacyEventSubscriber_ result = %{public}d", ret);
212         return;
213     }
214 
215     if (locatorEventSubscriber_ == nullptr) {
216         LBSLOGE(LOCATOR, "OnRemoveSystemAbility subscribeer is nullptr");
217         return;
218     }
219     bool result = OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(locatorEventSubscriber_);
220     isActionRegistered = false;
221     LBSLOGI(LOCATOR, "UnSubscribeCommonEvent locatorEventSubscriber_ result = %{public}d", result);
222 }
223 
Init()224 bool LocatorAbility::Init()
225 {
226     if (registerToAbility_) {
227         return true;
228     }
229     LBSLOGI(LOCATOR, "LocatorAbility Init.");
230     bool ret = Publish(AsObject());
231     if (!ret) {
232         LBSLOGE(LOCATOR, "Init add system ability failed!");
233         return false;
234     }
235     UpdateSaAbility();
236     if (locatorHandler_ != nullptr) {
237         locatorHandler_->SendHighPriorityEvent(EVENT_INIT_REQUEST_MANAGER, 0, RETRY_INTERVAL_OF_INIT_REQUEST_MANAGER);
238         locatorHandler_->SendHighPriorityEvent(EVENT_PERIODIC_CHECK, 0, EVENT_PERIODIC_INTERVAL);
239     }
240     SetLocationhubStateToSyspara(LOCATIONHUB_STATE_LOAD);
241     registerToAbility_ = true;
242     return registerToAbility_;
243 }
244 
InitRequestManagerMap()245 void LocatorAbility::InitRequestManagerMap()
246 {
247     std::unique_lock<ffrt::mutex> lock(requestsMutex_);
248     if (requests_ != nullptr) {
249 #ifdef FEATURE_GNSS_SUPPORT
250         std::list<std::shared_ptr<Request>> gnssList;
251         requests_->insert(make_pair(GNSS_ABILITY, gnssList));
252 #endif
253 #ifdef FEATURE_NETWORK_SUPPORT
254         std::list<std::shared_ptr<Request>> networkList;
255         requests_->insert(make_pair(NETWORK_ABILITY, networkList));
256 #endif
257 #ifdef FEATURE_PASSIVE_SUPPORT
258         std::list<std::shared_ptr<Request>> passiveList;
259         requests_->insert(make_pair(PASSIVE_ABILITY, passiveList));
260 #endif
261     }
262 }
263 
GetRequests()264 std::shared_ptr<std::map<std::string, std::list<std::shared_ptr<Request>>>> LocatorAbility::GetRequests()
265 {
266     std::unique_lock<ffrt::mutex> lock(requestsMutex_);
267     return requests_;
268 }
269 
GetActiveRequestNum()270 int LocatorAbility::GetActiveRequestNum()
271 {
272     std::unique_lock<ffrt::mutex> lock(requestsMutex_);
273     int num = 0;
274 #ifdef FEATURE_GNSS_SUPPORT
275     auto gpsListIter = requests_->find(GNSS_ABILITY);
276     if (gpsListIter != requests_->end()) {
277         auto list = &(gpsListIter->second);
278         num += static_cast<int>(list->size());
279     }
280 #endif
281 #ifdef FEATURE_NETWORK_SUPPORT
282     auto networkListIter = requests_->find(NETWORK_ABILITY);
283     if (networkListIter != requests_->end()) {
284         auto list = &(networkListIter->second);
285         num += static_cast<int>(list->size());
286     }
287 #endif
288     return num;
289 }
290 
GetReceivers()291 std::shared_ptr<std::map<sptr<IRemoteObject>, std::list<std::shared_ptr<Request>>>> LocatorAbility::GetReceivers()
292 {
293     std::unique_lock<ffrt::mutex> lock(receiversMutex_);
294     return receivers_;
295 }
296 
GetProxyMap()297 std::shared_ptr<std::map<std::string, sptr<IRemoteObject>>> LocatorAbility::GetProxyMap()
298 {
299     std::unique_lock<std::mutex> lock(proxyMapMutex_);
300     return proxyMap_;
301 }
302 
ApplyRequests(int delay)303 void LocatorAbility::ApplyRequests(int delay)
304 {
305     if (locatorHandler_ != nullptr) {
306         locatorHandler_->SendHighPriorityEvent(EVENT_APPLY_REQUIREMENTS, 0, delay * RETRY_INTERVAL_UNITE);
307     }
308 }
309 
InitSaAbility()310 void LocatorAbility::InitSaAbility()
311 {
312     LBSLOGI(LOCATOR, "initSaAbility start");
313     if (proxyMap_ == nullptr) {
314         return;
315     }
316     UpdateSaAbilityHandler();
317 }
318 
CheckSaValid()319 bool LocatorAbility::CheckSaValid()
320 {
321     std::unique_lock<std::mutex> lock(proxyMapMutex_);
322 #ifdef FEATURE_GNSS_SUPPORT
323     auto objectGnss = proxyMap_->find(GNSS_ABILITY);
324     if (objectGnss == proxyMap_->end()) {
325         LBSLOGI(LOCATOR, "gnss sa is null");
326         return false;
327     }
328 #endif
329 #ifdef FEATURE_NETWORK_SUPPORT
330     auto objectNetwork = proxyMap_->find(NETWORK_ABILITY);
331     if (objectNetwork == proxyMap_->end()) {
332         LBSLOGI(LOCATOR, "network sa is null");
333         return false;
334     }
335 #endif
336 #ifdef FEATURE_PASSIVE_SUPPORT
337     auto objectPassive = proxyMap_->find(PASSIVE_ABILITY);
338     if (objectPassive == proxyMap_->end()) {
339         LBSLOGI(LOCATOR, "passive sa is null");
340         return false;
341     }
342 #endif
343     return true;
344 }
345 
SetLocationhubStateToSyspara(int value)346 bool LocatorAbility::SetLocationhubStateToSyspara(int value)
347 {
348     char valueArray[MAX_SIZE] = {0};
349     (void)sprintf_s(valueArray, sizeof(valueArray), "%d", value);
350     int res = SetParameter(LOCATION_LOCATIONHUB_STATE, valueArray);
351     if (res != 0) {
352         LBSLOGE(LOCATOR, "%{public}s failed, res: %{public}d", __func__, res);
353         return false;
354     }
355     return true;
356 }
357 
UpdateSaAbility()358 LocationErrCode LocatorAbility::UpdateSaAbility()
359 {
360     auto event = AppExecFwk::InnerEvent::Get(EVENT_UPDATE_SA, 0);
361     if (locatorHandler_ != nullptr) {
362         locatorHandler_->SendHighPriorityEvent(event);
363     }
364     return ERRCODE_SUCCESS;
365 }
366 
UpdateSaAbilityHandler()367 void LocatorAbility::UpdateSaAbilityHandler()
368 {
369     int state = LocationDataRdbManager::QuerySwitchState();
370     LBSLOGI(LOCATOR, "update location subability enable state, switch state=%{public}d, action registered=%{public}d",
371         state, isActionRegistered);
372     if (state == DEFAULT_SWITCH_STATE) {
373         return;
374     }
375     bool isEnabled = (state == ENABLED);
376     auto locatorBackgroundProxy = LocatorBackgroundProxy::GetInstance();
377     locatorBackgroundProxy->OnSaStateChange(isEnabled);
378     UpdateLoadedSaMap();
379     std::unique_lock<ffrt::mutex> lock(loadedSaMapMutex_);
380     for (auto iter = loadedSaMap_->begin(); iter != loadedSaMap_->end(); iter++) {
381         sptr<IRemoteObject> remoteObject = iter->second;
382         MessageParcel data;
383         if (iter->first == GNSS_ABILITY) {
384 #ifdef FEATURE_GNSS_SUPPORT
385             data.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor());
386 #endif
387         } else if (iter->first == NETWORK_ABILITY) {
388 #ifdef FEATURE_NETWORK_SUPPORT
389             data.WriteInterfaceToken(NetworkAbilityProxy::GetDescriptor());
390 #endif
391         } else if (iter->first == PASSIVE_ABILITY) {
392 #ifdef FEATURE_PASSIVE_SUPPORT
393             data.WriteInterfaceToken(PassiveAbilityProxy::GetDescriptor());
394 #endif
395         }
396         data.WriteBool(isEnabled);
397 
398         MessageParcel reply;
399         MessageOption option;
400         int error = remoteObject->SendRequest(SET_ENABLE, data, reply, option);
401         if (error != ERR_OK) {
402             LBSLOGI(LOCATOR, "enable %{public}s ability, remote result %{public}d", (iter->first).c_str(), error);
403         }
404     }
405     SendSwitchState(isEnabled ? 1 : 0);
406 }
407 
CancelIdleState(uint32_t code)408 bool LocatorAbility::CancelIdleState(uint32_t code)
409 {
410     if (code == static_cast<uint16_t>(LocatorInterfaceCode::PROXY_PID_FOR_FREEZE) ||
411         code == static_cast<uint16_t>(LocatorInterfaceCode::RESET_ALL_PROXY)) {
412         return true;
413     }
414     SystemAbilityState state = GetAbilityState();
415     if (state != SystemAbilityState::IDLE) {
416         return true;
417     }
418     bool ret = CancelIdle();
419     if (!ret) {
420         LBSLOGE(LOCATOR, "%{public}s cancel idle failed!", __func__);
421         return false;
422     }
423     return true;
424 }
425 
RemoveUnloadTask(uint32_t code)426 void LocatorAbility::RemoveUnloadTask(uint32_t code)
427 {
428     if (locatorHandler_ == nullptr) {
429         LBSLOGE(LOCATOR, "%{public}s locatorHandler is nullptr", __func__);
430         return;
431     }
432     if (code == static_cast<uint16_t>(LocatorInterfaceCode::PROXY_PID_FOR_FREEZE) ||
433         code == static_cast<uint16_t>(LocatorInterfaceCode::RESET_ALL_PROXY)) {
434         return;
435     }
436     locatorHandler_->RemoveTask(UNLOAD_TASK);
437 }
438 
PostUnloadTask(uint32_t code)439 void LocatorAbility::PostUnloadTask(uint32_t code)
440 {
441     if (code == static_cast<uint16_t>(LocatorInterfaceCode::PROXY_PID_FOR_FREEZE) ||
442         code == static_cast<uint16_t>(LocatorInterfaceCode::RESET_ALL_PROXY)) {
443         return;
444     }
445     if (CheckIfLocatorConnecting()) {
446         return;
447     }
448     auto task = [this]() {
449         SaLoadWithStatistic::UnInitLocationSa(LOCATION_LOCATOR_SA_ID);
450     };
451     if (locatorHandler_ != nullptr) {
452         locatorHandler_->PostTask(task, UNLOAD_TASK, RETRY_INTERVAL_OF_UNLOAD_SA);
453     }
454 }
455 
SendSwitchState(const int state)456 void LocatorAbility::SendSwitchState(const int state)
457 {
458     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
459         Get(EVENT_SEND_SWITCHSTATE_TO_HIFENCE, state);
460     if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
461         LBSLOGD(LOCATOR, "%{public}s: EVENT_SEND_SWITCHSTATE_TO_HIFENCE Send Success", __func__);
462     }
463 }
464 
CheckIfLocatorConnecting()465 bool LocatorAbility::CheckIfLocatorConnecting()
466 {
467     return LocatorRequiredDataManager::GetInstance()->IsConnecting() || GetActiveRequestNum() > 0;
468 }
469 
EnableAbility(bool isEnabled)470 LocationErrCode LocatorAbility::EnableAbility(bool isEnabled)
471 {
472     LBSLOGI(LOCATOR, "EnableAbility %{public}d", isEnabled);
473     int modeValue = isEnabled ? ENABLED : DISABLED;
474     int currentSwitchState = LocationDataRdbManager::QuerySwitchState();
475     if (modeValue == currentSwitchState) {
476         LBSLOGD(LOCATOR, "no need to set location ability, enable:%{public}d", modeValue);
477         return ERRCODE_SUCCESS;
478     }
479     // update param
480     LocationDataRdbManager::SetSwitchStateToSysparaForCurrentUser(isEnabled ? ENABLED : DISABLED);
481     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
482         Get(EVENT_SET_SWITCH_STATE_TO_DB, modeValue);
483     if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
484         LBSLOGD(LOCATOR, "%{public}s: EVENT_SET_SWITCH_STATE_TO_DB Send Success", __func__);
485     }
486     return ERRCODE_SUCCESS;
487 }
488 
EnableAbilityForUser(bool isEnabled,int32_t userId)489 LocationErrCode LocatorAbility::EnableAbilityForUser(bool isEnabled, int32_t userId)
490 {
491     LBSLOGI(LOCATOR, "EnableAbilityForUser %{public}d, UserId %{public}d", isEnabled, userId);
492     // update param
493     int modeValue = isEnabled ? ENABLED : DISABLED;
494     std::unique_ptr<LocatorSwitchMessage> locatorSwitchMessage = std::make_unique<LocatorSwitchMessage>();
495     locatorSwitchMessage->SetModeValue(modeValue);
496     locatorSwitchMessage->SetUserId(userId);
497     LocationDataRdbManager::SetSwitchStateToSysparaForUser(isEnabled ? ENABLED : DISABLED, userId);
498     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
499         Get(EVENT_SET_SWITCH_STATE_TO_DB_BY_USERID, locatorSwitchMessage);
500     if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
501         LBSLOGD(LOCATOR, "%{public}s: EVENT_SET_SWITCH_STATE_TO_DB_BY_USERID Send Success", __func__);
502     }
503     return ERRCODE_SUCCESS;
504 }
505 
GetSwitchState(int & state)506 LocationErrCode LocatorAbility::GetSwitchState(int& state)
507 {
508     state = LocationDataRdbManager::QuerySwitchState();
509     return ERRCODE_SUCCESS;
510 }
511 
IsLocationPrivacyConfirmed(const int type,bool & isConfirmed)512 LocationErrCode LocatorAbility::IsLocationPrivacyConfirmed(const int type, bool& isConfirmed)
513 {
514     return LocationConfigManager::GetInstance()->GetPrivacyTypeState(type, isConfirmed);
515 }
516 
SetLocationPrivacyConfirmStatus(const int type,bool isConfirmed)517 LocationErrCode LocatorAbility::SetLocationPrivacyConfirmStatus(const int type, bool isConfirmed)
518 {
519     return LocationConfigManager::GetInstance()->SetPrivacyTypeState(type, isConfirmed);
520 }
521 
RegisterSwitchCallback(const sptr<IRemoteObject> & callback,pid_t uid)522 LocationErrCode LocatorAbility::RegisterSwitchCallback(const sptr<IRemoteObject>& callback, pid_t uid)
523 {
524     if (callback == nullptr) {
525         LBSLOGE(LOCATOR, "register an invalid switch callback");
526         return ERRCODE_INVALID_PARAM;
527     }
528     sptr<IRemoteObject::DeathRecipient> death(new (std::nothrow) SwitchCallbackDeathRecipient());
529     callback->AddDeathRecipient(death);
530     sptr<ISwitchCallback> switchCallback = iface_cast<ISwitchCallback>(callback);
531     if (switchCallback == nullptr) {
532         LBSLOGE(LOCATOR, "cast switch callback fail!");
533         return ERRCODE_INVALID_PARAM;
534     }
535     std::unique_lock<std::mutex> lock(switchMutex_);
536     switchCallbacks_->erase(uid);
537     if (switchCallbacks_->size() <= MAX_SWITCH_CALLBACKS_NUM) {
538         switchCallbacks_->insert(std::make_pair(uid, switchCallback));
539     } else {
540         LBSLOGE(LOCATOR, "RegisterSwitchCallback num max");
541         return ERRCODE_SERVICE_UNAVAILABLE;
542     }
543     LBSLOGD(LOCATOR, "after uid:%{public}d register, switch callback size:%{public}s",
544         uid, std::to_string(switchCallbacks_->size()).c_str());
545     return ERRCODE_SUCCESS;
546 }
547 
UnregisterSwitchCallback(const sptr<IRemoteObject> & callback)548 LocationErrCode LocatorAbility::UnregisterSwitchCallback(const sptr<IRemoteObject>& callback)
549 {
550     if (callback == nullptr) {
551         LBSLOGE(LOCATOR, "unregister an invalid switch callback");
552         return ERRCODE_INVALID_PARAM;
553     }
554     sptr<ISwitchCallback> switchCallback = iface_cast<ISwitchCallback>(callback);
555     if (switchCallback == nullptr) {
556         LBSLOGE(LOCATOR, "cast switch callback fail!");
557         return ERRCODE_INVALID_PARAM;
558     }
559 
560     std::unique_lock<std::mutex> lock(switchMutex_);
561     pid_t uid = -1;
562     for (auto iter = switchCallbacks_->begin(); iter != switchCallbacks_->end(); iter++) {
563         sptr<IRemoteObject> remoteObject = (iter->second)->AsObject();
564         if (remoteObject == callback) {
565             uid = iter->first;
566             break;
567         }
568     }
569     switchCallbacks_->erase(uid);
570     LBSLOGD(LOCATOR, "after uid:%{public}d unregister, switch callback size:%{public}s",
571         uid, std::to_string(switchCallbacks_->size()).c_str());
572     return ERRCODE_SUCCESS;
573 }
574 
575 #ifdef FEATURE_GNSS_SUPPORT
SendGnssRequest(int type,MessageParcel & data,MessageParcel & reply)576 LocationErrCode LocatorAbility::SendGnssRequest(int type, MessageParcel &data, MessageParcel &reply)
577 {
578     if (!SaLoadWithStatistic::InitLocationSa(LOCATION_GNSS_SA_ID)) {
579         return ERRCODE_SERVICE_UNAVAILABLE;
580     }
581     sptr<IRemoteObject> objectGnss =
582             CommonUtils::GetRemoteObject(LOCATION_GNSS_SA_ID, CommonUtils::InitDeviceId());
583     if (objectGnss == nullptr) {
584         return ERRCODE_SERVICE_UNAVAILABLE;
585     }
586     MessageOption option;
587     objectGnss->SendRequest(type, data, reply, option);
588     return LocationErrCode(reply.ReadInt32());
589 }
590 #endif
591 
592 #ifdef FEATURE_GNSS_SUPPORT
RegisterGnssStatusCallback(const sptr<IRemoteObject> & callback,AppIdentity & identity)593 LocationErrCode LocatorAbility::RegisterGnssStatusCallback(const sptr<IRemoteObject>& callback,
594     AppIdentity &identity)
595 {
596     LBSLOGD(LOCATOR, "uid is: %{public}d", identity.GetUid());
597     MessageParcel dataToStub;
598     MessageParcel replyToStub;
599     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
600         return ERRCODE_SERVICE_UNAVAILABLE;
601     }
602     identity.Marshalling(dataToStub);
603     dataToStub.WriteRemoteObject(callback);
604     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::REG_GNSS_STATUS), dataToStub, replyToStub);
605 }
606 #endif
607 
608 #ifdef FEATURE_GNSS_SUPPORT
UnregisterGnssStatusCallback(const sptr<IRemoteObject> & callback)609 LocationErrCode LocatorAbility::UnregisterGnssStatusCallback(const sptr<IRemoteObject>& callback)
610 {
611     MessageParcel dataToStub;
612     MessageParcel replyToStub;
613     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
614         return ERRCODE_SERVICE_UNAVAILABLE;
615     }
616     dataToStub.WriteRemoteObject(callback);
617     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::UNREG_GNSS_STATUS), dataToStub, replyToStub);
618 }
619 #endif
620 
621 #ifdef FEATURE_GNSS_SUPPORT
RegisterNmeaMessageCallback(const sptr<IRemoteObject> & callback,AppIdentity & identity)622 LocationErrCode LocatorAbility::RegisterNmeaMessageCallback(const sptr<IRemoteObject>& callback,
623     AppIdentity &identity)
624 {
625     MessageParcel dataToStub;
626     MessageParcel replyToStub;
627     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
628         return ERRCODE_SERVICE_UNAVAILABLE;
629     }
630     identity.Marshalling(dataToStub);
631     dataToStub.WriteRemoteObject(callback);
632     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::REG_NMEA), dataToStub, replyToStub);
633 }
634 #endif
635 
636 #ifdef FEATURE_GNSS_SUPPORT
UnregisterNmeaMessageCallback(const sptr<IRemoteObject> & callback)637 LocationErrCode LocatorAbility::UnregisterNmeaMessageCallback(const sptr<IRemoteObject>& callback)
638 {
639     MessageParcel dataToStub;
640     MessageParcel replyToStub;
641     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
642         return ERRCODE_SERVICE_UNAVAILABLE;
643     }
644     dataToStub.WriteRemoteObject(callback);
645     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::UNREG_NMEA), dataToStub, replyToStub);
646 }
647 #endif
648 
649 #ifdef FEATURE_GNSS_SUPPORT
RegisterCachedLocationCallback(std::unique_ptr<CachedGnssLocationsRequest> & request,sptr<ICachedLocationsCallback> & callback,std::string bundleName)650 LocationErrCode LocatorAbility::RegisterCachedLocationCallback(std::unique_ptr<CachedGnssLocationsRequest>& request,
651     sptr<ICachedLocationsCallback>& callback, std::string bundleName)
652 {
653     MessageParcel dataToStub;
654     MessageParcel replyToStub;
655     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
656         return ERRCODE_SERVICE_UNAVAILABLE;
657     }
658     dataToStub.WriteInt32(request->reportingPeriodSec);
659     dataToStub.WriteBool(request->wakeUpCacheQueueFull);
660     dataToStub.WriteRemoteObject(callback->AsObject());
661     dataToStub.WriteString16(Str8ToStr16(bundleName));
662     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::REG_CACHED), dataToStub, replyToStub);
663 }
664 #endif
665 
666 #ifdef FEATURE_GNSS_SUPPORT
UnregisterCachedLocationCallback(sptr<ICachedLocationsCallback> & callback)667 LocationErrCode LocatorAbility::UnregisterCachedLocationCallback(sptr<ICachedLocationsCallback>& callback)
668 {
669     MessageParcel dataToStub;
670     MessageParcel replyToStub;
671     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
672         return ERRCODE_SERVICE_UNAVAILABLE;
673     }
674     dataToStub.WriteRemoteObject(callback->AsObject());
675     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::UNREG_CACHED), dataToStub, replyToStub);
676 }
677 #endif
678 
679 #ifdef FEATURE_GNSS_SUPPORT
GetCachedGnssLocationsSize(int & size)680 LocationErrCode LocatorAbility::GetCachedGnssLocationsSize(int& size)
681 {
682     MessageParcel dataToStub;
683     MessageParcel replyToStub;
684     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
685         return ERRCODE_SERVICE_UNAVAILABLE;
686     }
687     LocationErrCode errorCode =
688         SendGnssRequest(static_cast<int>(GnssInterfaceCode::GET_CACHED_SIZE), dataToStub, replyToStub);
689     if (errorCode == ERRCODE_SUCCESS) {
690         size = replyToStub.ReadInt32();
691     }
692     return errorCode;
693 }
694 #endif
695 
696 #ifdef FEATURE_GNSS_SUPPORT
FlushCachedGnssLocations()697 LocationErrCode LocatorAbility::FlushCachedGnssLocations()
698 {
699     MessageParcel dataToStub;
700     MessageParcel replyToStub;
701     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
702         return ERRCODE_SERVICE_UNAVAILABLE;
703     }
704     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::FLUSH_CACHED), dataToStub, replyToStub);
705 }
706 #endif
707 
708 #ifdef FEATURE_GNSS_SUPPORT
SendCommand(std::unique_ptr<LocationCommand> & commands)709 LocationErrCode LocatorAbility::SendCommand(std::unique_ptr<LocationCommand>& commands)
710 {
711     MessageParcel dataToStub;
712     MessageParcel replyToStub;
713     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
714         return ERRCODE_SERVICE_UNAVAILABLE;
715     }
716     dataToStub.WriteInt32(commands->scenario);
717     dataToStub.WriteString16(Str8ToStr16(commands->command));
718     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::SEND_COMMANDS), dataToStub, replyToStub);
719 }
720 #endif
721 
722 #ifdef FEATURE_GNSS_SUPPORT
AddFence(std::shared_ptr<GeofenceRequest> & request)723 LocationErrCode LocatorAbility::AddFence(std::shared_ptr<GeofenceRequest>& request)
724 {
725     MessageParcel dataToStub;
726     MessageParcel replyToStub;
727     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
728         return ERRCODE_SERVICE_UNAVAILABLE;
729     }
730     request->Marshalling(dataToStub);
731     return SendGnssRequest(
732         static_cast<int>(GnssInterfaceCode::ADD_FENCE_INFO), dataToStub, replyToStub);
733 }
734 #endif
735 
736 #ifdef FEATURE_GNSS_SUPPORT
RemoveFence(std::shared_ptr<GeofenceRequest> & request)737 LocationErrCode LocatorAbility::RemoveFence(std::shared_ptr<GeofenceRequest>& request)
738 {
739     MessageParcel dataToStub;
740     MessageParcel replyToStub;
741     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
742         return ERRCODE_SERVICE_UNAVAILABLE;
743     }
744     request->Marshalling(dataToStub);
745     return SendGnssRequest(
746         static_cast<int>(GnssInterfaceCode::REMOVE_FENCE_INFO), dataToStub, replyToStub);
747 }
748 #endif
749 
750 #ifdef FEATURE_GNSS_SUPPORT
AddGnssGeofence(std::shared_ptr<GeofenceRequest> & request)751 LocationErrCode LocatorAbility::AddGnssGeofence(std::shared_ptr<GeofenceRequest>& request)
752 {
753     MessageParcel dataToStub;
754     MessageParcel replyToStub;
755     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
756         return ERRCODE_SERVICE_UNAVAILABLE;
757     }
758     request->Marshalling(dataToStub);
759     return SendGnssRequest(
760         static_cast<int>(GnssInterfaceCode::ADD_GNSS_GEOFENCE), dataToStub, replyToStub);
761 }
762 #endif
763 
764 #ifdef FEATURE_GNSS_SUPPORT
RemoveGnssGeofence(std::shared_ptr<GeofenceRequest> & request)765 LocationErrCode LocatorAbility::RemoveGnssGeofence(std::shared_ptr<GeofenceRequest>& request)
766 {
767     MessageParcel dataToStub;
768     MessageParcel replyToStub;
769     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
770         return ERRCODE_SERVICE_UNAVAILABLE;
771     }
772     dataToStub.WriteInt32(request->GetFenceId());
773     dataToStub.WriteString(request->GetBundleName());
774     return SendGnssRequest(
775         static_cast<int>(GnssInterfaceCode::REMOVE_GNSS_GEOFENCE), dataToStub, replyToStub);
776 }
777 #endif
778 
779 #ifdef FEATURE_GNSS_SUPPORT
SendLocationMockMsgToGnssSa(const sptr<IRemoteObject> obj,const int timeInterval,const std::vector<std::shared_ptr<Location>> & location,int msgId)780 LocationErrCode LocatorAbility::SendLocationMockMsgToGnssSa(const sptr<IRemoteObject> obj,
781     const int timeInterval, const std::vector<std::shared_ptr<Location>> &location, int msgId)
782 {
783     if (obj == nullptr) {
784         LBSLOGE(LOCATOR, "SendLocationMockMsgToGnssSa obj is nullptr");
785         return ERRCODE_SERVICE_UNAVAILABLE;
786     }
787     std::unique_ptr<GnssAbilityProxy> gnssProxy = std::make_unique<GnssAbilityProxy>(obj);
788     LocationErrCode errorCode = ERRCODE_NOT_SUPPORTED;
789     if (msgId == static_cast<int>(LocatorInterfaceCode::ENABLE_LOCATION_MOCK)) {
790         errorCode = gnssProxy->EnableMock();
791     } else if (msgId == static_cast<int>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK)) {
792         errorCode = gnssProxy->DisableMock();
793     } else if (msgId == static_cast<int>(LocatorInterfaceCode::SET_MOCKED_LOCATIONS)) {
794         errorCode = gnssProxy->SetMocked(timeInterval, location);
795     }
796     return errorCode;
797 }
798 #endif
799 
800 #ifdef FEATURE_NETWORK_SUPPORT
SendLocationMockMsgToNetworkSa(const sptr<IRemoteObject> obj,const int timeInterval,const std::vector<std::shared_ptr<Location>> & location,int msgId)801 LocationErrCode LocatorAbility::SendLocationMockMsgToNetworkSa(const sptr<IRemoteObject> obj,
802     const int timeInterval, const std::vector<std::shared_ptr<Location>> &location, int msgId)
803 {
804     if (obj == nullptr) {
805         LBSLOGE(LOCATOR, "SendLocationMockMsgToNetworkSa obj is nullptr");
806         return ERRCODE_SERVICE_UNAVAILABLE;
807     }
808     std::unique_ptr<NetworkAbilityProxy> networkProxy =
809         std::make_unique<NetworkAbilityProxy>(obj);
810     LocationErrCode errorCode = ERRCODE_NOT_SUPPORTED;
811     if (msgId == static_cast<int>(LocatorInterfaceCode::ENABLE_LOCATION_MOCK)) {
812         errorCode = networkProxy->EnableMock();
813     } else if (msgId == static_cast<int>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK)) {
814         errorCode = networkProxy->DisableMock();
815     } else if (msgId == static_cast<int>(LocatorInterfaceCode::SET_MOCKED_LOCATIONS)) {
816         errorCode = networkProxy->SetMocked(timeInterval, location);
817     }
818     return errorCode;
819 }
820 #endif
821 
822 #ifdef FEATURE_PASSIVE_SUPPORT
SendLocationMockMsgToPassiveSa(const sptr<IRemoteObject> obj,const int timeInterval,const std::vector<std::shared_ptr<Location>> & location,int msgId)823 LocationErrCode LocatorAbility::SendLocationMockMsgToPassiveSa(const sptr<IRemoteObject> obj,
824     const int timeInterval, const std::vector<std::shared_ptr<Location>> &location, int msgId)
825 {
826     if (obj == nullptr) {
827         LBSLOGE(LOCATOR, "SendLocationMockMsgToNetworkSa obj is nullptr");
828         return ERRCODE_SERVICE_UNAVAILABLE;
829     }
830     std::unique_ptr<PassiveAbilityProxy> passiveProxy =
831         std::make_unique<PassiveAbilityProxy>(obj);
832     LocationErrCode errorCode = ERRCODE_NOT_SUPPORTED;
833     if (msgId == static_cast<int>(LocatorInterfaceCode::ENABLE_LOCATION_MOCK)) {
834         errorCode = passiveProxy->EnableMock();
835     } else if (msgId == static_cast<int>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK)) {
836         errorCode = passiveProxy->DisableMock();
837     } else if (msgId == static_cast<int>(LocatorInterfaceCode::SET_MOCKED_LOCATIONS)) {
838         errorCode = passiveProxy->SetMocked(timeInterval, location);
839     }
840     return errorCode;
841 }
842 #endif
843 
ProcessLocationMockMsg(const int timeInterval,const std::vector<std::shared_ptr<Location>> & location,int msgId)844 LocationErrCode LocatorAbility::ProcessLocationMockMsg(
845     const int timeInterval, const std::vector<std::shared_ptr<Location>> &location, int msgId)
846 {
847 #if !defined(FEATURE_GNSS_SUPPORT) && !defined(FEATURE_NETWORK_SUPPORT) && !defined(FEATURE_PASSIVE_SUPPORT)
848     LBSLOGE(LOCATOR, "%{public}s: mock service unavailable", __func__);
849     return ERRCODE_NOT_SUPPORTED;
850 #endif
851     if (!CheckSaValid()) {
852         UpdateProxyMap();
853     }
854 
855     std::unique_lock<std::mutex> lock(proxyMapMutex_);
856     for (auto iter = proxyMap_->begin(); iter != proxyMap_->end(); iter++) {
857         auto obj = iter->second;
858         if (iter->first == GNSS_ABILITY) {
859 #ifdef FEATURE_GNSS_SUPPORT
860             SendLocationMockMsgToGnssSa(obj, timeInterval, location, msgId);
861 #endif
862         } else if (iter->first == NETWORK_ABILITY) {
863 #ifdef FEATURE_NETWORK_SUPPORT
864             SendLocationMockMsgToNetworkSa(obj, timeInterval, location, msgId);
865 #endif
866         } else if (iter->first == PASSIVE_ABILITY) {
867 #ifdef FEATURE_PASSIVE_SUPPORT
868             SendLocationMockMsgToPassiveSa(obj, timeInterval, location, msgId);
869 #endif
870         }
871     }
872     return ERRCODE_SUCCESS;
873 }
874 
UpdateLoadedSaMap()875 void LocatorAbility::UpdateLoadedSaMap()
876 {
877     std::unique_lock<ffrt::mutex> lock(loadedSaMapMutex_);
878     loadedSaMap_->clear();
879     if (LocationSaLoadManager::CheckIfSystemAbilityAvailable(LOCATION_GNSS_SA_ID)) {
880         sptr<IRemoteObject> objectGnss =
881             CommonUtils::GetRemoteObject(LOCATION_GNSS_SA_ID, CommonUtils::InitDeviceId());
882         loadedSaMap_->insert(make_pair(GNSS_ABILITY, objectGnss));
883     }
884     if (LocationSaLoadManager::CheckIfSystemAbilityAvailable(LOCATION_NETWORK_LOCATING_SA_ID)) {
885         sptr<IRemoteObject> objectNetwork =
886             CommonUtils::GetRemoteObject(LOCATION_NETWORK_LOCATING_SA_ID, CommonUtils::InitDeviceId());
887         loadedSaMap_->insert(make_pair(NETWORK_ABILITY, objectNetwork));
888     }
889     if (LocationSaLoadManager::CheckIfSystemAbilityAvailable(LOCATION_NOPOWER_LOCATING_SA_ID)) {
890         sptr<IRemoteObject> objectPassive =
891             CommonUtils::GetRemoteObject(LOCATION_NOPOWER_LOCATING_SA_ID, CommonUtils::InitDeviceId());
892         loadedSaMap_->insert(make_pair(PASSIVE_ABILITY, objectPassive));
893     }
894 }
895 
UpdateProxyMap()896 void LocatorAbility::UpdateProxyMap()
897 {
898     std::unique_lock<std::mutex> lock(proxyMapMutex_);
899 #ifdef FEATURE_GNSS_SUPPORT
900     // init gnss ability sa
901     if (!SaLoadWithStatistic::InitLocationSa(LOCATION_GNSS_SA_ID)) {
902         return;
903     }
904     sptr<IRemoteObject> objectGnss = CommonUtils::GetRemoteObject(LOCATION_GNSS_SA_ID, CommonUtils::InitDeviceId());
905     if (objectGnss != nullptr) {
906         proxyMap_->insert(make_pair(GNSS_ABILITY, objectGnss));
907     } else {
908         LBSLOGE(LOCATOR, "GetRemoteObject gnss sa is null");
909     }
910 #endif
911 #ifdef FEATURE_NETWORK_SUPPORT
912     // init network ability sa
913     if (!SaLoadWithStatistic::InitLocationSa(LOCATION_NETWORK_LOCATING_SA_ID)) {
914         return;
915     }
916     sptr<IRemoteObject> objectNetwork = CommonUtils::GetRemoteObject(LOCATION_NETWORK_LOCATING_SA_ID,
917         CommonUtils::InitDeviceId());
918     if (objectNetwork != nullptr) {
919         proxyMap_->insert(make_pair(NETWORK_ABILITY, objectNetwork));
920     } else {
921         LBSLOGE(LOCATOR, "GetRemoteObject network sa is null");
922     }
923 #endif
924 #ifdef FEATURE_PASSIVE_SUPPORT
925     // init passive ability sa
926     if (!SaLoadWithStatistic::InitLocationSa(LOCATION_NOPOWER_LOCATING_SA_ID)) {
927         return;
928     }
929     sptr<IRemoteObject> objectPassive = CommonUtils::GetRemoteObject(LOCATION_NOPOWER_LOCATING_SA_ID,
930         CommonUtils::InitDeviceId());
931     if (objectPassive != nullptr) {
932         proxyMap_->insert(make_pair(PASSIVE_ABILITY, objectPassive));
933     } else {
934         LBSLOGE(LOCATOR, "GetRemoteObject passive sa is null");
935     }
936 #endif
937 }
938 
EnableLocationMock()939 LocationErrCode LocatorAbility::EnableLocationMock()
940 {
941     int timeInterval = 0;
942     std::vector<std::shared_ptr<Location>> location;
943     return ProcessLocationMockMsg(timeInterval, location,
944         static_cast<int>(LocatorInterfaceCode::ENABLE_LOCATION_MOCK));
945 }
946 
DisableLocationMock()947 LocationErrCode LocatorAbility::DisableLocationMock()
948 {
949     int timeInterval = 0;
950     std::vector<std::shared_ptr<Location>> location;
951     return ProcessLocationMockMsg(timeInterval, location,
952         static_cast<int>(LocatorInterfaceCode::DISABLE_LOCATION_MOCK));
953 }
954 
SetMockedLocations(const int timeInterval,const std::vector<std::shared_ptr<Location>> & location)955 LocationErrCode LocatorAbility::SetMockedLocations(
956     const int timeInterval, const std::vector<std::shared_ptr<Location>> &location)
957 {
958     return ProcessLocationMockMsg(timeInterval, location,
959         static_cast<int>(LocatorInterfaceCode::SET_MOCKED_LOCATIONS));
960 }
961 
StartLocating(std::unique_ptr<RequestConfig> & requestConfig,sptr<ILocatorCallback> & callback,AppIdentity & identity)962 LocationErrCode LocatorAbility::StartLocating(std::unique_ptr<RequestConfig>& requestConfig,
963     sptr<ILocatorCallback>& callback, AppIdentity &identity)
964 {
965 #if !defined(FEATURE_GNSS_SUPPORT) && !defined(FEATURE_NETWORK_SUPPORT) && !defined(FEATURE_PASSIVE_SUPPORT)
966     LBSLOGE(LOCATOR, "%{public}s: service unavailable", __func__);
967     return ERRCODE_NOT_SUPPORTED;
968 #endif
969     if (LocationDataRdbManager::QuerySwitchState() != ENABLED &&
970         !GetLocationSwitchIgnoredFlag(identity.GetTokenId())) {
971         ReportErrorStatus(callback, ERROR_SWITCH_UNOPEN);
972     }
973     // update offset before add request
974     if (reportManager_ == nullptr || requestManager_ == nullptr) {
975         return ERRCODE_SERVICE_UNAVAILABLE;
976     }
977     reportManager_->UpdateRandom();
978     std::shared_ptr<Request> request = std::make_shared<Request>(requestConfig, callback, identity);
979     sptr<IRemoteObject::DeathRecipient> death(new (std::nothrow) LocatorCallbackDeathRecipient(identity.GetTokenId()));
980     callback->AsObject()->AddDeathRecipient(death);
981     request->SetLocatorCallbackRecipient(death);
982     OHOS::Security::AccessToken::PermUsedTypeEnum type =
983         Security::AccessToken::AccessTokenKit::GetPermissionUsedType(request->GetTokenId(),
984         ACCESS_APPROXIMATELY_LOCATION);
985     request->SetPermUsedType(static_cast<int>(type));
986     if (requestConfig->GetScenario() != SCENE_NO_POWER &&
987         requestConfig->GetScenario() != LOCATION_SCENE_NO_POWER_CONSUMPTION &&
988         !reportManager_->IsCacheGnssLocationValid()) {
989         LocatorRequiredDataManager::GetInstance()->SendWifiScanEvent();
990     }
991 #ifdef EMULATOR_ENABLED
992     // for emulator, report cache location is unnecessary
993     HandleStartLocating(request, callback);
994 #else
995     if (NeedReportCacheLocation(request, callback)) {
996         if (requestConfig->GetScenario() != SCENE_NO_POWER &&
997             requestConfig->GetScenario() != LOCATION_SCENE_NO_POWER_CONSUMPTION) {
998             SelfRequestManager::GetInstance()->StartSelfRequest();
999         }
1000         callback->AsObject()->RemoveDeathRecipient(death);
1001     } else {
1002         HandleStartLocating(request, callback);
1003     }
1004 #endif
1005     return ERRCODE_SUCCESS;
1006 }
1007 
IsCacheVaildScenario(const sptr<RequestConfig> & requestConfig)1008 bool LocatorAbility::IsCacheVaildScenario(const sptr<RequestConfig>& requestConfig)
1009 {
1010     if ((requestConfig->GetPriority() == LOCATION_PRIORITY_LOCATING_SPEED) ||
1011         (requestConfig->GetScenario() == SCENE_DAILY_LIFE_SERVICE) ||
1012         (requestConfig->GetScenario() == LOCATION_SCENE_DAILY_LIFE_SERVICE) ||
1013         (requestConfig->GetScenario() == LOCATION_SCENE_LOW_POWER_CONSUMPTION) ||
1014         ((requestConfig->GetScenario() == SCENE_UNSET) && (requestConfig->GetPriority() == PRIORITY_FAST_FIRST_FIX)) ||
1015         ((requestConfig->GetScenario() == SCENE_UNSET) && (requestConfig->GetPriority() == PRIORITY_LOW_POWER))) {
1016         return true;
1017     }
1018     return false;
1019 }
1020 
IsSingleRequest(const sptr<RequestConfig> & requestConfig)1021 bool LocatorAbility::IsSingleRequest(const sptr<RequestConfig>& requestConfig)
1022 {
1023     if (requestConfig->GetFixNumber() == 1) {
1024         return true;
1025     }
1026     return false;
1027 }
1028 
UpdatePermissionUsedRecord(uint32_t tokenId,std::string permissionName,int permUsedType,int succCnt,int failCnt)1029 int LocatorAbility::UpdatePermissionUsedRecord(uint32_t tokenId, std::string permissionName,
1030     int permUsedType, int succCnt, int failCnt)
1031 {
1032     Security::AccessToken::AddPermParamInfo info;
1033     info.tokenId = tokenId;
1034     info.permissionName = permissionName;
1035     info.successCount = succCnt;
1036     info.failCount = failCnt;
1037     info.type = static_cast<OHOS::Security::AccessToken::PermissionUsedType>(permUsedType);
1038     int ret = Security::AccessToken::PrivacyKit::AddPermissionUsedRecord(info);
1039     return ret;
1040 }
1041 
NeedReportCacheLocation(const std::shared_ptr<Request> & request,sptr<ILocatorCallback> & callback)1042 bool LocatorAbility::NeedReportCacheLocation(const std::shared_ptr<Request>& request, sptr<ILocatorCallback>& callback)
1043 {
1044     if (reportManager_ == nullptr || requestManager_ == nullptr || request == nullptr || callback == nullptr ||
1045         !IsCacheVaildScenario(request->GetRequestConfig())) {
1046         return false;
1047     }
1048     uint32_t tokenId = request->GetTokenId();
1049     uint32_t firstTokenId = request->GetFirstTokenId();
1050     if (!PermissionManager::CheckLocationPermission(tokenId, firstTokenId) &&
1051         !PermissionManager::CheckApproximatelyPermission(tokenId, firstTokenId)) {
1052         RequestManager::GetInstance()->ReportLocationError(LOCATING_FAILED_LOCATION_PERMISSION_DENIED, request);
1053         LBSLOGI(LOCATOR, "CheckLocationPermission return false, tokenId=%{public}d", tokenId);
1054         return false;
1055     }
1056     std::string bundleName = request->GetPackageName();
1057     pid_t uid = request->GetUid();
1058     pid_t pid = request->GetPid();
1059     auto reportManager = ReportManager::GetInstance();
1060     if (reportManager != nullptr) {
1061         if (reportManager->IsAppBackground(bundleName, tokenId, request->GetTokenIdEx(), uid, pid) &&
1062             !PermissionManager::CheckBackgroundPermission(tokenId, firstTokenId)) {
1063             RequestManager::GetInstance()->ReportLocationError(LOCATING_FAILED_BACKGROUND_PERMISSION_DENIED, request);
1064             LBSLOGE(REPORT_MANAGER, "CheckBackgroundPermission return false, tokenId=%{public}d", tokenId);
1065             return false;
1066         }
1067     }
1068     // report cache location
1069     auto cacheLocation = reportManager_->GetCacheLocation(request);
1070     if (cacheLocation == nullptr) {
1071         return false;
1072     }
1073     if (IsSingleRequest(request->GetRequestConfig())) {
1074         return ReportSingleCacheLocation(request, callback, cacheLocation);
1075     } else {
1076         return ReportCacheLocation(request, callback, cacheLocation);
1077     }
1078 }
1079 
ReportSingleCacheLocation(const std::shared_ptr<Request> & request,sptr<ILocatorCallback> & callback,std::unique_ptr<Location> & cacheLocation)1080 bool LocatorAbility::ReportSingleCacheLocation(
1081     const std::shared_ptr<Request>& request, sptr<ILocatorCallback>& callback, std::unique_ptr<Location>& cacheLocation)
1082 {
1083     requestManager_->IncreaseWorkingPidsCount(request->GetPid());
1084     if (requestManager_->IsNeedStartUsingPermission(request->GetPid())) {
1085         int ret = PrivacyKit::StartUsingPermission(
1086             request->GetTokenId(), ACCESS_APPROXIMATELY_LOCATION, request->GetPid());
1087         if (ret != ERRCODE_SUCCESS && ret != Security::AccessToken::ERR_PERMISSION_ALREADY_START_USING &&
1088             IsHapCaller(request->GetTokenId())) {
1089             requestManager_->DecreaseWorkingPidsCount(request->GetPid());
1090             LBSLOGE(LOCATOR, "StartUsingPermission failed ret=%{public}d", ret);
1091             return false;
1092         }
1093     }
1094     // add location permission using record
1095     int recordResult = UpdatePermissionUsedRecord(request->GetTokenId(), ACCESS_APPROXIMATELY_LOCATION,
1096         request->GetPermUsedType(), 1, 0);
1097     if (recordResult != ERRCODE_SUCCESS && IsHapCaller(request->GetTokenId())) {
1098         requestManager_->DecreaseWorkingPidsCount(request->GetPid());
1099         LBSLOGE(LOCATOR, "UpdatePermissionUsedRecord failed ret=%{public}d", recordResult);
1100         return false;
1101     }
1102     LBSLOGI(LOCATOR, "report cache location to %{public}s, uuid: %{public}s",
1103         request->GetPackageName().c_str(), request->GetUuid().c_str());
1104     callback->OnLocationReport(cacheLocation);
1105     requestManager_->DecreaseWorkingPidsCount(request->GetPid());
1106     if (requestManager_->IsNeedStopUsingPermission(request->GetPid())) {
1107         PrivacyKit::StopUsingPermission(request->GetTokenId(), ACCESS_APPROXIMATELY_LOCATION, request->GetPid());
1108     }
1109     return true;
1110 }
1111 
ReportCacheLocation(const std::shared_ptr<Request> & request,sptr<ILocatorCallback> & callback,std::unique_ptr<Location> & cacheLocation)1112 bool LocatorAbility::ReportCacheLocation(
1113     const std::shared_ptr<Request>& request, sptr<ILocatorCallback>& callback, std::unique_ptr<Location>& cacheLocation)
1114 {
1115     // add location permission using record
1116     int ret = UpdatePermissionUsedRecord(request->GetTokenId(), ACCESS_APPROXIMATELY_LOCATION,
1117         request->GetPermUsedType(), 1, 0);
1118     if (ret != ERRCODE_SUCCESS && IsHapCaller(request->GetTokenId())) {
1119         LBSLOGE(LOCATOR, "UpdatePermissionUsedRecord failed ret=%{public}d", ret);
1120         return false;
1121     }
1122     LBSLOGI(LOCATOR, "report cache location to %{public}s, uuid: %{public}s",
1123         request->GetPackageName().c_str(), request->GetUuid().c_str());
1124     callback->OnLocationReport(cacheLocation);
1125     return false;
1126 }
1127 
HandleStartLocating(const std::shared_ptr<Request> & request,sptr<ILocatorCallback> & callback)1128 void LocatorAbility::HandleStartLocating(const std::shared_ptr<Request>& request, sptr<ILocatorCallback>& callback)
1129 {
1130     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1131         Get(EVENT_START_LOCATING, request);
1132     if (locatorHandler_ != nullptr) {
1133         locatorHandler_->SendEvent(event);
1134     }
1135     if (callback != nullptr) {
1136         ReportLocationStatus(callback, SESSION_START);
1137     }
1138 }
1139 
StopLocating(sptr<ILocatorCallback> & callback)1140 LocationErrCode LocatorAbility::StopLocating(sptr<ILocatorCallback>& callback)
1141 {
1142 #if !defined(FEATURE_GNSS_SUPPORT) && !defined(FEATURE_NETWORK_SUPPORT) && !defined(FEATURE_PASSIVE_SUPPORT)
1143     LBSLOGE(LOCATOR, "%{public}s: service unavailable", __func__);
1144     return ERRCODE_NOT_SUPPORTED;
1145 #endif
1146     if (requestManager_ == nullptr) {
1147         return ERRCODE_SERVICE_UNAVAILABLE;
1148     }
1149     std::unique_ptr<LocatorCallbackMessage> callbackMessage = std::make_unique<LocatorCallbackMessage>();
1150     callbackMessage->SetCallback(callback);
1151     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1152         Get(EVENT_STOP_LOCATING, callbackMessage);
1153     if (locatorHandler_ != nullptr) {
1154         locatorHandler_->SendEvent(event);
1155     }
1156     if (callback != nullptr) {
1157         ReportLocationStatus(callback, SESSION_STOP);
1158     }
1159     return ERRCODE_SUCCESS;
1160 }
1161 
GetCacheLocation(std::unique_ptr<Location> & loc,AppIdentity & identity)1162 LocationErrCode LocatorAbility::GetCacheLocation(std::unique_ptr<Location>& loc, AppIdentity &identity)
1163 {
1164     if (locatorHandler_ == nullptr) {
1165         return ERRCODE_SERVICE_UNAVAILABLE;
1166     }
1167     auto lastLocation = reportManager_->GetLastLocation();
1168     std::unique_ptr<RequestConfig> requestConfig = std::make_unique<RequestConfig>();
1169     sptr<ILocatorCallback> callback;
1170     std::shared_ptr<Request> request = std::make_shared<Request>(requestConfig, callback, identity);
1171     loc = reportManager_->GetPermittedLocation(request, lastLocation);
1172     std::shared_ptr<AppIdentity> identityInfo = std::make_shared<AppIdentity>(identity);
1173     if (loc == nullptr) {
1174         locatorHandler_->SendHighPriorityEvent(EVENT_GET_CACHED_LOCATION_FAILED, identityInfo, 0);
1175         return ERRCODE_LOCATING_CACHE_FAIL;
1176     }
1177     reportManager_->UpdateLocationByRequest(identity.GetTokenId(), identity.GetTokenIdEx(), loc);
1178     requestManager_->IncreaseWorkingPidsCount(identity.GetPid());
1179     if (requestManager_->IsNeedStartUsingPermission(identity.GetPid())) {
1180         int ret = PrivacyKit::StartUsingPermission(
1181             identity.GetTokenId(), ACCESS_APPROXIMATELY_LOCATION, identity.GetPid());
1182         if (ret != ERRCODE_SUCCESS && ret != Security::AccessToken::ERR_PERMISSION_ALREADY_START_USING &&
1183             IsHapCaller(request->GetTokenId())) {
1184             LBSLOGE(LOCATOR, "StartUsingPermission failed ret=%{public}d", ret);
1185             locatorHandler_->SendHighPriorityEvent(EVENT_GET_CACHED_LOCATION_FAILED, identityInfo, 0);
1186             return ERRCODE_LOCATING_FAIL;
1187         }
1188     }
1189     // add location permission using record
1190     LBSLOGW(REPORT_MANAGER, "report last location to %{public}d, TimeSinceBoot : %{public}s, SourceType : %{public}d",
1191             identity.GetTokenId(), std::to_string(loc->GetTimeSinceBoot()).c_str(),
1192             loc->GetLocationSourceType());
1193     locatorHandler_->SendHighPriorityEvent(EVENT_GET_CACHED_LOCATION_SUCCESS, identityInfo, 0);
1194     return ERRCODE_SUCCESS;
1195 }
1196 
ReportLocation(const std::unique_ptr<Location> & location,std::string abilityName,AppIdentity & identity)1197 LocationErrCode LocatorAbility::ReportLocation(
1198     const std::unique_ptr<Location>& location, std::string abilityName, AppIdentity &identity)
1199 {
1200     if (requests_ == nullptr) {
1201         return ERRCODE_SERVICE_UNAVAILABLE;
1202     }
1203     std::unique_ptr<LocationMessage> locationMessage = std::make_unique<LocationMessage>();
1204     locationMessage->SetAbilityName(abilityName);
1205     locationMessage->SetLocation(location);
1206     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1207         Get(EVENT_REPORT_LOCATION_MESSAGE, locationMessage);
1208     if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
1209         return ERRCODE_SUCCESS;
1210     }
1211     return ERRCODE_SERVICE_UNAVAILABLE;
1212 }
1213 
ReportLocationStatus(sptr<ILocatorCallback> & callback,int result)1214 LocationErrCode LocatorAbility::ReportLocationStatus(sptr<ILocatorCallback>& callback, int result)
1215 {
1216     int state = DISABLED;
1217     LocationErrCode errorCode = GetSwitchState(state);
1218     if (errorCode != ERRCODE_SUCCESS) {
1219         return errorCode;
1220     }
1221     if (state == DISABLED) {
1222         LBSLOGE(LOCATOR, "%{public}s line:%{public}d location switch is off",
1223             __func__, __LINE__);
1224         return ERRCODE_SWITCH_OFF;
1225     }
1226     if (reportManager_->ReportRemoteCallback(callback, ILocatorCallback::RECEIVE_LOCATION_STATUS_EVENT, result)) {
1227         return ERRCODE_SUCCESS;
1228     }
1229     return ERRCODE_SERVICE_UNAVAILABLE;
1230 }
1231 
ReportErrorStatus(sptr<ILocatorCallback> & callback,int result)1232 LocationErrCode LocatorAbility::ReportErrorStatus(sptr<ILocatorCallback>& callback, int result)
1233 {
1234     int state = DISABLED;
1235     LocationErrCode errorCode = GetSwitchState(state);
1236     if (errorCode != ERRCODE_SUCCESS) {
1237         return errorCode;
1238     }
1239     if (state == DISABLED) {
1240         LBSLOGE(LOCATOR, "%{public}s line:%{public}d location switch is off",
1241             __func__, __LINE__);
1242         return ERRCODE_SWITCH_OFF;
1243     }
1244     if (reportManager_->ReportRemoteCallback(callback, ILocatorCallback::RECEIVE_ERROR_INFO_EVENT, result)) {
1245         return ERRCODE_SUCCESS;
1246     }
1247     return ERRCODE_SERVICE_UNAVAILABLE;
1248 }
1249 
RegisterAction()1250 void LocatorAbility::RegisterAction()
1251 {
1252     if (isActionRegistered) {
1253         LBSLOGI(LOCATOR, "action has already registered");
1254         return;
1255     }
1256     OHOS::EventFwk::MatchingSkills matchingSkills;
1257     matchingSkills.AddEvent(MODE_CHANGED_EVENT);
1258     matchingSkills.AddEvent(OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED);
1259     matchingSkills.AddEvent(OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_SIM_STATE_CHANGED);
1260     OHOS::EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills);
1261     locatorEventSubscriber_ = std::make_shared<LocatorEventSubscriber>(subscriberInfo);
1262 
1263     bool result = OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(locatorEventSubscriber_);
1264     if (!result) {
1265         LBSLOGE(LOCATOR, "Failed to subscriber locator event, result = %{public}d", result);
1266         isActionRegistered = false;
1267     } else {
1268         LBSLOGI(LOCATOR, "success to subscriber locator event, result = %{public}d", result);
1269         isActionRegistered = true;
1270     }
1271 }
1272 
RegisterLocationPrivacyAction()1273 void LocatorAbility::RegisterLocationPrivacyAction()
1274 {
1275     if (isLocationPrivacyActionRegistered_) {
1276         LBSLOGI(LOCATOR, "location privacy action has already registered");
1277         return;
1278     }
1279     OHOS::EventFwk::MatchingSkills matchingSkills;
1280     matchingSkills.AddEvent(LOCATION_PRIVACY_ACCEPT_EVENT);
1281     matchingSkills.AddEvent(LOCATION_PRIVACY_REJECT_EVENT);
1282     OHOS::EventFwk::CommonEventSubscribeInfo subscriberInfo(matchingSkills);
1283     subscriberInfo.SetPermission("ohos.permission.PUBLISH_LOCATION_EVENT");
1284     locationPrivacyEventSubscriber_ = std::make_shared<LocatorEventSubscriber>(subscriberInfo);
1285 
1286     bool result = OHOS::EventFwk::CommonEventManager::SubscribeCommonEvent(locationPrivacyEventSubscriber_);
1287     if (!result) {
1288         LBSLOGE(LOCATOR, "Failed to subscriber location privacy event, result = %{public}d", result);
1289         isLocationPrivacyActionRegistered_ = false;
1290     } else {
1291         LBSLOGI(LOCATOR, "success to subscriber location privacy event, result = %{public}d", result);
1292         isLocationPrivacyActionRegistered_ = true;
1293     }
1294 }
1295 
1296 #ifdef FEATURE_GEOCODE_SUPPORT
IsGeoConvertAvailable(bool & isAvailable)1297 LocationErrCode LocatorAbility::IsGeoConvertAvailable(bool &isAvailable)
1298 {
1299     MessageParcel dataParcel;
1300     MessageParcel replyParcel;
1301     if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1302         isAvailable = false;
1303         return ERRCODE_SERVICE_UNAVAILABLE;
1304     }
1305     SendGeoRequest(static_cast<int>(LocatorInterfaceCode::GEO_IS_AVAILABLE), dataParcel, replyParcel);
1306     LocationErrCode errorCode = LocationErrCode(replyParcel.ReadInt32());
1307     if (errorCode == ERRCODE_SUCCESS) {
1308         isAvailable = replyParcel.ReadBool();
1309     } else {
1310         isAvailable = false;
1311     }
1312     return errorCode;
1313 }
1314 #endif
1315 
1316 #ifdef FEATURE_GEOCODE_SUPPORT
GetAddressByCoordinate(MessageParcel & data,MessageParcel & reply,std::string bundleName)1317 void LocatorAbility::GetAddressByCoordinate(MessageParcel &data, MessageParcel &reply, std::string bundleName)
1318 {
1319     MessageParcel dataParcel;
1320     auto requestTime = CommonUtils::GetCurrentTimeStamp();
1321     GeoCodeType requestType = GeoCodeType::REQUEST_REVERSE_GEOCODE;
1322     GeoConvertRequest::OrderParcel(data, dataParcel, requestType, bundleName);
1323     auto geoConvertRequest = GeoConvertRequest::Unmarshalling(dataParcel, requestType);
1324     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1325         Get(EVENT_SEND_GEOREQUEST, geoConvertRequest);
1326     if (locatorHandler_ != nullptr) {
1327         locatorHandler_->SendEvent(event);
1328     }
1329     int errorCode = reply.ReadInt32();
1330     WriteLocationInnerEvent(GEOCODE_REQUEST, {
1331         "type", "ReverseGeocode",
1332         "appName", bundleName,
1333         "subCode", std::to_string(errorCode),
1334         "requestTime", std::to_string(requestTime),
1335         "receiveTime", std::to_string(CommonUtils::GetCurrentTimeStamp()),
1336     });
1337     HookUtils::ExecuteHookWhenGetAddressFromLocation(bundleName);
1338     reply.RewindRead(0);
1339 }
1340 #endif
1341 
1342 #ifdef FEATURE_GEOCODE_SUPPORT
GetAddressByLocationName(MessageParcel & data,MessageParcel & reply,std::string bundleName)1343 void LocatorAbility::GetAddressByLocationName(MessageParcel &data, MessageParcel &reply, std::string bundleName)
1344 {
1345     MessageParcel dataParcel;
1346     auto requestTime = CommonUtils::GetCurrentTimeStamp();
1347     GeoCodeType requestType = GeoCodeType::REQUEST_GEOCODE;
1348     GeoConvertRequest::OrderParcel(data, dataParcel, requestType, bundleName);
1349     auto geoConvertRequest = GeoConvertRequest::Unmarshalling(dataParcel, requestType);
1350     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1351         Get(EVENT_SEND_GEOREQUEST, geoConvertRequest);
1352     if (locatorHandler_ != nullptr) {
1353         locatorHandler_->SendEvent(event);
1354     }
1355     int errorCode = reply.ReadInt32();
1356     WriteLocationInnerEvent(GEOCODE_REQUEST, {
1357         "type", "Geocode",
1358         "appName", bundleName,
1359         "subCode", std::to_string(errorCode),
1360         "requestTime", std::to_string(requestTime),
1361         "receiveTime", std::to_string(CommonUtils::GetCurrentTimeStamp()),
1362     });
1363     HookUtils::ExecuteHookWhenGetAddressFromLocationName(bundleName);
1364     reply.RewindRead(0);
1365 }
1366 #endif
1367 
1368 #ifdef FEATURE_GEOCODE_SUPPORT
SendGeoRequest(int type,MessageParcel & data,MessageParcel & reply)1369 LocationErrCode LocatorAbility::SendGeoRequest(int type, MessageParcel &data, MessageParcel &reply)
1370 {
1371     if (!SaLoadWithStatistic::InitLocationSa(LOCATION_GEO_CONVERT_SA_ID)) {
1372         reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
1373         return ERRCODE_SERVICE_UNAVAILABLE;
1374     }
1375     sptr<IRemoteObject> remoteObject = CommonUtils::GetRemoteObject(LOCATION_GEO_CONVERT_SA_ID,
1376         CommonUtils::InitDeviceId());
1377     if (remoteObject == nullptr) {
1378         reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
1379         return ERRCODE_SERVICE_UNAVAILABLE;
1380     }
1381     MessageOption option;
1382     remoteObject->SendRequest(type, data, reply, option);
1383     return ERRCODE_SUCCESS;
1384 }
1385 #endif
1386 
1387 #ifdef FEATURE_GEOCODE_SUPPORT
EnableReverseGeocodingMock()1388 LocationErrCode LocatorAbility::EnableReverseGeocodingMock()
1389 {
1390     MessageParcel dataParcel;
1391     MessageParcel replyParcel;
1392     if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1393         return ERRCODE_SERVICE_UNAVAILABLE;
1394     }
1395     SendGeoRequest(static_cast<int>(LocatorInterfaceCode::ENABLE_REVERSE_GEOCODE_MOCK), dataParcel, replyParcel);
1396     return LocationErrCode(replyParcel.ReadInt32());
1397 }
1398 #endif
1399 
1400 #ifdef FEATURE_GEOCODE_SUPPORT
DisableReverseGeocodingMock()1401 LocationErrCode LocatorAbility::DisableReverseGeocodingMock()
1402 {
1403     MessageParcel dataParcel;
1404     MessageParcel replyParcel;
1405     if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1406         return ERRCODE_SERVICE_UNAVAILABLE;
1407     }
1408     SendGeoRequest(static_cast<int>(LocatorInterfaceCode::DISABLE_REVERSE_GEOCODE_MOCK), dataParcel, replyParcel);
1409     return LocationErrCode(replyParcel.ReadInt32());
1410 }
1411 #endif
1412 
1413 #ifdef FEATURE_GEOCODE_SUPPORT
SetReverseGeocodingMockInfo(std::vector<std::shared_ptr<GeocodingMockInfo>> & mockInfo)1414 LocationErrCode LocatorAbility::SetReverseGeocodingMockInfo(std::vector<std::shared_ptr<GeocodingMockInfo>>& mockInfo)
1415 {
1416     MessageParcel dataParcel;
1417     MessageParcel replyParcel;
1418     if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
1419         return ERRCODE_SERVICE_UNAVAILABLE;
1420     }
1421     dataParcel.WriteInt32(mockInfo.size());
1422     for (size_t i = 0; i < mockInfo.size(); i++) {
1423         mockInfo[i]->Marshalling(dataParcel);
1424     }
1425     SendGeoRequest(static_cast<int>(LocatorInterfaceCode::SET_REVERSE_GEOCODE_MOCKINFO), dataParcel, replyParcel);
1426     return LocationErrCode(replyParcel.ReadInt32());
1427 }
1428 #endif
1429 
ProxyForFreeze(std::set<int> pidList,bool isProxy)1430 LocationErrCode LocatorAbility::ProxyForFreeze(std::set<int> pidList, bool isProxy)
1431 {
1432     ProxyFreezeManager::GetInstance()->ProxyForFreeze(pidList, isProxy);
1433     if (GetActiveRequestNum() <= 0) {
1434         LBSLOGD(LOCATOR, "no active request, do not refresh.");
1435         return ERRCODE_SUCCESS;
1436     }
1437     // for proxy uid update, should send message to refresh requests
1438     ApplyRequests(0);
1439     return ERRCODE_SUCCESS;
1440 }
1441 
ResetAllProxy()1442 LocationErrCode LocatorAbility::ResetAllProxy()
1443 {
1444     LBSLOGI(LOCATOR, "Start locator ResetAllProxy");
1445     ProxyFreezeManager::GetInstance()->ResetAllProxy();
1446     if (GetActiveRequestNum() <= 0) {
1447         LBSLOGD(LOCATOR, "no active request, do not refresh.");
1448         return ERRCODE_SUCCESS;
1449     }
1450     // for proxy uid update, should send message to refresh requests
1451     ApplyRequests(0);
1452     return ERRCODE_SUCCESS;
1453 }
1454 
RegisterPermissionCallback(const uint32_t callingTokenId,const std::vector<std::string> & permissionNameList)1455 void LocatorAbility::RegisterPermissionCallback(const uint32_t callingTokenId,
1456     const std::vector<std::string>& permissionNameList)
1457 {
1458     std::unique_lock<ffrt::mutex> lock(permissionMapMutex_);
1459     if (permissionMap_ == nullptr) {
1460         LBSLOGE(LOCATOR, "permissionMap is null.");
1461         return;
1462     }
1463     PermStateChangeScope scopeInfo;
1464     scopeInfo.permList = permissionNameList;
1465     scopeInfo.tokenIDs = {callingTokenId};
1466     auto callbackPtr = std::make_shared<PermissionStatusChangeCb>(scopeInfo);
1467     permissionMap_->erase(callingTokenId);
1468     if (permissionMap_->size() <= MAX_PERMISSION_NUM) {
1469         permissionMap_->insert(std::make_pair(callingTokenId, callbackPtr));
1470     } else {
1471         LBSLOGE(LOCATOR, "RegisterPermissionCallback num max");
1472         return;
1473     }
1474     LBSLOGD(LOCATOR, "after tokenId:%{public}d register, permission callback size:%{public}s",
1475         callingTokenId, std::to_string(permissionMap_->size()).c_str());
1476     int32_t res = AccessTokenKit::RegisterPermStateChangeCallback(callbackPtr);
1477     if (res != SUCCESS) {
1478         LBSLOGE(LOCATOR, "RegisterPermStateChangeCallback failed.");
1479     }
1480 }
1481 
UnregisterPermissionCallback(const uint32_t callingTokenId)1482 void LocatorAbility::UnregisterPermissionCallback(const uint32_t callingTokenId)
1483 {
1484     std::unique_lock<ffrt::mutex> lock(permissionMapMutex_);
1485     if (permissionMap_ == nullptr) {
1486         LBSLOGE(LOCATOR, "permissionMap is null.");
1487         return;
1488     }
1489     auto iter = permissionMap_->find(callingTokenId);
1490     if (iter != permissionMap_->end()) {
1491         auto callbackPtr = iter->second;
1492         int32_t res = AccessTokenKit::UnRegisterPermStateChangeCallback(callbackPtr);
1493         if (res != SUCCESS) {
1494             LBSLOGE(LOCATOR, "UnRegisterPermStateChangeCallback failed.");
1495         }
1496     }
1497     permissionMap_->erase(callingTokenId);
1498     LBSLOGD(LOCATOR, "after tokenId:%{public}d unregister, permission callback size:%{public}s",
1499         callingTokenId, std::to_string(permissionMap_->size()).c_str());
1500 }
1501 
ReportDataToResSched(std::string state)1502 void LocatorAbility::ReportDataToResSched(std::string state)
1503 {
1504 #ifdef RES_SCHED_SUPPROT
1505     std::unordered_map<std::string, std::string> payload;
1506     payload["state"] = state;
1507     uint32_t type = ResourceSchedule::ResType::RES_TYPE_LOCATION_STATUS_CHANGE;
1508     int64_t value =  ResourceSchedule::ResType::LocationStatus::LOCATION_SWTICH_CHANGE;
1509     ResourceSchedule::ResSchedClient::GetInstance().ReportData(type, value, payload);
1510 #endif
1511 }
1512 
1513 #ifdef FEATURE_GNSS_SUPPORT
QuerySupportCoordinateSystemType(std::vector<CoordinateSystemType> & coordinateSystemTypes)1514 LocationErrCode LocatorAbility::QuerySupportCoordinateSystemType(
1515     std::vector<CoordinateSystemType>& coordinateSystemTypes)
1516 {
1517     MessageParcel dataToStub;
1518     MessageParcel replyToStub;
1519     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
1520         return ERRCODE_SERVICE_UNAVAILABLE;
1521     }
1522     auto errCode = SendGnssRequest(
1523         static_cast<int>(GnssInterfaceCode::GET_GEOFENCE_SUPPORT_COORDINATE_SYSTEM_TYPE),
1524         dataToStub, replyToStub);
1525     if (errCode == ERRCODE_SUCCESS) {
1526         int size = replyToStub.ReadInt32();
1527         size = size > COORDINATE_SYSTEM_TYPE_SIZE ? COORDINATE_SYSTEM_TYPE_SIZE : size;
1528         for (int i = 0; i < size; i++) {
1529             int coordinateSystemType = replyToStub.ReadInt32();
1530             coordinateSystemTypes.push_back(static_cast<CoordinateSystemType>(coordinateSystemType));
1531         }
1532     }
1533     return errCode;
1534 }
1535 
SendNetworkLocation(const std::unique_ptr<Location> & location)1536 LocationErrCode LocatorAbility::SendNetworkLocation(const std::unique_ptr<Location>& location)
1537 {
1538     LBSLOGI(LOCATOR, "%{public}s: send network location", __func__);
1539     int64_t time = location->GetTimeStamp();
1540     int64_t timeSinceBoot = location->GetTimeSinceBoot();
1541     double acc = location->GetAccuracy();
1542     LBSLOGI(LOCATOR,
1543         "receive network location: [ time=%{public}s timeSinceBoot=%{public}s acc=%{public}f]",
1544         std::to_string(time).c_str(), std::to_string(timeSinceBoot).c_str(), acc);
1545     MessageParcel dataToStub;
1546     MessageParcel replyToStub;
1547     if (!dataToStub.WriteInterfaceToken(GnssAbilityProxy::GetDescriptor())) {
1548         return ERRCODE_SERVICE_UNAVAILABLE;
1549     }
1550     location->Marshalling(dataToStub);
1551     return SendGnssRequest(static_cast<int>(GnssInterfaceCode::SEND_NETWORK_LOCATION), dataToStub, replyToStub);
1552 }
1553 #endif
1554 
StartScanBluetoohDevice(sptr<IBluetoohScanResultCallback> & callback,AppIdentity & identity)1555 LocationErrCode LocatorAbility::StartScanBluetoohDevice(
1556     sptr<IBluetoohScanResultCallback>& callback, AppIdentity &identity)
1557 {
1558     if (callback == nullptr) {
1559         LBSLOGE(LOCATOR, "%{public}s.callback == nullptr", __func__);
1560     }
1561     std::unique_ptr<BluetoothScanResultCallbackMessage> callbackMessage =
1562         std::make_unique<BluetoothScanResultCallbackMessage>();
1563     callbackMessage->SetCallback(callback);
1564     callbackMessage->SetAppIdentity(identity);
1565     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1566         Get(EVENT_START_SCAN_BLUETOOH_DEVICE, callbackMessage);
1567     if (locatorHandler_ != nullptr) {
1568         locatorHandler_->SendEvent(event);
1569     }
1570     return ERRCODE_SUCCESS;
1571 }
1572 
StopScanBluetoohDevice(sptr<IBluetoohScanResultCallback> & callback,AppIdentity & identity)1573 LocationErrCode LocatorAbility::StopScanBluetoohDevice(
1574     sptr<IBluetoohScanResultCallback>& callback, AppIdentity &identity)
1575 {
1576     std::unique_ptr<BluetoothScanResultCallbackMessage> callbackMessage =
1577         std::make_unique<BluetoothScanResultCallbackMessage>();
1578     callbackMessage->SetCallback(callback);
1579     callbackMessage->SetAppIdentity(identity);
1580     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1581         Get(EVENT_STOP_SCAN_BLUETOOH_DEVICE, callbackMessage);
1582     if (locatorHandler_ != nullptr) {
1583         locatorHandler_->SendEvent(event);
1584     }
1585     return ERRCODE_SUCCESS;
1586 }
1587 
RegisterLocationError(sptr<ILocatorCallback> & callback,AppIdentity & identity)1588 LocationErrCode LocatorAbility::RegisterLocationError(sptr<ILocatorCallback>& callback, AppIdentity &identity)
1589 {
1590     std::unique_ptr<LocatorCallbackMessage> callbackMessage = std::make_unique<LocatorCallbackMessage>();
1591     callbackMessage->SetCallback(callback);
1592     callbackMessage->SetAppIdentity(identity);
1593     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1594         Get(EVENT_REG_LOCATION_ERROR, callbackMessage);
1595     if (locatorHandler_ != nullptr) {
1596         locatorHandler_->SendEvent(event);
1597     }
1598     return ERRCODE_SUCCESS;
1599 }
1600 
UnregisterLocationError(sptr<ILocatorCallback> & callback,AppIdentity & identity)1601 LocationErrCode LocatorAbility::UnregisterLocationError(sptr<ILocatorCallback>& callback, AppIdentity &identity)
1602 {
1603     std::unique_ptr<LocatorCallbackMessage> callbackMessage = std::make_unique<LocatorCallbackMessage>();
1604     callbackMessage->SetCallback(callback);
1605     callbackMessage->SetAppIdentity(identity);
1606     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1607         Get(EVENT_UNREG_LOCATION_ERROR, callbackMessage);
1608     if (locatorHandler_ != nullptr) {
1609         locatorHandler_->SendEvent(event);
1610     }
1611     return ERRCODE_SUCCESS;
1612 }
1613 
SetLocationSwitchIgnored(bool isEnabled,AppIdentity & identity)1614 LocationErrCode LocatorAbility::SetLocationSwitchIgnored(bool isEnabled, AppIdentity &identity)
1615 {
1616     LBSLOGI(LOCATOR, "SetLocationSwitchIgnored %{public}d", isEnabled);
1617     SetLocationSwitchIgnoredFlag(identity.GetTokenId(), isEnabled);
1618     return ERRCODE_SUCCESS;
1619 }
1620 
ReportLocationError(std::string uuid,int32_t errCode,int32_t netErrCode)1621 void LocatorAbility::ReportLocationError(std::string uuid, int32_t errCode, int32_t netErrCode)
1622 {
1623     std::unique_ptr<LocatorErrorMessage> locatorErrorMessage = std::make_unique<LocatorErrorMessage>();
1624     locatorErrorMessage->SetUuid(uuid);
1625     locatorErrorMessage->SetErrCode(errCode);
1626     locatorErrorMessage->SetNetErrCode(netErrCode);
1627     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1628         Get(EVENT_REPORT_LOCATION_ERROR, locatorErrorMessage);
1629     if (locatorHandler_ != nullptr) {
1630         locatorHandler_->SendEvent(event);
1631     }
1632 }
1633 
RemoveInvalidRequests()1634 LocationErrCode LocatorAbility::RemoveInvalidRequests()
1635 {
1636     std::list<std::shared_ptr<Request>> invalidRequestList;
1637     int32_t requestNum = 0;
1638     int32_t invalidRequestNum = 0;
1639     {
1640         std::unique_lock<ffrt::mutex> lock(requestsMutex_);
1641 #ifdef FEATURE_GNSS_SUPPORT
1642         auto gpsListIter = requests_->find(GNSS_ABILITY);
1643         if (gpsListIter != requests_->end()) {
1644             auto list = &(gpsListIter->second);
1645             requestNum += static_cast<int>(list->size());
1646             for (auto& item : *list) {
1647                 if (IsInvalidRequest(item)) {
1648                     invalidRequestList.push_back(item);
1649                     invalidRequestNum++;
1650                 }
1651             }
1652         }
1653 #endif
1654 #ifdef FEATURE_NETWORK_SUPPORT
1655         auto networkListIter = requests_->find(NETWORK_ABILITY);
1656         if (networkListIter != requests_->end()) {
1657             auto list = &(networkListIter->second);
1658             requestNum += static_cast<int>(list->size());
1659             for (auto& item : *list) {
1660                 if (IsInvalidRequest(item)) {
1661                     invalidRequestList.push_back(item);
1662                     invalidRequestNum++;
1663                 }
1664             }
1665         }
1666 #endif
1667     }
1668     LBSLOGI(LOCATOR, "request num : %{public}d, invalid request num: %{public}d", requestNum, invalidRequestNum);
1669     if (invalidRequestList.size() > INVALID_REQUESTS_SIZE) {
1670         return ERRCODE_SUCCESS;
1671     }
1672     for (auto& item : invalidRequestList) {
1673         sptr<ILocatorCallback> callback = item->GetLocatorCallBack();
1674         StopLocating(callback);
1675     }
1676     return ERRCODE_SUCCESS;
1677 }
1678 
IsInvalidRequest(std::shared_ptr<Request> & request)1679 bool LocatorAbility::IsInvalidRequest(std::shared_ptr<Request>& request)
1680 {
1681     LBSLOGI(LOCATOR, "request : %{public}s %{public}s", request->GetPackageName().c_str(),
1682         request->GetRequestConfig()->ToString().c_str());
1683     int64_t timeDiff = fabs(CommonUtils::GetCurrentTime() - request->GetRequestConfig()->GetTimeStamp());
1684     if (request->GetRequestConfig()->GetFixNumber() == 1 &&
1685         timeDiff > (request->GetRequestConfig()->GetTimeOut() / MILLI_PER_SEC)) {
1686         LBSLOGI(LOCATOR, "once request is timeout");
1687         return true;
1688     }
1689 
1690     if (timeDiff > REQUEST_DEFAULT_TIMEOUT_SECOUND && !IsProcessRunning(request->GetPid(), request->GetTokenId())) {
1691         LBSLOGI(LOCATOR, "request process is not running");
1692         return true;
1693     }
1694     return false;
1695 }
1696 
IsProcessRunning(pid_t pid,const uint32_t tokenId)1697 bool LocatorAbility::IsProcessRunning(pid_t pid, const uint32_t tokenId)
1698 {
1699     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
1700     if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) {
1701         return true;
1702     }
1703     sptr<ISystemAbilityManager> samgrClient = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1704     if (samgrClient == nullptr) {
1705         LBSLOGE(LOCATOR, "Get system ability manager failed.");
1706         return true;
1707     }
1708     sptr<AppExecFwk::IAppMgr> iAppManager =
1709         iface_cast<AppExecFwk::IAppMgr>(samgrClient->GetSystemAbility(APP_MGR_SERVICE_ID));
1710     if (iAppManager == nullptr) {
1711         LBSLOGE(LOCATOR, "Failed to get ability manager service.");
1712         return true;
1713     }
1714     std::vector<AppExecFwk::RunningProcessInfo> runningProcessList;
1715     int32_t res = iAppManager->GetAllRunningProcesses(runningProcessList);
1716     if (res != ERR_OK) {
1717         LBSLOGE(LOCATOR, "Failed to get all running process.");
1718         return true;
1719     }
1720     auto it = std::find_if(runningProcessList.begin(), runningProcessList.end(), [pid] (auto runningProcessInfo) {
1721         return pid == runningProcessInfo.pid_;
1722     });
1723     if (it != runningProcessList.end()) {
1724         LBSLOGD(LOCATOR, "process : %{public}d is found.", pid);
1725         return true;
1726     }
1727     return false;
1728 }
1729 
SyncStillMovementState(bool state)1730 void LocatorAbility::SyncStillMovementState(bool state)
1731 {
1732     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1733         Get(EVENT_SYNC_STILL_MOVEMENT_STATE, state);
1734     if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
1735         LBSLOGD(LOCATOR, "%{public}s: EVENT_SYNC_MOVEMENT_STATE Send Success", __func__);
1736     }
1737 }
1738 
IsHapCaller(const uint32_t tokenId)1739 bool LocatorAbility::IsHapCaller(const uint32_t tokenId)
1740 {
1741     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
1742     if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) {
1743         return true;
1744     }
1745     return false;
1746 }
1747 
SyncIdleState(bool state)1748 void LocatorAbility::SyncIdleState(bool state)
1749 {
1750     AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::
1751         Get(EVENT_SYNC_IDLE_STATE, state);
1752     if (locatorHandler_ != nullptr && locatorHandler_->SendEvent(event)) {
1753         LBSLOGD(LOCATOR, "%{public}s: EVENT_SYNC_IDLE_STATE Send Success", __func__);
1754     }
1755 }
1756 
SetLocationSwitchIgnoredFlag(uint32_t tokenId,bool enable)1757 void LocatorAbility::SetLocationSwitchIgnoredFlag(uint32_t tokenId, bool enable)
1758 {
1759     std::unique_lock<std::mutex> lock(LocationSwitchIgnoredFlagMutex_);
1760     LBSLOGD(LOCATOR, "SetLocationSwitchIgnoredFlag enable = %{public}d", enable);
1761     AppSwitchIgnoredState appSwitchIgnoredState;
1762     appSwitchIgnoredState.state = enable;
1763     appSwitchIgnoredState.timeSinceBoot = CommonUtils::GetSinceBootTime();
1764     if (enable) {
1765         locationSettingsIgnoredFlagMap_[tokenId] = appSwitchIgnoredState;
1766         ApplyRequests(LOCATION_SWITCH_IGNORED_STATE_VALID_TIME / MILLI_PER_SEC);
1767     } else {
1768         auto iter = locationSettingsIgnoredFlagMap_.find(tokenId);
1769         if (iter != locationSettingsIgnoredFlagMap_.end()) {
1770             locationSettingsIgnoredFlagMap_.erase(iter);
1771             ApplyRequests(0);
1772         }
1773     }
1774 }
1775 
GetLocationSwitchIgnoredFlag(uint32_t tokenId)1776 bool LocatorAbility::GetLocationSwitchIgnoredFlag(uint32_t tokenId)
1777 {
1778     std::unique_lock<std::mutex> lock(LocationSwitchIgnoredFlagMutex_);
1779     auto iter = locationSettingsIgnoredFlagMap_.find(tokenId);
1780     if (iter == locationSettingsIgnoredFlagMap_.end()) {
1781         return false;
1782     }
1783     AppSwitchIgnoredState appSwitchIgnoredState = iter->second;
1784     if ((CommonUtils::GetSinceBootTime()- appSwitchIgnoredState.timeSinceBoot) / NANOS_PER_MICRO / MICRO_PER_MILLI >
1785         LOCATION_SWITCH_IGNORED_STATE_VALID_TIME) {
1786         locationSettingsIgnoredFlagMap_.erase(iter);
1787         return false;
1788     }
1789     LBSLOGD(LOCATOR, "GetLocationSwitchIgnoredFlag enable = %{public}d", appSwitchIgnoredState.state);
1790     return appSwitchIgnoredState.state;
1791 }
1792 
SetAbilityName(std::string abilityName)1793 void LocationMessage::SetAbilityName(std::string abilityName)
1794 {
1795     abilityName_ = abilityName;
1796 }
1797 
GetAbilityName()1798 std::string LocationMessage::GetAbilityName()
1799 {
1800     return abilityName_;
1801 }
1802 
SetLocation(const std::unique_ptr<Location> & location)1803 void LocationMessage::SetLocation(const std::unique_ptr<Location>& location)
1804 {
1805     if (location != nullptr) {
1806         location_ = std::make_unique<Location>(*location);
1807     }
1808 }
1809 
GetLocation()1810 std::unique_ptr<Location> LocationMessage::GetLocation()
1811 {
1812     if (location_ != nullptr) {
1813         return std::make_unique<Location>(*location_);
1814     } else {
1815         return nullptr;
1816     }
1817 }
1818 
SetCallback(const sptr<ILocatorCallback> & callback)1819 void LocatorCallbackMessage::SetCallback(const sptr<ILocatorCallback>& callback)
1820 {
1821     callback_ = callback;
1822 }
1823 
GetCallback()1824 sptr<ILocatorCallback> LocatorCallbackMessage::GetCallback()
1825 {
1826     return callback_;
1827 }
1828 
SetAppIdentity(AppIdentity & appIdentity)1829 void LocatorCallbackMessage::SetAppIdentity(AppIdentity& appIdentity)
1830 {
1831     appIdentity_ = appIdentity;
1832 }
1833 
GetAppIdentity()1834 AppIdentity LocatorCallbackMessage::GetAppIdentity()
1835 {
1836     return appIdentity_;
1837 }
1838 
SetCallback(const sptr<IBluetoohScanResultCallback> & callback)1839 void BluetoothScanResultCallbackMessage::SetCallback(const sptr<IBluetoohScanResultCallback>& callback)
1840 {
1841     callback_ = callback;
1842 }
1843 
GetCallback()1844 sptr<IBluetoohScanResultCallback> BluetoothScanResultCallbackMessage::GetCallback()
1845 {
1846     return callback_;
1847 }
1848 
SetAppIdentity(AppIdentity & appIdentity)1849 void BluetoothScanResultCallbackMessage::SetAppIdentity(AppIdentity& appIdentity)
1850 {
1851     appIdentity_ = appIdentity;
1852 }
1853 
GetAppIdentity()1854 AppIdentity BluetoothScanResultCallbackMessage::GetAppIdentity()
1855 {
1856     return appIdentity_;
1857 }
1858 
SetUuid(std::string uuid)1859 void LocatorErrorMessage::SetUuid(std::string uuid)
1860 {
1861     uuid_ = uuid;
1862 }
1863 
GetUuid()1864 std::string LocatorErrorMessage::GetUuid()
1865 {
1866     return uuid_;
1867 }
1868 
SetErrCode(int32_t errCode)1869 void LocatorErrorMessage::SetErrCode(int32_t errCode)
1870 {
1871     errCode_ = errCode;
1872 }
1873 
GetErrCode()1874 int32_t LocatorErrorMessage::GetErrCode()
1875 {
1876     return errCode_;
1877 }
1878 
SetNetErrCode(int32_t netErrCode)1879 void LocatorErrorMessage::SetNetErrCode(int32_t netErrCode)
1880 {
1881     netErrCode_ = netErrCode;
1882 }
1883 
GetNetErrCode()1884 int32_t LocatorErrorMessage::GetNetErrCode()
1885 {
1886     return netErrCode_;
1887 }
1888 
SetUserId(int32_t userId)1889 void LocatorSwitchMessage::SetUserId(int32_t userId)
1890 {
1891     userId_ = userId;
1892 }
1893 
GetUserId()1894 int32_t LocatorSwitchMessage::GetUserId()
1895 {
1896     return userId_;
1897 }
1898 
SetModeValue(int32_t modeValue)1899 void LocatorSwitchMessage::SetModeValue(int32_t modeValue)
1900 {
1901     modeValue_ = modeValue;
1902 }
1903 
GetModeValue()1904 int32_t LocatorSwitchMessage::GetModeValue()
1905 {
1906     return modeValue_;
1907 }
1908 
LocatorHandler(const std::shared_ptr<AppExecFwk::EventRunner> & runner)1909 LocatorHandler::LocatorHandler(const std::shared_ptr<AppExecFwk::EventRunner>& runner) : EventHandler(runner)
1910 {
1911     InitLocatorHandlerEventMap();
1912 }
1913 
~LocatorHandler()1914 LocatorHandler::~LocatorHandler() {}
1915 
InitLocatorHandlerEventMap()1916 void LocatorHandler::InitLocatorHandlerEventMap()
1917 {
1918     if (locatorHandlerEventMap_.size() != 0) {
1919         return;
1920     }
1921     locatorHandlerEventMap_[EVENT_UPDATE_SA] =
1922         [this](const AppExecFwk::InnerEvent::Pointer& event) { UpdateSaEvent(event); };
1923     locatorHandlerEventMap_[EVENT_INIT_REQUEST_MANAGER] =
1924         [this](const AppExecFwk::InnerEvent::Pointer& event) { InitRequestManagerEvent(event); };
1925     locatorHandlerEventMap_[EVENT_APPLY_REQUIREMENTS] =
1926         [this](const AppExecFwk::InnerEvent::Pointer& event) { ApplyRequirementsEvent(event); };
1927     locatorHandlerEventMap_[EVENT_RETRY_REGISTER_ACTION] =
1928         [this](const AppExecFwk::InnerEvent::Pointer& event) { RetryRegisterActionEvent(event); };
1929     locatorHandlerEventMap_[EVENT_REPORT_LOCATION_MESSAGE] =
1930         [this](const AppExecFwk::InnerEvent::Pointer& event) { ReportLocationMessageEvent(event); };
1931     locatorHandlerEventMap_[EVENT_SEND_SWITCHSTATE_TO_HIFENCE] =
1932         [this](const AppExecFwk::InnerEvent::Pointer& event) { SendSwitchStateToHifenceEvent(event); };
1933     locatorHandlerEventMap_[EVENT_START_LOCATING] =
1934         [this](const AppExecFwk::InnerEvent::Pointer& event) { StartLocatingEvent(event); };
1935     locatorHandlerEventMap_[EVENT_STOP_LOCATING] =
1936         [this](const AppExecFwk::InnerEvent::Pointer& event) { StopLocatingEvent(event); };
1937     locatorHandlerEventMap_[EVENT_UNLOAD_SA] =
1938         [this](const AppExecFwk::InnerEvent::Pointer& event) { UnloadSaEvent(event); };
1939     locatorHandlerEventMap_[EVENT_GET_CACHED_LOCATION_SUCCESS] =
1940         [this](const AppExecFwk::InnerEvent::Pointer& event) { GetCachedLocationSuccess(event); };
1941     locatorHandlerEventMap_[EVENT_GET_CACHED_LOCATION_FAILED] =
1942         [this](const AppExecFwk::InnerEvent::Pointer& event) { GetCachedLocationFailed(event); };
1943     locatorHandlerEventMap_[EVENT_REG_LOCATION_ERROR] =
1944         [this](const AppExecFwk::InnerEvent::Pointer& event) { RegLocationErrorEvent(event); };
1945     locatorHandlerEventMap_[EVENT_UNREG_LOCATION_ERROR] =
1946         [this](const AppExecFwk::InnerEvent::Pointer& event) { UnRegLocationErrorEvent(event); };
1947     locatorHandlerEventMap_[EVENT_REPORT_LOCATION_ERROR] =
1948         [this](const AppExecFwk::InnerEvent::Pointer& event) { ReportNetworkLocatingErrorEvent(event); };
1949     locatorHandlerEventMap_[EVENT_PERIODIC_CHECK] =
1950         [this](const AppExecFwk::InnerEvent::Pointer& event) { RequestCheckEvent(event); };
1951     locatorHandlerEventMap_[EVENT_SYNC_LOCATION_STATUS] =
1952         [this](const AppExecFwk::InnerEvent::Pointer& event) { SyncSwitchStatus(event); };
1953     locatorHandlerEventMap_[EVENT_SYNC_STILL_MOVEMENT_STATE] =
1954         [this](const AppExecFwk::InnerEvent::Pointer& event) { SyncStillMovementState(event); };
1955     locatorHandlerEventMap_[EVENT_SYNC_IDLE_STATE] =
1956         [this](const AppExecFwk::InnerEvent::Pointer& event) { SyncIdleState(event); };
1957     locatorHandlerEventMap_[EVENT_INIT_MSDP_MONITOR_MANAGER] =
1958         [this](const AppExecFwk::InnerEvent::Pointer& event) { InitMonitorManagerEvent(event); };
1959     locatorHandlerEventMap_[EVENT_IS_STAND_BY] =
1960         [this](const AppExecFwk::InnerEvent::Pointer& event) { IsStandByEvent(event); };
1961     ConstructDbHandleMap();
1962     ConstructGeocodeHandleMap();
1963     ConstructBluetoohScanHandleMap();
1964 }
1965 
ConstructGeocodeHandleMap()1966 void LocatorHandler::ConstructGeocodeHandleMap()
1967 {
1968     locatorHandlerEventMap_[EVENT_SEND_GEOREQUEST] =
1969         [this](const AppExecFwk::InnerEvent::Pointer& event) { SendGeoRequestEvent(event); };
1970 }
1971 
ConstructDbHandleMap()1972 void LocatorHandler::ConstructDbHandleMap()
1973 {
1974     locatorHandlerEventMap_[EVENT_SET_LOCATION_WORKING_STATE] =
1975         [this](const AppExecFwk::InnerEvent::Pointer& event) { SetLocationWorkingStateEvent(event); };
1976     locatorHandlerEventMap_[EVENT_SET_SWITCH_STATE_TO_DB] =
1977         [this](const AppExecFwk::InnerEvent::Pointer& event) { SetSwitchStateToDbEvent(event); };
1978     locatorHandlerEventMap_[EVENT_SET_SWITCH_STATE_TO_DB_BY_USERID] =
1979         [this](const AppExecFwk::InnerEvent::Pointer& event) { SetSwitchStateToDbForUserEvent(event); };
1980     locatorHandlerEventMap_[EVENT_WATCH_SWITCH_PARAMETER] =
1981         [this](const AppExecFwk::InnerEvent::Pointer& event) { WatchSwitchParameter(event); };
1982 }
1983 
ConstructBluetoohScanHandleMap()1984 void LocatorHandler::ConstructBluetoohScanHandleMap()
1985 {
1986     locatorHandlerEventMap_[EVENT_START_SCAN_BLUETOOH_DEVICE] =
1987         [this](const AppExecFwk::InnerEvent::Pointer& event) { StartScanBluetoohDeviceEvent(event); };
1988     locatorHandlerEventMap_[EVENT_STOP_SCAN_BLUETOOH_DEVICE] =
1989         [this](const AppExecFwk::InnerEvent::Pointer& event) { StopScanBluetoohDeviceEvent(event); };
1990 }
1991 
GetCachedLocationSuccess(const AppExecFwk::InnerEvent::Pointer & event)1992 void LocatorHandler::GetCachedLocationSuccess(const AppExecFwk::InnerEvent::Pointer& event)
1993 {
1994     std::shared_ptr<AppIdentity> identity = event->GetSharedObject<AppIdentity>();
1995     if (identity == nullptr) {
1996         LBSLOGE(LOCATOR, "%{public}s get identity failed", __func__);
1997         return;
1998     }
1999     int64_t tokenId = identity->GetTokenId();
2000     OHOS::Security::AccessToken::PermUsedTypeEnum type =
2001         Security::AccessToken::AccessTokenKit::GetPermissionUsedType(tokenId, ACCESS_APPROXIMATELY_LOCATION);
2002     auto locatorAbility = LocatorAbility::GetInstance();
2003     int ret;
2004     if (locatorAbility != nullptr) {
2005         ret = locatorAbility->UpdatePermissionUsedRecord(tokenId, ACCESS_APPROXIMATELY_LOCATION,
2006             static_cast<int>(type), 1, 0);
2007         LBSLOGD(LOCATOR, "UpdatePermissionUsedRecord, ret=%{public}d", ret);
2008     }
2009     auto requestManager = RequestManager::GetInstance();
2010     requestManager->DecreaseWorkingPidsCount(identity->GetPid());
2011     if (requestManager->IsNeedStopUsingPermission(identity->GetPid())) {
2012         ret = PrivacyKit::StopUsingPermission(tokenId, ACCESS_APPROXIMATELY_LOCATION, identity->GetPid());
2013         LBSLOGD(LOCATOR, "StopUsingPermission, ret=%{public}d", ret);
2014     }
2015 }
2016 
GetCachedLocationFailed(const AppExecFwk::InnerEvent::Pointer & event)2017 void LocatorHandler::GetCachedLocationFailed(const AppExecFwk::InnerEvent::Pointer& event)
2018 {
2019     std::shared_ptr<AppIdentity> identity = event->GetSharedObject<AppIdentity>();
2020     if (identity == nullptr) {
2021         LBSLOGE(LOCATOR, "%{public}s get identity failed", __func__);
2022         return;
2023     }
2024     int64_t tokenId = identity->GetTokenId();
2025     OHOS::Security::AccessToken::PermUsedTypeEnum type =
2026         Security::AccessToken::AccessTokenKit::GetPermissionUsedType(tokenId, ACCESS_APPROXIMATELY_LOCATION);
2027     auto locatorAbility = LocatorAbility::GetInstance();
2028     int ret;
2029     if (locatorAbility != nullptr) {
2030         ret = locatorAbility->UpdatePermissionUsedRecord(tokenId, ACCESS_APPROXIMATELY_LOCATION,
2031             static_cast<int>(type), 0, 1);
2032         LBSLOGD(LOCATOR, "UpdatePermissionUsedRecord, ret=%{public}d", ret);
2033     }
2034     auto requestManager = RequestManager::GetInstance();
2035     requestManager->DecreaseWorkingPidsCount(identity->GetPid());
2036     if (requestManager->IsNeedStopUsingPermission(identity->GetPid())) {
2037         ret = PrivacyKit::StopUsingPermission(tokenId, ACCESS_APPROXIMATELY_LOCATION, identity->GetPid());
2038         LBSLOGD(LOCATOR, "StopUsingPermission, ret=%{public}d", ret);
2039     }
2040 }
2041 
UpdateSaEvent(const AppExecFwk::InnerEvent::Pointer & event)2042 void LocatorHandler::UpdateSaEvent(const AppExecFwk::InnerEvent::Pointer& event)
2043 {
2044     auto locatorAbility = LocatorAbility::GetInstance();
2045     if (locatorAbility != nullptr) {
2046         locatorAbility->UpdateSaAbilityHandler();
2047     }
2048 }
2049 
InitRequestManagerEvent(const AppExecFwk::InnerEvent::Pointer & event)2050 void LocatorHandler::InitRequestManagerEvent(const AppExecFwk::InnerEvent::Pointer& event)
2051 {
2052     auto requestManager = RequestManager::GetInstance();
2053     if (!requestManager->InitSystemListeners()) {
2054         LBSLOGE(LOCATOR, "InitSystemListeners failed");
2055     }
2056 }
2057 
ApplyRequirementsEvent(const AppExecFwk::InnerEvent::Pointer & event)2058 void LocatorHandler::ApplyRequirementsEvent(const AppExecFwk::InnerEvent::Pointer& event)
2059 {
2060     auto requestManager = RequestManager::GetInstance();
2061     if (requestManager != nullptr) {
2062         requestManager->HandleRequest();
2063     }
2064 }
2065 
RetryRegisterActionEvent(const AppExecFwk::InnerEvent::Pointer & event)2066 void LocatorHandler::RetryRegisterActionEvent(const AppExecFwk::InnerEvent::Pointer& event)
2067 {
2068     auto locatorAbility = LocatorAbility::GetInstance();
2069     if (locatorAbility != nullptr) {
2070         locatorAbility->RegisterAction();
2071         locatorAbility->RegisterLocationPrivacyAction();
2072     }
2073 }
2074 
ReportLocationMessageEvent(const AppExecFwk::InnerEvent::Pointer & event)2075 void LocatorHandler::ReportLocationMessageEvent(const AppExecFwk::InnerEvent::Pointer& event)
2076 {
2077     auto reportManager = ReportManager::GetInstance();
2078     if (reportManager != nullptr) {
2079         std::unique_ptr<LocationMessage> locationMessage = event->GetUniqueObject<LocationMessage>();
2080         if (locationMessage == nullptr) {
2081             return;
2082         }
2083         std::unique_ptr<Location> location = locationMessage->GetLocation();
2084         std::string abilityName = locationMessage->GetAbilityName();
2085         int64_t time = location->GetTimeStamp();
2086         int64_t timeSinceBoot = location->GetTimeSinceBoot();
2087         double acc = location->GetAccuracy();
2088         LBSLOGW(LOCATOR,
2089             "receive location: [%{public}s time=%{public}s timeSinceBoot=%{public}s acc=%{public}f]",
2090             abilityName.c_str(), std::to_string(time).c_str(), std::to_string(timeSinceBoot).c_str(), acc);
2091         reportManager->OnReportLocation(location, abilityName);
2092         if (abilityName == NETWORK_ABILITY || abilityName == GNSS_ABILITY) {
2093             reportManager->OnReportLocation(location, PASSIVE_ABILITY);
2094         }
2095     }
2096 }
2097 
SendSwitchStateToHifenceEvent(const AppExecFwk::InnerEvent::Pointer & event)2098 void LocatorHandler::SendSwitchStateToHifenceEvent(const AppExecFwk::InnerEvent::Pointer& event)
2099 {
2100     auto locatorAbility = LocatorAbility::GetInstance();
2101     if (locatorAbility != nullptr) {
2102         int state = event->GetParam();
2103         if (!SaLoadWithStatistic::InitLocationSa(COMMON_SA_ID)) {
2104             return;
2105         }
2106         MessageParcel data;
2107         MessageParcel reply;
2108         MessageOption option;
2109         if (!data.WriteInterfaceToken(COMMON_DESCRIPTION)) {
2110             return;
2111         }
2112         data.WriteInt32(state);
2113         sptr<IRemoteObject> object =
2114                 CommonUtils::GetRemoteObject(COMMON_SA_ID, CommonUtils::InitDeviceId());
2115         if (object == nullptr) {
2116             return;
2117         }
2118         object->SendRequest(COMMON_SWITCH_STATE_ID, data, reply, option);
2119     }
2120 }
2121 
StartLocatingEvent(const AppExecFwk::InnerEvent::Pointer & event)2122 void LocatorHandler::StartLocatingEvent(const AppExecFwk::InnerEvent::Pointer& event)
2123 {
2124     auto requestManager = RequestManager::GetInstance();
2125     std::shared_ptr<Request> request = event->GetSharedObject<Request>();
2126     if (request == nullptr) {
2127         return;
2128     }
2129     if (requestManager != nullptr) {
2130         HookUtils::ExecuteHookWhenStartLocation(request);
2131         requestManager->HandleStartLocating(request);
2132     }
2133 }
2134 
StopLocatingEvent(const AppExecFwk::InnerEvent::Pointer & event)2135 void LocatorHandler::StopLocatingEvent(const AppExecFwk::InnerEvent::Pointer& event)
2136 {
2137     auto requestManager = RequestManager::GetInstance();
2138     std::unique_ptr<LocatorCallbackMessage> callbackMessage = event->GetUniqueObject<LocatorCallbackMessage>();
2139     if (callbackMessage == nullptr) {
2140         return;
2141     }
2142     if (requestManager != nullptr) {
2143         requestManager->HandleStopLocating(callbackMessage->GetCallback());
2144     }
2145 }
2146 
UnloadSaEvent(const AppExecFwk::InnerEvent::Pointer & event)2147 void LocatorHandler::UnloadSaEvent(const AppExecFwk::InnerEvent::Pointer& event)
2148 {
2149     auto locationSaLoadManager = LocationSaLoadManager::GetInstance();
2150     if (locationSaLoadManager != nullptr) {
2151         locationSaLoadManager->UnloadLocationSa(LOCATION_LOCATOR_SA_ID);
2152     }
2153 }
2154 
StartScanBluetoohDeviceEvent(const AppExecFwk::InnerEvent::Pointer & event)2155 void LocatorHandler::StartScanBluetoohDeviceEvent(const AppExecFwk::InnerEvent::Pointer& event)
2156 {
2157     std::unique_ptr<BluetoothScanResultCallbackMessage> callbackMessage =
2158         event->GetUniqueObject<BluetoothScanResultCallbackMessage>();
2159     if (callbackMessage == nullptr) {
2160         return;
2161     }
2162     LocatorRequiredDataManager::GetInstance()->StartScanBluetoohDevice(
2163         callbackMessage->GetCallback(), callbackMessage->GetAppIdentity());
2164 }
2165 
StopScanBluetoohDeviceEvent(const AppExecFwk::InnerEvent::Pointer & event)2166 void LocatorHandler::StopScanBluetoohDeviceEvent(const AppExecFwk::InnerEvent::Pointer& event)
2167 {
2168     std::unique_ptr<BluetoothScanResultCallbackMessage> callbackMessage =
2169         event->GetUniqueObject<BluetoothScanResultCallbackMessage>();
2170     if (callbackMessage == nullptr) {
2171         return;
2172     }
2173     LocatorRequiredDataManager::GetInstance()->StopScanBluetoohDevice(callbackMessage->GetCallback()->AsObject());
2174 }
2175 
RegLocationErrorEvent(const AppExecFwk::InnerEvent::Pointer & event)2176 void LocatorHandler::RegLocationErrorEvent(const AppExecFwk::InnerEvent::Pointer& event)
2177 {
2178     auto requestManager = RequestManager::GetInstance();
2179     std::unique_ptr<LocatorCallbackMessage> callbackMessage = event->GetUniqueObject<LocatorCallbackMessage>();
2180     if (callbackMessage == nullptr) {
2181         return;
2182     }
2183     if (requestManager != nullptr) {
2184         requestManager->RegisterLocationErrorCallback(callbackMessage->GetCallback(),
2185             callbackMessage->GetAppIdentity());
2186     }
2187 }
2188 
UnRegLocationErrorEvent(const AppExecFwk::InnerEvent::Pointer & event)2189 void LocatorHandler::UnRegLocationErrorEvent(const AppExecFwk::InnerEvent::Pointer& event)
2190 {
2191     auto requestManager = RequestManager::GetInstance();
2192     std::unique_ptr<LocatorCallbackMessage> callbackMessage = event->GetUniqueObject<LocatorCallbackMessage>();
2193     if (callbackMessage == nullptr) {
2194         return;
2195     }
2196     if (requestManager != nullptr) {
2197         requestManager->UnRegisterLocationErrorCallback(callbackMessage->GetCallback());
2198     }
2199 }
2200 
ReportNetworkLocatingErrorEvent(const AppExecFwk::InnerEvent::Pointer & event)2201 void LocatorHandler::ReportNetworkLocatingErrorEvent(const AppExecFwk::InnerEvent::Pointer& event)
2202 {
2203     std::unique_ptr<LocatorErrorMessage> locatorErrorMessage = event->GetUniqueObject<LocatorErrorMessage>();
2204     if (locatorErrorMessage == nullptr) {
2205         return;
2206     }
2207     auto uuid = locatorErrorMessage->GetUuid();
2208     auto errCode = locatorErrorMessage->GetErrCode();
2209     auto netErrCode = locatorErrorMessage->GetNetErrCode();
2210     auto requestMap = LocatorAbility::GetInstance()->GetRequests();
2211     if (requestMap == nullptr || requestMap->empty()) {
2212         LBSLOGE(REQUEST_MANAGER, "requests map is empty");
2213         return;
2214     }
2215     auto requestListIter = requestMap->find(NETWORK_ABILITY);
2216     if (requestListIter == requestMap->end()) {
2217         return;
2218     }
2219     auto requestList = requestListIter->second;
2220     for (auto iter = requestList.begin(); iter != requestList.end(); iter++) {
2221         auto request = *iter;
2222         if (uuid.compare(request->GetUuid()) == 0) {
2223             std::string requestInfo = "";
2224             if (request->GetRequestConfig() != nullptr) {
2225                 requestInfo = request->GetRequestConfig()->ToString();
2226             }
2227             WriteLocationInnerEvent(LOCATION_REQUEST_DENY, {"errorCode", std::to_string(netErrCode),
2228                 "requestAppName", request->GetPackageName(), "requestInfo", requestInfo});
2229             RequestManager::GetInstance()->ReportLocationError(errCode, request);
2230             break;
2231         }
2232     }
2233 }
2234 
SyncSwitchStatus(const AppExecFwk::InnerEvent::Pointer & event)2235 void LocatorHandler::SyncSwitchStatus(const AppExecFwk::InnerEvent::Pointer& event)
2236 {
2237     LocationDataRdbManager::SyncSwitchStatus();
2238 }
2239 
IsSwitchObserverReg()2240 bool LocatorHandler::IsSwitchObserverReg()
2241 {
2242     std::unique_lock<ffrt::mutex> lock(isSwitchObserverRegMutex_);
2243     return isSwitchObserverReg_;
2244 }
2245 
SetIsSwitchObserverReg(bool isSwitchObserverReg)2246 void LocatorHandler::SetIsSwitchObserverReg(bool isSwitchObserverReg)
2247 {
2248     std::unique_lock<ffrt::mutex> lock(isSwitchObserverRegMutex_);
2249     isSwitchObserverReg_ = isSwitchObserverReg;
2250 }
2251 
WatchSwitchParameter(const AppExecFwk::InnerEvent::Pointer & event)2252 void LocatorHandler::WatchSwitchParameter(const AppExecFwk::InnerEvent::Pointer& event)
2253 {
2254     if (IsSwitchObserverReg()) {
2255         return;
2256     }
2257     auto eventCallback = [](const char *key, const char *value, void *context) {
2258         LocationDataRdbManager::SyncSwitchStatus();
2259     };
2260 
2261     int ret = WatchParameter(LOCATION_SWITCH_MODE, eventCallback, nullptr);
2262     if (ret != SUCCESS) {
2263         LBSLOGE(LOCATOR, "WatchParameter fail");
2264         return;
2265     }
2266     SetIsSwitchObserverReg(true);
2267 }
2268 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)2269 void LocatorHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event)
2270 {
2271     uint32_t eventId = event->GetInnerEventId();
2272     LBSLOGD(LOCATOR, "ProcessEvent event:%{public}d, timestamp = %{public}s",
2273         eventId, std::to_string(CommonUtils::GetCurrentTimeStamp()).c_str());
2274     auto handleFunc = locatorHandlerEventMap_.find(eventId);
2275     if (handleFunc != locatorHandlerEventMap_.end() && handleFunc->second != nullptr) {
2276         auto memberFunc = handleFunc->second;
2277 #ifdef LOCATION_HICOLLIE_ENABLE
2278         int tid = gettid();
2279         std::string moduleName = "LocatorHandler";
2280         XCollieCallback callbackFunc = [moduleName, eventId, tid](void *) {
2281             LBSLOGE(LOCATOR, "TimeoutCallback tid:%{public}d moduleName:%{public}s excute eventId:%{public}u timeout.",
2282                 tid, moduleName.c_str(), eventId);
2283         };
2284         std::string dfxInfo = moduleName + "_" + std::to_string(eventId) + "_" + std::to_string(tid);
2285         int timerId = HiviewDFX::XCollie::GetInstance().SetTimer(dfxInfo, TIMEOUT_WATCHDOG, callbackFunc, nullptr,
2286             HiviewDFX::XCOLLIE_FLAG_LOG|HiviewDFX::XCOLLIE_FLAG_RECOVERY);
2287         memberFunc(event);
2288         HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
2289 #else
2290         memberFunc(event);
2291 #endif
2292     } else {
2293         LBSLOGE(LOCATOR, "ProcessEvent event:%{public}d, unsupport service.", eventId);
2294     }
2295 }
2296 
RequestCheckEvent(const AppExecFwk::InnerEvent::Pointer & event)2297 void LocatorHandler::RequestCheckEvent(const AppExecFwk::InnerEvent::Pointer& event)
2298 {
2299     auto locatorAbility = LocatorAbility::GetInstance();
2300     if (locatorAbility != nullptr) {
2301         locatorAbility->RemoveInvalidRequests();
2302     }
2303     SendHighPriorityEvent(EVENT_PERIODIC_CHECK, 0, EVENT_PERIODIC_INTERVAL);
2304 }
2305 
SyncStillMovementState(const AppExecFwk::InnerEvent::Pointer & event)2306 void LocatorHandler::SyncStillMovementState(const AppExecFwk::InnerEvent::Pointer& event)
2307 {
2308     bool state = event->GetParam();
2309     RequestManager::GetInstance()->SyncStillMovementState(state);
2310     LocatorRequiredDataManager::GetInstance()->SyncStillMovementState(state);
2311 }
2312 
SyncIdleState(const AppExecFwk::InnerEvent::Pointer & event)2313 void LocatorHandler::SyncIdleState(const AppExecFwk::InnerEvent::Pointer& event)
2314 {
2315     auto requestManager = RequestManager::GetInstance();
2316     if (requestManager != nullptr) {
2317         bool state = event->GetParam();
2318         requestManager->SyncIdleState(state);
2319     }
2320 }
2321 
SendGeoRequestEvent(const AppExecFwk::InnerEvent::Pointer & event)2322 void LocatorHandler::SendGeoRequestEvent(const AppExecFwk::InnerEvent::Pointer& event)
2323 {
2324     auto locatorAbility = LocatorAbility::GetInstance();
2325     if (locatorAbility != nullptr) {
2326         std::unique_ptr<GeoConvertRequest> geoConvertRequest = event->GetUniqueObject<GeoConvertRequest>();
2327         if (geoConvertRequest == nullptr) {
2328             return;
2329         }
2330         MessageParcel dataParcel;
2331         MessageParcel replyParcel;
2332         if (!dataParcel.WriteInterfaceToken(GeoConvertProxy::GetDescriptor())) {
2333             return;
2334         }
2335         geoConvertRequest->Marshalling(dataParcel);
2336         locatorAbility->SendGeoRequest(
2337             geoConvertRequest->GetRequestType() == GeoCodeType::REQUEST_GEOCODE ?
2338             static_cast<int>(LocatorInterfaceCode::GET_FROM_LOCATION_NAME) :
2339             static_cast<int>(LocatorInterfaceCode::GET_FROM_COORDINATE),
2340             dataParcel, replyParcel);
2341     }
2342 }
2343 
InitMonitorManagerEvent(const AppExecFwk::InnerEvent::Pointer & event)2344 void LocatorHandler::InitMonitorManagerEvent(const AppExecFwk::InnerEvent::Pointer& event)
2345 {
2346 #ifdef MOVEMENT_CLIENT_ENABLE
2347     LocatorMsdpMonitorManager::GetInstance();
2348 #endif
2349 }
2350 
IsStandByEvent(const AppExecFwk::InnerEvent::Pointer & event)2351 void LocatorHandler::IsStandByEvent(const AppExecFwk::InnerEvent::Pointer& event)
2352 {
2353     auto requestManager = RequestManager::GetInstance();
2354     if (requestManager != nullptr) {
2355         requestManager->IsStandby();
2356     }
2357 }
2358 
SetLocationWorkingStateEvent(const AppExecFwk::InnerEvent::Pointer & event)2359 void LocatorHandler::SetLocationWorkingStateEvent(const AppExecFwk::InnerEvent::Pointer& event)
2360 {
2361     if (!LocationDataRdbManager::SetLocationWorkingState(0)) {
2362         LBSLOGD(LOCATOR, "LocatorAbility::reset LocationWorkingState failed.");
2363     }
2364 }
2365 
SetSwitchStateToDbEvent(const AppExecFwk::InnerEvent::Pointer & event)2366 void LocatorHandler::SetSwitchStateToDbEvent(const AppExecFwk::InnerEvent::Pointer& event)
2367 {
2368     int modeValue = event->GetParam();
2369     if (LocationDataRdbManager::SetSwitchStateToDb(modeValue) != ERRCODE_SUCCESS) {
2370         LBSLOGE(LOCATOR, "%{public}s: can not set state to db", __func__);
2371         return;
2372     }
2373     auto locatorAbility = LocatorAbility::GetInstance();
2374     if (locatorAbility != nullptr) {
2375         locatorAbility->UpdateSaAbility();
2376         locatorAbility->ApplyRequests(0);
2377         bool isEnabled = (modeValue == ENABLED);
2378         std::string state = isEnabled ? "enable" : "disable";
2379         locatorAbility->ReportDataToResSched(state);
2380         WriteLocationSwitchStateEvent(state);
2381     }
2382 }
2383 
SetSwitchStateToDbForUserEvent(const AppExecFwk::InnerEvent::Pointer & event)2384 void LocatorHandler::SetSwitchStateToDbForUserEvent(const AppExecFwk::InnerEvent::Pointer& event)
2385 {
2386     std::unique_ptr<LocatorSwitchMessage> locatorSwitchMessage = event->GetUniqueObject<LocatorSwitchMessage>();
2387     if (locatorSwitchMessage == nullptr) {
2388         return;
2389     }
2390     auto modeValue = locatorSwitchMessage->GetModeValue();
2391     auto userId = locatorSwitchMessage->GetUserId();
2392     if (LocationDataRdbManager::SetSwitchStateToDbForUser(modeValue, userId) != ERRCODE_SUCCESS) {
2393         LBSLOGE(LOCATOR, "%{public}s: can not set state to db", __func__);
2394         return;
2395     }
2396     LocatorAbility::GetInstance()->UpdateSaAbility();
2397     LocatorAbility::GetInstance()->ApplyRequests(0);
2398     int currentUserId = 0;
2399     if (CommonUtils::GetCurrentUserId(currentUserId) && userId != currentUserId) {
2400         return;
2401     }
2402     bool isEnabled = (modeValue == ENABLED);
2403     std::string state = isEnabled ? "enable" : "disable";
2404     // background task only check the current user switch state
2405     LocatorAbility::GetInstance()->ReportDataToResSched(state);
2406     WriteLocationSwitchStateEvent(state);
2407 }
2408 
LocatorCallbackDeathRecipient(int32_t tokenId)2409 LocatorCallbackDeathRecipient::LocatorCallbackDeathRecipient(int32_t tokenId)
2410 {
2411     tokenId_ = tokenId;
2412 }
2413 
~LocatorCallbackDeathRecipient()2414 LocatorCallbackDeathRecipient::~LocatorCallbackDeathRecipient()
2415 {
2416 }
2417 
OnRemoteDied(const wptr<IRemoteObject> & remote)2418 void LocatorCallbackDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
2419 {
2420     sptr<ILocatorCallback> callback = iface_cast<ILocatorCallback>(remote.promote());
2421     auto locatorAbility = LocatorAbility::GetInstance();
2422     if (locatorAbility != nullptr) {
2423         locatorAbility->RemoveUnloadTask(DEFAULT_CODE);
2424         locatorAbility->StopLocating(callback);
2425         locatorAbility->PostUnloadTask(DEFAULT_CODE);
2426         LBSLOGI(LOCATOR, "locator callback OnRemoteDied tokenId = %{public}d", tokenId_);
2427     }
2428 }
2429 } // namespace Location
2430 } // namespace OHOS
2431