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