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