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