• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "networkshare_tracker.h"
17 
18 #include <net/if.h>
19 #include <netinet/in.h>
20 #include <securec.h>
21 #include <sys/ioctl.h>
22 #include <sys/socket.h>
23 
24 #include "net_manager_constants.h"
25 #include "net_manager_ext_constants.h"
26 #include "netmgr_ext_log_wrapper.h"
27 #include "netsys_controller.h"
28 #include "network_sharing.h"
29 #include "networkshare_constants.h"
30 #include "networkshare_state_common.h"
31 #include "usb_srv_client.h"
32 #include "usb_srv_support.h"
33 #include "usb_errors.h"
34 #include "system_ability_definition.h"
35 
36 namespace OHOS {
37 namespace NetManagerStandard {
38 static constexpr const char *WIFI_AP_DEFAULT_IFACE_NAME = "wlan0";
39 static constexpr const char *BLUETOOTH_DEFAULT_IFACE_NAME = "bt-pan";
40 static constexpr const char *ERROR_MSG_ENABLE_WIFI = "Enable Wifi Iface failed";
41 static constexpr const char *ERROR_MSG_DISABLE_WIFI = "Disable Wifi Iface failed";
42 static constexpr const char *ERROR_MSG_ENABLE_BTPAN = "Enable BlueTooth Iface failed";
43 static constexpr const char *ERROR_MSG_DISABLE_BTPAN = "Disable BlueTooth Iface failed";
44 static constexpr int32_t BYTE_TRANSFORM_KB = 1024;
45 static constexpr int32_t MAX_CALLBACK_COUNT = 100;
46 
OnInterfaceAddressUpdated(const std::string &,const std::string &,int,int)47 int32_t NetworkShareTracker::NetsysCallback::OnInterfaceAddressUpdated(const std::string &, const std::string &, int,
48                                                                        int)
49 {
50     return 0;
51 }
52 
OnInterfaceAddressRemoved(const std::string &,const std::string &,int,int)53 int32_t NetworkShareTracker::NetsysCallback::OnInterfaceAddressRemoved(const std::string &, const std::string &, int,
54                                                                        int)
55 {
56     return 0;
57 }
58 
OnInterfaceAdded(const std::string & iface)59 int32_t NetworkShareTracker::NetsysCallback::OnInterfaceAdded(const std::string &iface)
60 {
61     NetworkShareTracker::GetInstance().InterfaceAdded(iface);
62     return 0;
63 }
64 
OnInterfaceRemoved(const std::string & iface)65 int32_t NetworkShareTracker::NetsysCallback::OnInterfaceRemoved(const std::string &iface)
66 {
67     NetworkShareTracker::GetInstance().InterfaceRemoved(iface);
68     return 0;
69 }
70 
OnInterfaceChanged(const std::string & iface,bool up)71 int32_t NetworkShareTracker::NetsysCallback::OnInterfaceChanged(const std::string &iface, bool up)
72 {
73     NetworkShareTracker::GetInstance().InterfaceStatusChanged(iface, up);
74     return 0;
75 }
76 
OnInterfaceLinkStateChanged(const std::string & iface,bool up)77 int32_t NetworkShareTracker::NetsysCallback::OnInterfaceLinkStateChanged(const std::string &iface, bool up)
78 {
79     NetworkShareTracker::GetInstance().InterfaceStatusChanged(iface, up);
80     return 0;
81 }
82 
OnRouteChanged(bool,const std::string &,const std::string &,const std::string &)83 int32_t NetworkShareTracker::NetsysCallback::OnRouteChanged(bool, const std::string &, const std::string &,
84                                                             const std::string &)
85 {
86     return 0;
87 }
88 
OnDhcpSuccess(NetsysControllerCallback::DhcpResult & dhcpResult)89 int32_t NetworkShareTracker::NetsysCallback::OnDhcpSuccess(NetsysControllerCallback::DhcpResult &dhcpResult)
90 {
91     return 0;
92 }
93 
OnBandwidthReachedLimit(const std::string & limitName,const std::string & iface)94 int32_t NetworkShareTracker::NetsysCallback::OnBandwidthReachedLimit(const std::string &limitName,
95                                                                      const std::string &iface)
96 {
97     return 0;
98 }
99 
ManagerEventHandler(const std::shared_ptr<AppExecFwk::EventRunner> & runner)100 NetworkShareTracker::ManagerEventHandler::ManagerEventHandler(const std::shared_ptr<AppExecFwk::EventRunner> &runner)
101     : AppExecFwk::EventHandler(runner)
102 {
103 }
104 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)105 void NetworkShareTracker::ManagerEventHandler::ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event)
106 {
107     if (event == nullptr) {
108         NETMGR_EXT_LOG_I("event is null");
109         return;
110     }
111     EHandlerEventType eventId = static_cast<EHandlerEventType>(event->GetInnerEventId());
112     if (eventId == EHandlerEventType::EVENT_HANDLER_MSG_FIR) {
113         NETMGR_EXT_LOG_I("EVENT_HANDLER_MSG_FIR");
114         return;
115     }
116     NETMGR_EXT_LOG_W("because eventId is unkonwn.");
117 }
118 
OnUpstreamStateChanged(int32_t msgName,int32_t param1)119 void NetworkShareTracker::MainSmUpstreamCallback::OnUpstreamStateChanged(int32_t msgName, int32_t param1)
120 {
121     (void)msgName;
122     MessageUpstreamInfo temp;
123     temp.cmd_ = param1;
124     temp.upstreamInfo_ = nullptr;
125     NETMGR_EXT_LOG_I("NOTIFY TO Main SM EVENT_UPSTREAM_CALLBACK with one param.");
126     NetworkShareTracker::GetInstance().GetMainStateMachine()->MainSmEventHandle(EVENT_UPSTREAM_CALLBACK, temp);
127 }
128 
OnUpstreamStateChanged(int32_t msgName,int32_t param1,int32_t param2,const std::any & messageObj)129 void NetworkShareTracker::MainSmUpstreamCallback::OnUpstreamStateChanged(int32_t msgName, int32_t param1,
130                                                                          int32_t param2, const std::any &messageObj)
131 {
132     (void)msgName;
133     (void)param2;
134     std::shared_ptr<UpstreamNetworkInfo> upstreamInfo = std::any_cast<std::shared_ptr<UpstreamNetworkInfo>>(messageObj);
135     if (upstreamInfo != nullptr) {
136         NetworkShareTracker::GetInstance().SendSharingUpstreamChange(upstreamInfo->netHandle_);
137     }
138     MessageUpstreamInfo temp;
139     temp.cmd_ = param1;
140     temp.upstreamInfo_ = upstreamInfo;
141     NETMGR_EXT_LOG_I("NOTIFY TO Main SM EVENT_UPSTREAM_CALLBACK with two param.");
142     NetworkShareTracker::GetInstance().GetMainStateMachine()->MainSmEventHandle(EVENT_UPSTREAM_CALLBACK, temp);
143 }
144 
OnUpdateInterfaceState(const std::shared_ptr<NetworkShareSubStateMachine> & paraSubStateMachine,int state,int lastError)145 void NetworkShareTracker::SubSmUpstreamCallback::OnUpdateInterfaceState(
146     const std::shared_ptr<NetworkShareSubStateMachine> &paraSubStateMachine, int state, int lastError)
147 {
148     NetworkShareTracker::GetInstance().HandleSubSmUpdateInterfaceState(paraSubStateMachine, state, lastError);
149 }
150 
NetSharingSubSmState(const std::shared_ptr<NetworkShareSubStateMachine> & subStateMachine,bool isNcm)151 NetworkShareTracker::NetSharingSubSmState::NetSharingSubSmState(
152     const std::shared_ptr<NetworkShareSubStateMachine> &subStateMachine, bool isNcm)
153     : subStateMachine_(subStateMachine),
154       lastState_(SUB_SM_STATE_AVAILABLE),
155       lastError_(NETMANAGER_EXT_SUCCESS),
156       isNcm_(isNcm)
157 {
158 }
159 
OnHotspotStateChanged(int state)160 void NetworkShareTracker::WifiShareHotspotEventCallback::OnHotspotStateChanged(int state)
161 {
162     NETMGR_EXT_LOG_I("Receive Hotspot state changed event, state[%{public}d]", state);
163     Wifi::ApState curState = static_cast<Wifi::ApState>(state);
164     NetworkShareTracker::GetInstance().SetWifiState(curState);
165     switch (curState) {
166         case Wifi::ApState::AP_STATE_STARTING:
167             break;
168         case Wifi::ApState::AP_STATE_STARTED: {
169             NetworkShareTracker::GetInstance().EnableWifiSubStateMachine();
170             break;
171         }
172         case Wifi::ApState::AP_STATE_CLOSING:
173             break;
174         case Wifi::ApState::AP_STATE_CLOSED: {
175             NetworkShareTracker::GetInstance().StopSubStateMachine(WIFI_AP_DEFAULT_IFACE_NAME,
176                                                                    SharingIfaceType::SHARING_WIFI);
177             break;
178         }
179         default:
180             break;
181     }
182 }
183 
OnHotspotStaJoin(const Wifi::StationInfo & info)184 void NetworkShareTracker::WifiShareHotspotEventCallback::OnHotspotStaJoin(const Wifi::StationInfo &info)
185 {
186     NETMGR_EXT_LOG_I("Receive Hotspot join event.");
187 }
188 
OnHotspotStaLeave(const Wifi::StationInfo & info)189 void NetworkShareTracker::WifiShareHotspotEventCallback::OnHotspotStaLeave(const Wifi::StationInfo &info)
190 {
191     NETMGR_EXT_LOG_I("Receive Hotspot leave event.");
192 }
193 
AsObject()194 OHOS::sptr<OHOS::IRemoteObject> NetworkShareTracker::WifiShareHotspotEventCallback::AsObject()
195 {
196     return nullptr;
197 }
198 
OnConnectionStateChanged(const Bluetooth::BluetoothRemoteDevice & device,int state)199 void NetworkShareTracker::SharingPanObserver::OnConnectionStateChanged(const Bluetooth::BluetoothRemoteDevice &device,
200                                                                        int state)
201 {
202     NETMGR_EXT_LOG_I("Recieve bt-pan state changed event, state[%{public}d].", state);
203     Bluetooth::BTConnectState curState = static_cast<Bluetooth::BTConnectState>(state);
204     NetworkShareTracker::GetInstance().SetBluetoothState(curState);
205     switch (curState) {
206         case Bluetooth::BTConnectState::CONNECTING:
207             break;
208         case Bluetooth::BTConnectState::CONNECTED: {
209             NetworkShareTracker::GetInstance().EnableBluetoothSubStateMachine();
210             break;
211         }
212         case Bluetooth::BTConnectState::DISCONNECTING:
213             break;
214         case Bluetooth::BTConnectState::DISCONNECTED: {
215             NetworkShareTracker::GetInstance().StopSubStateMachine(BLUETOOTH_DEFAULT_IFACE_NAME,
216                                                                    SharingIfaceType::SHARING_BLUETOOTH);
217             break;
218         }
219         default:
220             break;
221     }
222 }
223 
GetInstance()224 NetworkShareTracker &NetworkShareTracker::GetInstance()
225 {
226     static NetworkShareTracker instance;
227     return instance;
228 }
229 
Init()230 bool NetworkShareTracker::Init()
231 {
232     configuration_ = std::make_shared<NetworkShareConfiguration>();
233     std::shared_ptr<AppExecFwk::EventRunner> eventRunner = AppExecFwk::EventRunner::Create("network_share_tracker");
234     eventHandler_ = std::make_shared<NetworkShareTracker::ManagerEventHandler>(eventRunner);
235 
236     std::shared_ptr<NetworkShareUpstreamMonitor> upstreamNetworkMonitor =
237         DelayedSingleton<NetworkShareUpstreamMonitor>::GetInstance();
238     std::shared_ptr<AppExecFwk::EventRunner> monitorRunner = AppExecFwk::EventRunner::Create("network_share_monitor");
239     monitorHandler_ =
240         std::make_shared<NetworkShareUpstreamMonitor::MonitorEventHandler>(upstreamNetworkMonitor, monitorRunner);
241     upstreamNetworkMonitor->SetOptionData(EVENT_UPSTREAM_CALLBACK, monitorHandler_);
242     upstreamNetworkMonitor->ListenDefaultNetwork();
243     upstreamNetworkMonitor->RegisterUpstreamChangedCallback(std::make_shared<MainSmUpstreamCallback>());
244     mainStateMachine_ = std::make_shared<NetworkShareMainStateMachine>(upstreamNetworkMonitor);
245 
246     netsysCallback_ = new (std::nothrow) NetsysCallback();
247     NetsysController::GetInstance().RegisterCallback(netsysCallback_);
248 
249     RegisterWifiApCallback();
250     RegisterBtPanCallback();
251 
252     isNetworkSharing_ = false;
253     isInit = true;
254     NETMGR_EXT_LOG_I("Tracker Init sucessful.");
255     return true;
256 }
257 
RegisterWifiApCallback()258 void NetworkShareTracker::RegisterWifiApCallback()
259 {
260     sptr<WifiShareHotspotEventCallback> wifiHotspotCallback = new (std::nothrow) WifiShareHotspotEventCallback();
261     std::unique_ptr<Wifi::WifiHotspot> wifiHotspot = Wifi::WifiHotspot::GetInstance(WIFI_HOTSPOT_ABILITY_ID);
262     if (wifiHotspot != nullptr) {
263         int32_t ret = wifiHotspot->RegisterCallBack(wifiHotspotCallback);
264         if (ret != Wifi::ErrCode::WIFI_OPT_SUCCESS) {
265             NETMGR_EXT_LOG_E("Register wifi hotspot callback error[%{public}d].", ret);
266         }
267     }
268 }
269 
RegisterBtPanCallback()270 void NetworkShareTracker::RegisterBtPanCallback()
271 {
272     Bluetooth::Pan *profile = Bluetooth::Pan::GetProfile();
273     if (profile == nullptr) {
274         return;
275     }
276     panObserver_ = std::make_shared<SharingPanObserver>();
277     if (panObserver_ != nullptr) {
278         profile->RegisterObserver(panObserver_.get());
279     }
280 }
281 
Uninit()282 void NetworkShareTracker::Uninit()
283 {
284     isInit = false;
285     Bluetooth::Pan *profile = Bluetooth::Pan::GetProfile();
286     if (profile == nullptr || panObserver_ == nullptr) {
287         NETMGR_EXT_LOG_E("bt-pan profile or observer is null.");
288         return;
289     }
290     profile->DeregisterObserver(panObserver_.get());
291     NETMGR_EXT_LOG_I("Uninit successful.");
292 }
293 
GetMainStateMachine()294 std::shared_ptr<NetworkShareMainStateMachine> &NetworkShareTracker::GetMainStateMachine()
295 {
296     return mainStateMachine_;
297 }
298 
SetWifiState(const Wifi::ApState & state)299 void NetworkShareTracker::SetWifiState(const Wifi::ApState &state)
300 {
301     curWifiState_ = state;
302 }
303 
SetBluetoothState(const Bluetooth::BTConnectState & state)304 void NetworkShareTracker::SetBluetoothState(const Bluetooth::BTConnectState &state)
305 {
306     curBluetoothState_ = state;
307 }
308 
HandleSubSmUpdateInterfaceState(const std::shared_ptr<NetworkShareSubStateMachine> & who,int32_t state,int32_t lastError)309 void NetworkShareTracker::HandleSubSmUpdateInterfaceState(const std::shared_ptr<NetworkShareSubStateMachine> &who,
310                                                           int32_t state, int32_t lastError)
311 {
312     if (who == nullptr) {
313         NETMGR_EXT_LOG_E("subsm is null.");
314         return;
315     }
316     std::shared_ptr<NetSharingSubSmState> shareState = nullptr;
317     std::string ifaceName;
318     {
319         std::lock_guard lock(mutex_);
320         auto iter = subStateMachineMap_.find(who->GetInterfaceName());
321         if (iter != subStateMachineMap_.end()) {
322             ifaceName = iter->first;
323             shareState = iter->second;
324         }
325     }
326     if (shareState != nullptr) {
327         NETMGR_EXT_LOG_I("iface=%{public}s state is change from[%{public}d] to[%{public}d].", ifaceName.c_str(),
328                          shareState->lastState_, state);
329         shareState->lastError_ = lastError;
330         if (shareState->lastState_ != state) {
331             shareState->lastState_ = state;
332             SendIfaceSharingStateChange(who->GetNetShareType(), ifaceName, SubSmStateToExportState(state));
333         }
334     } else {
335         NETMGR_EXT_LOG_W("iface=%{public}s is not find", (who->GetInterfaceName()).c_str());
336     }
337 
338     if (lastError == NETWORKSHARE_ERROR_INTERNAL_ERROR) {
339         SendMainSMEvent(who, CMD_CLEAR_ERROR, 0);
340     }
341     int32_t which = 0;
342     switch (state) {
343         case SUB_SM_STATE_AVAILABLE:
344         case SUB_SM_STATE_UNAVAILABLE:
345             which = EVENT_IFACE_SM_STATE_INACTIVE;
346             break;
347         case SUB_SM_STATE_SHARED:
348             which = EVENT_IFACE_SM_STATE_ACTIVE;
349             break;
350         default:
351             NETMGR_EXT_LOG_E("Unknown interface state=%{public}d", state);
352             return;
353     }
354     SendMainSMEvent(who, which, state);
355     SendGlobalSharingStateChange();
356 }
357 
SendMainSMEvent(const std::shared_ptr<NetworkShareSubStateMachine> & subSM,int32_t event,int32_t state)358 void NetworkShareTracker::SendMainSMEvent(const std::shared_ptr<NetworkShareSubStateMachine> &subSM, int32_t event,
359                                           int32_t state)
360 {
361     if (mainStateMachine_ == nullptr) {
362         NETMGR_EXT_LOG_I("MainSM is null");
363         return;
364     }
365     NETMGR_EXT_LOG_I("Notify to Main SM event[%{public}d].", event);
366     MessageIfaceActive message;
367     message.value_ = state;
368     message.subsm_ = subSM;
369     mainStateMachine_->MainSmEventHandle(event, message);
370 }
371 
IsNetworkSharingSupported(int32_t & supported)372 int32_t NetworkShareTracker::IsNetworkSharingSupported(int32_t &supported)
373 {
374     if (configuration_ == nullptr) {
375         supported = NETWORKSHARE_IS_UNSUPPORTED;
376         return NETWORKSHARE_ERROR_IFACE_CFG_ERROR;
377     }
378     if (configuration_->IsNetworkSharingSupported()) {
379         supported = NETWORKSHARE_IS_SUPPORTED;
380     } else {
381         supported = NETWORKSHARE_IS_UNSUPPORTED;
382     }
383     return NETMANAGER_EXT_SUCCESS;
384 }
385 
IsSharing(int32_t & sharingStatus)386 int32_t NetworkShareTracker::IsSharing(int32_t &sharingStatus)
387 {
388     std::lock_guard lock(mutex_);
389     for (auto &iter : subStateMachineMap_) {
390         std::shared_ptr<NetSharingSubSmState> shareState = iter.second;
391         if (shareState == nullptr) {
392             continue;
393         }
394         if (shareState->lastState_ == SUB_SM_STATE_SHARED) {
395             sharingStatus = NETWORKSHARE_IS_SHARING;
396             return NETMANAGER_EXT_SUCCESS;
397         }
398     }
399     sharingStatus = NETWORKSHARE_IS_UNSHARING;
400     return NETMANAGER_EXT_SUCCESS;
401 }
402 
StartNetworkSharing(const SharingIfaceType & type)403 int32_t NetworkShareTracker::StartNetworkSharing(const SharingIfaceType &type)
404 {
405     auto fit = find(clientRequestsVector_.begin(), clientRequestsVector_.end(), type);
406     if (fit != clientRequestsVector_.end()) {
407         int ret = EnableNetSharingInternal(type, false);
408         if (ret != NETMANAGER_EXT_SUCCESS) {
409             NETMGR_EXT_LOG_E("stop current [%{public}d] sharing error [%{public}ul]", static_cast<int32_t>(type), ret);
410             return ret;
411         }
412     } else {
413         clientRequestsVector_.push_back(type);
414     }
415 
416     return EnableNetSharingInternal(type, true);
417 }
418 
StopNetworkSharing(const SharingIfaceType & type)419 int32_t NetworkShareTracker::StopNetworkSharing(const SharingIfaceType &type)
420 {
421     auto fit = find(clientRequestsVector_.begin(), clientRequestsVector_.end(), type);
422     if (fit != clientRequestsVector_.end()) {
423         clientRequestsVector_.erase(fit);
424     }
425 
426     return EnableNetSharingInternal(type, false);
427 }
428 
GetSharableRegexs(SharingIfaceType type,std::vector<std::string> & ifaceRegexs)429 int32_t NetworkShareTracker::GetSharableRegexs(SharingIfaceType type, std::vector<std::string> &ifaceRegexs)
430 {
431     if (configuration_ == nullptr) {
432         return NETWORKSHARE_ERROR_IFACE_CFG_ERROR;
433     }
434     switch (type) {
435         case SharingIfaceType::SHARING_WIFI: {
436             ifaceRegexs = configuration_->GetWifiIfaceRegexs();
437             return NETMANAGER_EXT_SUCCESS;
438         }
439         case SharingIfaceType::SHARING_USB: {
440             ifaceRegexs = configuration_->GetUsbIfaceRegexs();
441             return NETMANAGER_EXT_SUCCESS;
442         }
443         case SharingIfaceType::SHARING_BLUETOOTH: {
444             ifaceRegexs = configuration_->GetBluetoothIfaceRegexs();
445             return NETMANAGER_EXT_SUCCESS;
446         }
447         default: {
448             NETMGR_EXT_LOG_E("type[%{public}d] is unkonwn.", type);
449             return NETWORKSHARE_ERROR_UNKNOWN_TYPE;
450         }
451     }
452 }
453 
IsInterfaceMatchType(const std::string & iface,const SharingIfaceType & type)454 bool NetworkShareTracker::IsInterfaceMatchType(const std::string &iface, const SharingIfaceType &type)
455 {
456     if (configuration_ == nullptr) {
457         return false;
458     }
459     if (type == SharingIfaceType::SHARING_WIFI && configuration_->IsWifiIface(iface)) {
460         return true;
461     }
462     if (type == SharingIfaceType::SHARING_USB && configuration_->IsUsbIface(iface)) {
463         return true;
464     }
465     if (type == SharingIfaceType::SHARING_BLUETOOTH && configuration_->IsBluetoothIface(iface)) {
466         return true;
467     }
468     return false;
469 }
470 
GetSharingState(const SharingIfaceType type,SharingIfaceState & state)471 int32_t NetworkShareTracker::GetSharingState(const SharingIfaceType type, SharingIfaceState &state)
472 {
473     if (type != SharingIfaceType::SHARING_WIFI &&
474         type != SharingIfaceType::SHARING_USB &&
475         type != SharingIfaceType::SHARING_BLUETOOTH) {
476         return NETWORKSHARE_ERROR_UNKNOWN_TYPE;
477     }
478     bool isFindType = false;
479     state = SharingIfaceState::SHARING_NIC_CAN_SERVER;
480     std::lock_guard lock(mutex_);
481     for (const auto &iter : subStateMachineMap_) {
482         if (IsInterfaceMatchType(iter.first, type)) {
483             std::shared_ptr<NetSharingSubSmState> subsmState = iter.second;
484             if (subsmState == nullptr) {
485                 NETMGR_EXT_LOG_W("subsmState is null.");
486                 continue;
487             }
488             if (subsmState->lastState_ == SUB_SM_STATE_UNAVAILABLE) {
489                 state = SharingIfaceState::SHARING_NIC_ERROR;
490                 isFindType = true;
491                 break;
492             }
493             if (subsmState->lastState_ == SUB_SM_STATE_AVAILABLE) {
494                 state = SharingIfaceState::SHARING_NIC_CAN_SERVER;
495                 isFindType = true;
496                 break;
497             }
498             if (subsmState->lastState_ == SUB_SM_STATE_SHARED) {
499                 state = SharingIfaceState::SHARING_NIC_SERVING;
500                 isFindType = true;
501                 break;
502             }
503             NETMGR_EXT_LOG_W("lastState_=%{public}d is unknown data.", subsmState->lastState_);
504         } else {
505             NETMGR_EXT_LOG_W("iface=%{public}s is not match type[%{public}d]", iter.first.c_str(), type);
506         }
507     }
508     if (!isFindType) {
509         NETMGR_EXT_LOG_E("type=%{public}d is not find, used default value.", type);
510     }
511     return NETMANAGER_EXT_SUCCESS;
512 }
513 
GetNetSharingIfaces(const SharingIfaceState & state,std::vector<std::string> & ifaces)514 int32_t NetworkShareTracker::GetNetSharingIfaces(const SharingIfaceState &state, std::vector<std::string> &ifaces)
515 {
516     std::lock_guard lock(mutex_);
517     for_each(subStateMachineMap_.begin(), subStateMachineMap_.end(), [&](auto iter) {
518         std::shared_ptr<NetSharingSubSmState> subsmState = iter.second;
519         if (subsmState == nullptr) {
520             NETMGR_EXT_LOG_W("iface=%{public}s subsmState is null.", (iter.first).c_str());
521             return;
522         }
523         NETMGR_EXT_LOG_I("iface=%{public}s, state=%{public}d", (iter.first).c_str(), subsmState->lastState_);
524         if ((state == SharingIfaceState::SHARING_NIC_ERROR && subsmState->lastState_ == SUB_SM_STATE_UNAVAILABLE) ||
525             (state == SharingIfaceState::SHARING_NIC_CAN_SERVER && subsmState->lastState_ == SUB_SM_STATE_AVAILABLE) ||
526             (state == SharingIfaceState::SHARING_NIC_SERVING && subsmState->lastState_ == SUB_SM_STATE_SHARED)) {
527             ifaces.push_back(iter.first);
528         }
529     });
530 
531     return NETMANAGER_EXT_SUCCESS;
532 }
533 
RegisterSharingEvent(sptr<ISharingEventCallback> callback)534 int32_t NetworkShareTracker::RegisterSharingEvent(sptr<ISharingEventCallback> callback)
535 {
536     if (callback == nullptr) {
537         NETMGR_EXT_LOG_E("callback is null.");
538         return NETMANAGER_EXT_ERR_LOCAL_PTR_NULL;
539     }
540     std::lock_guard lock(callbackMutex_);
541     if (sharingEventCallback_.size() >= MAX_CALLBACK_COUNT) {
542         NETMGR_EXT_LOG_E("callback above max count, return error.");
543         return NETWORKSHARE_ERROR_ISSHARING_CALLBACK_ERROR;
544     }
545     sharingEventCallback_.push_back(callback);
546     return NETMANAGER_EXT_SUCCESS;
547 }
548 
UnregisterSharingEvent(sptr<ISharingEventCallback> callback)549 int32_t NetworkShareTracker::UnregisterSharingEvent(sptr<ISharingEventCallback> callback)
550 {
551     for (auto iter = sharingEventCallback_.begin(); iter != sharingEventCallback_.end(); ++iter) {
552         if (callback->AsObject().GetRefPtr() == (*iter)->AsObject().GetRefPtr()) {
553             sharingEventCallback_.erase(iter);
554             break;
555         }
556     }
557     return NETMANAGER_EXT_SUCCESS;
558 }
559 
GetSharedSubSMTraffic(const TrafficType & type,int32_t & kbByte)560 int32_t NetworkShareTracker::GetSharedSubSMTraffic(const TrafficType &type, int32_t &kbByte)
561 {
562     int64_t bytes = 0;
563     for (auto &subSM : sharedSubSM_) {
564         if (subSM == nullptr) {
565             continue;
566         }
567         std::string downIface;
568         std::string upIface;
569         subSM->GetDownIfaceName(downIface);
570         subSM->GetUpIfaceName(upIface);
571         nmd::NetworkSharingTraffic traffic;
572         NETMGR_EXT_LOG_I("DownIface[%{public}s], upIface[%{public}s].", downIface.c_str(), upIface.c_str());
573         int32_t ret = NetsysController::GetInstance().GetNetworkSharingTraffic(downIface, upIface, traffic);
574         if (ret != NETMANAGER_SUCCESS) {
575             NETMGR_EXT_LOG_E("GetTrafficBytes err, ret[%{public}d].", ret);
576             continue;
577         }
578         switch (type) {
579             case TrafficType::TRAFFIC_RX:
580                 bytes += traffic.receive;
581                 break;
582             case TrafficType::TRAFFIC_TX:
583                 bytes += traffic.send;
584                 break;
585             case TrafficType::TRAFFIC_ALL:
586                 bytes += traffic.all;
587                 break;
588             default:
589                 break;
590         }
591     }
592 
593     kbByte = static_cast<int32_t>(bytes / BYTE_TRANSFORM_KB);
594     if (kbByte > std::numeric_limits<int32_t>::max()) {
595         NETMGR_EXT_LOG_I("GetBytes [%{public}s] is above max.", std::to_string(kbByte).c_str());
596         kbByte = std::numeric_limits<int32_t>::max();
597     }
598     return NETMANAGER_EXT_SUCCESS;
599 }
600 
EnableNetSharingInternal(const SharingIfaceType & type,bool enable)601 int32_t NetworkShareTracker::EnableNetSharingInternal(const SharingIfaceType &type, bool enable)
602 {
603     NETMGR_EXT_LOG_I("NetSharing type[%{public}d] enable[%{public}d].", type, enable);
604     int32_t result = NETMANAGER_EXT_SUCCESS;
605     switch (type) {
606         case SharingIfaceType::SHARING_WIFI:
607             result = SetWifiNetworkSharing(enable);
608             break;
609         case SharingIfaceType::SHARING_USB:
610             result = SetUsbNetworkSharing(enable);
611             break;
612         case SharingIfaceType::SHARING_BLUETOOTH:
613             result = SetBluetoothNetworkSharing(enable);
614             break;
615         default:
616             NETMGR_EXT_LOG_E("Invalid networkshare type.");
617             result = NETWORKSHARE_ERROR_UNKNOWN_TYPE;
618             break;
619     }
620 
621     if (result != NETMANAGER_EXT_SUCCESS) {
622         auto it = find(clientRequestsVector_.begin(), clientRequestsVector_.end(), type);
623         if (it != clientRequestsVector_.end()) {
624             clientRequestsVector_.erase(it);
625         }
626     }
627 
628     return result;
629 }
630 
SetWifiNetworkSharing(bool enable)631 int32_t NetworkShareTracker::SetWifiNetworkSharing(bool enable)
632 {
633     int32_t result = NETMANAGER_EXT_SUCCESS;
634     std::unique_ptr<Wifi::WifiHotspot> wifiHotspot = Wifi::WifiHotspot::GetInstance(WIFI_HOTSPOT_ABILITY_ID);
635     if (wifiHotspot == nullptr) {
636         NETMGR_EXT_LOG_E("wifiHotspotPtr is null.");
637         return NETWORKSHARE_ERROR_WIFI_SHARING;
638     }
639     if (enable) {
640         int32_t ret = wifiHotspot->EnableHotspot(Wifi::ServiceType::DEFAULT);
641         if (ret != Wifi::ErrCode::WIFI_OPT_SUCCESS) {
642             NETMGR_EXT_LOG_E("EnableHotspot error[%{public}d].", ret);
643             result = NETWORKSHARE_ERROR_WIFI_SHARING;
644             NetworkShareHisysEvent::GetInstance().SendFaultEvent(
645                 SharingIfaceType::SHARING_WIFI, NetworkShareEventOperator::OPERATION_ENABLE_IFACE,
646                 NetworkShareEventErrorType::ERROR_ENABLE_IFACE, ERROR_MSG_ENABLE_WIFI,
647                 NetworkShareEventType::SETUP_EVENT);
648         } else {
649             NETMGR_EXT_LOG_I("EnableHotspot successfull.");
650             if (wifiShareCount_ < INT32_MAX) {
651                 wifiShareCount_++;
652             }
653             NetworkShareHisysEvent::GetInstance().SendBehaviorEvent(wifiShareCount_, SharingIfaceType::SHARING_WIFI);
654         }
655     } else {
656         int32_t ret = wifiHotspot->DisableHotspot();
657         if (ret != Wifi::ErrCode::WIFI_OPT_SUCCESS) {
658             NetworkShareHisysEvent::GetInstance().SendFaultEvent(
659                 SharingIfaceType::SHARING_WIFI, NetworkShareEventOperator::OPERATION_DISABLE_IFACE,
660                 NetworkShareEventErrorType::ERROR_DISABLE_IFACE, ERROR_MSG_DISABLE_WIFI,
661                 NetworkShareEventType::CANCEL_EVENT);
662             NETMGR_EXT_LOG_E("DisableHotspot error[%{public}d].", ret);
663             result = NETWORKSHARE_ERROR_WIFI_SHARING;
664         } else {
665             NETMGR_EXT_LOG_I("DisableHotspot successful.");
666         }
667     }
668 
669     return result;
670 }
671 
SetUsbNetworkSharing(bool enable)672 int32_t NetworkShareTracker::SetUsbNetworkSharing(bool enable)
673 {
674     auto &usbSrvClient = USB::UsbSrvClient::GetInstance();
675     if (enable) {
676         curUsbState_ = UsbShareState::USB_SHARING;
677         int32_t funcs = 0;
678         int32_t ret = usbSrvClient.GetCurrentFunctions(funcs);
679         if (ret != USB::UEC_OK) {
680             NETMGR_EXT_LOG_E("GetCurrentFunctions error[%{public}d].", ret);
681             return NETWORKSHARE_ERROR_USB_SHARING;
682         }
683         uint32_t tmpData = USB::UsbSrvSupport::FUNCTION_RNDIS | static_cast<uint32_t>(funcs);
684         ret = usbSrvClient.SetCurrentFunctions(tmpData);
685         if (ret != USB::UEC_OK) {
686             NETMGR_EXT_LOG_E("SetCurrentFunctions error[%{public}d].", ret);
687             return NETWORKSHARE_ERROR_USB_SHARING;
688         }
689         if (NetsysController::GetInstance().InterfaceSetIpAddress(configuration_->GetUsbRndisIfaceName(),
690                                                                   configuration_->GetUsbRndisIpv4Addr()) != 0) {
691             NETMGR_EXT_LOG_E("Failed setting usb ip address");
692             return NETWORKSHARE_ERROR_USB_SHARING;
693         }
694         if (NetsysController::GetInstance().InterfaceSetIffUp(configuration_->GetUsbRndisIfaceName()) != 0) {
695             NETMGR_EXT_LOG_E("Failed setting usb iface up");
696             return NETWORKSHARE_ERROR_USB_SHARING;
697         }
698         if (usbShareCount_ < INT32_MAX) {
699             usbShareCount_++;
700         }
701         NetworkShareHisysEvent::GetInstance().SendBehaviorEvent(usbShareCount_, SharingIfaceType::SHARING_USB);
702     } else {
703         curUsbState_ = UsbShareState::USB_CLOSING;
704         int32_t funcs = 0;
705         int32_t ret = usbSrvClient.GetCurrentFunctions(funcs);
706         if (ret != USB::UEC_OK) {
707             NETMGR_EXT_LOG_E("usb GetCurrentFunctions error[%{public}d].", ret);
708             return NETWORKSHARE_ERROR_USB_SHARING;
709         }
710         uint32_t tmpData = static_cast<uint32_t>(funcs) & (~USB::UsbSrvSupport::FUNCTION_RNDIS);
711         ret = usbSrvClient.SetCurrentFunctions(tmpData);
712         if (ret != USB::UEC_OK) {
713             NETMGR_EXT_LOG_E("usb SetCurrentFunctions error[%{public}d].", ret);
714             return NETWORKSHARE_ERROR_USB_SHARING;
715         }
716     }
717     return NETMANAGER_EXT_SUCCESS;
718 }
719 
SetBluetoothNetworkSharing(bool enable)720 int32_t NetworkShareTracker::SetBluetoothNetworkSharing(bool enable)
721 {
722     Bluetooth::Pan *profile = Bluetooth::Pan::GetProfile();
723     if (profile == nullptr) {
724         NETMGR_EXT_LOG_E("SetBluetoothNetworkSharing(%{public}s) profile is null].", enable ? "true" : "false");
725         return NETWORKSHARE_ERROR_BT_SHARING;
726     }
727     if (enable && panObserver_ == nullptr) {
728         RegisterBtPanCallback();
729     }
730     bool ret = profile->SetTethering(enable);
731     if (ret) {
732         NETMGR_EXT_LOG_I("SetBluetoothNetworkSharing(%{public}s) is success.", enable ? "true" : "false");
733         if (enable && bluetoothShareCount_ < INT32_MAX) {
734             bluetoothShareCount_++;
735         }
736         NetworkShareHisysEvent::GetInstance().SendBehaviorEvent(bluetoothShareCount_,
737                                                                 SharingIfaceType::SHARING_BLUETOOTH);
738         return NETMANAGER_EXT_SUCCESS;
739     }
740     if (enable) {
741         NetworkShareHisysEvent::GetInstance().SendFaultEvent(
742             SharingIfaceType::SHARING_BLUETOOTH, NetworkShareEventOperator::OPERATION_ENABLE_IFACE,
743             NetworkShareEventErrorType::ERROR_ENABLE_IFACE, ERROR_MSG_ENABLE_BTPAN, NetworkShareEventType::SETUP_EVENT);
744     } else {
745         NetworkShareHisysEvent::GetInstance().SendFaultEvent(
746             SharingIfaceType::SHARING_BLUETOOTH, NetworkShareEventOperator::OPERATION_DISABLE_IFACE,
747             NetworkShareEventErrorType::ERROR_DISABLE_IFACE, ERROR_MSG_DISABLE_BTPAN,
748             NetworkShareEventType::CANCEL_EVENT);
749     }
750 
751     NETMGR_EXT_LOG_E("SetBluetoothNetworkSharing(%{public}s) is error.", enable ? "true" : "false");
752     return NETWORKSHARE_ERROR_BT_SHARING;
753 }
754 
Sharing(const std::string & iface,int32_t reqState)755 int32_t NetworkShareTracker::Sharing(const std::string &iface, int32_t reqState)
756 {
757     std::shared_ptr<NetSharingSubSmState> subSMState = nullptr;
758     {
759         std::lock_guard lock(mutex_);
760         std::map<std::string, std::shared_ptr<NetSharingSubSmState>>::iterator iter = subStateMachineMap_.find(iface);
761         if (iter == subStateMachineMap_.end()) {
762             NETMGR_EXT_LOG_E("Try to share an unknown iface:%{public}s, ignore.", iface.c_str());
763             return NETWORKSHARE_ERROR_UNKNOWN_IFACE;
764         }
765         subSMState = iter->second;
766     }
767     if (subSMState == nullptr) {
768         NETMGR_EXT_LOG_E("NetSharingSubSmState is null.");
769         return NETMANAGER_EXT_ERR_LOCAL_PTR_NULL;
770     }
771     if (subSMState->lastState_ != SUB_SM_STATE_AVAILABLE) {
772         NETMGR_EXT_LOG_E("Try to share an unavailable iface:%{public}s, ignore.", iface.c_str());
773         return NETWORKSHARE_ERROR_UNAVAIL_IFACE;
774     }
775 
776     if (subSMState->subStateMachine_ != nullptr) {
777         NETMGR_EXT_LOG_I("NOTIFY TO SUB SM [%{public}s] CMD_NETSHARE_REQUESTED.",
778                          subSMState->subStateMachine_->GetInterfaceName().c_str());
779         subSMState->subStateMachine_->SubSmEventHandle(CMD_NETSHARE_REQUESTED, reqState);
780         return NETMANAGER_EXT_SUCCESS;
781     }
782 
783     NETMGR_EXT_LOG_E("subStateMachine_ is null.");
784     return NETWORKSHARE_ERROR_SHARING_IFACE_ERROR;
785 }
786 
FindSubStateMachine(const std::string & iface,const SharingIfaceType & interfaceType,std::shared_ptr<NetworkShareSubStateMachine> & subSM,std::string & findKey)787 bool NetworkShareTracker::FindSubStateMachine(const std::string &iface, const SharingIfaceType &interfaceType,
788                                               std::shared_ptr<NetworkShareSubStateMachine> &subSM, std::string &findKey)
789 {
790     std::lock_guard lock(mutex_);
791     std::map<std::string, std::shared_ptr<NetSharingSubSmState>>::iterator iter = subStateMachineMap_.find(iface);
792     if (iter != subStateMachineMap_.end()) {
793         if (iter->second == nullptr) {
794             NETMGR_EXT_LOG_E("NetSharingSubSmState is null.");
795             return false;
796         }
797         if (iter->second->subStateMachine_ == nullptr) {
798             NETMGR_EXT_LOG_E("NetSharingSubSm is null.");
799             return false;
800         }
801         subSM = iter->second->subStateMachine_;
802         findKey = iter->first;
803         NETMGR_EXT_LOG_I("find subSM by iface[%{public}s].", iface.c_str());
804         return true;
805     }
806 
807     for (auto &it : subStateMachineMap_) {
808         if (it.second == nullptr) {
809             NETMGR_EXT_LOG_W("NetSharingSubSmState is null.");
810             continue;
811         }
812         if (it.second->subStateMachine_ == nullptr) {
813             NETMGR_EXT_LOG_E("NetSharingSubSm is null.");
814             continue;
815         }
816         if (it.second->subStateMachine_->GetNetShareType() == interfaceType) {
817             subSM = it.second->subStateMachine_;
818             findKey = it.first;
819             NETMGR_EXT_LOG_I("find subsm by type[%{public}d].", interfaceType);
820             return true;
821         }
822     }
823     return false;
824 }
825 
EnableWifiSubStateMachine()826 void NetworkShareTracker::EnableWifiSubStateMachine()
827 {
828     int32_t ret = CreateSubStateMachine(WIFI_AP_DEFAULT_IFACE_NAME, SharingIfaceType::SHARING_WIFI, false);
829     if (ret != NETMANAGER_EXT_SUCCESS) {
830         NETMGR_EXT_LOG_E("create wifi sub SM failed, error[%{public}d].", ret);
831         return;
832     }
833 
834     ret = Sharing(WIFI_AP_DEFAULT_IFACE_NAME, SUB_SM_STATE_SHARED);
835     if (ret != NETMANAGER_EXT_SUCCESS) {
836         NETMGR_EXT_LOG_E("start wifi sharing failed, error[%{public}d].", ret);
837     }
838 }
839 
EnableBluetoothSubStateMachine()840 void NetworkShareTracker::EnableBluetoothSubStateMachine()
841 {
842     int32_t ret = CreateSubStateMachine(BLUETOOTH_DEFAULT_IFACE_NAME, SharingIfaceType::SHARING_BLUETOOTH, false);
843     if (ret != NETMANAGER_EXT_SUCCESS) {
844         NETMGR_EXT_LOG_E("create bluetooth sub SM failed, error[%{public}d].", ret);
845         return;
846     }
847     ret = Sharing(BLUETOOTH_DEFAULT_IFACE_NAME, SUB_SM_STATE_SHARED);
848     if (ret != NETMANAGER_EXT_SUCCESS) {
849         NETMGR_EXT_LOG_E("create sub SM failed, error[%{public}d].", ret);
850     }
851 }
852 
UpstreamWanted()853 bool NetworkShareTracker::UpstreamWanted()
854 {
855     return sharedSubSM_.size() != 0;
856 }
857 
ModifySharedSubStateMachineList(bool isAdd,const std::shared_ptr<NetworkShareSubStateMachine> & subSm)858 void NetworkShareTracker::ModifySharedSubStateMachineList(bool isAdd,
859                                                           const std::shared_ptr<NetworkShareSubStateMachine> &subSm)
860 {
861     if (isAdd) {
862         std::vector<std::shared_ptr<NetworkShareSubStateMachine>>::iterator iter =
863             find(sharedSubSM_.begin(), sharedSubSM_.end(), subSm);
864         if (iter == sharedSubSM_.end()) {
865             NETMGR_EXT_LOG_I("add new shared subSm.");
866             sharedSubSM_.push_back(subSm);
867         }
868     } else {
869         std::vector<std::shared_ptr<NetworkShareSubStateMachine>>::iterator iter =
870             find(sharedSubSM_.begin(), sharedSubSM_.end(), subSm);
871         if (iter != sharedSubSM_.end()) {
872             NETMGR_EXT_LOG_I("remove the shared subSm.");
873             sharedSubSM_.erase(iter);
874         }
875     }
876 }
877 
SetUpstreamNetHandle(const std::shared_ptr<UpstreamNetworkInfo> & netinfo)878 void NetworkShareTracker::SetUpstreamNetHandle(const std::shared_ptr<UpstreamNetworkInfo> &netinfo)
879 {
880     if (netinfo != nullptr && netinfo->netHandle_ != nullptr) {
881         SetDnsForwarders(*(netinfo->netHandle_));
882     } else {
883         StopDnsProxy();
884     }
885     NotifyDownstreamsHasNewUpstreamIface(netinfo);
886 }
887 
SetDnsForwarders(const NetHandle & netHandle)888 void NetworkShareTracker::SetDnsForwarders(const NetHandle &netHandle)
889 {
890     if (mainStateMachine_ == nullptr) {
891         NETMGR_EXT_LOG_I("MainSM is null");
892         return;
893     }
894     int32_t ret = NETMANAGER_SUCCESS;
895     if (!isStartDnsProxy_) {
896         ret = NetsysController::GetInstance().StartDnsProxyListen();
897         if (ret != NETSYS_SUCCESS) {
898             NETMGR_EXT_LOG_E("StartDnsProxy error, result[%{public}d].", ret);
899             mainStateMachine_->SwitcheToErrorState(CMD_SET_DNS_FORWARDERS_ERROR);
900             return;
901         }
902         NETMGR_EXT_LOG_I("StartDnsProxy successful.");
903         isStartDnsProxy_ = true;
904     }
905     int32_t netId = netHandle.GetNetId();
906     if (netId < 0) {
907         NETMGR_EXT_LOG_E("netId less than 0.");
908         mainStateMachine_->SwitcheToErrorState(CMD_SET_DNS_FORWARDERS_ERROR);
909         return;
910     }
911     ret = NetsysController::GetInstance().ShareDnsSet(netId);
912     if (ret != NETSYS_SUCCESS) {
913         NETMGR_EXT_LOG_E("SetDns error, result[%{public}d].", ret);
914         mainStateMachine_->SwitcheToErrorState(CMD_SET_DNS_FORWARDERS_ERROR);
915         return;
916     }
917     NETMGR_EXT_LOG_I("SetDns netId[%{public}d] success.", netId);
918 }
919 
StopDnsProxy()920 void NetworkShareTracker::StopDnsProxy()
921 {
922     if (isStartDnsProxy_) {
923         int32_t ret = NetsysController::GetInstance().StopDnsProxyListen();
924         if (ret != NETSYS_SUCCESS) {
925             NETMGR_EXT_LOG_E("StopDnsProxy error, result[%{public}d].", ret);
926         } else {
927             NETMGR_EXT_LOG_I("StopDnsProxy success.");
928             isStartDnsProxy_ = false;
929         }
930     }
931 }
932 
NotifyDownstreamsHasNewUpstreamIface(const std::shared_ptr<UpstreamNetworkInfo> & netinfo)933 void NetworkShareTracker::NotifyDownstreamsHasNewUpstreamIface(const std::shared_ptr<UpstreamNetworkInfo> &netinfo)
934 {
935     upstreamInfo_ = netinfo;
936     for_each(sharedSubSM_.begin(), sharedSubSM_.end(), [netinfo](std::shared_ptr<NetworkShareSubStateMachine> subsm) {
937         if (subsm != nullptr) {
938             NETMGR_EXT_LOG_I("NOTIFY TO SUB SM [%{public}s] CMD_NETSHARE_CONNECTION_CHANGED.",
939                              subsm->GetInterfaceName().c_str());
940             subsm->SubSmEventHandle(CMD_NETSHARE_CONNECTION_CHANGED, netinfo);
941         }
942     });
943 }
944 
GetUpstreamInfo(std::shared_ptr<UpstreamNetworkInfo> & upstreamInfo)945 void NetworkShareTracker::GetUpstreamInfo(std::shared_ptr<UpstreamNetworkInfo> &upstreamInfo)
946 {
947     upstreamInfo = upstreamInfo_;
948 }
949 
CreateSubStateMachine(const std::string & iface,const SharingIfaceType & interfaceType,bool isNcm)950 int32_t NetworkShareTracker::CreateSubStateMachine(const std::string &iface, const SharingIfaceType &interfaceType,
951                                                    bool isNcm)
952 {
953     {
954         std::lock_guard lock(mutex_);
955         if (subStateMachineMap_.count(iface) != 0) {
956             NETMGR_EXT_LOG_W("iface[%{public}s] has added, ignoring", iface.c_str());
957             return NETMANAGER_EXT_SUCCESS;
958         }
959     }
960 
961     std::shared_ptr<NetworkShareSubStateMachine> subSm =
962         std::make_shared<NetworkShareSubStateMachine>(iface, interfaceType, configuration_);
963     std::shared_ptr<SubSmUpstreamCallback> smcallback = std::make_shared<SubSmUpstreamCallback>();
964     subSm->RegisterSubSMCallback(smcallback);
965 
966     {
967         std::lock_guard lock(mutex_);
968         std::shared_ptr<NetSharingSubSmState> netShareState = std::make_shared<NetSharingSubSmState>(subSm, isNcm);
969         subStateMachineMap_.insert(std::make_pair(iface, netShareState));
970     }
971     NETMGR_EXT_LOG_I("adding subSM[%{public}s], type[%{public}d], current subSM count[%{public}s]", iface.c_str(),
972                      static_cast<SharingIfaceType>(interfaceType), std::to_string(subStateMachineMap_.size()).c_str());
973     return NETMANAGER_EXT_SUCCESS;
974 }
975 
StopSubStateMachine(const std::string & iface,const SharingIfaceType & interfaceType)976 void NetworkShareTracker::StopSubStateMachine(const std::string &iface, const SharingIfaceType &interfaceType)
977 {
978     std::shared_ptr<NetworkShareSubStateMachine> subSM = nullptr;
979     std::string findKey;
980     if (!FindSubStateMachine(iface, interfaceType, subSM, findKey) || subSM == nullptr) {
981         NETMGR_EXT_LOG_W("not find the subSM.");
982         return;
983     }
984     NETMGR_EXT_LOG_I("NOTIFY TO SUB SM [%{public}s] CMD_NETSHARE_UNREQUESTED.", subSM->GetInterfaceName().c_str());
985     subSM->SubSmEventHandle(CMD_NETSHARE_UNREQUESTED, 0);
986 
987     {
988         std::lock_guard lock(mutex_);
989         if (subStateMachineMap_.count(findKey) > 0) {
990             subStateMachineMap_.erase(findKey);
991             NETMGR_EXT_LOG_I("removed iface[%{public}s] subSM, current subSM count[%{public}s].", iface.c_str(),
992                              std::to_string(subStateMachineMap_.size()).c_str());
993         }
994     }
995 }
996 
InterfaceNameToType(const std::string & iface,SharingIfaceType & type)997 bool NetworkShareTracker::InterfaceNameToType(const std::string &iface, SharingIfaceType &type)
998 {
999     if (configuration_ == nullptr) {
1000         NETMGR_EXT_LOG_E("configuration is null.");
1001         return false;
1002     }
1003     if (configuration_->IsWifiIface(iface)) {
1004         type = SharingIfaceType::SHARING_WIFI;
1005         return true;
1006     }
1007     if (configuration_->IsUsbIface(iface)) {
1008         type = SharingIfaceType::SHARING_USB;
1009         return true;
1010     }
1011     if (configuration_->IsBluetoothIface(iface)) {
1012         type = SharingIfaceType::SHARING_BLUETOOTH;
1013         return true;
1014     }
1015     return false;
1016 }
1017 
IsHandleNetlinkEvent(const SharingIfaceType & type,bool up)1018 bool NetworkShareTracker::IsHandleNetlinkEvent(const SharingIfaceType &type, bool up)
1019 {
1020     if (type == SharingIfaceType::SHARING_WIFI) {
1021         return up ? curWifiState_ == Wifi::ApState::AP_STATE_STARTING
1022                   : curWifiState_ == Wifi::ApState::AP_STATE_CLOSING;
1023     }
1024     if (type == SharingIfaceType::SHARING_BLUETOOTH) {
1025         return up ? curBluetoothState_ == Bluetooth::BTConnectState::CONNECTING
1026                   : curBluetoothState_ == Bluetooth::BTConnectState::DISCONNECTING;
1027     }
1028     if (type == SharingIfaceType::SHARING_USB) {
1029         return up ? curUsbState_ == UsbShareState::USB_SHARING
1030                   : curUsbState_ == UsbShareState::USB_CLOSING;
1031     }
1032     return false;
1033 }
1034 
InterfaceStatusChanged(const std::string & iface,bool up)1035 void NetworkShareTracker::InterfaceStatusChanged(const std::string &iface, bool up)
1036 {
1037     if (eventHandler_ == nullptr || !isInit) {
1038         NETMGR_EXT_LOG_E("eventHandler is null.");
1039         return;
1040     }
1041     SharingIfaceType type;
1042     if (!InterfaceNameToType(iface, type) || !IsHandleNetlinkEvent(type, up)) {
1043         NETMGR_EXT_LOG_E("iface[%{public}s] is not downsteam or not correct event.", iface.c_str());
1044         return;
1045     }
1046     NETMGR_EXT_LOG_I("interface[%{public}s] for [%{public}s]", iface.c_str(), up ? "up" : "down");
1047     if (up) {
1048         std::string taskName = "InterfaceAdded_task";
1049         if (iface == configuration_->GetUsbRndisIfaceName()) {
1050             std::function<void()> sharingUsbFunc =
1051                 std::bind(&NetworkShareTracker::Sharing, this, iface, SUB_SM_STATE_SHARED);
1052             eventHandler_->PostTask(sharingUsbFunc, taskName, 0, AppExecFwk::EventQueue::Priority::HIGH);
1053         } else {
1054             std::function<void()> createSubStateMachineFunc =
1055                 std::bind(&NetworkShareTracker::CreateSubStateMachine, this, iface, type, false);
1056             eventHandler_->PostTask(createSubStateMachineFunc, taskName, 0, AppExecFwk::EventQueue::Priority::HIGH);
1057         }
1058     } else {
1059         std::string taskName = "InterfaceRemoved_task";
1060         std::function<void()> stopSubStateMachineFunc =
1061             std::bind(&NetworkShareTracker::StopSubStateMachine, this, iface, type);
1062         eventHandler_->PostTask(stopSubStateMachineFunc, taskName, 0, AppExecFwk::EventQueue::Priority::HIGH);
1063     }
1064 }
1065 
InterfaceAdded(const std::string & iface)1066 void NetworkShareTracker::InterfaceAdded(const std::string &iface)
1067 {
1068     if (eventHandler_ == nullptr || !isInit) {
1069         NETMGR_EXT_LOG_E("eventHandler is null.");
1070         return;
1071     }
1072     SharingIfaceType type;
1073     if (!InterfaceNameToType(iface, type) || !IsHandleNetlinkEvent(type, true)) {
1074         NETMGR_EXT_LOG_E("iface[%{public}s] is not downsteam or not correct event.", iface.c_str());
1075         return;
1076     }
1077     NETMGR_EXT_LOG_I("iface[%{public}s], type[%{public}d].", iface.c_str(), static_cast<int32_t>(type));
1078     std::string taskName = "InterfaceAdded_task";
1079     std::function<void()> createSubStateMachineFunc =
1080         std::bind(&NetworkShareTracker::CreateSubStateMachine, this, iface, type, false);
1081     eventHandler_->PostTask(createSubStateMachineFunc, taskName, 0, AppExecFwk::EventQueue::Priority::HIGH);
1082 }
1083 
InterfaceRemoved(const std::string & iface)1084 void NetworkShareTracker::InterfaceRemoved(const std::string &iface)
1085 {
1086     if (eventHandler_ == nullptr || !isInit) {
1087         NETMGR_EXT_LOG_E("eventHandler is null.");
1088         return;
1089     }
1090     SharingIfaceType type;
1091     if (!InterfaceNameToType(iface, type) || !IsHandleNetlinkEvent(type, false)) {
1092         NETMGR_EXT_LOG_E("iface[%{public}s] is not downsteam or not correct event.", iface.c_str());
1093         return;
1094     }
1095     NETMGR_EXT_LOG_I("iface[%{public}s], type[%{public}d].", iface.c_str(), static_cast<int32_t>(type));
1096     std::string taskName = "InterfaceRemoved_task";
1097     std::function<void()> stopSubStateMachineFunc =
1098         std::bind(&NetworkShareTracker::StopSubStateMachine, this, iface, type);
1099     eventHandler_->PostTask(stopSubStateMachineFunc, taskName, 0, AppExecFwk::EventQueue::Priority::HIGH);
1100 }
1101 
SendGlobalSharingStateChange()1102 void NetworkShareTracker::SendGlobalSharingStateChange()
1103 {
1104     uint32_t callbackSize = 0;
1105     {
1106         std::lock_guard lock(callbackMutex_);
1107         callbackSize = sharingEventCallback_.size();
1108     }
1109     if (callbackSize == 0) {
1110         NETMGR_EXT_LOG_E("sharingEventCallback is empty.");
1111         return;
1112     }
1113     bool isSharing = false;
1114     {
1115         std::lock_guard lock(mutex_);
1116         for (auto &iter : subStateMachineMap_) {
1117             std::shared_ptr<NetSharingSubSmState> subsmState = iter.second;
1118             if (subsmState == nullptr) {
1119                 NETMGR_EXT_LOG_W("iface[%{public}s] subsmState is null.", iter.first.c_str());
1120                 continue;
1121             }
1122             if (subsmState->lastState_ == SUB_SM_STATE_SHARED) {
1123                 isSharing = true;
1124                 break;
1125             }
1126         }
1127     }
1128     if (isNetworkSharing_ != isSharing) {
1129         isNetworkSharing_ = isSharing;
1130         std::lock_guard lock(callbackMutex_);
1131         for_each(sharingEventCallback_.begin(), sharingEventCallback_.end(),
1132                  [isSharing](sptr<ISharingEventCallback> &callback) {
1133                      if (callback != nullptr) {
1134                          callback->OnSharingStateChanged(isSharing);
1135                      }
1136                  });
1137     }
1138 }
1139 
SendIfaceSharingStateChange(const SharingIfaceType & type,const std::string & iface,const SharingIfaceState & state)1140 void NetworkShareTracker::SendIfaceSharingStateChange(const SharingIfaceType &type, const std::string &iface,
1141                                                       const SharingIfaceState &state)
1142 {
1143     std::lock_guard lock(callbackMutex_);
1144     if (sharingEventCallback_.size() == 0) {
1145         NETMGR_EXT_LOG_E("sharingEventCallback is empty.");
1146         return;
1147     }
1148     for_each(sharingEventCallback_.begin(), sharingEventCallback_.end(),
1149              [type, iface, state](sptr<ISharingEventCallback> &callback) {
1150                  if (callback != nullptr) {
1151                      callback->OnInterfaceSharingStateChanged(type, iface, state);
1152                  }
1153              });
1154 }
1155 
SendSharingUpstreamChange(const sptr<NetHandle> & netHandle)1156 void NetworkShareTracker::SendSharingUpstreamChange(const sptr<NetHandle> &netHandle)
1157 {
1158     std::lock_guard lock(callbackMutex_);
1159     if (sharingEventCallback_.size() == 0) {
1160         NETMGR_EXT_LOG_E("sharingEventCallback is empty.");
1161         return;
1162     }
1163     for_each(sharingEventCallback_.begin(), sharingEventCallback_.end(),
1164              [netHandle](sptr<ISharingEventCallback> &callback) {
1165                  if (callback != nullptr) {
1166                      callback->OnSharingUpstreamChanged(netHandle);
1167                  }
1168              });
1169 }
1170 
SubSmStateToExportState(int32_t state)1171 SharingIfaceState NetworkShareTracker::SubSmStateToExportState(int32_t state)
1172 {
1173     SharingIfaceState newState = SharingIfaceState::SHARING_NIC_CAN_SERVER;
1174     if (state == SUB_SM_STATE_AVAILABLE) {
1175         newState = SharingIfaceState::SHARING_NIC_CAN_SERVER;
1176     } else if (state == SUB_SM_STATE_SHARED) {
1177         newState = SharingIfaceState::SHARING_NIC_SERVING;
1178     } else if (state == SUB_SM_STATE_UNAVAILABLE) {
1179         newState = SharingIfaceState::SHARING_NIC_ERROR;
1180     } else {
1181         NETMGR_EXT_LOG_E("SubSmStateToExportState state[%{public}d] is unknown type.", state);
1182         newState = SharingIfaceState::SHARING_NIC_ERROR;
1183     }
1184     return newState;
1185 }
1186 } // namespace NetManagerStandard
1187 } // namespace OHOS
1188