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 #ifdef FEATURE_NETWORK_SUPPORT
17 #include "network_ability.h"
18 #include <file_ex.h>
19 #include <thread>
20 #include "ability_connect_callback_stub.h"
21 #include "ability_manager_client.h"
22 #include "ipc_skeleton.h"
23 #include "iservice_registry.h"
24 #include "system_ability_definition.h"
25 #include "want_agent_helper.h"
26
27 #include "common_utils.h"
28 #include "location_config_manager.h"
29 #include "location_dumper.h"
30 #include "location_log.h"
31 #include "location_sa_load_manager.h"
32 #include "network_callback_host.h"
33 #include "locationhub_ipc_interface_code.h"
34 #include "location_log_event_ids.h"
35 #include "common_hisysevent.h"
36 #include "location_data_rdb_manager.h"
37 #include "hook_utils.h"
38
39 #ifdef LOCATION_HICOLLIE_ENABLE
40 #include "xcollie/xcollie.h"
41 #include "xcollie/xcollie_define.h"
42 #endif
43
44 namespace OHOS {
45 namespace Location {
46 const uint32_t EVENT_REPORT_MOCK_LOCATION = 0x0100;
47 const uint32_t EVENT_RESTART_ALL_LOCATION_REQUEST = 0x0200;
48 const uint32_t EVENT_STOP_ALL_LOCATION_REQUEST = 0x0300;
49 const uint32_t EVENT_DISCONNECT_SERVICES = 0x0400;
50 const uint32_t EVENT_INTERVAL_UNITE = 1000;
51 const uint32_t DELAY_RESTART_MS = 500;
52 const uint32_t DELAY_DINCONNECT_MS = 5 * 1000;
53 constexpr uint32_t WAIT_MS = 100;
54 const int MAX_RETRY_COUNT = 5;
55 const std::string UNLOAD_NETWORK_TASK = "network_sa_unload";
56 const std::string DISCONNECT_NETWORK_TASK = "disconnect_network_ability";
57 const uint32_t RETRY_INTERVAL_OF_UNLOAD_SA = 4 * 60 * EVENT_INTERVAL_UNITE;
58 const int TIMEOUT_WATCHDOG = 60; // s
59 const bool REGISTER_RESULT = NetworkAbility::MakeAndRegisterAbility(
60 NetworkAbility::GetInstance());
61
NetworkAbility()62 NetworkAbility::NetworkAbility() : SystemAbility(LOCATION_NETWORK_LOCATING_SA_ID, true)
63 {
64 SetAbility(NETWORK_ABILITY);
65 networkHandler_ =
66 std::make_shared<NetworkHandler>(AppExecFwk::EventRunner::Create(true, AppExecFwk::ThreadMode::FFRT));
67 LBSLOGI(NETWORK, "ability constructed.");
68 }
69
~NetworkAbility()70 NetworkAbility::~NetworkAbility()
71 {
72 std::unique_lock<ffrt::mutex> uniqueLock(connMutex_);
73 conn_ = nullptr;
74 }
75
OnStart()76 void NetworkAbility::OnStart()
77 {
78 if (state_ == ServiceRunningState::STATE_RUNNING) {
79 LBSLOGI(NETWORK, "ability has already started.");
80 return;
81 }
82 if (!Init()) {
83 LBSLOGE(NETWORK, "failed to init ability");
84 OnStop();
85 return;
86 }
87 state_ = ServiceRunningState::STATE_RUNNING;
88 LBSLOGI(NETWORK, "OnStart start ability success.");
89 }
90
OnStop()91 void NetworkAbility::OnStop()
92 {
93 state_ = ServiceRunningState::STATE_NOT_START;
94 registerToAbility_ = false;
95 LBSLOGI(NETWORK, "OnStop ability stopped.");
96 }
97
GetInstance()98 NetworkAbility* NetworkAbility::GetInstance()
99 {
100 static NetworkAbility data;
101 return &data;
102 }
103
Init()104 bool NetworkAbility::Init()
105 {
106 if (!registerToAbility_) {
107 if (!Publish(AsObject())) {
108 LBSLOGE(NETWORK, "Init Publish failed!");
109 return false;
110 }
111 registerToAbility_ = true;
112 }
113 return true;
114 }
115
116 class AbilityConnection : public AAFwk::AbilityConnectionStub {
117 public:
OnAbilityConnectDone(const AppExecFwk::ElementName & element,const sptr<IRemoteObject> & remoteObject,int resultCode)118 void OnAbilityConnectDone(
119 const AppExecFwk::ElementName& element, const sptr<IRemoteObject>& remoteObject, int resultCode) override
120 {
121 std::string uri = element.GetURI();
122 LBSLOGD(NETWORK, "Connected uri is %{public}s, result is %{public}d.", uri.c_str(), resultCode);
123 if (resultCode != ERR_OK) {
124 return;
125 }
126 NetworkAbility::GetInstance()->NotifyConnected(remoteObject);
127 }
128
OnAbilityDisconnectDone(const AppExecFwk::ElementName & element,int)129 void OnAbilityDisconnectDone(const AppExecFwk::ElementName& element, int) override
130 {
131 std::string uri = element.GetURI();
132 LBSLOGD(NETWORK, "Disconnected uri is %{public}s.", uri.c_str());
133 NetworkAbility::GetInstance()->NotifyDisConnected();
134 }
135 };
136
ConnectNlpService()137 bool NetworkAbility::ConnectNlpService()
138 {
139 LBSLOGD(NETWORK, "start ConnectNlpService");
140 if (!IsConnect()) {
141 AAFwk::Want connectionWant;
142 std::string serviceName;
143 bool result = LocationConfigManager::GetInstance()->GetNlpServiceName(serviceName);
144 if (!result || serviceName.empty()) {
145 LBSLOGE(NETWORK, "get service name failed!");
146 return false;
147 }
148 std::string abilityName;
149 bool res = LocationConfigManager::GetInstance()->GetNlpAbilityName(abilityName);
150 if (!res || abilityName.empty()) {
151 LBSLOGE(NETWORK, "get service name failed!");
152 return false;
153 }
154 connectionWant.SetElementName(serviceName, abilityName);
155 std::unique_lock<ffrt::mutex> lock(connMutex_, std::defer_lock);
156 connMutex_.lock();
157 conn_ = sptr<AAFwk::IAbilityConnection>(new (std::nothrow) AbilityConnection());
158 if (conn_ == nullptr) {
159 LBSLOGE(NETWORK, "get connection failed!");
160 connMutex_.unlock();
161 return false;
162 }
163 int32_t ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(connectionWant, conn_, -1);
164 connMutex_.unlock();
165 if (ret != ERR_OK) {
166 LBSLOGE(NETWORK, "Connect cloud service failed, ret = %{public}d", ret);
167 return false;
168 }
169 std::unique_lock<ffrt::mutex> uniqueLock(nlpServiceMutex_);
170 auto waitStatus = connectCondition_.wait_for(
171 uniqueLock, std::chrono::seconds(CONNECT_TIME_OUT), [this]() { return nlpServiceProxy_ != nullptr; });
172 if (!waitStatus) {
173 WriteLocationInnerEvent(NLP_SERVICE_TIMEOUT, {});
174 LBSLOGE(NETWORK, "Connect cloudService timeout!");
175 return false;
176 }
177 }
178 RegisterNlpServiceDeathRecipient();
179 return true;
180 }
181
ReConnectNlpService()182 bool NetworkAbility::ReConnectNlpService()
183 {
184 int retryCount = 0;
185 if (IsConnect()) {
186 LBSLOGI(NETWORK, "Connect success!");
187 return true;
188 }
189 while (retryCount < MAX_RETRY_COUNT) {
190 retryCount++;
191 bool ret = ConnectNlpService();
192 if (ret) {
193 LBSLOGI(NETWORK, "Connect success!");
194 return true;
195 }
196 std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_MS));
197 }
198 return false;
199 }
200
ResetServiceProxy()201 bool NetworkAbility::ResetServiceProxy()
202 {
203 if (networkHandler_ == nullptr) {
204 return false;
205 }
206 networkHandler_->SendHighPriorityEvent(EVENT_DISCONNECT_SERVICES, 0, 0);
207 return true;
208 }
209
ClearServiceProxy()210 void NetworkAbility::ClearServiceProxy()
211 {
212 std::unique_lock<ffrt::mutex> uniqueLock(nlpServiceMutex_);
213 nlpServiceProxy_ = nullptr;
214 }
215
NotifyConnected(const sptr<IRemoteObject> & remoteObject)216 void NetworkAbility::NotifyConnected(const sptr<IRemoteObject>& remoteObject)
217 {
218 std::unique_lock<ffrt::mutex> uniqueLock(nlpServiceMutex_);
219 nlpServiceProxy_ = remoteObject;
220 connectCondition_.notify_all();
221 }
222
NotifyDisConnected()223 void NetworkAbility::NotifyDisConnected()
224 {
225 std::unique_lock<ffrt::mutex> uniqueLock(nlpServiceMutex_);
226 connectCondition_.notify_all();
227 }
228
SendLocationRequest(WorkRecord & workrecord)229 LocationErrCode NetworkAbility::SendLocationRequest(WorkRecord &workrecord)
230 {
231 LocationRequest(workrecord);
232 return ERRCODE_SUCCESS;
233 }
234
SetEnable(bool state)235 LocationErrCode NetworkAbility::SetEnable(bool state)
236 {
237 LBSLOGD(NETWORK, "SetEnable: %{public}d", state);
238 if (networkHandler_ == nullptr) {
239 LBSLOGE(NETWORK, "%{public}s networkHandler is nullptr", __func__);
240 return ERRCODE_SERVICE_UNAVAILABLE;
241 }
242 auto event = state ? AppExecFwk::InnerEvent::Get(EVENT_RESTART_ALL_LOCATION_REQUEST, 0) :
243 AppExecFwk::InnerEvent::Get(EVENT_STOP_ALL_LOCATION_REQUEST, 0);
244 networkHandler_->SendHighPriorityEvent(event);
245 return ERRCODE_SUCCESS;
246 }
247
CancelIdleState()248 bool NetworkAbility::CancelIdleState()
249 {
250 SystemAbilityState state = GetAbilityState();
251 if (state != SystemAbilityState::IDLE) {
252 return true;
253 }
254 bool ret = CancelIdle();
255 if (!ret) {
256 LBSLOGE(NETWORK, "%{public}s cancel idle failed!", __func__);
257 return false;
258 }
259 return true;
260 }
261
UnloadNetworkSystemAbility()262 void NetworkAbility::UnloadNetworkSystemAbility()
263 {
264 if (networkHandler_ == nullptr) {
265 LBSLOGE(NETWORK, "%{public}s networkHandler is nullptr", __func__);
266 return;
267 }
268 networkHandler_->RemoveTask(UNLOAD_NETWORK_TASK);
269 if (CheckIfNetworkConnecting()) {
270 return;
271 }
272 auto task = [this]() {
273 SaLoadWithStatistic::UnInitLocationSa(LOCATION_NETWORK_LOCATING_SA_ID);
274 };
275 if (networkHandler_ != nullptr) {
276 networkHandler_->PostTask(task, UNLOAD_NETWORK_TASK, RETRY_INTERVAL_OF_UNLOAD_SA);
277 }
278 }
279
CheckIfNetworkConnecting()280 bool NetworkAbility::CheckIfNetworkConnecting()
281 {
282 return IsMockEnabled() || !GetLocationMock().empty() || GetRequestNum() != 0;
283 }
284
RequestRecord(WorkRecord & workRecord,bool isAdded)285 void NetworkAbility::RequestRecord(WorkRecord &workRecord, bool isAdded)
286 {
287 if (!IsConnect()) {
288 std::string serviceName;
289 bool result = LocationConfigManager::GetInstance()->GetNlpServiceName(serviceName);
290 if (!result || serviceName.empty()) {
291 LBSLOGE(NETWORK, "get service name failed!");
292 return;
293 }
294 if (!CommonUtils::CheckAppInstalled(serviceName)) { // app is not installed
295 LBSLOGE(NETWORK, "nlp service is not available.");
296 return;
297 } else if (!ReConnectNlpService()) {
298 LBSLOGE(NETWORK, "nlp service is not ready.");
299 return;
300 }
301 }
302 if (isAdded) {
303 RequestNetworkLocation(workRecord);
304 if (networkHandler_ != nullptr) {
305 networkHandler_->RemoveTask(DISCONNECT_NETWORK_TASK);
306 }
307 } else {
308 RemoveNetworkLocation(workRecord);
309 if (networkHandler_ == nullptr) {
310 return;
311 }
312 networkHandler_->RemoveTask(DISCONNECT_NETWORK_TASK);
313 auto disconnectTask = [this]() {
314 auto networkAbility = NetworkAbility::GetInstance();
315 if (networkAbility == nullptr) {
316 LBSLOGE(NETWORK, "OnRemoteDied: NetworkAbility is nullptr");
317 return;
318 };
319 networkAbility->DisconnectAbilityConnect();
320 };
321 networkHandler_->PostTask(disconnectTask, DISCONNECT_NETWORK_TASK, DELAY_DINCONNECT_MS);
322 }
323 }
324
DisconnectAbilityConnect()325 void NetworkAbility::DisconnectAbilityConnect()
326 {
327 std::unique_lock<ffrt::mutex> uniqueLock(connMutex_);
328 if (GetRequestNum() == 0 && conn_ != nullptr) {
329 LBSLOGI(NETWORK, "RequestRecord disconnect");
330 UnregisterNlpServiceDeathRecipient();
331 AAFwk::AbilityManagerClient::GetInstance()->DisconnectAbility(conn_);
332 conn_ = nullptr;
333 std::unique_lock<ffrt::mutex> uniqueLock(nlpServiceMutex_);
334 nlpServiceProxy_ = nullptr;
335 LBSLOGD(NETWORK, "disconnect cloudService success!");
336 }
337 }
338
RequestNetworkLocation(WorkRecord & workRecord)339 bool NetworkAbility::RequestNetworkLocation(WorkRecord &workRecord)
340 {
341 LBSLOGW(NETWORK, "start network location, uuid: %{public}s", workRecord.GetUuid(0).c_str());
342 sptr<NetworkCallbackHost> callback = new (std::nothrow) NetworkCallbackHost();
343 if (callback == nullptr) {
344 LBSLOGE(NETWORK, "can not get valid callback.");
345 return false;
346 }
347 HookUtils::ExecuteHookWhenAddNetworkRequest(workRecord.GetUuid(0));
348 std::unique_lock<ffrt::mutex> uniqueLock(nlpServiceMutex_);
349 if (nlpServiceProxy_ == nullptr) {
350 LBSLOGE(NETWORK, "nlpProxy is nullptr.");
351 return false;
352 }
353 MessageParcel data;
354
355 MessageParcel reply;
356 MessageOption option;
357 data.WriteInterfaceToken(nlpServiceProxy_->GetInterfaceDescriptor());
358 data.WriteString16(Str8ToStr16(workRecord.GetUuid(0)));
359 data.WriteInt64(workRecord.GetTimeInterval(0) * MILLI_PER_SEC);
360 data.WriteInt32(workRecord.GetNlpRequestType(0));
361 data.WriteRemoteObject(callback->AsObject());
362 if (workRecord.GetName(0).size() == 0) {
363 data.WriteString16(Str8ToStr16(std::to_string(workRecord.GetUid(0)))); // uid
364 } else {
365 data.WriteString16(Str8ToStr16(workRecord.GetName(0))); // bundleName
366 }
367 int error = nlpServiceProxy_->SendRequest(REQUEST_NETWORK_LOCATION, data, reply, option);
368 if (error != ERR_OK) {
369 LBSLOGE(NETWORK, "SendRequest to cloud service failed. error = %{public}d", error);
370 return false;
371 }
372 return true;
373 }
374
RemoveNetworkLocation(WorkRecord & workRecord)375 bool NetworkAbility::RemoveNetworkLocation(WorkRecord &workRecord)
376 {
377 HookUtils::ExecuteHookWhenRemoveNetworkRequest(workRecord.GetUuid(0));
378 std::unique_lock<ffrt::mutex> uniqueLock(nlpServiceMutex_);
379 if (nlpServiceProxy_ == nullptr) {
380 LBSLOGE(NETWORK, "nlpProxy is nullptr.");
381 return false;
382 }
383 LBSLOGW(NETWORK, "stop network location, uuid: %{public}s", workRecord.GetUuid(0).c_str());
384 MessageParcel data;
385 MessageParcel reply;
386 MessageOption option;
387 data.WriteInterfaceToken(nlpServiceProxy_->GetInterfaceDescriptor());
388 data.WriteString16(Str8ToStr16(workRecord.GetUuid(0)));
389 data.WriteString16(Str8ToStr16(workRecord.GetName(0))); // bundleName
390 int error = nlpServiceProxy_->SendRequest(REMOVE_NETWORK_LOCATION, data, reply, option);
391 if (error != ERR_OK) {
392 LBSLOGE(NETWORK, "SendRequest to cloud service failed.");
393 return false;
394 }
395 return true;
396 }
397
EnableMock()398 LocationErrCode NetworkAbility::EnableMock()
399 {
400 if (!EnableLocationMock()) {
401 return ERRCODE_NOT_SUPPORTED;
402 }
403 return ERRCODE_SUCCESS;
404 }
405
DisableMock()406 LocationErrCode NetworkAbility::DisableMock()
407 {
408 if (!DisableLocationMock()) {
409 return ERRCODE_NOT_SUPPORTED;
410 }
411 return ERRCODE_SUCCESS;
412 }
413
IsMockEnabled()414 bool NetworkAbility::IsMockEnabled()
415 {
416 return IsLocationMocked();
417 }
418
SetMocked(const int timeInterval,const std::vector<std::shared_ptr<Location>> & location)419 LocationErrCode NetworkAbility::SetMocked(const int timeInterval,
420 const std::vector<std::shared_ptr<Location>> &location)
421 {
422 if (!SetMockedLocations(timeInterval, location)) {
423 return ERRCODE_NOT_SUPPORTED;
424 }
425 return ERRCODE_SUCCESS;
426 }
427
ProcessReportLocationMock()428 void NetworkAbility::ProcessReportLocationMock()
429 {
430 std::vector<std::shared_ptr<Location>> mockLocationArray = GetLocationMock();
431 if (mockLocationIndex_ < mockLocationArray.size()) {
432 ReportMockedLocation(mockLocationArray[mockLocationIndex_++]);
433 if (networkHandler_ != nullptr) {
434 networkHandler_->SendHighPriorityEvent(EVENT_REPORT_MOCK_LOCATION,
435 0, GetTimeIntervalMock() * EVENT_INTERVAL_UNITE);
436 }
437 } else {
438 ClearLocationMock();
439 mockLocationIndex_ = 0;
440 }
441 }
442
SendReportMockLocationEvent()443 void NetworkAbility::SendReportMockLocationEvent()
444 {
445 if (networkHandler_ == nullptr) {
446 return;
447 }
448 networkHandler_->SendHighPriorityEvent(EVENT_REPORT_MOCK_LOCATION, 0, 0);
449 }
450
ReportMockedLocation(const std::shared_ptr<Location> location)451 int32_t NetworkAbility::ReportMockedLocation(const std::shared_ptr<Location> location)
452 {
453 if ((IsLocationMocked() && !location->GetIsFromMock()) ||
454 (!IsLocationMocked() && location->GetIsFromMock())) {
455 LBSLOGE(NETWORK, "location mock is enabled, do not report network location!");
456 return ERR_OK;
457 }
458 location->SetTimeSinceBoot(CommonUtils::GetSinceBootTime());
459 location->SetTimeStamp(CommonUtils::GetCurrentTimeStamp() * MICRO_PER_MILLI);
460 location->SetLocationSourceType(LocationSourceType::NETWORK_TYPE);
461 ReportLocationInfo(NETWORK_ABILITY, location);
462 #ifdef FEATURE_PASSIVE_SUPPORT
463 ReportLocationInfo(PASSIVE_ABILITY, location);
464 #endif
465 return ERR_OK;
466 }
467
SaDumpInfo(std::string & result)468 void NetworkAbility::SaDumpInfo(std::string& result)
469 {
470 result += "Network Location enable status: false";
471 result += "\n";
472 }
473
Dump(int32_t fd,const std::vector<std::u16string> & args)474 int32_t NetworkAbility::Dump(int32_t fd, const std::vector<std::u16string>& args)
475 {
476 std::vector<std::string> vecArgs;
477 std::transform(args.begin(), args.end(), std::back_inserter(vecArgs), [](const std::u16string &arg) {
478 return Str16ToStr8(arg);
479 });
480
481 LocationDumper dumper;
482 std::string result;
483 dumper.NetWorkDump(SaDumpInfo, vecArgs, result);
484 if (!SaveStringToFd(fd, result)) {
485 LBSLOGE(NETWORK, "Network save string to fd failed!");
486 return ERR_OK;
487 }
488 return ERR_OK;
489 }
490
SendMessage(uint32_t code,MessageParcel & data,MessageParcel & reply)491 void NetworkAbility::SendMessage(uint32_t code, MessageParcel &data, MessageParcel &reply)
492 {
493 if (networkHandler_ == nullptr) {
494 reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
495 return;
496 }
497 switch (code) {
498 case static_cast<uint32_t>(NetworkInterfaceCode::SEND_LOCATION_REQUEST): {
499 std::unique_ptr<WorkRecord> workrecord = WorkRecord::Unmarshalling(data);
500 AppExecFwk::InnerEvent::Pointer event = AppExecFwk::InnerEvent::Get(code, workrecord);
501 if (networkHandler_->SendEvent(event)) {
502 reply.WriteInt32(ERRCODE_SUCCESS);
503 } else {
504 reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
505 }
506 break;
507 }
508 case static_cast<uint32_t>(NetworkInterfaceCode::SET_MOCKED_LOCATIONS): {
509 if (!IsMockEnabled()) {
510 reply.WriteInt32(ERRCODE_NOT_SUPPORTED);
511 break;
512 }
513 int timeInterval = data.ReadInt32();
514 int locationSize = data.ReadInt32();
515 timeInterval = timeInterval < 0 ? 1 : timeInterval;
516 locationSize = locationSize > INPUT_ARRAY_LEN_MAX ? INPUT_ARRAY_LEN_MAX :
517 locationSize;
518 std::shared_ptr<std::vector<std::shared_ptr<Location>>> vcLoc =
519 std::make_shared<std::vector<std::shared_ptr<Location>>>();
520 for (int i = 0; i < locationSize; i++) {
521 vcLoc->push_back(Location::UnmarshallingShared(data));
522 }
523 AppExecFwk::InnerEvent::Pointer event =
524 AppExecFwk::InnerEvent::Get(code, vcLoc, timeInterval);
525 if (networkHandler_->SendEvent(event)) {
526 reply.WriteInt32(ERRCODE_SUCCESS);
527 } else {
528 reply.WriteInt32(ERRCODE_SERVICE_UNAVAILABLE);
529 }
530 break;
531 }
532 default:
533 break;
534 }
535 }
536
RegisterNlpServiceDeathRecipient()537 void NetworkAbility::RegisterNlpServiceDeathRecipient()
538 {
539 std::unique_lock<ffrt::mutex> uniqueLock(nlpServiceMutex_);
540 if (nlpServiceProxy_ == nullptr) {
541 LBSLOGE(NETWORK, "%{public}s: nlpServiceProxy_ is nullptr", __func__);
542 return;
543 }
544 if (nlpServiceRecipient_ == nullptr) {
545 nlpServiceRecipient_ = sptr<NlpServiceDeathRecipient>(new (std::nothrow) NlpServiceDeathRecipient());
546 }
547 nlpServiceProxy_->AddDeathRecipient(nlpServiceRecipient_);
548 LBSLOGI(NETWORK, "%{public}s: success", __func__);
549 }
550
UnregisterNlpServiceDeathRecipient()551 void NetworkAbility::UnregisterNlpServiceDeathRecipient()
552 {
553 std::unique_lock<ffrt::mutex> uniqueLock(nlpServiceMutex_);
554 LBSLOGI(NETWORK, "UnRegisterNLPServiceDeathRecipient enter");
555 if (nlpServiceProxy_ == nullptr) {
556 LBSLOGE(NETWORK, "%{public}s: nlpServiceProxy_ is nullptr", __func__);
557 return;
558 }
559 if (nlpServiceRecipient_ != nullptr) {
560 nlpServiceProxy_->RemoveDeathRecipient(nlpServiceRecipient_);
561 nlpServiceRecipient_ = nullptr;
562 }
563 }
564
IsConnect()565 bool NetworkAbility::IsConnect()
566 {
567 std::unique_lock<ffrt::mutex> uniqueLock(nlpServiceMutex_);
568 return nlpServiceProxy_ != nullptr;
569 }
570
RestartNlpRequests()571 void NetworkAbility::RestartNlpRequests()
572 {
573 if (GetRequestNum() > 0) {
574 if (networkHandler_ != nullptr) {
575 networkHandler_->SendHighPriorityEvent(EVENT_RESTART_ALL_LOCATION_REQUEST, 0, DELAY_RESTART_MS);
576 LBSLOGI(NETWORK, "CheckNetworkRequests needRecoverRequests");
577 }
578 }
579 }
580
ReportLocationError(int32_t errCode,std::string errMsg,std::string uuid)581 void NetworkAbility::ReportLocationError(int32_t errCode, std::string errMsg, std::string uuid)
582 {
583 MessageParcel data;
584 MessageParcel reply;
585 MessageOption option;
586 data.WriteInterfaceToken(u"location.ILocator");
587 data.WriteInt32(LOCATING_FAILED_INTERNET_ACCESS_FAILURE);
588 data.WriteString(errMsg);
589 data.WriteString(uuid);
590 data.WriteInt32(errCode);
591 sptr<IRemoteObject> objectLocator =
592 CommonUtils::GetRemoteObject(LOCATION_LOCATOR_SA_ID, CommonUtils::InitDeviceId());
593 if (objectLocator == nullptr) {
594 LBSLOGE(NETWORK, "%{public}s get locator sa failed", __func__);
595 return;
596 }
597 objectLocator->SendRequest(static_cast<int>(LocatorInterfaceCode::REPORT_LOCATION_ERROR), data, reply, option);
598 }
599
NetworkHandler(const std::shared_ptr<AppExecFwk::EventRunner> & runner)600 NetworkHandler::NetworkHandler(const std::shared_ptr<AppExecFwk::EventRunner>& runner) : EventHandler(runner)
601 {
602 InitNetworkEventProcessMap();
603 }
604
~NetworkHandler()605 NetworkHandler::~NetworkHandler() {}
606
InitNetworkEventProcessMap()607 void NetworkHandler::InitNetworkEventProcessMap()
608 {
609 if (networkEventProcessMap_.size() != 0) {
610 return;
611 }
612 networkEventProcessMap_[static_cast<uint32_t>(EVENT_REPORT_MOCK_LOCATION)] =
613 [this](const AppExecFwk::InnerEvent::Pointer& event) { HandleReportLocationMock(event); };
614 networkEventProcessMap_[static_cast<uint32_t>(EVENT_RESTART_ALL_LOCATION_REQUEST)] =
615 [this](const AppExecFwk::InnerEvent::Pointer& event) { HandleRestartAllLocationRequests(event); };
616 networkEventProcessMap_[static_cast<uint32_t>(EVENT_STOP_ALL_LOCATION_REQUEST)] =
617 [this](const AppExecFwk::InnerEvent::Pointer& event) { HandleStopAllLocationRequests(event); };
618 networkEventProcessMap_[static_cast<uint32_t>(EVENT_DISCONNECT_SERVICES)] =
619 [this](const AppExecFwk::InnerEvent::Pointer& event) { HandleClearServiceEvent(event); };
620 networkEventProcessMap_[static_cast<uint32_t>(NetworkInterfaceCode::SEND_LOCATION_REQUEST)] =
621 [this](const AppExecFwk::InnerEvent::Pointer& event) { HandleLocationRequest(event); };
622 networkEventProcessMap_[static_cast<uint32_t>(NetworkInterfaceCode::SET_MOCKED_LOCATIONS)] =
623 [this](const AppExecFwk::InnerEvent::Pointer& event) { HandleSetMocked(event); };
624 }
625
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)626 void NetworkHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer& event)
627 {
628 uint32_t eventId = event->GetInnerEventId();
629 LBSLOGD(NETWORK, "ProcessEvent event:%{public}d", eventId);
630
631 auto handleFunc = networkEventProcessMap_.find(eventId);
632 if (handleFunc != networkEventProcessMap_.end() && handleFunc->second != nullptr) {
633 auto memberFunc = handleFunc->second;
634 #ifdef LOCATION_HICOLLIE_ENABLE
635 int tid = gettid();
636 std::string moduleName = "NetworkHandler";
637 XCollieCallback callbackFunc = [moduleName, eventId, tid](void *) {
638 LBSLOGE(NETWORK, "TimeoutCallback tid:%{public}d moduleName:%{public}s excute eventId:%{public}u timeout.",
639 tid, moduleName.c_str(), eventId);
640 };
641 std::string dfxInfo = moduleName + "_" + std::to_string(eventId) + "_" + std::to_string(tid);
642 int timerId = HiviewDFX::XCollie::GetInstance().SetTimer(dfxInfo, TIMEOUT_WATCHDOG, callbackFunc, nullptr,
643 HiviewDFX::XCOLLIE_FLAG_LOG|HiviewDFX::XCOLLIE_FLAG_RECOVERY);
644 memberFunc(event);
645 HiviewDFX::XCollie::GetInstance().CancelTimer(timerId);
646 #else
647 memberFunc(event);
648 #endif
649 }
650 auto networkAbility = NetworkAbility::GetInstance();
651 networkAbility->UnloadNetworkSystemAbility();
652 }
653
HandleReportLocationMock(const AppExecFwk::InnerEvent::Pointer & event)654 void NetworkHandler::HandleReportLocationMock(const AppExecFwk::InnerEvent::Pointer& event)
655 {
656 auto networkAbility = NetworkAbility::GetInstance();
657 networkAbility->ProcessReportLocationMock();
658 }
659
HandleRestartAllLocationRequests(const AppExecFwk::InnerEvent::Pointer & event)660 void NetworkHandler::HandleRestartAllLocationRequests(const AppExecFwk::InnerEvent::Pointer& event)
661 {
662 auto networkAbility = NetworkAbility::GetInstance();
663 networkAbility->RestartAllLocationRequests();
664 }
665
HandleStopAllLocationRequests(const AppExecFwk::InnerEvent::Pointer & event)666 void NetworkHandler::HandleStopAllLocationRequests(const AppExecFwk::InnerEvent::Pointer& event)
667 {
668 auto networkAbility = NetworkAbility::GetInstance();
669 networkAbility->StopAllLocationRequests();
670 }
671
HandleLocationRequest(const AppExecFwk::InnerEvent::Pointer & event)672 void NetworkHandler::HandleLocationRequest(const AppExecFwk::InnerEvent::Pointer& event)
673 {
674 std::unique_ptr<WorkRecord> workrecord = event->GetUniqueObject<WorkRecord>();
675 if (workrecord != nullptr) {
676 auto networkAbility = NetworkAbility::GetInstance();
677 networkAbility->LocationRequest(*workrecord);
678 }
679 }
680
HandleClearServiceEvent(const AppExecFwk::InnerEvent::Pointer & event)681 void NetworkHandler::HandleClearServiceEvent(const AppExecFwk::InnerEvent::Pointer& event)
682 {
683 auto networkAbility = NetworkAbility::GetInstance();
684 networkAbility->ClearServiceProxy();
685 }
686
HandleSetMocked(const AppExecFwk::InnerEvent::Pointer & event)687 void NetworkHandler::HandleSetMocked(const AppExecFwk::InnerEvent::Pointer& event)
688 {
689 auto networkAbility = NetworkAbility::GetInstance();
690 int timeInterval = event->GetParam();
691 auto vcLoc = event->GetSharedObject<std::vector<std::shared_ptr<Location>>>();
692 if (vcLoc != nullptr) {
693 std::vector<std::shared_ptr<Location>> mockLocations;
694 for (auto it = vcLoc->begin(); it != vcLoc->end(); ++it) {
695 mockLocations.push_back(*it);
696 }
697 networkAbility->SetMocked(timeInterval, mockLocations);
698 }
699 }
700
NlpServiceDeathRecipient()701 NlpServiceDeathRecipient::NlpServiceDeathRecipient()
702 {
703 }
704
~NlpServiceDeathRecipient()705 NlpServiceDeathRecipient::~NlpServiceDeathRecipient()
706 {
707 }
708
OnRemoteDied(const wptr<IRemoteObject> & remote)709 void NlpServiceDeathRecipient::OnRemoteDied(const wptr<IRemoteObject> &remote)
710 {
711 auto networkAbility = NetworkAbility::GetInstance();
712 if (networkAbility == nullptr) {
713 LBSLOGE(NETWORK, "OnRemoteDied: NetworkAbility is nullptr");
714 return;
715 }
716 networkAbility->ResetServiceProxy();
717 networkAbility->RestartNlpRequests();
718 }
719 } // namespace Location
720 } // namespace OHOS
721 #endif // FEATURE_NETWORK_SUPPORT
722