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