• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2024 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 "networkshare_tracker.h"
17 
18 #include <net/if.h>
19 #include <netinet/in.h>
20 #include <regex>
21 #include <securec.h>
22 #include <sys/ioctl.h>
23 #include <sys/socket.h>
24 
25 #include "battery_srv_client.h"
26 #include "net_manager_constants.h"
27 #include "net_manager_ext_constants.h"
28 #include "netmgr_ext_log_wrapper.h"
29 #include "netsys_controller.h"
30 #include "network_sharing.h"
31 #include "networkshare_constants.h"
32 #include "networkshare_state_common.h"
33 #ifdef SHARE_NOTIFICATION_ENABLE
34 #include "networkshare_notification.h"
35 #endif
36 #include "system_ability_definition.h"
37 #include "sys_timer.h"
38 #ifdef USB_MODOULE
39 #include "usb_errors.h"
40 #include "usb_srv_client.h"
41 #include "usb_srv_support.h"
42 #endif
43 #ifdef SHARE_TRAFFIC_LIMIT_ENABLE
44 #include "networkshare_trafficlimit.h"
45 #endif
46 
47 #define IFACENAME_LEN 20
48 
49 namespace OHOS {
50 namespace NetManagerStandard {
51 namespace {
52 constexpr const char *BLUETOOTH_DEFAULT_IFACE_NAME = "bt-pan";
53 #ifdef WIFI_MODOULE
54 constexpr const char *WIFI_AP_DEFAULT_IFACE_NAME = "wlan0";
55 constexpr const char *ERROR_MSG_ENABLE_WIFI = "Enable Wifi Iface failed";
56 constexpr const char *ERROR_MSG_DISABLE_WIFI = "Disable Wifi Iface failed";
57 constexpr const int IDLE_SOFTAP_STOP_INTERVAL_MS = 10 * 60 * 1000;
58 #endif
59 #ifdef BLUETOOTH_MODOULE
60 constexpr const char *ERROR_MSG_ENABLE_BTPAN = "Enable BlueTooth Iface failed";
61 constexpr const char *ERROR_MSG_DISABLE_BTPAN = "Disable BlueTooth Iface failed";
62 #endif
63 constexpr int32_t BYTE_TRANSFORM_KB = 1024;
64 constexpr int32_t MAX_CALLBACK_COUNT = 100;
65 }
66 constexpr const SharingIfaceType SHARE_VALID_INTERFACES[3] = {SharingIfaceType::SHARING_WIFI,
67     SharingIfaceType::SHARING_USB, SharingIfaceType::SHARING_BLUETOOTH};
68 
OnInterfaceAddressUpdated(const std::string &,const std::string &,int,int)69 int32_t NetworkShareTracker::NetsysCallback::OnInterfaceAddressUpdated(const std::string &, const std::string &, int,
70                                                                        int)
71 {
72     return 0;
73 }
74 
OnInterfaceAddressRemoved(const std::string &,const std::string &,int,int)75 int32_t NetworkShareTracker::NetsysCallback::OnInterfaceAddressRemoved(const std::string &, const std::string &, int,
76                                                                        int)
77 {
78     return 0;
79 }
80 
OnInterfaceAdded(const std::string & iface)81 int32_t NetworkShareTracker::NetsysCallback::OnInterfaceAdded(const std::string &iface)
82 {
83     NetworkShareTracker::GetInstance().InterfaceAdded(iface);
84     return 0;
85 }
86 
OnInterfaceRemoved(const std::string & iface)87 int32_t NetworkShareTracker::NetsysCallback::OnInterfaceRemoved(const std::string &iface)
88 {
89     NetworkShareTracker::GetInstance().InterfaceRemoved(iface);
90     return 0;
91 }
92 
OnInterfaceChanged(const std::string & iface,bool up)93 int32_t NetworkShareTracker::NetsysCallback::OnInterfaceChanged(const std::string &iface, bool up)
94 {
95     NetworkShareTracker::GetInstance().InterfaceStatusChanged(iface, up);
96     return 0;
97 }
98 
OnInterfaceLinkStateChanged(const std::string & iface,bool up)99 int32_t NetworkShareTracker::NetsysCallback::OnInterfaceLinkStateChanged(const std::string &iface, bool up)
100 {
101     NetworkShareTracker::GetInstance().InterfaceStatusChanged(iface, up);
102     return 0;
103 }
104 
OnRouteChanged(bool,const std::string &,const std::string &,const std::string &)105 int32_t NetworkShareTracker::NetsysCallback::OnRouteChanged(bool, const std::string &, const std::string &,
106                                                             const std::string &)
107 {
108     return 0;
109 }
110 
OnDhcpSuccess(NetsysControllerCallback::DhcpResult & dhcpResult)111 int32_t NetworkShareTracker::NetsysCallback::OnDhcpSuccess(NetsysControllerCallback::DhcpResult &dhcpResult)
112 {
113     return 0;
114 }
115 
OnBandwidthReachedLimit(const std::string & limitName,const std::string & iface)116 int32_t NetworkShareTracker::NetsysCallback::OnBandwidthReachedLimit(const std::string &limitName,
117                                                                      const std::string &iface)
118 {
119     return 0;
120 }
121 
ManagerEventHandler(const std::shared_ptr<AppExecFwk::EventRunner> & runner)122 NetworkShareTracker::ManagerEventHandler::ManagerEventHandler(const std::shared_ptr<AppExecFwk::EventRunner> &runner)
123     : AppExecFwk::EventHandler(runner)
124 {
125 }
126 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)127 void NetworkShareTracker::ManagerEventHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event)
128 {
129     if (event == nullptr) {
130         NETMGR_EXT_LOG_I("event is null");
131         return;
132     }
133     EHandlerEventType eventId = static_cast<EHandlerEventType>(event->GetInnerEventId());
134     if (eventId == EHandlerEventType::EVENT_HANDLER_MSG_FIR) {
135         NETMGR_EXT_LOG_I("EVENT_HANDLER_MSG_FIR");
136         return;
137     }
138     NETMGR_EXT_LOG_W("because eventId is unkonwn.");
139 }
140 
OnUpstreamStateChanged(int32_t msgName,int32_t param1)141 void NetworkShareTracker::MainSmUpstreamCallback::OnUpstreamStateChanged(int32_t msgName, int32_t param1)
142 {
143     (void)msgName;
144     MessageUpstreamInfo temp;
145     temp.cmd_ = param1;
146     temp.upstreamInfo_ = nullptr;
147     NETMGR_EXT_LOG_I("NOTIFY TO Main SM EVENT_UPSTREAM_CALLBACK with one param.");
148     NetworkShareTracker::GetInstance().GetMainStateMachine()->MainSmEventHandle(EVENT_UPSTREAM_CALLBACK, temp);
149 }
150 
OnUpstreamStateChanged(int32_t msgName,int32_t param1,int32_t param2,const std::any & messageObj)151 void NetworkShareTracker::MainSmUpstreamCallback::OnUpstreamStateChanged(int32_t msgName, int32_t param1,
152                                                                          int32_t param2, const std::any &messageObj)
153 {
154     (void)msgName;
155     (void)param2;
156     std::shared_ptr<UpstreamNetworkInfo> upstreamInfo = std::any_cast<std::shared_ptr<UpstreamNetworkInfo>>(messageObj);
157     if (upstreamInfo != nullptr) {
158         NetworkShareTracker::GetInstance().SendSharingUpstreamChange(upstreamInfo->netHandle_);
159     }
160     MessageUpstreamInfo temp;
161     temp.cmd_ = param1;
162     temp.upstreamInfo_ = upstreamInfo;
163     NETMGR_EXT_LOG_I("NOTIFY TO Main SM EVENT_UPSTREAM_CALLBACK with two param.");
164     NetworkShareTracker::GetInstance().GetMainStateMachine()->MainSmEventHandle(EVENT_UPSTREAM_CALLBACK, temp);
165 }
166 
OnUpdateInterfaceState(const std::shared_ptr<NetworkShareSubStateMachine> & paraSubStateMachine,int state,int lastError)167 void NetworkShareTracker::SubSmUpstreamCallback::OnUpdateInterfaceState(
168     const std::shared_ptr<NetworkShareSubStateMachine> &paraSubStateMachine, int state, int lastError)
169 {
170     NetworkShareTracker::GetInstance().HandleSubSmUpdateInterfaceState(paraSubStateMachine, state, lastError);
171 }
172 
NetSharingSubSmState(const std::shared_ptr<NetworkShareSubStateMachine> & subStateMachine,bool isNcm)173 NetworkShareTracker::NetSharingSubSmState::NetSharingSubSmState(
174     const std::shared_ptr<NetworkShareSubStateMachine> &subStateMachine, bool isNcm)
175     : subStateMachine_(subStateMachine),
176       lastState_(SUB_SM_STATE_AVAILABLE),
177       lastError_(NETMANAGER_EXT_SUCCESS),
178       isNcm_(isNcm)
179 {
180 }
181 
182 #ifdef BLUETOOTH_MODOULE
OnConnectionStateChanged(const Bluetooth::BluetoothRemoteDevice & device,int state,int cause)183 void NetworkShareTracker::SharingPanObserver::OnConnectionStateChanged(const Bluetooth::BluetoothRemoteDevice &device,
184                                                                        int state, int cause)
185 {
186     NETMGR_EXT_LOG_I("Recieve bt-pan state changed event, state[%{public}d].", state);
187     Bluetooth::BTConnectState curState = static_cast<Bluetooth::BTConnectState>(state);
188     NetworkShareTracker::GetInstance().SetBluetoothState(curState);
189     switch (curState) {
190         case Bluetooth::BTConnectState::CONNECTING:
191             break;
192         case Bluetooth::BTConnectState::CONNECTED: {
193             NetworkShareTracker::GetInstance().EnableBluetoothSubStateMachine();
194             break;
195         }
196         case Bluetooth::BTConnectState::DISCONNECTING:
197             break;
198         case Bluetooth::BTConnectState::DISCONNECTED: {
199             NetworkShareTracker::GetInstance().StopSubStateMachine(BLUETOOTH_DEFAULT_IFACE_NAME,
200                                                                    SharingIfaceType::SHARING_BLUETOOTH);
201             break;
202         }
203         default:
204             break;
205     }
206 }
207 #endif
GetInstance()208 NetworkShareTracker &NetworkShareTracker::GetInstance()
209 {
210     static NetworkShareTracker instance;
211     return instance;
212 }
213 
RecoverSharingType()214 void NetworkShareTracker::RecoverSharingType()
215 {
216     NETMGR_EXT_LOG_I("NetworkShareTracker::RecoverSharingType in");
217     std::set<uint32_t> sharingTypeIsOn;
218     int32_t ret = NetsysController::GetInstance().GetNetworkSharingType(sharingTypeIsOn);
219     if (ret == NETMANAGER_EXT_SUCCESS) {
220         clientRequestsVector_.clear();
221         for (auto mem : sharingTypeIsOn) {
222             clientRequestsVector_.push_back(static_cast<SharingIfaceType>(mem));
223             NETMGR_EXT_LOG_D("clientRequestsVector_.push_back = [%{public}u]", mem);
224             EnableNetSharingInternal(static_cast<SharingIfaceType>(mem), false);
225             EnableNetSharingInternal(static_cast<SharingIfaceType>(mem), true);
226         }
227         NETMGR_EXT_LOG_I("now clientRequestsVector_.size() = [%{public}zu], ret = [%{public}d]",
228                          clientRequestsVector_.size(), ret);
229     }
230 }
231 
Init()232 bool NetworkShareTracker::Init()
233 {
234     configuration_ = std::make_shared<NetworkShareConfiguration>();
235     networkShareTrackerFfrtQueue_ =  std::make_shared<ffrt::queue>("networkShareTrackerFfrtQueue_");
236     if (!networkShareTrackerFfrtQueue_) {
237         NETMGR_EXT_LOG_E("ffrt create failed!");
238         return false;
239     }
240 
241     std::shared_ptr<NetworkShareUpstreamMonitor> upstreamNetworkMonitor =
242         DelayedSingleton<NetworkShareUpstreamMonitor>::GetInstance();
243     upstreamNetworkMonitor->SetOptionData(EVENT_UPSTREAM_CALLBACK);
244     upstreamNetworkMonitor->RegisterUpstreamChangedCallback(std::make_shared<MainSmUpstreamCallback>());
245     mainStateMachine_ = std::make_shared<NetworkShareMainStateMachine>(upstreamNetworkMonitor);
246 
247     netsysCallback_ = new (std::nothrow) NetsysCallback();
248     NetsysController::GetInstance().RegisterCallback(netsysCallback_);
249 
250     RegisterWifiApCallback();
251     RegisterBtPanCallback();
252 
253     isNetworkSharing_ = false;
254     isInit = true;
255     NETMGR_EXT_LOG_I("Tracker Init sucessful.");
256 
257     RecoverSharingType();
258 
259     return true;
260 }
261 
OnChangeSharingState(const SharingIfaceType & type,bool state)262 void NetworkShareTracker::OnChangeSharingState(const SharingIfaceType &type, bool state)
263 {
264     auto fit = find(clientRequestsVector_.begin(), clientRequestsVector_.end(), type);
265     if (state && fit == clientRequestsVector_.end()) {
266         clientRequestsVector_.push_back(type);
267     }
268     if (!state && fit != clientRequestsVector_.end()) {
269         clientRequestsVector_.erase(fit);
270     }
271     SendGlobalSharingStateChange();
272     NETMGR_EXT_LOG_I("Hotspot OnChangeSharing, clientRequestsVector_ [%{public}zu]", clientRequestsVector_.size());
273 }
274 
OnWifiHotspotStateChanged(int state)275 void NetworkShareTracker::OnWifiHotspotStateChanged(int state)
276 {
277     NETMGR_EXT_LOG_I("Receive Hotspot state changed event, state[%{public}d]", state);
278 #ifdef WIFI_MODOULE
279     Wifi::ApState curState = static_cast<Wifi::ApState>(state);
280     NetworkShareTracker::GetInstance().SetWifiState(curState);
281     switch (curState) {
282         case Wifi::ApState::AP_STATE_STARTING:
283             break;
284         case Wifi::ApState::AP_STATE_STARTED: {
285             NetworkShareTracker::GetInstance().HandleHotSpotStarted();
286             break;
287         }
288         case Wifi::ApState::AP_STATE_CLOSING:
289             break;
290         case Wifi::ApState::AP_STATE_CLOSED: {
291             NetworkShareTracker::GetInstance().HandleHotSpotClosed();
292             break;
293         }
294         default:
295             break;
296     }
297 #endif
298 }
299 
OnWifiHotspotStaLeave(StationInfo * info)300 void NetworkShareTracker::OnWifiHotspotStaLeave(StationInfo *info)
301 {
302 #ifdef WIFI_MODOULE
303     NetworkShareTracker::GetInstance().HandleHotSpotStaLeave();
304 #endif
305 }
306 
OnWifiHotspotStaJoin(StationInfo * info)307 void NetworkShareTracker::OnWifiHotspotStaJoin(StationInfo *info)
308 {
309 #ifdef WIFI_MODOULE
310     NetworkShareTracker::GetInstance().HandleHotSpotStaJoin();
311 #endif
312 }
313 
RegisterWifiApCallback()314 void NetworkShareTracker::RegisterWifiApCallback()
315 {
316 #ifdef WIFI_MODOULE
317     g_wifiEvent.OnHotspotStateChanged = NetworkShareTracker::OnWifiHotspotStateChanged;
318     g_wifiEvent.OnHotspotStaLeave = NetworkShareTracker::OnWifiHotspotStaLeave;
319     g_wifiEvent.OnHotspotStaJoin = NetworkShareTracker::OnWifiHotspotStaJoin;
320     int32_t ret = RegisterWifiEvent(&g_wifiEvent);
321     if (ret != WIFI_SUCCESS) {
322         NETMGR_EXT_LOG_E("Register wifi hotspot callback error[%{public}d].", ret);
323     }
324     return;
325 #endif
326 }
327 
RegisterBtPanCallback()328 void NetworkShareTracker::RegisterBtPanCallback()
329 {
330 #ifdef BLUETOOTH_MODOULE
331     Bluetooth::Pan *profile = Bluetooth::Pan::GetProfile();
332     if (profile == nullptr) {
333         return;
334     }
335     panObserver_ = std::make_shared<SharingPanObserver>();
336     if (panObserver_ != nullptr) {
337         profile->RegisterObserver(panObserver_);
338     }
339 #endif
340 }
341 
Uninit()342 void NetworkShareTracker::Uninit()
343 {
344     isInit = false;
345 #ifdef BLUETOOTH_MODOULE
346     Bluetooth::Pan *profile = Bluetooth::Pan::GetProfile();
347     if (profile == nullptr || panObserver_ == nullptr) {
348         NETMGR_EXT_LOG_E("bt-pan profile or observer is null.");
349         return;
350     }
351     profile->DeregisterObserver(panObserver_);
352 #endif
353     NETMGR_EXT_LOG_I("Uninit successful.");
354 }
355 
GetMainStateMachine()356 std::shared_ptr<NetworkShareMainStateMachine> &NetworkShareTracker::GetMainStateMachine()
357 {
358     return mainStateMachine_;
359 }
360 
361 #ifdef WIFI_MODOULE
SetWifiState(const Wifi::ApState & state)362 void NetworkShareTracker::SetWifiState(const Wifi::ApState &state)
363 {
364     curWifiState_ = state;
365 }
366 #endif
367 
368 #ifdef BLUETOOTH_MODOULE
SetBluetoothState(const Bluetooth::BTConnectState & state)369 void NetworkShareTracker::SetBluetoothState(const Bluetooth::BTConnectState &state)
370 {
371     curBluetoothState_ = state;
372 }
373 #endif
374 
HandleSubSmUpdateInterfaceState(const std::shared_ptr<NetworkShareSubStateMachine> & who,int32_t state,int32_t lastError)375 void NetworkShareTracker::HandleSubSmUpdateInterfaceState(const std::shared_ptr<NetworkShareSubStateMachine> &who,
376                                                           int32_t state, int32_t lastError)
377 {
378     if (who == nullptr) {
379         NETMGR_EXT_LOG_E("subsm is null.");
380         return;
381     }
382     std::shared_ptr<NetSharingSubSmState> shareState = nullptr;
383     std::string ifaceName;
384     {
385         std::lock_guard<ffrt::mutex> lock(mutex_);
386         auto iter = subStateMachineMap_.find(who->GetInterfaceName());
387         if (iter != subStateMachineMap_.end()) {
388             ifaceName = iter->first;
389             shareState = iter->second;
390         }
391     }
392     if (shareState != nullptr) {
393         NETMGR_EXT_LOG_I("iface=%{public}s state is change from[%{public}d] to[%{public}d].", ifaceName.c_str(),
394                          shareState->lastState_, state);
395         shareState->lastError_ = lastError;
396         if (shareState->lastState_ != state) {
397             shareState->lastState_ = state;
398             SendIfaceSharingStateChange(who->GetNetShareType(), ifaceName, SubSmStateToExportState(state));
399         }
400     } else {
401         NETMGR_EXT_LOG_W("iface=%{public}s is not find", (who->GetInterfaceName()).c_str());
402     }
403 
404     if (lastError == NETWORKSHARE_ERROR_INTERNAL_ERROR) {
405         SendMainSMEvent(who, CMD_CLEAR_ERROR, 0);
406     }
407     int32_t which = 0;
408     switch (state) {
409         case SUB_SM_STATE_AVAILABLE:
410         case SUB_SM_STATE_UNAVAILABLE:
411             which = EVENT_IFACE_SM_STATE_INACTIVE;
412             break;
413         case SUB_SM_STATE_SHARED:
414             which = EVENT_IFACE_SM_STATE_ACTIVE;
415             break;
416         default:
417             NETMGR_EXT_LOG_E("Unknown interface state=%{public}d", state);
418             return;
419     }
420     SendMainSMEvent(who, which, state);
421 }
422 
SendMainSMEvent(const std::shared_ptr<NetworkShareSubStateMachine> & subSM,int32_t event,int32_t state)423 void NetworkShareTracker::SendMainSMEvent(const std::shared_ptr<NetworkShareSubStateMachine> &subSM, int32_t event,
424                                           int32_t state)
425 {
426     if (mainStateMachine_ == nullptr) {
427         NETMGR_EXT_LOG_I("MainSM is null");
428         return;
429     }
430     NETMGR_EXT_LOG_I("Notify to Main SM event[%{public}d].", event);
431     MessageIfaceActive message;
432     message.value_ = state;
433     message.subsm_ = subSM;
434     mainStateMachine_->MainSmEventHandle(event, message);
435 }
436 
IsNetworkSharingSupported(int32_t & supported)437 int32_t NetworkShareTracker::IsNetworkSharingSupported(int32_t &supported)
438 {
439     if (configuration_ == nullptr) {
440         supported = NETWORKSHARE_IS_UNSUPPORTED;
441         return NETWORKSHARE_ERROR_IFACE_CFG_ERROR;
442     }
443     if (configuration_->IsNetworkSharingSupported()) {
444         supported = NETWORKSHARE_IS_SUPPORTED;
445     } else {
446         supported = NETWORKSHARE_IS_UNSUPPORTED;
447     }
448     NETMGR_EXT_LOG_I("NetworkShareTracker supported is %{public}d", supported);
449     return NETMANAGER_EXT_SUCCESS;
450 }
451 
IsSharing(int32_t & sharingStatus)452 int32_t NetworkShareTracker::IsSharing(int32_t &sharingStatus)
453 {
454     std::lock_guard<ffrt::mutex> lock(mutex_);
455     for (auto &iter : subStateMachineMap_) {
456         std::shared_ptr<NetSharingSubSmState> shareState = iter.second;
457         if (shareState == nullptr) {
458             continue;
459         }
460         if (shareState->lastState_ == SUB_SM_STATE_SHARED) {
461             NETMGR_EXT_LOG_I("NetworkShareTracker is sharing.");
462             sharingStatus = NETWORKSHARE_IS_SHARING;
463             return NETMANAGER_EXT_SUCCESS;
464         }
465     }
466     NETMGR_EXT_LOG_I("NetworkShareTracker is unsharing.");
467     sharingStatus = NETWORKSHARE_IS_UNSHARING;
468     return NETMANAGER_EXT_SUCCESS;
469 }
470 
StartNetworkSharing(const SharingIfaceType & type)471 int32_t NetworkShareTracker::StartNetworkSharing(const SharingIfaceType &type)
472 {
473     NETMGR_EXT_LOG_I("NetworkShare start sharing,clientRequestsVector_.size = %{public}zu.",
474                      clientRequestsVector_.size());
475     auto fit = find(clientRequestsVector_.begin(), clientRequestsVector_.end(), type);
476     if (fit != clientRequestsVector_.end()) {
477         NETMGR_EXT_LOG_I("type[%{public}d] is sharing, will close", type);
478         int32_t ret = EnableNetSharingInternal(type, false);
479         if (ret != NETMANAGER_EXT_SUCCESS) {
480             NETMGR_EXT_LOG_E("stop current [%{public}d] sharing error [%{public}ul]", static_cast<int32_t>(type), ret);
481             return ret;
482         }
483     } else {
484         clientRequestsVector_.push_back(type);
485     }
486 #ifdef SHARE_TRAFFIC_LIMIT_ENABLE
487     NetworkShareTrafficLimit::GetInstance().StartHandleSharingLimitEvent();
488 #endif
489     return EnableNetSharingInternal(type, true);
490 }
491 
StopNetworkSharing(const SharingIfaceType & type)492 int32_t NetworkShareTracker::StopNetworkSharing(const SharingIfaceType &type)
493 {
494     NETMGR_EXT_LOG_I("NetworkShare stop sharing,clientRequestsVector_.size = %{public}zu.",
495                      clientRequestsVector_.size());
496     auto fit = find(clientRequestsVector_.begin(), clientRequestsVector_.end(), type);
497     if (fit != clientRequestsVector_.end()) {
498         clientRequestsVector_.erase(fit);
499     }
500 #ifdef SHARE_TRAFFIC_LIMIT_ENABLE
501     NetworkShareTrafficLimit::GetInstance().EndHandleSharingLimitEvent();
502 #endif
503     return EnableNetSharingInternal(type, false);
504 }
505 
GetSharableRegexs(SharingIfaceType type,std::vector<std::string> & ifaceRegexs)506 int32_t NetworkShareTracker::GetSharableRegexs(SharingIfaceType type, std::vector<std::string> &ifaceRegexs)
507 {
508     if (configuration_ == nullptr) {
509         NETMGR_EXT_LOG_E("configuration_ is null.");
510         return NETWORKSHARE_ERROR_IFACE_CFG_ERROR;
511     }
512     NETMGR_EXT_LOG_I("NetworkSharing GetSharableRegexs type is %{public}d", type);
513     switch (type) {
514         case SharingIfaceType::SHARING_WIFI: {
515             ifaceRegexs = configuration_->GetWifiIfaceRegexs();
516             return NETMANAGER_EXT_SUCCESS;
517         }
518         case SharingIfaceType::SHARING_USB: {
519             ifaceRegexs = configuration_->GetUsbIfaceRegexs();
520             return NETMANAGER_EXT_SUCCESS;
521         }
522         case SharingIfaceType::SHARING_BLUETOOTH: {
523             ifaceRegexs = configuration_->GetBluetoothIfaceRegexs();
524             return NETMANAGER_EXT_SUCCESS;
525         }
526         default: {
527             NETMGR_EXT_LOG_E("type[%{public}d] is unkonwn.", type);
528             return NETWORKSHARE_ERROR_UNKNOWN_TYPE;
529         }
530     }
531 }
532 
IsInterfaceMatchType(const std::string & iface,const SharingIfaceType & type)533 bool NetworkShareTracker::IsInterfaceMatchType(const std::string &iface, const SharingIfaceType &type)
534 {
535     if (configuration_ == nullptr) {
536         return false;
537     }
538     if (type == SharingIfaceType::SHARING_WIFI && configuration_->IsWifiIface(iface)) {
539         return true;
540     }
541     if (type == SharingIfaceType::SHARING_USB && configuration_->IsUsbIface(iface)) {
542         return true;
543     }
544     if (type == SharingIfaceType::SHARING_BLUETOOTH && configuration_->IsBluetoothIface(iface)) {
545         return true;
546     }
547     return false;
548 }
549 
GetSharingState(const SharingIfaceType type,SharingIfaceState & state)550 int32_t NetworkShareTracker::GetSharingState(const SharingIfaceType type, SharingIfaceState &state)
551 {
552     NETMGR_EXT_LOG_I("NetworkSharing GetSharingState type is %{public}d", type);
553     if (type != SharingIfaceType::SHARING_WIFI &&
554         type != SharingIfaceType::SHARING_USB &&
555         type != SharingIfaceType::SHARING_BLUETOOTH) {
556         return NETWORKSHARE_ERROR_UNKNOWN_TYPE;
557     }
558     bool isFindType = false;
559     state = SharingIfaceState::SHARING_NIC_CAN_SERVER;
560     std::lock_guard<ffrt::mutex> lock(mutex_);
561     for (const auto &iter : subStateMachineMap_) {
562         if (IsInterfaceMatchType(iter.first, type)) {
563             std::shared_ptr<NetSharingSubSmState> subsmState = iter.second;
564             if (subsmState == nullptr) {
565                 NETMGR_EXT_LOG_W("subsmState is null.");
566                 continue;
567             }
568             if (subsmState->lastState_ == SUB_SM_STATE_UNAVAILABLE) {
569                 state = SharingIfaceState::SHARING_NIC_ERROR;
570                 isFindType = true;
571                 break;
572             }
573             if (subsmState->lastState_ == SUB_SM_STATE_AVAILABLE) {
574                 state = SharingIfaceState::SHARING_NIC_CAN_SERVER;
575                 isFindType = true;
576                 break;
577             }
578             if (subsmState->lastState_ == SUB_SM_STATE_SHARED) {
579                 state = SharingIfaceState::SHARING_NIC_SERVING;
580                 isFindType = true;
581                 break;
582             }
583             NETMGR_EXT_LOG_W("lastState_=%{public}d is unknown data.", subsmState->lastState_);
584         } else {
585             NETMGR_EXT_LOG_W("iface=%{public}s is not match type[%{public}d]", iter.first.c_str(), type);
586         }
587     }
588     if (!isFindType) {
589         NETMGR_EXT_LOG_E("type=%{public}d is not find, used default value.", type);
590     }
591     NETMGR_EXT_LOG_I("type=%{public}d is find, isFindType is %{public}d.", type, isFindType);
592     return NETMANAGER_EXT_SUCCESS;
593 }
594 
GetNetSharingIfaces(const SharingIfaceState & state,std::vector<std::string> & ifaces)595 int32_t NetworkShareTracker::GetNetSharingIfaces(const SharingIfaceState &state, std::vector<std::string> &ifaces)
596 {
597     NETMGR_EXT_LOG_I("NetworkSharing GetNetSharingIfaces type is %{public}d", state);
598     if (state != SharingIfaceState::SHARING_NIC_ERROR &&
599         state != SharingIfaceState::SHARING_NIC_CAN_SERVER &&
600         state != SharingIfaceState::SHARING_NIC_SERVING) {
601         return NETWORKSHARE_ERROR_UNKNOWN_TYPE;
602     }
603     std::lock_guard<ffrt::mutex> lock(mutex_);
604     for_each(subStateMachineMap_.begin(), subStateMachineMap_.end(), [&](auto iter) {
605         std::shared_ptr<NetSharingSubSmState> subsmState = iter.second;
606         if (subsmState == nullptr) {
607             NETMGR_EXT_LOG_W("iface=%{public}s subsmState is null.", (iter.first).c_str());
608             return;
609         }
610         NETMGR_EXT_LOG_I("iface=%{public}s, state=%{public}d", (iter.first).c_str(), subsmState->lastState_);
611         if ((state == SharingIfaceState::SHARING_NIC_ERROR && subsmState->lastState_ == SUB_SM_STATE_UNAVAILABLE) ||
612             (state == SharingIfaceState::SHARING_NIC_CAN_SERVER && subsmState->lastState_ == SUB_SM_STATE_AVAILABLE) ||
613             (state == SharingIfaceState::SHARING_NIC_SERVING && subsmState->lastState_ == SUB_SM_STATE_SHARED)) {
614             ifaces.push_back(iter.first);
615         }
616     });
617     NETMGR_EXT_LOG_I("GetNetSharingIfaces ifaces.size is %{public}zu", ifaces.size());
618     return NETMANAGER_EXT_SUCCESS;
619 }
620 
RegisterSharingEvent(sptr<ISharingEventCallback> callback)621 int32_t NetworkShareTracker::RegisterSharingEvent(sptr<ISharingEventCallback> callback)
622 {
623     if (callback == nullptr) {
624         NETMGR_EXT_LOG_E("callback is null.");
625         return NETMANAGER_EXT_ERR_LOCAL_PTR_NULL;
626     }
627     std::lock_guard<ffrt::mutex> lock(callbackMutex_);
628     if (sharingEventCallback_.size() >= MAX_CALLBACK_COUNT) {
629         NETMGR_EXT_LOG_E("callback above max count, return error.");
630         return NETWORKSHARE_ERROR_ISSHARING_CALLBACK_ERROR;
631     }
632     for (auto iter = sharingEventCallback_.begin(); iter != sharingEventCallback_.end(); ++iter) {
633         if (callback->AsObject().GetRefPtr() == (*iter)->AsObject().GetRefPtr()) {
634             NETMGR_EXT_LOG_I("SharingEventCallback find same callback");
635             return NETMANAGER_EXT_SUCCESS;
636         }
637     }
638     sharingEventCallback_.push_back(callback);
639     NETMGR_EXT_LOG_I("RegisterSharingEvent is successful, sharingEventCallback_.size = %{public}zu",
640                      sharingEventCallback_.size());
641     return NETMANAGER_EXT_SUCCESS;
642 }
643 
UnregisterSharingEvent(sptr<ISharingEventCallback> callback)644 int32_t NetworkShareTracker::UnregisterSharingEvent(sptr<ISharingEventCallback> callback)
645 {
646     std::lock_guard<ffrt::mutex> lock(callbackMutex_);
647     for (auto iter = sharingEventCallback_.begin(); iter != sharingEventCallback_.end(); ++iter) {
648         if (callback->AsObject().GetRefPtr() == (*iter)->AsObject().GetRefPtr()) {
649             sharingEventCallback_.erase(iter);
650             break;
651         }
652     }
653     NETMGR_EXT_LOG_I("UnregisterSharingEvent is successful, sharingEventCallback_.size = %{public}zu",
654                      sharingEventCallback_.size());
655     return NETMANAGER_EXT_SUCCESS;
656 }
657 
GetSharedSubSMTraffic(const TrafficType & type,int32_t & kbByte)658 int32_t NetworkShareTracker::GetSharedSubSMTraffic(const TrafficType &type, int32_t &kbByte)
659 {
660     int64_t bytes = 0;
661     NETMGR_EXT_LOG_I("GetSharedSubSMTraffic start, type is %{public}d", type);
662     for (auto &subSM : sharedSubSM_) {
663         if (subSM == nullptr) {
664             continue;
665         }
666         std::string downIface;
667         std::string upIface;
668         subSM->GetDownIfaceName(downIface);
669         subSM->GetUpIfaceName(upIface);
670         nmd::NetworkSharingTraffic traffic;
671         NETMGR_EXT_LOG_I("DownIface[%{public}s], upIface[%{public}s].", downIface.c_str(), upIface.c_str());
672         int32_t ret = NetsysController::GetInstance().GetNetworkSharingTraffic(downIface, upIface, traffic);
673         if (ret != NETMANAGER_SUCCESS) {
674             NETMGR_EXT_LOG_E("GetTrafficBytes err, ret[%{public}d].", ret);
675             continue;
676         }
677         switch (type) {
678             case TrafficType::TRAFFIC_RX:
679                 bytes += traffic.receive;
680                 break;
681             case TrafficType::TRAFFIC_TX:
682                 bytes += traffic.send;
683                 break;
684             case TrafficType::TRAFFIC_ALL:
685                 bytes += traffic.all;
686                 break;
687             default:
688                 break;
689         }
690     }
691 
692     kbByte = static_cast<int32_t>(bytes / BYTE_TRANSFORM_KB);
693     if (kbByte > std::numeric_limits<int32_t>::max()) {
694         NETMGR_EXT_LOG_I("GetBytes [%{public}s] is above max.", std::to_string(kbByte).c_str());
695         kbByte = std::numeric_limits<int32_t>::max();
696     }
697     return NETMANAGER_EXT_SUCCESS;
698 }
699 
EnableNetSharingInternal(const SharingIfaceType & type,bool enable)700 int32_t NetworkShareTracker::EnableNetSharingInternal(const SharingIfaceType &type, bool enable)
701 {
702     NETMGR_EXT_LOG_I("NetSharing type[%{public}d] enable[%{public}d].", type, enable);
703     int32_t result = NETMANAGER_EXT_SUCCESS;
704     switch (type) {
705         case SharingIfaceType::SHARING_WIFI:
706             result = SetWifiNetworkSharing(enable);
707             break;
708         case SharingIfaceType::SHARING_USB:
709             result = SetUsbNetworkSharing(enable);
710             break;
711         case SharingIfaceType::SHARING_BLUETOOTH:
712             result = SetBluetoothNetworkSharing(enable);
713             break;
714         default:
715             NETMGR_EXT_LOG_E("Invalid networkshare type.");
716             result = NETWORKSHARE_ERROR_UNKNOWN_TYPE;
717             break;
718     }
719     NETMGR_EXT_LOG_I("NetSharing EnableNetSharingInternal result is %{public}d.", result);
720     if (result != NETMANAGER_EXT_SUCCESS) {
721         auto it = find(clientRequestsVector_.begin(), clientRequestsVector_.end(), type);
722         if (it != clientRequestsVector_.end()) {
723             clientRequestsVector_.erase(it);
724         }
725     }
726 
727     return result;
728 }
729 
SetWifiNetworkSharing(bool enable)730 int32_t NetworkShareTracker::SetWifiNetworkSharing(bool enable)
731 {
732     int32_t result = NETMANAGER_EXT_SUCCESS;
733 #ifdef WIFI_MODOULE
734     if (enable) {
735         int32_t ret = EnableHotspot();
736         if (ret != WIFI_SUCCESS) {
737             NETMGR_EXT_LOG_E("EnableHotspot error[%{public}d].", ret);
738             result = NETWORKSHARE_ERROR_WIFI_SHARING;
739             NetworkShareHisysEvent::GetInstance().SendFaultEvent(
740                 SharingIfaceType::SHARING_WIFI, NetworkShareEventOperator::OPERATION_ENABLE_IFACE,
741                 NetworkShareEventErrorType::ERROR_ENABLE_IFACE, ERROR_MSG_ENABLE_WIFI,
742                 NetworkShareEventType::SETUP_EVENT);
743         } else {
744             NETMGR_EXT_LOG_I("EnableHotspot successfull.");
745             if (wifiShareCount_ < INT32_MAX) {
746                 wifiShareCount_++;
747             }
748             NetworkShareHisysEvent::GetInstance().SendBehaviorEvent(wifiShareCount_, SharingIfaceType::SHARING_WIFI);
749             NETMGR_EXT_LOG_E("wifiShareCount_[%{public}d].", wifiShareCount_);
750         }
751     } else {
752         int32_t ret = DisableHotspot();
753         if (ret != WIFI_SUCCESS) {
754             NetworkShareHisysEvent::GetInstance().SendFaultEvent(
755                 SharingIfaceType::SHARING_WIFI, NetworkShareEventOperator::OPERATION_DISABLE_IFACE,
756                 NetworkShareEventErrorType::ERROR_DISABLE_IFACE, ERROR_MSG_DISABLE_WIFI,
757                 NetworkShareEventType::CANCEL_EVENT);
758             NETMGR_EXT_LOG_E("DisableHotspot error[%{public}d].", ret);
759             result = NETWORKSHARE_ERROR_WIFI_SHARING;
760         } else {
761             NETMGR_EXT_LOG_I("DisableHotspot successful.");
762         }
763     }
764 #endif
765     return result;
766 }
767 
SetUsbNetworkSharing(bool enable)768 int32_t NetworkShareTracker::SetUsbNetworkSharing(bool enable)
769 {
770 #ifdef USB_MODOULE
771     auto &usbSrvClient = USB::UsbSrvClient::GetInstance();
772     if (enable) {
773         curUsbState_ = UsbShareState::USB_SHARING;
774         int32_t ret = usbSrvClient.GetCurrentFunctions(previousFuncs_);
775         if (ret != USB::UEC_OK) {
776             NETMGR_EXT_LOG_E("GetCurrentFunctions error[%{public}d].", ret);
777             return NETWORKSHARE_ERROR_USB_SHARING;
778         }
779         ret = usbSrvClient.SetCurrentFunctions(USB::UsbSrvSupport::FUNCTION_RNDIS);
780         if (ret != USB::UEC_OK) {
781             NETMGR_EXT_LOG_E("SetCurrentFunctions error[%{public}d].", ret);
782             return NETWORKSHARE_ERROR_USB_SHARING;
783         }
784         if (usbShareCount_ < INT32_MAX) {
785             usbShareCount_++;
786         }
787         NetworkShareHisysEvent::GetInstance().SendBehaviorEvent(usbShareCount_, SharingIfaceType::SHARING_USB);
788     } else {
789         if (curUsbState_ == UsbShareState::USB_NONE) {
790             return NETMANAGER_EXT_SUCCESS;
791         }
792         curUsbState_ = UsbShareState::USB_CLOSING;
793         int32_t ret = usbSrvClient.SetCurrentFunctions(previousFuncs_);
794         if (ret != USB::UEC_OK) {
795             NETMGR_EXT_LOG_E("usb SetCurrentFunctions error[%{public}d].", ret);
796             return NETWORKSHARE_ERROR_USB_SHARING;
797         }
798     }
799 #endif
800     return NETMANAGER_EXT_SUCCESS;
801 }
802 
SetBluetoothNetworkSharing(bool enable)803 int32_t NetworkShareTracker::SetBluetoothNetworkSharing(bool enable)
804 {
805 #ifdef BLUETOOTH_MODOULE
806     Bluetooth::Pan *profile = Bluetooth::Pan::GetProfile();
807     if (profile == nullptr) {
808         NETMGR_EXT_LOG_E("SetBluetoothNetworkSharing(%{public}s) profile is null].", enable ? "true" : "false");
809         return NETWORKSHARE_ERROR_BT_SHARING;
810     }
811     if (enable && panObserver_ == nullptr) {
812         NETMGR_EXT_LOG_I("register bluetooth pan callback.");
813         RegisterBtPanCallback();
814     }
815     bool ret = profile->SetTethering(enable);
816     if (ret) {
817         NETMGR_EXT_LOG_I("SetBluetoothNetworkSharing(%{public}s) is success.", enable ? "true" : "false");
818         if (enable && bluetoothShareCount_ < INT32_MAX) {
819             bluetoothShareCount_++;
820         }
821         NetworkShareHisysEvent::GetInstance().SendBehaviorEvent(bluetoothShareCount_,
822                                                                 SharingIfaceType::SHARING_BLUETOOTH);
823         return NETMANAGER_EXT_SUCCESS;
824     }
825     if (enable) {
826         NetworkShareHisysEvent::GetInstance().SendFaultEvent(
827             SharingIfaceType::SHARING_BLUETOOTH, NetworkShareEventOperator::OPERATION_ENABLE_IFACE,
828             NetworkShareEventErrorType::ERROR_ENABLE_IFACE, ERROR_MSG_ENABLE_BTPAN, NetworkShareEventType::SETUP_EVENT);
829     } else {
830         NetworkShareHisysEvent::GetInstance().SendFaultEvent(
831             SharingIfaceType::SHARING_BLUETOOTH, NetworkShareEventOperator::OPERATION_DISABLE_IFACE,
832             NetworkShareEventErrorType::ERROR_DISABLE_IFACE, ERROR_MSG_DISABLE_BTPAN,
833             NetworkShareEventType::CANCEL_EVENT);
834     }
835 
836     NETMGR_EXT_LOG_E("SetBluetoothNetworkSharing(%{public}s) is error.", enable ? "true" : "false");
837 #endif
838     return NETWORKSHARE_ERROR_BT_SHARING;
839 }
840 
Sharing(const std::string & iface,int32_t reqState)841 int32_t NetworkShareTracker::Sharing(const std::string &iface, int32_t reqState)
842 {
843     std::shared_ptr<NetSharingSubSmState> subSMState = nullptr;
844     {
845         std::lock_guard<ffrt::mutex> lock(mutex_);
846         std::map<std::string, std::shared_ptr<NetSharingSubSmState>>::iterator iter = subStateMachineMap_.find(iface);
847         if (iter == subStateMachineMap_.end()) {
848             NETMGR_EXT_LOG_E("Try to share an unknown iface:%{public}s, ignore.", iface.c_str());
849             return NETWORKSHARE_ERROR_UNKNOWN_IFACE;
850         }
851         subSMState = iter->second;
852     }
853     if (subSMState == nullptr) {
854         NETMGR_EXT_LOG_E("NetSharingSubSmState is null.");
855         return NETMANAGER_EXT_ERR_LOCAL_PTR_NULL;
856     }
857     if (subSMState->lastState_ != SUB_SM_STATE_AVAILABLE) {
858         NETMGR_EXT_LOG_E("Try to share an unavailable iface:%{public}s, ignore.", iface.c_str());
859         return NETWORKSHARE_ERROR_UNAVAIL_IFACE;
860     }
861 
862     if (subSMState->subStateMachine_ != nullptr) {
863         NETMGR_EXT_LOG_I("NOTIFY TO SUB SM [%{public}s] CMD_NETSHARE_REQUESTED.",
864                          subSMState->subStateMachine_->GetInterfaceName().c_str());
865         subSMState->subStateMachine_->SubSmEventHandle(CMD_NETSHARE_REQUESTED, reqState);
866         return NETMANAGER_EXT_SUCCESS;
867     }
868 
869     NETMGR_EXT_LOG_E("subStateMachine_ is null.");
870     return NETWORKSHARE_ERROR_SHARING_IFACE_ERROR;
871 }
872 
FindSubStateMachine(const std::string & iface,const SharingIfaceType & interfaceType,std::shared_ptr<NetworkShareSubStateMachine> & subSM,std::string & findKey)873 bool NetworkShareTracker::FindSubStateMachine(const std::string &iface, const SharingIfaceType &interfaceType,
874                                               std::shared_ptr<NetworkShareSubStateMachine> &subSM, std::string &findKey)
875 {
876     std::lock_guard<ffrt::mutex> lock(mutex_);
877     std::map<std::string, std::shared_ptr<NetSharingSubSmState>>::iterator iter = subStateMachineMap_.find(iface);
878     if (iter != subStateMachineMap_.end()) {
879         if (iter->second == nullptr) {
880             NETMGR_EXT_LOG_E("NetSharingSubSmState is null.");
881             return false;
882         }
883         if (iter->second->subStateMachine_ == nullptr) {
884             NETMGR_EXT_LOG_E("NetSharingSubSm is null.");
885             return false;
886         }
887         subSM = iter->second->subStateMachine_;
888         findKey = iter->first;
889         NETMGR_EXT_LOG_I("find subSM by iface[%{public}s].", iface.c_str());
890         return true;
891     }
892 
893     for (const auto &it : subStateMachineMap_) {
894         if (it.second == nullptr) {
895             NETMGR_EXT_LOG_W("NetSharingSubSmState is null.");
896             continue;
897         }
898         if (it.second->subStateMachine_ == nullptr) {
899             NETMGR_EXT_LOG_E("NetSharingSubSm is null.");
900             continue;
901         }
902         if (it.second->subStateMachine_->GetNetShareType() == interfaceType) {
903             subSM = it.second->subStateMachine_;
904             findKey = it.first;
905             NETMGR_EXT_LOG_I("find subsm by type[%{public}d].", interfaceType);
906             return true;
907         }
908     }
909     return false;
910 }
911 
EnableWifiSubStateMachine()912 void NetworkShareTracker::EnableWifiSubStateMachine()
913 {
914     int32_t ret = CreateSubStateMachine(mApIfaceName_, SharingIfaceType::SHARING_WIFI, false);
915     if (ret != NETMANAGER_EXT_SUCCESS) {
916         NETMGR_EXT_LOG_E("create wifi sub SM failed, error[%{public}d].", ret);
917         return;
918     }
919 
920     ret = Sharing(mApIfaceName_, SUB_SM_STATE_SHARED);
921     if (ret != NETMANAGER_EXT_SUCCESS) {
922         NETMGR_EXT_LOG_E("start wifi sharing failed, error[%{public}d].", ret);
923     }
924 }
925 
EnableBluetoothSubStateMachine()926 void NetworkShareTracker::EnableBluetoothSubStateMachine()
927 {
928     int32_t ret = CreateSubStateMachine(BLUETOOTH_DEFAULT_IFACE_NAME, SharingIfaceType::SHARING_BLUETOOTH, false);
929     if (ret != NETMANAGER_EXT_SUCCESS) {
930         NETMGR_EXT_LOG_E("create bluetooth sub SM failed, error[%{public}d].", ret);
931         return;
932     }
933     ret = Sharing(BLUETOOTH_DEFAULT_IFACE_NAME, SUB_SM_STATE_SHARED);
934     if (ret != NETMANAGER_EXT_SUCCESS) {
935         NETMGR_EXT_LOG_E("create sub SM failed, error[%{public}d].", ret);
936     }
937 }
938 
UpstreamWanted()939 bool NetworkShareTracker::UpstreamWanted()
940 {
941     return sharedSubSM_.size() != 0;
942 }
943 
ModifySharedSubStateMachineList(bool isAdd,const std::shared_ptr<NetworkShareSubStateMachine> & subSm)944 void NetworkShareTracker::ModifySharedSubStateMachineList(bool isAdd,
945                                                           const std::shared_ptr<NetworkShareSubStateMachine> &subSm)
946 {
947     if (isAdd) {
948         std::vector<std::shared_ptr<NetworkShareSubStateMachine>>::iterator iter =
949             find(sharedSubSM_.begin(), sharedSubSM_.end(), subSm);
950         if (iter == sharedSubSM_.end()) {
951             NETMGR_EXT_LOG_I("add new shared subSm.");
952             sharedSubSM_.push_back(subSm);
953         }
954     } else {
955         std::vector<std::shared_ptr<NetworkShareSubStateMachine>>::iterator iter =
956             find(sharedSubSM_.begin(), sharedSubSM_.end(), subSm);
957         if (iter != sharedSubSM_.end()) {
958             NETMGR_EXT_LOG_I("remove the shared subSm.");
959             sharedSubSM_.erase(iter);
960         }
961     }
962 }
963 
SetUpstreamNetHandle(const std::shared_ptr<UpstreamNetworkInfo> & netinfo)964 void NetworkShareTracker::SetUpstreamNetHandle(const std::shared_ptr<UpstreamNetworkInfo> &netinfo)
965 {
966     if (netinfo != nullptr && netinfo->netHandle_ != nullptr) {
967         SetDnsForwarders(*(netinfo->netHandle_));
968     } else {
969         StopDnsProxy();
970     }
971     NotifyDownstreamsHasNewUpstreamIface(netinfo);
972 }
973 
SetDnsForwarders(const NetHandle & netHandle)974 void NetworkShareTracker::SetDnsForwarders(const NetHandle &netHandle)
975 {
976     if (mainStateMachine_ == nullptr) {
977         NETMGR_EXT_LOG_I("MainSM is null");
978         return;
979     }
980     int32_t ret = NETMANAGER_SUCCESS;
981     if (!isStartDnsProxy_) {
982         ret = NetsysController::GetInstance().StartDnsProxyListen();
983         if (ret != NETSYS_SUCCESS) {
984             NETMGR_EXT_LOG_E("StartDnsProxy error, result[%{public}d].", ret);
985             mainStateMachine_->SwitcheToErrorState(CMD_SET_DNS_FORWARDERS_ERROR);
986             return;
987         }
988         NETMGR_EXT_LOG_I("StartDnsProxy successful.");
989         isStartDnsProxy_ = true;
990     }
991     int32_t netId = netHandle.GetNetId();
992     if (netId < 0) {
993         NETMGR_EXT_LOG_E("netId less than 0.");
994         mainStateMachine_->SwitcheToErrorState(CMD_SET_DNS_FORWARDERS_ERROR);
995         return;
996     }
997     ret = NetsysController::GetInstance().ShareDnsSet(netId);
998     if (ret != NETSYS_SUCCESS) {
999         NETMGR_EXT_LOG_E("SetDns error, result[%{public}d].", ret);
1000         mainStateMachine_->SwitcheToErrorState(CMD_SET_DNS_FORWARDERS_ERROR);
1001         return;
1002     }
1003 
1004     netId_ = netId;
1005     NETMGR_EXT_LOG_I("SetDns netId[%{public}d] success.", netId);
1006 }
1007 
StopDnsProxy()1008 void NetworkShareTracker::StopDnsProxy()
1009 {
1010     if (isStartDnsProxy_) {
1011         int32_t ret = NetsysController::GetInstance().StopDnsProxyListen();
1012         if (ret != NETSYS_SUCCESS) {
1013             NETMGR_EXT_LOG_E("StopDnsProxy error, result[%{public}d].", ret);
1014         } else {
1015             NETMGR_EXT_LOG_I("StopDnsProxy success.");
1016             isStartDnsProxy_ = false;
1017         }
1018     }
1019 }
1020 
NotifyDownstreamsHasNewUpstreamIface(const std::shared_ptr<UpstreamNetworkInfo> & netinfo)1021 void NetworkShareTracker::NotifyDownstreamsHasNewUpstreamIface(const std::shared_ptr<UpstreamNetworkInfo> &netinfo)
1022 {
1023     upstreamInfo_ = netinfo;
1024     for_each(sharedSubSM_.begin(), sharedSubSM_.end(), [netinfo](std::shared_ptr<NetworkShareSubStateMachine> subsm) {
1025         if (subsm != nullptr) {
1026             NETMGR_EXT_LOG_I("NOTIFY TO SUB SM [%{public}s] CMD_NETSHARE_CONNECTION_CHANGED.",
1027                              subsm->GetInterfaceName().c_str());
1028             subsm->SubSmEventHandle(CMD_NETSHARE_CONNECTION_CHANGED, netinfo);
1029         }
1030     });
1031 }
1032 
GetUpstreamInfo(std::shared_ptr<UpstreamNetworkInfo> & upstreamInfo)1033 void NetworkShareTracker::GetUpstreamInfo(std::shared_ptr<UpstreamNetworkInfo> &upstreamInfo)
1034 {
1035     upstreamInfo = upstreamInfo_;
1036 }
1037 
CreateSubStateMachine(const std::string & iface,const SharingIfaceType & interfaceType,bool isNcm)1038 int32_t NetworkShareTracker::CreateSubStateMachine(const std::string &iface, const SharingIfaceType &interfaceType,
1039                                                    bool isNcm)
1040 {
1041     {
1042         std::lock_guard<ffrt::mutex> lock(mutex_);
1043         if (subStateMachineMap_.count(iface) != 0) {
1044             NETMGR_EXT_LOG_W("iface[%{public}s] has added, ignoring", iface.c_str());
1045             return NETMANAGER_EXT_SUCCESS;
1046         }
1047     }
1048 
1049     std::shared_ptr<NetworkShareSubStateMachine> subSm =
1050         std::make_shared<NetworkShareSubStateMachine>(iface, interfaceType, configuration_);
1051     std::shared_ptr<SubSmUpstreamCallback> smcallback = std::make_shared<SubSmUpstreamCallback>();
1052     subSm->RegisterSubSMCallback(smcallback);
1053 
1054     {
1055         std::lock_guard<ffrt::mutex> lock(mutex_);
1056         std::shared_ptr<NetSharingSubSmState> netShareState = std::make_shared<NetSharingSubSmState>(subSm, isNcm);
1057         subStateMachineMap_.insert(std::make_pair(iface, netShareState));
1058     }
1059     NETMGR_EXT_LOG_I("adding subSM[%{public}s], type[%{public}d], current subSM count[%{public}s]", iface.c_str(),
1060                      static_cast<SharingIfaceType>(interfaceType), std::to_string(subStateMachineMap_.size()).c_str());
1061     return NETMANAGER_EXT_SUCCESS;
1062 }
1063 
StopSubStateMachine(const std::string & iface,const SharingIfaceType & interfaceType)1064 __attribute__((no_sanitize("cfi"))) void NetworkShareTracker::StopSubStateMachine(
1065     const std::string &iface, const SharingIfaceType &interfaceType)
1066 {
1067     std::shared_ptr<NetworkShareSubStateMachine> subSM = nullptr;
1068     std::string findKey;
1069     if (!FindSubStateMachine(iface, interfaceType, subSM, findKey) || subSM == nullptr) {
1070         NETMGR_EXT_LOG_W("not find the subSM.");
1071         return;
1072     }
1073     NETMGR_EXT_LOG_I("NOTIFY TO SUB SM [%{public}s] CMD_NETSHARE_UNREQUESTED.", subSM->GetInterfaceName().c_str());
1074     subSM->SubSmEventHandle(CMD_NETSHARE_UNREQUESTED, 0);
1075 
1076     {
1077         std::lock_guard<ffrt::mutex> lock(mutex_);
1078         if (subStateMachineMap_.count(findKey) > 0) {
1079             subStateMachineMap_.erase(findKey);
1080             NETMGR_EXT_LOG_I("removed iface[%{public}s] subSM, current subSM count[%{public}s].", iface.c_str(),
1081                              std::to_string(subStateMachineMap_.size()).c_str());
1082         }
1083     }
1084 }
1085 
InterfaceNameToType(const std::string & iface,SharingIfaceType & type)1086 bool NetworkShareTracker::InterfaceNameToType(const std::string &iface, SharingIfaceType &type)
1087 {
1088     if (configuration_ == nullptr) {
1089         NETMGR_EXT_LOG_E("configuration is null.");
1090         return false;
1091     }
1092     if (configuration_->IsWifiIface(iface)) {
1093         type = SharingIfaceType::SHARING_WIFI;
1094         return true;
1095     }
1096     if (configuration_->IsUsbIface(iface)) {
1097         type = SharingIfaceType::SHARING_USB;
1098         return true;
1099     }
1100     if (configuration_->IsBluetoothIface(iface)) {
1101         type = SharingIfaceType::SHARING_BLUETOOTH;
1102         return true;
1103     }
1104     return false;
1105 }
1106 
IsHandleNetlinkEvent(const SharingIfaceType & type,bool up)1107 bool NetworkShareTracker::IsHandleNetlinkEvent(const SharingIfaceType &type, bool up)
1108 {
1109 #ifdef WIFI_MODOULE
1110     if (type == SharingIfaceType::SHARING_WIFI) {
1111         return up ? curWifiState_ == Wifi::ApState::AP_STATE_STARTING
1112                   : curWifiState_ == Wifi::ApState::AP_STATE_CLOSING;
1113     }
1114 #endif
1115 #ifdef BLUETOOTH_MODOULE
1116     if (type == SharingIfaceType::SHARING_BLUETOOTH) {
1117         return up ? curBluetoothState_ == Bluetooth::BTConnectState::CONNECTING
1118                   : curBluetoothState_ == Bluetooth::BTConnectState::DISCONNECTING;
1119     }
1120 #endif
1121 #ifdef USB_MODOULE
1122     if (type == SharingIfaceType::SHARING_USB) {
1123         return up ? curUsbState_ == UsbShareState::USB_SHARING
1124                   : curUsbState_ == UsbShareState::USB_CLOSING;
1125     }
1126 #endif
1127     return false;
1128 }
1129 
InterfaceStatusChanged(const std::string & iface,bool up)1130 void NetworkShareTracker::InterfaceStatusChanged(const std::string &iface, bool up)
1131 {
1132     if (!isInit) {
1133         NETMGR_EXT_LOG_E("eventHandler is null.");
1134         return;
1135     }
1136     SharingIfaceType type;
1137     if (!InterfaceNameToType(iface, type) || !IsHandleNetlinkEvent(type, up)) {
1138         NETMGR_EXT_LOG_E("iface[%{public}s] is not downsteam or not correct event.", iface.c_str());
1139         return;
1140     }
1141     NETMGR_EXT_LOG_I("interface[%{public}s] for [%{public}s]", iface.c_str(), up ? "up" : "down");
1142     if (up) {
1143         if (configuration_ == nullptr) {
1144             NETMGR_EXT_LOG_E("configuration_ is null");
1145             return;
1146         }
1147         std::string taskName = "InterfaceAdded_task";
1148         if (configuration_->IsUsbIface(iface)) {
1149             std::function<void()> sharingUsbFunc =
1150                 [this, iface]() { Sharing(iface, SUB_SM_STATE_SHARED); };
1151             networkShareTrackerFfrtQueue_->submit(sharingUsbFunc, ffrt::task_attr().name(taskName.c_str()));
1152         } else {
1153             std::function<void()> createSubStateMachineFunc =
1154                 [this, iface, type]() { CreateSubStateMachine(iface, type, false); };
1155             networkShareTrackerFfrtQueue_->submit(createSubStateMachineFunc, ffrt::task_attr().name(taskName.c_str()));
1156         }
1157     } else {
1158         std::string taskName = "InterfaceRemoved_task";
1159         std::function<void()> stopSubStateMachineFunc =
1160             [this, iface, type]() { StopSubStateMachine(iface, type); };
1161         networkShareTrackerFfrtQueue_->submit(stopSubStateMachineFunc, ffrt::task_attr().name(taskName.c_str()));
1162     }
1163 }
1164 
CheckIfUpUsbIface(const std::string & iface)1165 bool NetworkShareTracker::CheckIfUpUsbIface(const std::string &iface)
1166 {
1167     if (!configuration_->IsUsbIface(iface)) {
1168         NETMGR_EXT_LOG_I("Iface is not usb, no need to up.");
1169         return true;
1170     }
1171     if (NetsysController::GetInstance().InterfaceSetIpAddress(iface, configuration_->GetUsbRndisIpv4Addr()) != 0) {
1172         NETMGR_EXT_LOG_E("Failed setting usb ip address");
1173         return false;
1174     }
1175     if (NetsysController::GetInstance().SetInterfaceUp(iface) != 0) {
1176         NETMGR_EXT_LOG_E("Failed setting usb iface up");
1177         return false;
1178     }
1179     return true;
1180 }
1181 
InterfaceAdded(const std::string & iface)1182 void NetworkShareTracker::InterfaceAdded(const std::string &iface)
1183 {
1184     if (!CheckValidShareInterface(iface)) {
1185         NETMGR_EXT_LOG_I("invalid share interface");
1186         return;
1187     }
1188     if (configuration_ == nullptr) {
1189         NETMGR_EXT_LOG_E("configuration_ is null");
1190         return;
1191     }
1192     if (!isInit) {
1193         NETMGR_EXT_LOG_E("eventHandler is null.");
1194         return;
1195     }
1196     SharingIfaceType type;
1197     if (!InterfaceNameToType(iface, type) || !IsHandleNetlinkEvent(type, true)) {
1198         NETMGR_EXT_LOG_E("iface[%{public}s] is not downsteam or not correct event.", iface.c_str());
1199         return;
1200     }
1201     NETMGR_EXT_LOG_I("iface[%{public}s], type[%{public}d].", iface.c_str(), static_cast<int32_t>(type));
1202     if (!CheckIfUpUsbIface(iface)) {
1203         return;
1204     }
1205     std::string taskName = "InterfaceAdded_task";
1206     std::function<void()> createSubStateMachineFunc =
1207         [this, iface, type]() { CreateSubStateMachine(iface, type, false); };
1208     networkShareTrackerFfrtQueue_->submit(createSubStateMachineFunc, ffrt::task_attr().name(taskName.c_str()));
1209 }
1210 
InterfaceRemoved(const std::string & iface)1211 void NetworkShareTracker::InterfaceRemoved(const std::string &iface)
1212 {
1213     if (!isInit) {
1214         NETMGR_EXT_LOG_E("eventHandler is null.");
1215         return;
1216     }
1217     SharingIfaceType type;
1218     if (!InterfaceNameToType(iface, type) || !IsHandleNetlinkEvent(type, false)) {
1219         NETMGR_EXT_LOG_E("iface[%{public}s] is not downsteam or not correct event.", iface.c_str());
1220         return;
1221     }
1222     NETMGR_EXT_LOG_I("iface[%{public}s], type[%{public}d].", iface.c_str(), static_cast<int32_t>(type));
1223     std::string taskName = "InterfaceRemoved_task";
1224     std::function<void()> stopSubStateMachineFunc =
1225         [this, iface, type]() { StopSubStateMachine(iface, type); };
1226     networkShareTrackerFfrtQueue_->submit(stopSubStateMachineFunc, ffrt::task_attr().name(taskName.c_str()));
1227 }
1228 
SendGlobalSharingStateChange()1229 void NetworkShareTracker::SendGlobalSharingStateChange()
1230 {
1231     uint32_t callbackSize = 0;
1232     {
1233         std::lock_guard<ffrt::mutex> lock(callbackMutex_);
1234         callbackSize = sharingEventCallback_.size();
1235     }
1236     if (callbackSize == 0) {
1237         NETMGR_EXT_LOG_E("sharingEventCallback is empty.");
1238         return;
1239     }
1240     bool isSharing = false;
1241     {
1242         std::lock_guard<ffrt::mutex> lock(mutex_);
1243         for (auto &iter : subStateMachineMap_) {
1244             std::shared_ptr<NetSharingSubSmState> subsmState = iter.second;
1245             if (subsmState == nullptr) {
1246                 NETMGR_EXT_LOG_W("iface[%{public}s] subsmState is null.", iter.first.c_str());
1247                 continue;
1248             }
1249             if (subsmState->lastState_ == SUB_SM_STATE_SHARED) {
1250                 isSharing = true;
1251                 break;
1252             }
1253         }
1254     }
1255     NETMGR_EXT_LOG_I("send global sharing state change, isNetworkSharing_[%{public}d] isSharing[%{public}d].",
1256                      isNetworkSharing_, isSharing);
1257     if (isNetworkSharing_ != isSharing) {
1258         isNetworkSharing_ = isSharing;
1259         std::lock_guard<ffrt::mutex> lock(callbackMutex_);
1260         for_each(sharingEventCallback_.begin(), sharingEventCallback_.end(),
1261                  [isSharing](sptr<ISharingEventCallback> &callback) {
1262                      if (callback != nullptr) {
1263                          callback->OnSharingStateChanged(isSharing);
1264                      }
1265                  });
1266     }
1267 }
1268 
SendIfaceSharingStateChange(const SharingIfaceType & type,const std::string & iface,const SharingIfaceState & state)1269 void NetworkShareTracker::SendIfaceSharingStateChange(const SharingIfaceType &type, const std::string &iface,
1270                                                       const SharingIfaceState &state)
1271 {
1272     std::lock_guard<ffrt::mutex> lock(callbackMutex_);
1273     if (sharingEventCallback_.size() == 0) {
1274         NETMGR_EXT_LOG_E("sharingEventCallback is empty.");
1275         return;
1276     }
1277     NETMGR_EXT_LOG_I("send iface sharing state change, type[%{public}d] iface[%{public}s]", type, iface.c_str());
1278     for_each(sharingEventCallback_.begin(), sharingEventCallback_.end(),
1279              [type, iface, state](sptr<ISharingEventCallback> &callback) {
1280                  if (callback != nullptr) {
1281                      callback->OnInterfaceSharingStateChanged(type, iface, state);
1282                  }
1283              });
1284 }
1285 
SendSharingUpstreamChange(const sptr<NetHandle> & netHandle)1286 void NetworkShareTracker::SendSharingUpstreamChange(const sptr<NetHandle> &netHandle)
1287 {
1288     std::lock_guard<ffrt::mutex> lock(callbackMutex_);
1289     if (sharingEventCallback_.size() == 0 || netHandle == nullptr) {
1290         NETMGR_EXT_LOG_E("sharingEventCallback is empty.");
1291         return;
1292     }
1293     NETMGR_EXT_LOG_I("send sharing upstream change, netId[%{public}d]", netHandle->GetNetId());
1294     for_each(sharingEventCallback_.begin(), sharingEventCallback_.end(),
1295              [netHandle](sptr<ISharingEventCallback> &callback) {
1296                  if (callback != nullptr) {
1297                      callback->OnSharingUpstreamChanged(netHandle);
1298                  }
1299              });
1300 }
1301 
SubSmStateToExportState(int32_t state)1302 SharingIfaceState NetworkShareTracker::SubSmStateToExportState(int32_t state)
1303 {
1304     SharingIfaceState newState = SharingIfaceState::SHARING_NIC_CAN_SERVER;
1305     if (state == SUB_SM_STATE_AVAILABLE) {
1306         newState = SharingIfaceState::SHARING_NIC_CAN_SERVER;
1307     } else if (state == SUB_SM_STATE_SHARED) {
1308         newState = SharingIfaceState::SHARING_NIC_SERVING;
1309     } else if (state == SUB_SM_STATE_UNAVAILABLE) {
1310         newState = SharingIfaceState::SHARING_NIC_ERROR;
1311     } else {
1312         NETMGR_EXT_LOG_E("SubSmStateToExportState state[%{public}d] is unknown type.", state);
1313         newState = SharingIfaceState::SHARING_NIC_ERROR;
1314     }
1315     return newState;
1316 }
1317 
RestartResume()1318 void NetworkShareTracker::RestartResume()
1319 {
1320     if (clientRequestsVector_.empty()) {
1321         NETMGR_EXT_LOG_E("RestartResume, no StartDnsProxy.");
1322         return;
1323     }
1324 
1325     int32_t ret = NETMANAGER_SUCCESS;
1326 
1327     if (isStartDnsProxy_) {
1328         StopDnsProxy();
1329 
1330         ret = NetsysController::GetInstance().StartDnsProxyListen();
1331         if (ret != NETSYS_SUCCESS) {
1332             NETMGR_EXT_LOG_E("StartDnsProxy error, result[%{public}d].", ret);
1333             mainStateMachine_->SwitcheToErrorState(CMD_SET_DNS_FORWARDERS_ERROR);
1334             return;
1335         }
1336         isStartDnsProxy_ = true;
1337         NETMGR_EXT_LOG_I("StartDnsProxy successful.");
1338     }
1339 
1340     ret = NetsysController::GetInstance().ShareDnsSet(netId_);
1341     if (ret != NETSYS_SUCCESS) {
1342         NETMGR_EXT_LOG_E("SetDns error, result[%{public}d].", ret);
1343         mainStateMachine_->SwitcheToErrorState(CMD_SET_DNS_FORWARDERS_ERROR);
1344         return;
1345     }
1346 
1347     NETMGR_EXT_LOG_I("SetDns netId[%{public}d] success.", netId_);
1348 
1349     for (auto &subsm : sharedSubSM_) {
1350         if (subsm != nullptr) {
1351             NETMGR_EXT_LOG_I("NOTIFY TO SUB SM [%{public}s] CMD_NETSHARE_CONNECTION_CHANGED.",
1352                 subsm->GetInterfaceName().c_str());
1353             subsm->HandleConnection();
1354         }
1355     }
1356 }
1357 
CheckValidShareInterface(const std::string & iface)1358 bool NetworkShareTracker::CheckValidShareInterface(const std::string &iface)
1359 {
1360     bool ret = false;
1361     uint32_t ifacesize = sizeof(SHARE_VALID_INTERFACES) / sizeof(SHARE_VALID_INTERFACES[0]);
1362 
1363     for (uint32_t i = 0; i < ifacesize; ++i) {
1364         ret = IsInterfaceMatchType(iface, SHARE_VALID_INTERFACES[i]);
1365         if (ret) {
1366             break;
1367         }
1368     }
1369     return ret;
1370 }
1371 
OnPowerConnected()1372 void NetworkShareTracker::OnPowerConnected()
1373 {
1374 #ifdef WIFI_MODOULE
1375     std::lock_guard<ffrt::mutex> lock(apStopTimerMutex_);
1376     NETMGR_EXT_LOG_I("Power connected and stop idle ap timer");
1377     powerConnected_ = true;
1378     NetworkShareTracker::GetInstance().HandleIdleApStopTimer();
1379 #endif
1380 }
1381 
OnPowerDisConnected()1382 void NetworkShareTracker::OnPowerDisConnected()
1383 {
1384 #ifdef WIFI_MODOULE
1385     std::lock_guard<ffrt::mutex> lock(apStopTimerMutex_);
1386     NETMGR_EXT_LOG_I("Power disConnected");
1387     powerConnected_ = false;
1388 
1389     unsigned int size = 0;
1390     int32_t ret = GetStationNum(&size);
1391     if (ret != WIFI_SUCCESS) {
1392         NETMGR_EXT_LOG_E("Get softap station num, ret:%{public}d", ret);
1393     }
1394     NETMGR_EXT_LOG_I("Current connected station mum is:%{public}d", size);
1395     staConnected_ = size != 0;
1396     NetworkShareTracker::GetInstance().HandleIdleApStopTimer();
1397 #endif
1398 }
1399 
1400 #ifdef WIFI_MODOULE
HandleHotSpotStarted()1401 void NetworkShareTracker::HandleHotSpotStarted()
1402 {
1403     char tmpData[IFACENAME_LEN];
1404     if (NetworkShareTracker::GetInstance().mApIfaceName_.empty()) {
1405         if (ErrCode(GetApIfaceName(tmpData, IFACENAME_LEN)) != 0) {
1406             NETMGR_EXT_LOG_E("get AP ifcace name failed! use default value");
1407             NetworkShareTracker::GetInstance().mApIfaceName_ = WIFI_AP_DEFAULT_IFACE_NAME;
1408         } else {
1409             NetworkShareTracker::GetInstance().mApIfaceName_ = tmpData;
1410         }
1411     }
1412     NetworkShareTracker::GetInstance().OnChangeSharingState(SharingIfaceType::SHARING_WIFI, true);
1413     NetworkShareTracker::GetInstance().EnableWifiSubStateMachine();
1414 #ifdef SHARE_NOTIFICATION_ENABLE
1415     NetworkShareNotification::GetInstance().CancelNetworkShareNotification(
1416         NotificationId::HOTSPOT_IDLE_NOTIFICATION_ID);
1417 #endif
1418     {
1419         std::lock_guard<ffrt::mutex> lock(apStopTimerMutex_);
1420         staConnected_ = false;
1421         NetworkShareTracker::GetInstance().GetPowerConnected();
1422         NetworkShareTracker::GetInstance().HandleIdleApStopTimer();
1423     }
1424 }
1425 
HandleHotSpotClosed()1426 void NetworkShareTracker::HandleHotSpotClosed()
1427 {
1428     {
1429         std::lock_guard<ffrt::mutex> lock(apStopTimerMutex_);
1430         staConnected_ = false;
1431         NetworkShareTracker::GetInstance().HandleIdleApStopTimer();
1432     }
1433     NetworkShareTracker::GetInstance().OnChangeSharingState(SharingIfaceType::SHARING_WIFI, false);
1434     NetworkShareTracker::GetInstance().StopSubStateMachine(NetworkShareTracker::GetInstance().mApIfaceName_,
1435         SharingIfaceType::SHARING_WIFI);
1436     NetworkShareTracker::GetInstance().mApIfaceName_ = "";
1437 }
1438 
HandleHotSpotStaJoin()1439 void NetworkShareTracker::HandleHotSpotStaJoin()
1440 {
1441     std::lock_guard<ffrt::mutex> lock(apStopTimerMutex_);
1442     NETMGR_EXT_LOG_I("Receive hotspot sta join");
1443     staConnected_ = true;
1444     NetworkShareTracker::GetInstance().HandleIdleApStopTimer();
1445 }
1446 
HandleHotSpotStaLeave()1447 void NetworkShareTracker::HandleHotSpotStaLeave()
1448 {
1449     std::lock_guard<ffrt::mutex> lock(apStopTimerMutex_);
1450     NETMGR_EXT_LOG_I("Receive hotspot sta leave");
1451     NetworkShareTracker::GetInstance().GetPowerConnected();
1452 
1453     unsigned int size = 0;
1454     int32_t ret = GetStationNum(&size);
1455     if (ret != WIFI_SUCCESS) {
1456         NETMGR_EXT_LOG_E("Get softap station num, ret:%{public}d", ret);
1457     }
1458     NETMGR_EXT_LOG_I("Current connected station mum is:%{public}d", size);
1459     staConnected_ = size != 0;
1460     NetworkShareTracker::GetInstance().HandleIdleApStopTimer();
1461 }
1462 
GetPowerConnected()1463 void NetworkShareTracker::GetPowerConnected()
1464 {
1465 #ifdef SUPPORT_BATTERY_MANAGER
1466     auto batteryPluggedType = PowerMgr::BatterySrvClient::GetInstance().GetPluggedType();
1467     powerConnected_ = batteryPluggedType != PowerMgr::BatteryPluggedType::PLUGGED_TYPE_NONE;
1468     NETMGR_EXT_LOG_I("Current power connected:%{public}d", powerConnected_);
1469 #endif
1470 }
1471 
HandleIdleApStopTimer()1472 void NetworkShareTracker::HandleIdleApStopTimer()
1473 {
1474     NETMGR_EXT_LOG_I("Current powerConnected:%{public}d, staConnected:%{public}d, apStarted:%{public}d",
1475         powerConnected_, staConnected_, curWifiState_);
1476     bool startTimer = !powerConnected_ && !staConnected_ &&
1477         curWifiState_ == Wifi::ApState::AP_STATE_STARTED;
1478     if (startTimer) {
1479         NetworkShareTracker::GetInstance().StartIdleApStopTimer();
1480     } else {
1481         NetworkShareTracker::GetInstance().StopIdleApStopTimer();
1482     }
1483 }
1484 
IdleApStopTimer()1485 static void IdleApStopTimer()
1486 {
1487     NETMGR_EXT_LOG_I("Disable hotspot and push network share notification");
1488 #ifdef SHARE_NOTIFICATION_ENABLE
1489     NetworkShareNotification::GetInstance().PublishNetworkShareNotification(
1490         NotificationId::HOTSPOT_IDLE_NOTIFICATION_ID);
1491 #endif
1492     int32_t ret = DisableHotspot();
1493     if (ret != WIFI_SUCCESS) {
1494         NETMGR_EXT_LOG_E("DisableHotspot error[%{public}d].", ret);
1495     } else {
1496         NETMGR_EXT_LOG_I("DisableHotspot successful.");
1497     }
1498 }
1499 
StartIdleApStopTimer()1500 void NetworkShareTracker::StartIdleApStopTimer()
1501 {
1502     if (idleApStopTimerId_ != 0) {
1503         NETMGR_EXT_LOG_I("IdleApStopTimer exist, id:%{public}u", idleApStopTimerId_);
1504         return;
1505     }
1506 
1507     std::shared_ptr<SysTimer> timer = std::make_shared<SysTimer>(false, 0, false, false);
1508     timer->SetCallbackInfo(IdleApStopTimer);
1509     idleApStopTimerId_ = MiscServices::TimeServiceClient::GetInstance()->CreateTimer(timer);
1510     int64_t currentTime = MiscServices::TimeServiceClient::GetInstance()->GetBootTimeMs();
1511     MiscServices::TimeServiceClient::GetInstance()->StartTimer(idleApStopTimerId_,
1512         currentTime + IDLE_SOFTAP_STOP_INTERVAL_MS);
1513     NETMGR_EXT_LOG_I("Start new IdleApStopTimer, id:%{public}u", idleApStopTimerId_);
1514 }
1515 
StopIdleApStopTimer()1516 void NetworkShareTracker::StopIdleApStopTimer()
1517 {
1518     NETMGR_EXT_LOG_I("Stop IdleApStopTimer, id:%{public}u", idleApStopTimerId_);
1519     if (idleApStopTimerId_ == 0) {
1520         return;
1521     }
1522     MiscServices::TimeServiceClient::GetInstance()->StopTimer(idleApStopTimerId_);
1523     MiscServices::TimeServiceClient::GetInstance()->DestroyTimer(idleApStopTimerId_);
1524     idleApStopTimerId_ = 0;
1525 }
1526 #endif
1527 } // namespace NetManagerStandard
1528 } // namespace OHOS
1529