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