1 /*
2  * Copyright (c) 2022-2023 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 "net_policy_core.h"
17 
18 #include <pthread.h>
19 #include <thread>
20 
21 #include "net_mgr_log_wrapper.h"
22 #include "net_policy_base.h"
23 #include "net_policy_event_handler.h"
24 #include "netmanager_base_common_utils.h"
25 
26 namespace OHOS {
27 namespace NetManagerStandard {
28 using namespace AppExecFwk;
29 namespace {
30 constexpr const char *DEVICE_IDLE_MODE_KEY = "0";
31 constexpr uint32_t AGAIN_REGISTER_CALLBACK_INTERVAL = 500;
32 constexpr uint32_t CORE_EVENT_PRIORITY = 1;
33 constexpr uint32_t MAX_RETRY_TIMES = 10;
34 } // namespace
35 
36 NetPolicyCore::NetPolicyCore() = default;
37 
~NetPolicyCore()38 NetPolicyCore::~NetPolicyCore()
39 {
40     cores_.clear();
41 }
42 
Init(std::shared_ptr<NetPolicyEventHandler> & handler)43 void NetPolicyCore::Init(std::shared_ptr<NetPolicyEventHandler> &handler)
44 {
45     handler_ = handler;
46     SubscribeCommonEvent();
47 
48     netAppStatusCallback_ = new (std::nothrow) AppStatus((std::static_pointer_cast<NetPolicyCore>(shared_from_this())));
49     if (netAppStatusCallback_ == nullptr) {
50         NETMGR_LOG_E("netAppStatusCallback is nullptr.");
51         return;
52     }
53     std::thread t([this]() {
54         auto appManager = std::make_unique<AppMgrClient>();
55         uint32_t count = 0;
56         int32_t connectResult = AppMgrResultCode::ERROR_SERVICE_NOT_READY;
57         while (connectResult != AppMgrResultCode::RESULT_OK && count <= MAX_RETRY_TIMES) {
58             std::this_thread::sleep_for(std::chrono::milliseconds(AGAIN_REGISTER_CALLBACK_INTERVAL));
59             connectResult = appManager->ConnectAppMgrService();
60             count++;
61         }
62         if (count > MAX_RETRY_TIMES && connectResult != AppMgrResultCode::RESULT_OK) {
63             NETMGR_LOG_E("Connect AppMgrService fail.");
64         } else {
65             appManager->RegisterAppStateCallback(netAppStatusCallback_);
66         }
67     });
68 
69     std::string threadName = "NetPolicyInit";
70     pthread_setname_np(t.native_handle(), threadName.c_str());
71     t.detach();
72 }
73 
HandleEvent(int32_t eventId,std::shared_ptr<PolicyEvent> eventData)74 void NetPolicyCore::HandleEvent(int32_t eventId, std::shared_ptr<PolicyEvent> eventData)
75 {
76     for (const auto &core : cores_) {
77         if (eventData && core && core != eventData->sender) {
78             core->HandleEvent(eventId, eventData);
79         }
80     }
81 }
82 
SendEvent(int32_t eventId,std::shared_ptr<PolicyEvent> & eventData,int64_t delayTime)83 void NetPolicyCore::SendEvent(int32_t eventId, std::shared_ptr<PolicyEvent> &eventData, int64_t delayTime)
84 {
85     NETMGR_LOG_D("NetPolicyCore SendEvent: eventId[%{public}d]", eventId);
86     auto event = AppExecFwk::InnerEvent::Get(eventId, eventData);
87     if (handler_ == nullptr) {
88         NETMGR_LOG_E("handler is null");
89         return;
90     }
91 
92     handler_->SendEvent(event, delayTime);
93 }
94 
SubscribeCommonEvent()95 void NetPolicyCore::SubscribeCommonEvent()
96 {
97     NETMGR_LOG_D("SubscribeCommonEvent");
98     std::thread t([this]() {
99         EventFwk::MatchingSkills matchingSkills;
100         matchingSkills.AddEvent(COMMON_EVENT_POWER_SAVE_MODE_CHANGED);
101         matchingSkills.AddEvent(COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED);
102         matchingSkills.AddEvent(COMMON_EVENT_PACKAGE_REMOVED);
103         EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
104         subscribeInfo.SetPriority(CORE_EVENT_PRIORITY);
105         subscriber_ = std::make_shared<ReceiveMessage>(subscribeInfo, shared_from_this());
106         uint32_t count = 0;
107         bool result = false;
108         while (!result && count <= MAX_RETRY_TIMES) {
109             std::this_thread::sleep_for(std::chrono::milliseconds(AGAIN_REGISTER_CALLBACK_INTERVAL));
110             result = EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_);
111             count++;
112         }
113         if (count > MAX_RETRY_TIMES || !result) {
114             NETMGR_LOG_E("SubscribeCommonEvent fail.");
115         } else {
116             NETMGR_LOG_D("SubscribeCommonEvent successful");
117         }
118     });
119     std::string threadName = "PolicyEvent";
120     pthread_setname_np(t.native_handle(), threadName.c_str());
121     t.detach();
122 }
123 
OnReceiveEvent(const EventFwk::CommonEventData & eventData)124 void NetPolicyCore::ReceiveMessage::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
125 {
126     if (receiveMessage_ == nullptr) {
127         NETMGR_LOG_E("receive message is nullptr");
128         return;
129     }
130     const auto &action = eventData.GetWant().GetAction();
131     const auto &data = eventData.GetData();
132     const auto &code = eventData.GetCode();
133     if (action == COMMON_EVENT_POWER_SAVE_MODE_CHANGED) {
134 #ifdef NETMGR_POWER_SAVE_ENABLE
135         bool isPowerSave = (code == SAVE_MODE || code == LOWPOWER_MODE);
136         auto policyEvent = std::make_shared<PolicyEvent>();
137         policyEvent->powerSaveMode = isPowerSave;
138         receiveMessage_->SendEvent(NetPolicyEventHandler::MSG_POWER_SAVE_MODE_CHANGED, policyEvent);
139 #endif
140         return;
141     }
142 
143     if (action == COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED) {
144         bool isDeviceIdle = eventData.GetWant().GetBoolParam(DEVICE_IDLE_MODE_KEY, false);
145         auto policyEvent = std::make_shared<PolicyEvent>();
146         policyEvent->deviceIdleMode = isDeviceIdle;
147         receiveMessage_->SendEvent(NetPolicyEventHandler::MSG_DEVICE_IDLE_MODE_CHANGED, policyEvent);
148         return;
149     }
150 
151     if (action == COMMON_EVENT_PACKAGE_REMOVED) {
152         if (eventData.GetWant().GetIntParam(AppExecFwk::Constants::UID, 0) < 0) {
153             NETMGR_LOG_E("error:deletedUid < 0!,return");
154             return;
155         }
156         uint32_t deletedUid = static_cast<uint32_t>(eventData.GetWant().GetIntParam(AppExecFwk::Constants::UID, 0));
157         auto policyEvent = std::make_shared<PolicyEvent>();
158         policyEvent->deletedUid = deletedUid;
159         receiveMessage_->SendEvent(NetPolicyEventHandler::MSG_UID_REMOVED, policyEvent);
160         return;
161     }
162     NETMGR_LOG_E("Unknow action:[%{public}s], data:[%{public}s], code:[%{public}d]", action.c_str(), data.c_str(),
163                  code);
164 }
165 
SendAppStatusMessage(const AppProcessData & appProcessData)166 void NetPolicyCore::SendAppStatusMessage(const AppProcessData &appProcessData)
167 {
168     for (const auto &appdata : appProcessData.appDatas) {
169         auto policyEvent = std::make_shared<PolicyEvent>();
170         NETMGR_LOG_D(
171             "SendAppStatusMessage : appProcessData.appState[%{public}d] appProcessName[%{public}s] uid[%{public}d]",
172             appProcessData.appState, appProcessData.processName.c_str(), appdata.uid);
173         policyEvent->uid = appdata.uid;
174         if (appProcessData.appState == ApplicationState::APP_STATE_FOREGROUND) {
175             SendEvent(NetPolicyEventHandler::MSG_UID_STATE_FOREGROUND, policyEvent);
176         }
177 
178         if (appProcessData.appState == ApplicationState::APP_STATE_BACKGROUND) {
179             SendEvent(NetPolicyEventHandler::MSG_UID_STATE_BACKGROUND, policyEvent);
180         }
181     }
182 }
183 
ReceiveMessage(const EventFwk::CommonEventSubscribeInfo & subscriberInfo,std::shared_ptr<NetPolicyCore> core)184 NetPolicyCore::ReceiveMessage::ReceiveMessage(const EventFwk::CommonEventSubscribeInfo &subscriberInfo,
185                                               std::shared_ptr<NetPolicyCore> core)
186     : EventFwk::CommonEventSubscriber(subscriberInfo), receiveMessage_(core)
187 {
188 }
189 } // namespace NetManagerStandard
190 } // namespace OHOS
191