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