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