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