• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "networkshare_sub_statemachine.h"
17 
18 #include "net_manager_constants.h"
19 #include "net_manager_ext_constants.h"
20 #include "netmgr_ext_log_wrapper.h"
21 #include "netsys_controller.h"
22 #include "route_utils.h"
23 
24 namespace OHOS {
25 namespace NetManagerStandard {
26 namespace {
27 constexpr const char *NEXT_HOT = "0.0.0.0";
28 constexpr const char *ERROR_MSG_CONFIG_FORWARD = "Config Forward failed";
29 constexpr const char *ERROR_MSG_ADD_ROUTE_STRATEGY = "Add Route Strategy failed";
30 constexpr const char *ERROR_MSG_ADD_ROUTE_RULE = "Add Route Rule failed";
31 constexpr const char *ERROR_MSG_REMOVE_ROUTE_RULE = "Remove Route Rule failed";
32 constexpr const char *EMPTY_UPSTREAM_IFACENAME = "";
33 constexpr int32_t IP_V4 = 0;
34 }
35 
NetworkShareSubStateMachine(const std::string & ifaceName,const SharingIfaceType & interfaceType,const std::shared_ptr<NetworkShareConfiguration> & configuration)36 NetworkShareSubStateMachine::NetworkShareSubStateMachine(
37     const std::string &ifaceName, const SharingIfaceType &interfaceType,
38     const std::shared_ptr<NetworkShareConfiguration> &configuration)
39     : ifaceName_(ifaceName), netShareType_(interfaceType), configuration_(configuration)
40 {
41     CreateInitStateTable();
42     CreateSharedStateTable();
43 }
44 
CreateInitStateTable()45 void NetworkShareSubStateMachine::CreateInitStateTable()
46 {
47     SubSmStateTable temp;
48     temp.event_ = CMD_NETSHARE_REQUESTED;
49     temp.curState_ = SUBSTATE_INIT;
50     temp.func_ = &NetworkShareSubStateMachine::HandleInitSharingRequest;
51     temp.nextState_ = SUBSTATE_SHARED;
52     stateTable_.push_back(temp);
53 
54     temp.event_ = CMD_INTERFACE_DOWN;
55     temp.curState_ = SUBSTATE_INIT;
56     temp.func_ = &NetworkShareSubStateMachine::HandleInitInterfaceDown;
57     temp.nextState_ = SUBSTATE_UNAVAILABLE;
58     stateTable_.push_back(temp);
59 }
60 
CreateSharedStateTable()61 void NetworkShareSubStateMachine::CreateSharedStateTable()
62 {
63     SubSmStateTable temp;
64     temp.event_ = CMD_NETSHARE_UNREQUESTED;
65     temp.curState_ = SUBSTATE_SHARED;
66     temp.func_ = &NetworkShareSubStateMachine::HandleSharedUnrequest;
67     temp.nextState_ = SUBSTATE_INIT;
68     stateTable_.push_back(temp);
69 
70     temp.event_ = CMD_INTERFACE_DOWN;
71     temp.curState_ = SUBSTATE_SHARED;
72     temp.func_ = &NetworkShareSubStateMachine::HandleSharedInterfaceDown;
73     temp.nextState_ = SUBSTATE_UNAVAILABLE;
74     stateTable_.push_back(temp);
75 
76     temp.event_ = CMD_NETSHARE_CONNECTION_CHANGED;
77     temp.curState_ = SUBSTATE_SHARED;
78     temp.func_ = &NetworkShareSubStateMachine::HandleSharedConnectionChange;
79     temp.nextState_ = NO_NEXT_STATE;
80     stateTable_.push_back(temp);
81 
82     temp.event_ = CMD_IP_FORWARDING_ENABLE_ERROR;
83     temp.curState_ = SUBSTATE_SHARED;
84     temp.func_ = &NetworkShareSubStateMachine::HandleSharedErrors;
85     temp.nextState_ = SUBSTATE_INIT;
86     stateTable_.push_back(temp);
87 
88     temp.event_ = CMD_IP_FORWARDING_DISABLE_ERROR;
89     temp.curState_ = SUBSTATE_SHARED;
90     temp.func_ = &NetworkShareSubStateMachine::HandleSharedErrors;
91     temp.nextState_ = SUBSTATE_INIT;
92     stateTable_.push_back(temp);
93 
94     temp.event_ = CMD_START_SHARING_ERROR;
95     temp.curState_ = SUBSTATE_SHARED;
96     temp.func_ = &NetworkShareSubStateMachine::HandleSharedErrors;
97     temp.nextState_ = SUBSTATE_INIT;
98     stateTable_.push_back(temp);
99 
100     temp.event_ = CMD_STOP_SHARING_ERROR;
101     temp.curState_ = SUBSTATE_SHARED;
102     temp.func_ = &NetworkShareSubStateMachine::HandleSharedErrors;
103     temp.nextState_ = SUBSTATE_INIT;
104     stateTable_.push_back(temp);
105 
106     temp.event_ = CMD_SET_DNS_FORWARDERS_ERROR;
107     temp.curState_ = SUBSTATE_SHARED;
108     temp.func_ = &NetworkShareSubStateMachine::HandleSharedErrors;
109     temp.nextState_ = SUBSTATE_INIT;
110     stateTable_.push_back(temp);
111 }
112 
SubSmStateSwitch(int newState)113 void NetworkShareSubStateMachine::SubSmStateSwitch(int newState)
114 {
115     int oldState = curState_;
116     curState_ = newState;
117     NETMGR_EXT_LOG_I("Sub SM from[%{public}d] to[%{public}d].", oldState, newState);
118 
119     if (oldState == SUBSTATE_INIT) {
120         InitStateExit();
121     } else if (oldState == SUBSTATE_SHARED) {
122         SharedStateExit();
123     } else if (oldState == SUBSTATE_UNAVAILABLE) {
124         UnavailableStateExit();
125     } else {
126         NETMGR_EXT_LOG_E("oldState is unknow type value.");
127     }
128 
129     if (newState == SUBSTATE_INIT) {
130         InitStateEnter();
131     } else if (newState == SUBSTATE_SHARED) {
132         SharedStateEnter();
133     } else if (newState == SUBSTATE_UNAVAILABLE) {
134         UnavailableStateEnter();
135     } else {
136         NETMGR_EXT_LOG_E("newState is unknow type value.");
137     }
138 }
139 
SubSmEventHandle(int eventId,const std::any & messageObj)140 void NetworkShareSubStateMachine::SubSmEventHandle(int eventId, const std::any &messageObj)
141 {
142     std::lock_guard<std::recursive_mutex> lock(mutex_);
143     int nextState = NO_NEXT_STATE;
144     int (NetworkShareSubStateMachine::*eventFunc)(const std::any &messageObj) = nullptr;
145     for (const auto &iterState : stateTable_) {
146         if ((eventId == iterState.event_) && (curState_ == iterState.curState_)) {
147             eventFunc = iterState.func_;
148             nextState = iterState.nextState_;
149             break;
150         }
151     }
152     if (eventFunc == nullptr) {
153         NETMGR_EXT_LOG_W("SubSM currentstate[%{public}d] eventId[%{public}d] is not matched.", curState_, eventId);
154         return;
155     }
156     (this->*eventFunc)(messageObj);
157     if (nextState >= SUBSTATE_INIT && nextState < SUBSTATE_MAX) {
158         SubSmStateSwitch(nextState);
159     }
160 
161     NETMGR_EXT_LOG_I("SubSM eventId[%{public}d] handle successfull.", eventId);
162 }
163 
GetDownIfaceName(std::string & downIface)164 void NetworkShareSubStateMachine::GetDownIfaceName(std::string &downIface)
165 {
166     downIface = ifaceName_;
167 }
168 
GetUpIfaceName(std::string & upIface)169 void NetworkShareSubStateMachine::GetUpIfaceName(std::string &upIface)
170 {
171     upIface = upstreamIfaceName_;
172 }
173 
InitStateEnter()174 void NetworkShareSubStateMachine::InitStateEnter()
175 {
176     if (trackerCallback_ == nullptr) {
177         NETMGR_EXT_LOG_E("Enter Sub StateMachine Init State error, trackerCallback_ is null.");
178         return;
179     }
180     NETMGR_EXT_LOG_I("Enter Sub StateMachine[%{public}s] Init State.", ifaceName_.c_str());
181     trackerCallback_->OnUpdateInterfaceState(shared_from_this(), SUB_SM_STATE_AVAILABLE, lastError_);
182 }
183 
InitStateExit()184 void NetworkShareSubStateMachine::InitStateExit()
185 {
186     NETMGR_EXT_LOG_I("Exit Sub StateMachine[%{public}s] Init State.", ifaceName_.c_str());
187 }
188 
HandleInitSharingRequest(const std::any & messageObj)189 int NetworkShareSubStateMachine::HandleInitSharingRequest(const std::any &messageObj)
190 {
191     (void)messageObj;
192     lastError_ = NETMANAGER_EXT_SUCCESS;
193     return NETMANAGER_EXT_SUCCESS;
194 }
195 
HandleInitInterfaceDown(const std::any & messageObj)196 int NetworkShareSubStateMachine::HandleInitInterfaceDown(const std::any &messageObj)
197 {
198     (void)messageObj;
199     return NETMANAGER_EXT_SUCCESS;
200 }
201 
SharedStateEnter()202 void NetworkShareSubStateMachine::SharedStateEnter()
203 {
204     NETMGR_EXT_LOG_I("Enter Sub StateMachine[%{public}s] Shared State.", ifaceName_.c_str());
205     if (!ConfigureShareDhcp(true)) {
206         lastError_ = NETWORKSHARE_ERROR_IFACE_CFG_ERROR;
207         NETMGR_EXT_LOG_E("Enter sub StateMachine[%{public}s] Shared State configIpv4 error.", ifaceName_.c_str());
208     }
209     if (lastError_ != NETMANAGER_EXT_SUCCESS) {
210         SubSmStateSwitch(SUBSTATE_INIT);
211         return;
212     }
213     if (trackerCallback_ == nullptr) {
214         NETMGR_EXT_LOG_E("Enter Sub StateMachine Shared State error, trackerCallback_ is null.");
215         return;
216     }
217     trackerCallback_->OnUpdateInterfaceState(shared_from_this(), SUB_SM_STATE_SHARED, lastError_);
218 }
219 
SharedStateExit()220 void NetworkShareSubStateMachine::SharedStateExit()
221 {
222     NETMGR_EXT_LOG_I("Exit Sub StateMachine[%{public}s] Shared State.", ifaceName_.c_str());
223     CleanupUpstreamInterface();
224     ConfigureShareDhcp(false);
225 }
226 
HandleSharedUnrequest(const std::any & messageObj)227 int NetworkShareSubStateMachine::HandleSharedUnrequest(const std::any &messageObj)
228 {
229     (void)messageObj;
230     return NETMANAGER_EXT_SUCCESS;
231 }
232 
HandleSharedInterfaceDown(const std::any & messageObj)233 int NetworkShareSubStateMachine::HandleSharedInterfaceDown(const std::any &messageObj)
234 {
235     (void)messageObj;
236     return NETMANAGER_EXT_SUCCESS;
237 }
238 
HandleSharedConnectionChange(const std::any & messageObj)239 int NetworkShareSubStateMachine::HandleSharedConnectionChange(const std::any &messageObj)
240 {
241     std::shared_ptr<UpstreamNetworkInfo> upstreamNetInfo =
242         std::any_cast<std::shared_ptr<UpstreamNetworkInfo>>(messageObj);
243     if (upstreamNetInfo == nullptr) {
244         NETMGR_EXT_LOG_I("Sub StateMachine[%{public}s] upstreamNetInfo is null, need clean.", ifaceName_.c_str());
245         CleanupUpstreamInterface();
246         upstreamIfaceName_ = EMPTY_UPSTREAM_IFACENAME;
247         return NETMANAGER_EXT_SUCCESS;
248     }
249     HandleConnectionChanged(upstreamNetInfo);
250     return NETMANAGER_EXT_SUCCESS;
251 }
252 
HandleSharedErrors(const std::any & messageObj)253 int NetworkShareSubStateMachine::HandleSharedErrors(const std::any &messageObj)
254 {
255     (void)messageObj;
256     NETMGR_EXT_LOG_I("Sub StateMachine[%{public}s] SharedState has ERROR.", ifaceName_.c_str());
257     lastError_ = NETWORKSHARE_ERROR_INTERNAL_ERROR;
258     return NETMANAGER_EXT_SUCCESS;
259 }
260 
UnavailableStateEnter()261 void NetworkShareSubStateMachine::UnavailableStateEnter()
262 {
263     NETMGR_EXT_LOG_I("Enter Sub StateMachine[%{public}s] Unavailable State.", ifaceName_.c_str());
264     lastError_ = NETMANAGER_EXT_SUCCESS;
265     if (trackerCallback_ == nullptr) {
266         NETMGR_EXT_LOG_E("Enter Sub StateMachine Unavailable State error, trackerCallback_ is null.");
267         return;
268     }
269     trackerCallback_->OnUpdateInterfaceState(shared_from_this(), SUB_SM_STATE_UNAVAILABLE, NETMANAGER_EXT_SUCCESS);
270 }
271 
UnavailableStateExit()272 void NetworkShareSubStateMachine::UnavailableStateExit()
273 {
274     NETMGR_EXT_LOG_I("Exit Sub StateMachine[%{public}s] Unavailable State.", ifaceName_.c_str());
275 }
276 
HandleConnectionChanged(const std::shared_ptr<UpstreamNetworkInfo> & upstreamNetInfo)277 void NetworkShareSubStateMachine::HandleConnectionChanged(const std::shared_ptr<UpstreamNetworkInfo> &upstreamNetInfo)
278 {
279     if (upstreamNetInfo == nullptr) {
280         return;
281     }
282     if (upstreamNetInfo->netLinkPro_ == nullptr) {
283         NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] HandleConnectionChanged netLinkPro_ is null.",
284                          ifaceName_.c_str());
285         return;
286     }
287     if (!HasChangeUpstreamIfaceSet(upstreamNetInfo->netLinkPro_->ifaceName_)) {
288         NETMGR_EXT_LOG_I("Sub StateMachine[%{public}s] HandleConnectionChanged Upstream Iface no change.",
289                          ifaceName_.c_str());
290         return;
291     }
292 
293     CleanupUpstreamInterface();
294     upstreamIfaceName_ = upstreamNetInfo->netLinkPro_->ifaceName_;
295 
296     HandleConnection();
297     AddRoutesToLocalNetwork();
298 }
299 
HandleConnection()300 void NetworkShareSubStateMachine::HandleConnection()
301 {
302     int32_t result = NetsysController::GetInstance().IpfwdAddInterfaceForward(ifaceName_, upstreamIfaceName_);
303     if (result != NETSYS_SUCCESS) {
304         NetworkShareHisysEvent::GetInstance().SendFaultEvent(
305             netShareType_, NetworkShareEventOperator::OPERATION_CONFIG_FORWARD,
306             NetworkShareEventErrorType::ERROR_CONFIG_FORWARD, ERROR_MSG_CONFIG_FORWARD,
307             NetworkShareEventType::SETUP_EVENT);
308         NETMGR_EXT_LOG_E(
309             "Sub StateMachine[%{public}s] IpfwdAddInterfaceForward newIface[%{public}s] error[%{public}d].",
310             ifaceName_.c_str(), upstreamIfaceName_.c_str(), result);
311         lastError_ = NETWORKSHARE_ERROR_ENABLE_FORWARDING_ERROR;
312         SubSmStateSwitch(SUBSTATE_INIT);
313         return;
314     }
315 
316     result = NetsysController::GetInstance().NetworkAddInterface(LOCAL_NET_ID, ifaceName_);
317     if (result != NETMANAGER_SUCCESS) {
318         NetworkShareHisysEvent::GetInstance().SendFaultEvent(
319             netShareType_, NetworkShareEventOperator::OPERATION_CONFIG_FORWARD,
320             NetworkShareEventErrorType::ERROR_CONFIG_FORWARD, ERROR_MSG_ADD_ROUTE_STRATEGY,
321             NetworkShareEventType::SETUP_EVENT);
322         NETMGR_EXT_LOG_E(
323             "Sub StateMachine[%{public}s] SharedState NetworkAddInterface newIface[%{public}s] error[%{public}d].",
324             ifaceName_.c_str(), upstreamIfaceName_.c_str(), result);
325         NetsysController::GetInstance().IpfwdRemoveInterfaceForward(ifaceName_, upstreamIfaceName_);
326         lastError_ = NETWORKSHARE_ERROR_ENABLE_FORWARDING_ERROR;
327         SubSmStateSwitch(SUBSTATE_INIT);
328         return;
329     }
330 }
331 
RemoveRoutesToLocalNetwork()332 void NetworkShareSubStateMachine::RemoveRoutesToLocalNetwork()
333 {
334     std::string destination;
335     if (!FindDestinationAddr(destination)) {
336         NETMGR_EXT_LOG_E("Get Destination fail");
337         return;
338     }
339     int32_t result =
340         NetsysController::GetInstance().NetworkRemoveRoute(LOCAL_NET_ID, ifaceName_, destination, NEXT_HOT);
341     if (result != NETSYS_SUCCESS) {
342         NetworkShareHisysEvent::GetInstance().SendFaultEvent(
343             netShareType_, NetworkShareEventOperator::OPERATION_CANCEL_FORWARD,
344             NetworkShareEventErrorType::ERROR_CANCEL_FORWARD, ERROR_MSG_REMOVE_ROUTE_RULE,
345             NetworkShareEventType::CANCEL_EVENT);
346         NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] Remove Route error[%{public}d].", ifaceName_.c_str(), result);
347     }
348 }
349 
AddRoutesToLocalNetwork()350 void NetworkShareSubStateMachine::AddRoutesToLocalNetwork()
351 {
352     std::string destination;
353     if (!FindDestinationAddr(destination)) {
354         NETMGR_EXT_LOG_E("Get Destination fail");
355         return;
356     }
357     int32_t result = NetsysController::GetInstance().NetworkAddRoute(LOCAL_NET_ID, ifaceName_, destination, NEXT_HOT);
358     if (result != NETSYS_SUCCESS) {
359         NetworkShareHisysEvent::GetInstance().SendFaultEvent(
360             netShareType_, NetworkShareEventOperator::OPERATION_CONFIG_FORWARD,
361             NetworkShareEventErrorType::ERROR_CONFIG_FORWARD, ERROR_MSG_ADD_ROUTE_RULE,
362             NetworkShareEventType::SETUP_EVENT);
363         NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] Add Route error[%{public}d].", ifaceName_.c_str(), result);
364     }
365 }
366 
FindDestinationAddr(std::string & destination)367 bool NetworkShareSubStateMachine::FindDestinationAddr(std::string &destination)
368 {
369     if (netShareType_ == SharingIfaceType::SHARING_BLUETOOTH) {
370         if (!GetBtDestinationAddr(destination)) {
371             NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] Add Route Get btpan Destination Addr failed.",
372                              ifaceName_.c_str());
373             return false;
374         }
375         return true;
376     }
377     if (netShareType_ == SharingIfaceType::SHARING_WIFI) {
378         if (!GetWifiApDestinationAddr(destination)) {
379             NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] Add Route Get wifi Destination Addr failed.",
380                              ifaceName_.c_str());
381             return false;
382         }
383         return true;
384     }
385     if (netShareType_ == SharingIfaceType::SHARING_USB) {
386         if (!GetUsbDestinationAddr(destination)) {
387             NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] Add Route Get usb Destination Addr failed.",
388                              ifaceName_.c_str());
389             return false;
390         }
391         return true;
392     }
393     NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] Add Route sharetype is unknown.", ifaceName_.c_str());
394     return false;
395 }
396 
GetWifiHotspotDhcpFlag()397 bool NetworkShareSubStateMachine::GetWifiHotspotDhcpFlag()
398 {
399     if (configuration_ == nullptr) {
400         return false;
401     }
402     return configuration_->GetWifiHotspotSetDhcpFlag();
403 }
404 
GetBtDestinationAddr(std::string & addrStr)405 bool NetworkShareSubStateMachine::GetBtDestinationAddr(std::string &addrStr)
406 {
407     if (configuration_ == nullptr) {
408         NETMGR_EXT_LOG_E("GetBtDestinationAddr configuration is null.");
409         return false;
410     }
411     std::string btpanIpv4Addr = configuration_->GetBtpanIpv4Addr();
412     if (btpanIpv4Addr.empty()) {
413         NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] get btpan ipv4 addr failed.", ifaceName_.c_str());
414         return false;
415     }
416     std::string::size_type dotPos = btpanIpv4Addr.rfind(".");
417     if (dotPos == std::string::npos) {
418         NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] btpan ipv4 addr error.", ifaceName_.c_str());
419         return false;
420     }
421     std::string routeSuffix = configuration_->GetRouteSuffix();
422     if (routeSuffix.empty()) {
423         NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] get route suffix failed.", ifaceName_.c_str());
424         return false;
425     }
426 
427     addrStr = btpanIpv4Addr.substr(0, dotPos) + routeSuffix;
428     return true;
429 }
430 
GetWifiApDestinationAddr(std::string & addrStr)431 bool NetworkShareSubStateMachine::GetWifiApDestinationAddr(std::string &addrStr)
432 {
433     if (configuration_ == nullptr) {
434         NETMGR_EXT_LOG_E("GetWifiApDestinationAddr configuration is null.");
435         return false;
436     }
437     std::string wifiIpv4Addr = configuration_->GetWifiHotspotIpv4Addr();
438     if (wifiIpv4Addr.empty()) {
439         NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] get wifi ipv4 addr failed.", ifaceName_.c_str());
440         return false;
441     }
442     std::string::size_type dotPos = wifiIpv4Addr.rfind(".");
443     if (dotPos == std::string::npos) {
444         NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] wifi ipv4 addr error.", ifaceName_.c_str());
445         return false;
446     }
447     std::string routeSuffix = configuration_->GetRouteSuffix();
448     if (routeSuffix.empty()) {
449         NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] get route suffix failed.", ifaceName_.c_str());
450         return false;
451     }
452     addrStr = wifiIpv4Addr.substr(0, dotPos) + routeSuffix;
453     return true;
454 }
455 
GetUsbDestinationAddr(std::string & addrStr)456 bool NetworkShareSubStateMachine::GetUsbDestinationAddr(std::string &addrStr)
457 {
458     if (configuration_ == nullptr) {
459         NETMGR_EXT_LOG_E("GetUsbDestinationAddr configuration is null.");
460         return false;
461     }
462     std::string usbIpv4Addr = configuration_->GetUsbRndisIpv4Addr();
463     if (usbIpv4Addr.empty()) {
464         NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] get usb ipv4 addr failed.", ifaceName_.c_str());
465         return false;
466     }
467     std::string::size_type dotPos = usbIpv4Addr.rfind(".");
468     if (dotPos == std::string::npos) {
469         NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] usb ipv4 addr error.", ifaceName_.c_str());
470         return false;
471     }
472     std::string routeSuffix = configuration_->GetRouteSuffix();
473     if (routeSuffix.empty()) {
474         NETMGR_EXT_LOG_E("Sub StateMachine[%{public}s] get route suffix failed.", ifaceName_.c_str());
475         return false;
476     }
477     addrStr = usbIpv4Addr.substr(0, dotPos) + routeSuffix;
478     return true;
479 }
480 
StartDhcp(const std::shared_ptr<INetAddr> & netAddr)481 bool NetworkShareSubStateMachine::StartDhcp(const std::shared_ptr<INetAddr> &netAddr)
482 {
483     if (dhcpService_ == nullptr) {
484         dhcpService_ = OHOS::Wifi::DhcpServiceApi::GetInstance();
485         if (dhcpService_ == nullptr) {
486             NETMGR_EXT_LOG_E("StartDhcp DhcpService create failed.");
487             return false;
488         }
489     }
490     if (netAddr == nullptr) {
491         NETMGR_EXT_LOG_E("StartDhcp netAddr is null.");
492         return false;
493     }
494     std::string endIp;
495     std::string mask;
496     if (!CheckConfig(endIp, mask)) {
497         NETMGR_EXT_LOG_E("StartDhcp Get necessary config failed.");
498         return false;
499     }
500 
501     std::string ipAddr = netAddr->address_;
502     std::string::size_type pos = ipAddr.rfind(".");
503     if (pos == std::string::npos) {
504         NETMGR_EXT_LOG_E("StartDhcp addr is error.");
505         return false;
506     }
507     std::string ipHead = ipAddr.substr(0, pos);
508     std::string ipEnd = ipAddr.substr(pos + 1);
509     std::string startIp = std::to_string(atoi(ipEnd.c_str()) + 1);
510 
511     OHOS::Wifi::DhcpRange range;
512     range.iptype = IP_V4;
513     range.strStartip = ipHead + "." + startIp;
514     range.strEndip = ipHead + "." + endIp;
515     range.strSubnet = mask;
516     range.strTagName = ifaceName_;
517     NETMGR_EXT_LOG_I(
518         "Set dhcp range : ifaceName[%{public}s] TagName[%{public}s] start ip[%{private}s] end ip[%{private}s]",
519         ifaceName_.c_str(), range.strTagName.c_str(), range.strStartip.c_str(), range.strEndip.c_str());
520     if (dhcpService_->SetDhcpRange(ifaceName_, range) != Wifi::DHCP_OPT_SUCCESS) {
521         NETMGR_EXT_LOG_E("StartDhcp SetDhcpRange failed.");
522         return false;
523     }
524     if (dhcpService_->StartDhcpServer(ifaceName_) != Wifi::DHCP_OPT_SUCCESS) {
525         NETMGR_EXT_LOG_E("StartDhcpServer failed.");
526         return false;
527     }
528 
529     NETMGR_EXT_LOG_I("StartDhcpServer successful.");
530     return true;
531 }
532 
CheckConfig(std::string & endIp,std::string & mask)533 bool NetworkShareSubStateMachine::CheckConfig(std::string &endIp, std::string &mask)
534 {
535     if (configuration_ == nullptr) {
536         NETMGR_EXT_LOG_E("StartDhcp configuration is null.");
537         return false;
538     }
539     endIp = configuration_->GetDhcpEndIP();
540     if (endIp.empty()) {
541         NETMGR_EXT_LOG_E("StartDhcp GetDhcpEndIP is null.");
542         return false;
543     }
544     mask = configuration_->GetDefaultMask();
545     if (mask.empty()) {
546         NETMGR_EXT_LOG_E("StartDhcp GetDefaultMask is null.");
547         return false;
548     }
549     return true;
550 }
551 
StopDhcp()552 bool NetworkShareSubStateMachine::StopDhcp()
553 {
554     if (netShareType_ == SharingIfaceType::SHARING_WIFI) {
555         NETMGR_EXT_LOG_W("StopDhcp wifi hotspot not need stop.");
556         return true;
557     }
558     if (dhcpService_ == nullptr) {
559         NETMGR_EXT_LOG_E("StopDhcp dhcpService is null.");
560         return false;
561     }
562     int ret = dhcpService_->StopDhcpServer(ifaceName_);
563     if (ret != Wifi::DHCP_OPT_SUCCESS) {
564         NETMGR_EXT_LOG_E("StopDhcpServer failed, error[%{public}d].", ret);
565         return false;
566     }
567     NETMGR_EXT_LOG_I("StopDhcpServer successful.");
568     return true;
569 }
570 
ConfigureShareDhcp(bool enabled)571 bool NetworkShareSubStateMachine::ConfigureShareDhcp(bool enabled)
572 {
573     std::shared_ptr<INetAddr> ipv4Address = nullptr;
574     if (enabled) {
575         bool ret = RequestIpv4Address(ipv4Address);
576         if (ipv4Address == nullptr || !ret) {
577             NETMGR_EXT_LOG_E("ConfigureShareDhcp no available ipv4 address.");
578             return false;
579         }
580         if (netShareType_ == SharingIfaceType::SHARING_WIFI && !GetWifiHotspotDhcpFlag()) {
581             NETMGR_EXT_LOG_W("StartDhcp wifi hotspot not need start.");
582             return true;
583         }
584         return StartDhcp(ipv4Address);
585     }
586     return StopDhcp();
587 }
588 
RequestIpv4Address(std::shared_ptr<INetAddr> & netAddr)589 bool NetworkShareSubStateMachine::RequestIpv4Address(std::shared_ptr<INetAddr> &netAddr)
590 {
591     if (configuration_ == nullptr) {
592         NETMGR_EXT_LOG_E("RequestIpv4Address get configuration failed.");
593         return false;
594     }
595 
596     netAddr = std::make_shared<INetAddr>();
597     netAddr->type_ = INetAddr::IPV4;
598     netAddr->prefixlen_ = PREFIX_LENGTH_24;
599     netAddr->netMask_ = configuration_->GetDefaultMask();
600     if (netAddr->netMask_.empty()) {
601         NETMGR_EXT_LOG_E("RequestIpv4Address get default mask failed.");
602         return false;
603     }
604     switch (netShareType_) {
605         case SharingIfaceType::SHARING_BLUETOOTH: {
606             netAddr->address_ = configuration_->GetBtpanIpv4Addr();
607             netAddr->hostName_ = configuration_->GetBtpanDhcpServerName();
608             break;
609         }
610         case SharingIfaceType::SHARING_WIFI: {
611             netAddr->address_ = configuration_->GetWifiHotspotIpv4Addr();
612             netAddr->hostName_ = configuration_->GetWifiHotspotDhcpServerName();
613             break;
614         }
615         case SharingIfaceType::SHARING_USB: {
616             netAddr->address_ = configuration_->GetUsbRndisIpv4Addr();
617             netAddr->hostName_ = configuration_->GetUsbRndisDhcpServerName();
618             break;
619         }
620         default:
621             NETMGR_EXT_LOG_E("Unknown share type");
622             return false;
623     }
624 
625     if (netAddr->address_.empty() || netAddr->hostName_.empty()) {
626         NETMGR_EXT_LOG_E("Failed to get ipv4 Address or dhcp server name.");
627         return false;
628     }
629     return true;
630 }
631 
CleanupUpstreamInterface()632 void NetworkShareSubStateMachine::CleanupUpstreamInterface()
633 {
634     NETMGR_EXT_LOG_I("Clearn Forward, downstream Iface[%{public}s], upstream iface[%{public}s].", ifaceName_.c_str(),
635                      upstreamIfaceName_.c_str());
636     RemoveRoutesToLocalNetwork();
637     NetsysController::GetInstance().NetworkRemoveInterface(LOCAL_NET_ID, ifaceName_);
638     NetsysController::GetInstance().IpfwdRemoveInterfaceForward(ifaceName_, upstreamIfaceName_);
639 }
640 
HasChangeUpstreamIfaceSet(const std::string & newUpstreamIface)641 bool NetworkShareSubStateMachine::HasChangeUpstreamIfaceSet(const std::string &newUpstreamIface)
642 {
643     if ((upstreamIfaceName_.empty()) && (newUpstreamIface.empty())) {
644         return false;
645     }
646     if ((!upstreamIfaceName_.empty()) && (!newUpstreamIface.empty())) {
647         return upstreamIfaceName_ != newUpstreamIface;
648     }
649     return true;
650 }
651 
RegisterSubSMCallback(const std::shared_ptr<SubStateMachineCallback> & callback)652 void NetworkShareSubStateMachine::RegisterSubSMCallback(const std::shared_ptr<SubStateMachineCallback> &callback)
653 {
654     trackerCallback_ = callback;
655 }
656 
GetNetShareType() const657 SharingIfaceType NetworkShareSubStateMachine::GetNetShareType() const
658 {
659     return netShareType_;
660 }
661 
GetInterfaceName() const662 const std::string &NetworkShareSubStateMachine::GetInterfaceName() const
663 {
664     return ifaceName_;
665 }
666 } // namespace NetManagerStandard
667 } // namespace OHOS
668