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