1 /*
2  * Copyright (C) 2023-2023 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 "self_cure_state_machine.h"
17 #include <vector>
18 #include <string>
19 #include "wifi_cmd_client.h"
20 #include "wifi_logger.h"
21 #include "mac_address.h"
22 #include "multi_gateway.h"
23 #include "wifi_manager.h"
24 #include "event_runner.h"
25 #include "wifi_sta_hal_interface.h"
26 #include "network_status_history_manager.h"
27 #include "wifi_hisysevent.h"
28 #include "wifi_config_center.h"
29 #include "wifi_app_state_aware.h"
30 #include "ip_qos_monitor.h"
31 #include "wifi_net_agent.h"
32 #include "wifi_internal_event_dispatcher.h"
33 #include "wifi_net_agent.h"
34 #include "parameter.h"
35 #include "wifi_common_event_helper.h"
36 #include "wifi_country_code_manager.h"
37 
38 namespace OHOS {
39 namespace Wifi {
40 std::vector<std::string> chinaPublicDnses(SELF_CURE_DNS_SIZE);
41 std::vector<std::string> overseaPublicDnses(SELF_CURE_DNS_SIZE);
42 const std::string CLASS_NAME = "WifiSelfCure";
43 
44 DEFINE_WIFILOG_LABEL("SelfCureStateMachine");
45 
46 const uint32_t CONNECT_NETWORK_RETRY = 1;
47 const uint32_t WIFI_SINGLE_ITEM_BYTE_LEN = 8;
48 const uint32_t WIFI_SINGLE_MAC_LEN = 6;
49 const uint32_t WIFI_MAX_BLA_LIST_NUM = 16;
50 const uint32_t DHCP_OFFER_COUNT = 2;
51 const int CMD_WIFI_CONNECT_TIMEOUT_SCREEN = 8 * 1000;
52 const int CMD_WIFI_CONNECT_TIMEOUT = 16 * 1000;
53 const int PUBLIC_DNS_SERVERS_SIZE = 46;
54 const int PUBLIC_IP_ADDR_NUM = 4;
55 const std::string INIT_SELFCURE_HISTORY = "0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0|0";
56 const std::string COUNTRY_CHINA_CAPITAL = "CN";
57 const std::string COUNTRY_CODE_CN = "460";
58 
SelfCureStateMachine(int instId)59 SelfCureStateMachine::SelfCureStateMachine(int instId)
60     : StateMachine("SelfCureStateMachine"),
61       pDefaultState(nullptr),
62       pConnectedMonitorState(nullptr),
63       pDisconnectedMonitorState(nullptr),
64       pConnectionSelfCureState(nullptr),
65       pInternetSelfCureState(nullptr),
66       pWifi6SelfCureState(nullptr),
67       pNoInternetState(nullptr),
68       m_instId(instId)
69 {
70     mNetWorkDetect = sptr<NetStateObserver>(new NetStateObserver());
71 }
72 
~SelfCureStateMachine()73 SelfCureStateMachine::~SelfCureStateMachine()
74 {
75     WIFI_LOGI("~SelfCureStateMachine");
76     StopHandlerThread();
77     ParsePointer(pDefaultState);
78     ParsePointer(pConnectedMonitorState);
79     ParsePointer(pDisconnectedMonitorState);
80     ParsePointer(pConnectionSelfCureState);
81     ParsePointer(pInternetSelfCureState);
82     ParsePointer(pWifi6SelfCureState);
83     ParsePointer(pNoInternetState);
84 }
85 
BuildStateTree()86 void SelfCureStateMachine::BuildStateTree()
87 {
88     StatePlus(pDefaultState, nullptr);
89     StatePlus(pConnectedMonitorState, pDefaultState);
90     StatePlus(pDisconnectedMonitorState, pDefaultState);
91     StatePlus(pConnectionSelfCureState, pDefaultState);
92     StatePlus(pInternetSelfCureState, pDefaultState);
93     StatePlus(pWifi6SelfCureState, pDefaultState);
94     StatePlus(pNoInternetState, pDefaultState);
95 }
96 
InitSelfCureStates()97 ErrCode SelfCureStateMachine::InitSelfCureStates()
98 {
99     WIFI_LOGI("Enter InitSelfCureStates\n");
100     int tmpErrNumber;
101     pDefaultState = new (std::nothrow)DefaultState(this);
102     tmpErrNumber = JudgmentEmpty(pDefaultState);
103     pConnectedMonitorState = new (std::nothrow)ConnectedMonitorState(this);
104     tmpErrNumber += JudgmentEmpty(pConnectedMonitorState);
105     pDisconnectedMonitorState = new (std::nothrow)DisconnectedMonitorState(this);
106     tmpErrNumber += JudgmentEmpty(pDisconnectedMonitorState);
107     pConnectionSelfCureState = new (std::nothrow)ConnectionSelfCureState(this);
108     tmpErrNumber += JudgmentEmpty(pConnectionSelfCureState);
109     pInternetSelfCureState = new (std::nothrow)InternetSelfCureState(this);
110     tmpErrNumber += JudgmentEmpty(pInternetSelfCureState);
111     pWifi6SelfCureState = new (std::nothrow)Wifi6SelfCureState(this);
112     tmpErrNumber += JudgmentEmpty(pWifi6SelfCureState);
113     pNoInternetState = new (std::nothrow)NoInternetState(this);
114     tmpErrNumber += JudgmentEmpty(pNoInternetState);
115     if (tmpErrNumber != 0) {
116         WIFI_LOGE("InitSelfCureStates some one state is null\n");
117         return WIFI_OPT_FAILED;
118     }
119     return WIFI_OPT_SUCCESS;
120 }
121 
Initialize()122 ErrCode SelfCureStateMachine::Initialize()
123 {
124     if (!InitialStateMachine("SelfCureStateMachine")) {
125         WIFI_LOGE("Initial StateMachine failed.\n");
126         return WIFI_OPT_FAILED;
127     }
128     if (InitSelfCureStates() == WIFI_OPT_FAILED) {
129         return WIFI_OPT_FAILED;
130     }
131     BuildStateTree();
132     SetFirstState(pDisconnectedMonitorState);
133     StartStateMachine();
134     InitDnsServer();
135     return WIFI_OPT_SUCCESS;
136 }
137 
138 /* --------------------------- state machine default state ------------------------------ */
DefaultState(SelfCureStateMachine * selfCureStateMachine)139 SelfCureStateMachine::DefaultState::DefaultState(SelfCureStateMachine *selfCureStateMachine)
140     : State("DefaultState"),
141       pSelfCureStateMachine(selfCureStateMachine)
142 {
143     WIFI_LOGD("DefaultState construct success.");
144 }
145 
~DefaultState()146 SelfCureStateMachine::DefaultState::~DefaultState() {}
147 
GoInState()148 void SelfCureStateMachine::DefaultState::GoInState()
149 {
150     pSelfCureStateMachine->selfCureOnGoing = false;
151     WIFI_LOGI("DefaultState GoInState function.");
152 }
153 
GoOutState()154 void SelfCureStateMachine::DefaultState::GoOutState()
155 {
156     WIFI_LOGI("DefaultState GoOutState function.");
157     return;
158 }
159 
ExecuteStateMsg(InternalMessagePtr msg)160 bool SelfCureStateMachine::DefaultState::ExecuteStateMsg(InternalMessagePtr msg)
161 {
162     if (msg == nullptr) {
163         return false;
164     }
165     WIFI_LOGD("DefaultState-msgCode=%{public}d is received.\n", msg->GetMessageName());
166     bool ret = NOT_EXECUTED;
167     switch (msg->GetMessageName()) {
168         case WIFI_CURE_DHCP_OFFER_PKT_RCV: {
169             IpInfo info;
170             msg->GetMessageObj(info);
171             HandleDhcpOfferPacketRcv(info);
172             ret = EXECUTED;
173             break;
174         }
175         case WIFI_CURE_CMD_P2P_ENHANCE_STATE_CHANGED: {
176             int state = msg->GetParam1();
177             HandleP2pEnhanceStateChange(state);
178             ret = EXECUTED;
179             break;
180         }
181         default:
182             WIFI_LOGD("DefaultState-msgCode=%{public}d not handled.\n", msg->GetMessageName());
183             break;
184     }
185     return ret;
186 }
187 
HandleDhcpOfferPacketRcv(const IpInfo & info)188 void SelfCureStateMachine::DefaultState::HandleDhcpOfferPacketRcv(const IpInfo &info)
189 {
190     IEnhanceService *pEnhanceService = WifiServiceManager::GetInstance().GetEnhanceServiceInst();
191     if (pEnhanceService == nullptr) {
192         WIFI_LOGE("HandleDhcpOfferPacketRcv get pEnhanceService service failed!");
193         return;
194     }
195     uint32_t retSize = 0;
196     pEnhanceService->DealDhcpOfferResult(OperationCmd::DHCP_OFFER_ADD, info, retSize);
197     WIFI_LOGI("dhcpOfferPackets size: %{public}u", retSize);
198 }
199 
HandleP2pEnhanceStateChange(int state)200 void SelfCureStateMachine::DefaultState::HandleP2pEnhanceStateChange(int state)
201 {
202     pSelfCureStateMachine->p2pEnhanceConnected_ = (state == 1) ? true : false;
203     if ((!pSelfCureStateMachine->p2pEnhanceConnected_) &&
204        (pSelfCureStateMachine->GetCurStateName() == pSelfCureStateMachine->pInternetSelfCureState->GetStateName())) {
205         pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_P2P_DISCONNECTED_EVENT);
206     }
207 }
208 /* --------------------------- state machine connected monitor state ------------------------------ */
ConnectedMonitorState(SelfCureStateMachine * selfCureStateMachine)209 SelfCureStateMachine::ConnectedMonitorState::ConnectedMonitorState(SelfCureStateMachine *selfCureStateMachine)
210     : State("ConnectedMonitorState"),
211       pSelfCureStateMachine(selfCureStateMachine)
212 {
213     InitSelfCureCmsHandleMap();
214     WIFI_LOGD("ConnectedMonitorState construct success.");
215 }
216 
~ConnectedMonitorState()217 SelfCureStateMachine::ConnectedMonitorState::~ConnectedMonitorState() {}
218 
GoInState()219 void SelfCureStateMachine::ConnectedMonitorState::GoInState()
220 {
221     WIFI_LOGI("ConnectedMonitorState GoInState function.");
222     if (!pSelfCureStateMachine->IsSuppOnCompletedState()) {
223         WIFI_LOGI("%{public}s: Wifi connection not completed", __FUNCTION__);
224         pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_NOTIFY_NETWORK_CONNECTED_RCVD,
225                                                     SELF_CURE_MONITOR_DELAYED_MS);
226     }
227     pSelfCureStateMachine->StopTimer(WIFI_CURE_NOTIFY_NETWORK_CONNECTED_RCVD);
228     IpQosMonitor::GetInstance().StartMonitor();
229     WifiLinkedInfo linkedInfo;
230     WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo);
231     lastConnectedBssid = linkedInfo.bssid;
232     pSelfCureStateMachine->arpDetectionFailedCnt = 0;
233     hasInternetRecently = false;
234     portalUnthenEver = false;
235     pSelfCureStateMachine->internetUnknown = false;
236     userSetStaticIpConfig = false;
237     ipv4DnsEnabled = true;
238     wifiSwitchAllowed = false;
239     mobileHotspot = linkedInfo.isDataRestricted == 1 ? true : false;
240     pSelfCureStateMachine->connectNetworkRetryCnt = 0;
241     WifiConfigCenter::GetInstance().SetLastNetworkId(linkedInfo.networkId);
242     WifiConfigCenter::GetInstance().SetWifiSelfcureReset(false);
243     pSelfCureStateMachine->SetIsReassocWithFactoryMacAddress(0);
244     lastSignalLevel = WifiSettings::GetInstance().GetSignalLevel(linkedInfo.rssi, linkedInfo.band,
245         pSelfCureStateMachine->m_instId);
246     if (pSelfCureStateMachine->useWithRandMacAddress != 0 && pSelfCureStateMachine->selfCureOnGoing == true) {
247         pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_RAND_MAC_SELFCURE_COMPLETE, SELF_CURE_DELAYED_MS);
248         pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pInternetSelfCureState);
249         return;
250     }
251     if (!SetupSelfCureMonitor()) {
252         WIFI_LOGI("ConnectedMonitorState, config is null when connected broadcast received, delay to setup again.");
253         pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_RESETUP_SELF_CURE_MONITOR,
254                                                     SELF_CURE_MONITOR_DELAYED_MS);
255     }
256     pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_PERIODIC_ARP_DETECTED, FAST_ARP_DETECTED_MS);
257     pSelfCureStateMachine->MessageExecutedLater(CMD_INTERNET_STATUS_DETECT_INTERVAL,
258         INTERNET_STATUS_DETECT_INTERVAL_MS);
259     return;
260 }
261 
GoOutState()262 void SelfCureStateMachine::ConnectedMonitorState::GoOutState()
263 {
264     WIFI_LOGI("ConnectedMonitorState GoOutState function.");
265     return;
266 }
267 
ExecuteStateMsg(InternalMessagePtr msg)268 bool SelfCureStateMachine::ConnectedMonitorState::ExecuteStateMsg(InternalMessagePtr msg)
269 {
270     if (msg == nullptr) {
271         return false;
272     }
273     WIFI_LOGD("ConnectedMonitorState-msgCode=%{public}d is received.\n", msg->GetMessageName());
274     auto iter = selfCureCmsHandleFuncMap.find(msg->GetMessageName());
275     if (iter != selfCureCmsHandleFuncMap.end()) {
276         (this->*(iter->second))(msg);
277         return EXECUTED;
278     }
279     return NOT_EXECUTED;
280 }
281 
InitSelfCureCmsHandleMap()282 int SelfCureStateMachine::ConnectedMonitorState::InitSelfCureCmsHandleMap()
283 {
284     selfCureCmsHandleFuncMap[WIFI_CURE_CMD_RESETUP_SELF_CURE_MONITOR] =
285     &SelfCureStateMachine::ConnectedMonitorState::HandleResetupSelfCure;
286     selfCureCmsHandleFuncMap[WIFI_CURE_CMD_PERIODIC_ARP_DETECTED] =
287     &SelfCureStateMachine::ConnectedMonitorState::HandlePeriodicArpDetection;
288     selfCureCmsHandleFuncMap[WIFI_CURE_CMD_ARP_FAILED_DETECTED] =
289     &SelfCureStateMachine::ConnectedMonitorState::HandleArpDetectionFailed;
290     selfCureCmsHandleFuncMap[WIFI_CURE_CMD_INVALID_IP_CONFIRM] =
291     &SelfCureStateMachine::ConnectedMonitorState::HandleInvalidIp;
292     selfCureCmsHandleFuncMap[WIFI_CURE_NOTIFY_NETWORK_CONNECTED_RCVD] =
293     &SelfCureStateMachine::ConnectedMonitorState::HandleNetworkConnect;
294     selfCureCmsHandleFuncMap[WIFI_CURE_NOTIFY_NETWORK_DISCONNECTED_RCVD] =
295     &SelfCureStateMachine::ConnectedMonitorState::HandleNetworkDisconnect;
296     selfCureCmsHandleFuncMap[WIFI_CURE_NOTIFY_RSSI_LEVEL_CHANGED_EVENT] =
297     &SelfCureStateMachine::ConnectedMonitorState::HandleRssiLevelChange;
298     selfCureCmsHandleFuncMap[WIFI_CURE_CMD_INTERNET_FAILURE_DETECTED] =
299     &SelfCureStateMachine::ConnectedMonitorState::HandleInternetFailedDetected;
300     selfCureCmsHandleFuncMap[CMD_INTERNET_STATUS_DETECT_INTERVAL] =
301     &SelfCureStateMachine::ConnectedMonitorState::HandleTcpQualityQuery;
302     selfCureCmsHandleFuncMap[WIFI_CURE_CMD_GATEWAY_CHANGED_DETECT] =
303     &SelfCureStateMachine::ConnectedMonitorState::HandleGatewayChanged;
304     return WIFI_OPT_SUCCESS;
305 }
306 
TransitionToSelfCureState(int reason)307 void SelfCureStateMachine::ConnectedMonitorState::TransitionToSelfCureState(int reason)
308 {
309     if (mobileHotspot && reason != WIFI_CURE_INTERNET_FAILED_TYPE_ROAMING) {
310         WIFI_LOGI("transitionToSelfCureState, don't support SCE, do nothing or mobileHotspot = %{public}d.",
311                   mobileHotspot);
312         pSelfCureStateMachine->selfCureOnGoing = false;
313         return;
314     }
315     WIFI_LOGI("transitionToSelfCureState, reason is : %{public}d.", reason);
316     IpInfo wifiIpInfo;
317     WifiConfigCenter::GetInstance().GetIpInfo(wifiIpInfo, pSelfCureStateMachine->m_instId);
318     IpV6Info wifiIpv6Info;
319     WifiConfigCenter::GetInstance().GetIpv6Info(wifiIpv6Info, pSelfCureStateMachine->m_instId);
320     ipv4DnsEnabled = wifiIpInfo.primaryDns != 0 || wifiIpInfo.secondDns != 0;
321     gatewayInvalid = wifiIpInfo.gateway == 0 && wifiIpv6Info.gateway == "";
322     if (!ipv4DnsEnabled || gatewayInvalid) {
323         WIFI_LOGI("transitionToSelfCureState, don't support SCE, do nothing or ipv4DnsEnabled = %{public}d.",
324                   ipv4DnsEnabled);
325         pSelfCureStateMachine->selfCureOnGoing = false;
326         return;
327     }
328     pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_INTERNET_FAILED_SELF_CURE, reason, SELF_CURE_DELAYED_MS);
329     pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pInternetSelfCureState);
330 }
331 
HandleResetupSelfCure(InternalMessagePtr msg)332 void SelfCureStateMachine::ConnectedMonitorState::HandleResetupSelfCure(InternalMessagePtr msg)
333 {
334     WIFI_LOGD("enter HandleResetupSelfCure.");
335     if (msg == nullptr) {
336         WIFI_LOGE("msg is nullptr.");
337         return;
338     }
339     SetupSelfCureMonitor();
340     return;
341 }
342 
HandlePeriodicArpDetection(InternalMessagePtr msg)343 void SelfCureStateMachine::ConnectedMonitorState::HandlePeriodicArpDetection(InternalMessagePtr msg)
344 {
345     WIFI_LOGD("enter HandlePeriodicArpDetection.");
346     if (msg == nullptr) {
347         WIFI_LOGE("msg is nullptr.");
348         return;
349     }
350     pSelfCureStateMachine->PeriodicArpDetection();
351     return;
352 }
353 
HandleNetworkConnect(InternalMessagePtr msg)354 void SelfCureStateMachine::ConnectedMonitorState::HandleNetworkConnect(InternalMessagePtr msg)
355 {
356     WIFI_LOGD("enter HandleNetworkConnect.");
357     if (msg == nullptr) {
358         WIFI_LOGE("msg is nullptr.");
359         return;
360     }
361     GoInState();
362     return;
363 }
364 
HandleNetworkDisconnect(InternalMessagePtr msg)365 void SelfCureStateMachine::ConnectedMonitorState::HandleNetworkDisconnect(InternalMessagePtr msg)
366 {
367     WIFI_LOGD("enter HandleNetworkDisconnect.");
368     if (msg == nullptr) {
369         WIFI_LOGE("msg is nullptr.");
370         return;
371     }
372     pSelfCureStateMachine->StopTimer(WIFI_CURE_CMD_GATEWAY_CHANGED_DETECT);
373     pSelfCureStateMachine->StopTimer(WIFI_CURE_CMD_RESETUP_SELF_CURE_MONITOR);
374     pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pDisconnectedMonitorState);
375     return;
376 }
377 
HandleRssiLevelChange(InternalMessagePtr msg)378 void SelfCureStateMachine::ConnectedMonitorState::HandleRssiLevelChange(InternalMessagePtr msg)
379 {
380     WIFI_LOGD("enter HandleRssiLevelChange.");
381     if (msg == nullptr) {
382         WIFI_LOGE("msg is nullptr.");
383         return;
384     }
385     lastSignalLevel = pSelfCureStateMachine->GetCurSignalLevel();
386     return;
387 }
388 
HandleArpDetectionFailed(InternalMessagePtr msg)389 void SelfCureStateMachine::ConnectedMonitorState::HandleArpDetectionFailed(InternalMessagePtr msg)
390 {
391     WIFI_LOGD("enter HandleArpDetectionFailed.");
392     if (pSelfCureStateMachine->ShouldTransToWifi6SelfCure(msg, lastConnectedBssid)) {
393         return;
394     }
395     if (pSelfCureStateMachine->IsHttpReachable()) {
396         WIFI_LOGI("Http Reachable.");
397         pSelfCureStateMachine->selfCureOnGoing = false;
398         return;
399     }
400     pSelfCureStateMachine->selfCureOnGoing = true;
401     pSelfCureStateMachine->selfCureReason = WIFI_CURE_INTERNET_FAILED_TYPE_TCP;
402     TransitionToSelfCureState(WIFI_CURE_INTERNET_FAILED_TYPE_TCP);
403 }
404 
SetupSelfCureMonitor()405 bool SelfCureStateMachine::ConnectedMonitorState::SetupSelfCureMonitor()
406 {
407     WifiDeviceConfig config;
408     if (pSelfCureStateMachine->GetCurrentWifiDeviceConfig(config) == WIFI_OPT_SUCCESS) {
409         configAuthType = pSelfCureStateMachine->GetAuthType();
410         AssignIpMethod ipAssignment;
411         pSelfCureStateMachine->GetIpAssignment(ipAssignment);
412         userSetStaticIpConfig = ipAssignment == AssignIpMethod::STATIC;
413         pSelfCureStateMachine->internetUnknown = NetworkStatusHistoryManager::IsEmptyNetworkStatusHistory(
414             pSelfCureStateMachine->GetNetworkStatusHistory());
415         hasInternetRecently = NetworkStatusHistoryManager::IsInternetAccessByHistory(
416             pSelfCureStateMachine->GetNetworkStatusHistory());
417         portalUnthenEver = NetworkStatusHistoryManager::IsPortalByHistory(
418             pSelfCureStateMachine->GetNetworkStatusHistory());
419         if (!mobileHotspot) {
420             if ((!pSelfCureStateMachine->staticIpCureSuccess) &&
421                 (hasInternetRecently || pSelfCureStateMachine->internetUnknown) &&
422                 (pSelfCureStateMachine->IsIpAddressInvalid())) {
423                 pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_INVALID_IP_CONFIRM,
424                     SELF_CURE_MONITOR_DELAYED_MS);
425                 return true;
426             }
427             if (IsGatewayChanged()) {
428                 WIFI_LOGI("current gateway is different with history gateway that has internet.");
429                 pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_GATEWAY_CHANGED_DETECT,
430                     GATEWAY_CHANGED_DETECT_DELAYED_MS);
431                 return true;
432             }
433         }
434         /** setup dns failed monitor when connected (the router's dns server maybe disabled). */
435         if ((!mobileHotspot) && (!pSelfCureStateMachine->staticIpCureSuccess) && hasInternetRecently) {
436             pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_DNS_FAILED_MONITOR, INTERNET_DETECT_INTERVAL_MS);
437         }
438         return true;
439     }
440     return false;
441 }
442 
IsGatewayChanged()443 bool SelfCureStateMachine::ConnectedMonitorState::IsGatewayChanged()
444 {
445     IEnhanceService *pEnhanceService = WifiServiceManager::GetInstance().GetEnhanceServiceInst();
446     if (pEnhanceService == nullptr) {
447         WIFI_LOGE("IsGatewayChanged get pEnhanceService service failed!");
448         return false;
449     }
450     bool isChanged = false;
451     pEnhanceService->IsGatewayChanged(isChanged);
452     WIFI_LOGI("IsGatewayChanged, isChanged: %{public}d", isChanged);
453     return isChanged;
454 }
455 
RequestReassocWithFactoryMac()456 void SelfCureStateMachine::ConnectedMonitorState::RequestReassocWithFactoryMac()
457 {
458     pSelfCureStateMachine->useWithRandMacAddress = FAC_MAC_REASSOC;
459     pSelfCureStateMachine->selfCureReason = WIFI_CURE_INTERNET_FAILED_RAND_MAC;
460     TransitionToSelfCureState(WIFI_CURE_INTERNET_FAILED_RAND_MAC);
461 }
462 
HandleInvalidIp(InternalMessagePtr msg)463 void SelfCureStateMachine::ConnectedMonitorState::HandleInvalidIp(InternalMessagePtr msg)
464 {
465     pSelfCureStateMachine->selfCureOnGoing = true;
466     if (pSelfCureStateMachine->IsHttpReachable()) {
467         pSelfCureStateMachine->selfCureOnGoing = false;
468         pSelfCureStateMachine->noTcpRxCounter = 0;
469     } else {
470         int selfCureType = pSelfCureStateMachine->IsMultiDhcpOffer() ?
471                             WIFI_CURE_INTERNET_FAILED_TYPE_GATEWAY :
472                             WIFI_CURE_INTERNET_FAILED_INVALID_IP;
473         pSelfCureStateMachine->selfCureReason = selfCureType;
474         TransitionToSelfCureState(selfCureType);
475     }
476 }
477 
HandleInternetFailedDetected(InternalMessagePtr msg)478 void SelfCureStateMachine::ConnectedMonitorState::HandleInternetFailedDetected(InternalMessagePtr msg)
479 {
480     if (pSelfCureStateMachine->IsCustNetworkSelfCure()) {
481         WIFI_LOGI("current network do not need selfcure");
482         return;
483     }
484 
485     if (!pSelfCureStateMachine->IsSuppOnCompletedState()) {
486         WIFI_LOGI("%{public}s: Wifi connection not completed", __FUNCTION__);
487         return;
488     }
489     if (mobileHotspot && !pSelfCureStateMachine->IsWifi6Network(lastConnectedBssid)) {
490         WIFI_LOGI("don't support selfcure, do nothing, mobileHotspot = %{public}d", mobileHotspot);
491         return;
492     }
493     if (pSelfCureStateMachine->ShouldTransToWifi6SelfCure(msg, lastConnectedBssid)) {
494         WIFI_LOGI("%{public}s: TransToWifi6SelfCure", __FUNCTION__);
495         return;
496     }
497 
498     if ((msg != nullptr) && (!pSelfCureStateMachine->internetUnknown)) {
499         pSelfCureStateMachine->internetUnknown = msg->GetParam1() == 1;
500     }
501     if (pSelfCureStateMachine->IsNeedWifiReassocUseDeviceMac()) {
502         RequestReassocWithFactoryMac();
503         return;
504     }
505     if (!pSelfCureStateMachine->staticIpCureSuccess && msg->GetParam2() == 1) {
506         if (hasInternetRecently || portalUnthenEver || pSelfCureStateMachine->internetUnknown) {
507             pSelfCureStateMachine->selfCureReason = WIFI_CURE_INTERNET_FAILED_TYPE_DNS;
508             TransitionToSelfCureState(WIFI_CURE_INTERNET_FAILED_TYPE_DNS);
509             return;
510         } else if (pSelfCureStateMachine->internetUnknown && pSelfCureStateMachine->IfMultiGateway()) {
511             pSelfCureStateMachine->selfCureReason = WIFI_CURE_INTERNET_FAILED_TYPE_TCP;
512             TransitionToSelfCureState(WIFI_CURE_INTERNET_FAILED_TYPE_TCP);
513             return;
514         } else {
515             WIFI_LOGI("Handle network disable, there is not a expectant condition!.");
516         }
517     }
518     pSelfCureStateMachine->selfCureOnGoing = true;
519     if (pSelfCureStateMachine->mIsHttpReachable) {
520         pSelfCureStateMachine->selfCureOnGoing = false;
521         pSelfCureStateMachine->noTcpRxCounter = 0;
522         return;
523     } else {
524         pSelfCureStateMachine->selfCureReason = WIFI_CURE_INTERNET_FAILED_TYPE_TCP;
525     }
526     WIFI_LOGI("HandleInternetFailedDetected, http unreachable, transition to SelfCureState,"
527         "selfCureReason: %{public}d", pSelfCureStateMachine->selfCureReason);
528     TransitionToSelfCureState(pSelfCureStateMachine->selfCureReason);
529 }
530 
HandleTcpQualityQuery(InternalMessagePtr msg)531 void SelfCureStateMachine::ConnectedMonitorState::HandleTcpQualityQuery(InternalMessagePtr msg)
532 {
533     if (msg == nullptr) {
534         WIFI_LOGE("msg is nullptr.");
535         return;
536     }
537     pSelfCureStateMachine->StopTimer(CMD_INTERNET_STATUS_DETECT_INTERVAL);
538     if (WifiConfigCenter::GetInstance().GetScreenState() != MODE_STATE_CLOSE) {
539         IpQosMonitor::GetInstance().QueryPackets();
540     }
541     pSelfCureStateMachine->MessageExecutedLater(CMD_INTERNET_STATUS_DETECT_INTERVAL,
542         INTERNET_STATUS_DETECT_INTERVAL_MS);
543 }
544 
HandleGatewayChanged(InternalMessagePtr msg)545 void SelfCureStateMachine::ConnectedMonitorState::HandleGatewayChanged(InternalMessagePtr msg)
546 {
547     WIFI_LOGI("enter HandleGatewayChanged");
548     if (msg == nullptr) {
549         WIFI_LOGE("msg is nullptr.");
550         return;
551     }
552     if (pSelfCureStateMachine->IsMultiDhcpOffer() ||
553         (hasInternetRecently && pSelfCureStateMachine->IsEncryptedAuthType(configAuthType))) {
554         if (pSelfCureStateMachine->IsHttpReachable()) {
555             pSelfCureStateMachine->selfCureOnGoing = false;
556             return;
557         }
558         TransitionToSelfCureState(WIFI_CURE_INTERNET_FAILED_TYPE_GATEWAY);
559     }
560 }
561 
562 /* --------------------------- state machine disconnect monitor state ------------------------------ */
DisconnectedMonitorState(SelfCureStateMachine * selfCureStateMachine)563 SelfCureStateMachine::DisconnectedMonitorState::DisconnectedMonitorState(SelfCureStateMachine *selfCureStateMachine)
564     : State("DisconnectedMonitorState"),
565       pSelfCureStateMachine(selfCureStateMachine)
566 {
567     WIFI_LOGD("DisconnectedMonitorState construct success.");
568 }
569 
~DisconnectedMonitorState()570 SelfCureStateMachine::DisconnectedMonitorState::~DisconnectedMonitorState() {}
571 
GoInState()572 void SelfCureStateMachine::DisconnectedMonitorState::GoInState()
573 {
574     WIFI_LOGI("DisconnectedMonitorState GoInState function.");
575     setStaticIpConfig = false;
576     pSelfCureStateMachine->staticIpCureSuccess = false;
577     pSelfCureStateMachine->isWifi6ArpSuccess = false;
578     pSelfCureStateMachine->hasTestWifi6Reassoc = false;
579     pSelfCureStateMachine->noAutoConnCounter = 0;
580     pSelfCureStateMachine->noAutoConnReason = -1;
581     pSelfCureStateMachine->connectedTime = 0;
582     pSelfCureStateMachine->ClearDhcpOffer();
583     return;
584 }
585 
GoOutState()586 void SelfCureStateMachine::DisconnectedMonitorState::GoOutState()
587 {
588     WIFI_LOGI("DisconnectedMonitorState GoOutState function.");
589     return;
590 }
591 
ExecuteStateMsg(InternalMessagePtr msg)592 bool SelfCureStateMachine::DisconnectedMonitorState::ExecuteStateMsg(InternalMessagePtr msg)
593 {
594     if (msg == nullptr) {
595         return false;
596     }
597     WIFI_LOGD("DisconnectedMonitorState-msgCode=%{public}d is received.\n", msg->GetMessageName());
598     bool ret = NOT_EXECUTED;
599     switch (msg->GetMessageName()) {
600         case WIFI_CURE_NOTIFY_NETWORK_CONNECTED_RCVD:
601             ret = EXECUTED;
602             pSelfCureStateMachine->HandleNetworkConnected();
603             pSelfCureStateMachine->CheckConflictIpForSoftAp();
604             break;
605         case WIFI_CURE_OPEN_WIFI_SUCCEED_RESET:
606             ret = EXECUTED;
607             HandleResetConnectNetwork(msg);
608             break;
609         case WIFI_CURE_CMD_CONN_FAILED_TIMEOUT:
610             ret = EXECUTED;
611             HandleConnectFailed(msg);
612             break;
613         case WIFI_CURE_CMD_WIFI7_DISCONNECT_COUNT:
614             ret = EXECUTED;
615             HandleNetworkConnectFailCount(msg);
616             break;
617         case WIFI_CURE_CMD_WIFI7_MLD_BACKOFF:
618             ret = EXECUTED;
619             HandleWifi7MldBackoff(msg);
620             break;
621         case WIFI_CURE_CMD_WIFI7_NON_MLD_BACKOFF:
622             ret = EXECUTED;
623             HandleWifi7WithoutMldBackoff(msg);
624             break;
625         case WIFI_CURE_CMD_WIFI7_BACKOFF_RECOVER:
626             ret = EXECUTED;
627             HandleWifi7BlacklistRecover(msg);
628             break;
629         default:
630             WIFI_LOGD("DisconnectedMonitorState-msgCode=%{public}d not handled.\n", msg->GetMessageName());
631             break;
632     }
633     return ret;
634 }
635 
HandleWifi7BlacklistRecover(InternalMessagePtr msg)636 void SelfCureStateMachine::DisconnectedMonitorState::HandleWifi7BlacklistRecover(InternalMessagePtr msg)
637 {
638     if (msg == nullptr) {
639         WIFI_LOGE("%{public}s: msg is nullptr.", __FUNCTION__);
640         return;
641     }
642     WifiLinkedInfo info;
643     msg->GetMessageObj(info);
644     if (info.bssid.empty()) {
645         WIFI_LOGE("%{public}s: lastconnect bssid is empty.", __FUNCTION__);
646         return;
647     }
648     WIFI_LOGI("remove %{public}s from wifi7 blalist.", MacAnonymize(info.bssid).c_str());
649     WifiConfigCenter::GetInstance().RemoveWifiCategoryBlackListCache(EVENT_BE_BLA_LIST, info.bssid);
650     pSelfCureStateMachine->SendBlaListToDriver(EVENT_BE_BLA_LIST);
651 }
652 
HandleWifi7WithoutMldBackoff(InternalMessagePtr msg)653 void SelfCureStateMachine::DisconnectedMonitorState::HandleWifi7WithoutMldBackoff(InternalMessagePtr msg)
654 {
655     if (msg == nullptr) {
656         WIFI_LOGE("%{public}s: msg is nullptr.", __FUNCTION__);
657         return;
658     }
659     WifiLinkedInfo info;
660     msg->GetMessageObj(info);
661     if (info.bssid.empty()) {
662         WIFI_LOGE("%{public}s: lastconnect bssid is empty.", __FUNCTION__);
663         return;
664     }
665     WifiCategoryBlackListInfo wifi7BlackListInfo(ACTION_TYPE_WIFI7, pSelfCureStateMachine->GetNowMilliSeconds());
666     WifiConfigCenter::GetInstance().InsertWifiCategoryBlackListCache(EVENT_BE_BLA_LIST, info.bssid, wifi7BlackListInfo);
667     WIFI_LOGI("add %{public}s to wifi7 blalist.", MacAnonymize(info.bssid).c_str());
668     pSelfCureStateMachine->SendBlaListToDriver(EVENT_BE_BLA_LIST);
669 
670     WifiCategoryConnectFailInfo wifi7ConnectFailInfo(ACTION_TYPE_RECOVER_FAIL,
671         0, pSelfCureStateMachine->GetNowMilliSeconds());
672     WifiConfigCenter::GetInstance().UpdateWifiConnectFailListCache(EVENT_BE_BLA_LIST, info.bssid, wifi7ConnectFailInfo);
673 }
674 
HandleWifi7MldBackoff(InternalMessagePtr msg)675 void SelfCureStateMachine::DisconnectedMonitorState::HandleWifi7MldBackoff(InternalMessagePtr msg)
676 {
677     if (msg == nullptr) {
678         WIFI_LOGE("%{public}s: msg is nullptr.", __FUNCTION__);
679         return;
680     }
681     WifiLinkedInfo info;
682     msg->GetMessageObj(info);
683     if (info.bssid.empty()) {
684         WIFI_LOGE("%{public}s: lastconnect bssid is empty.", __FUNCTION__);
685         return;
686     }
687     WifiCategoryBlackListInfo wifi7BlackListInfo(ACTION_TYPE_MLD, pSelfCureStateMachine->GetNowMilliSeconds());
688     WifiConfigCenter::GetInstance().InsertWifiCategoryBlackListCache(EVENT_BE_BLA_LIST, info.bssid, wifi7BlackListInfo);
689     WIFI_LOGI("add %{public}s to wifi7 blalist.", MacAnonymize(info.bssid).c_str());
690     pSelfCureStateMachine->SendBlaListToDriver(EVENT_BE_BLA_LIST);
691 
692     WifiCategoryConnectFailInfo wifi7ConnectFailInfo(ACTION_TYPE_WIFI7, 0, pSelfCureStateMachine->GetNowMilliSeconds());
693     WifiConfigCenter::GetInstance().UpdateWifiConnectFailListCache(EVENT_BE_BLA_LIST, info.bssid, wifi7ConnectFailInfo);
694 }
695 
HandleNetworkConnectFailCount(InternalMessagePtr msg)696 void SelfCureStateMachine::DisconnectedMonitorState::HandleNetworkConnectFailCount(InternalMessagePtr msg)
697 {
698     if (msg == nullptr) {
699         WIFI_LOGE("%{public}s: msg is nullptr.", __FUNCTION__);
700         return;
701     }
702     WifiLinkedInfo info;
703     msg->GetMessageObj(info);
704     if (info.bssid.empty()) {
705         WIFI_LOGE("%{public}s: lastconnect bssid is empty.", __FUNCTION__);
706         return;
707     }
708     pSelfCureStateMachine->AgeOutWifiConnectFailList();
709     int actionType = ACTION_TYPE_MLD;
710     std::map<std::string, WifiCategoryConnectFailInfo> connectFailCache;
711     WifiConfigCenter::GetInstance().GetWifiConnectFailListCache(connectFailCache);
712     WIFI_LOGI("add %{public}s to wifi7 connect fail list.", MacAnonymize(info.bssid).c_str());
713     if (connectFailCache.find(info.bssid) != connectFailCache.end()) {
714         actionType = connectFailCache[info.bssid].actionType;
715     }
716     WifiCategoryConnectFailInfo wifi7ConnectFailInfo(actionType, 1, pSelfCureStateMachine->GetNowMilliSeconds());
717     WifiConfigCenter::GetInstance().UpdateWifiConnectFailListCache(EVENT_BE_BLA_LIST, info.bssid, wifi7ConnectFailInfo);
718     pSelfCureStateMachine->ShouldTransToWifi7SelfCure(info);
719 }
720 
HandleConnectFailed(InternalMessagePtr msg)721 void SelfCureStateMachine::DisconnectedMonitorState::HandleConnectFailed(InternalMessagePtr msg)
722 {
723     WIFI_LOGI("enter HandleConnectFailed");
724     if (msg == nullptr) {
725         WIFI_LOGE("%{public}s: msg is nullptr.", __FUNCTION__);
726         return;
727     }
728     if (pSelfCureStateMachine->useWithRandMacAddress != 0 && pSelfCureStateMachine->selfCureOnGoing) {
729         pSelfCureStateMachine->useWithRandMacAddress = 0;
730         pSelfCureStateMachine->selfCureOnGoing = false;
731         WifiDeviceConfig config;
732         int networkId = WifiConfigCenter::GetInstance().GetLastNetworkId();
733         if (WifiSettings::GetInstance().GetDeviceConfig(networkId, config) != 0) {
734             WIFI_LOGE("%{public}s: GetDeviceConfig failed!.", __FUNCTION__);
735             return;
736         }
737         // Connect failed, updateSelfcureConnectHistoryInfo
738         WifiSelfCureHistoryInfo selfCureHistoryInfo;
739         std::string internetSelfCureHistory = config.internetSelfCureHistory;
740         pSelfCureStateMachine->String2InternetSelfCureHistoryInfo(internetSelfCureHistory, selfCureHistoryInfo);
741         int requestCureLevel = WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC;
742         pSelfCureStateMachine->UpdateSelfCureConnectHistoryInfo(selfCureHistoryInfo, requestCureLevel, false);
743         config.internetSelfCureHistory = selfCureHistoryInfo.GetSelfCureHistory();
744 
745         config.isReassocSelfCureWithFactoryMacAddress = 0;
746         config.wifiPrivacySetting = WifiPrivacyConfig::RANDOMMAC;
747         WifiSettings::GetInstance().AddDeviceConfig(config);
748         WifiSettings::GetInstance().SyncDeviceConfig();
749         // Connect failed, add broadcast: DISCONNECTED
750         WifiLinkedInfo linkedInfo;
751         WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo);
752         WifiEventCallbackMsg cbMsg;
753         cbMsg.msgCode = WIFI_CBK_MSG_CONNECTION_CHANGE;
754         cbMsg.msgData = ConnState::DISCONNECTED;
755         cbMsg.linkInfo = linkedInfo;
756         cbMsg.id = pSelfCureStateMachine->m_instId;
757         WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg);
758     }
759 }
760 
HandleResetConnectNetwork(InternalMessagePtr msg)761 void SelfCureStateMachine::DisconnectedMonitorState::HandleResetConnectNetwork(InternalMessagePtr msg)
762 {
763     if (msg == nullptr) {
764         WIFI_LOGE("msg is nullptr.");
765         return;
766     }
767     if (!WifiConfigCenter::GetInstance().GetWifiSelfcureReset() ||
768         pSelfCureStateMachine->connectNetworkRetryCnt > CONNECT_NETWORK_RETRY) {
769         WifiConfigCenter::GetInstance().SetWifiSelfcureReset(false);
770         return;
771     }
772     pSelfCureStateMachine->connectNetworkRetryCnt++;
773     WIFI_LOGI("reset selfcure, connect to last connected network.");
774     if (WifiConfigCenter::GetInstance().GetScreenState() == MODE_STATE_OPEN) {
775         pSelfCureStateMachine->StartTimer(WIFI_CURE_OPEN_WIFI_SUCCEED_RESET, CMD_WIFI_CONNECT_TIMEOUT_SCREEN);
776     } else {
777         pSelfCureStateMachine->StartTimer(WIFI_CURE_OPEN_WIFI_SUCCEED_RESET, CMD_WIFI_CONNECT_TIMEOUT);
778     }
779     pSelfCureStateMachine->UpdateSelfcureState(static_cast<int>(SelfCureType::SCE_TYPE_RESET), false);
780     IStaService *pStaService = WifiServiceManager::GetInstance().GetStaServiceInst(pSelfCureStateMachine->m_instId);
781     if (pStaService == nullptr) {
782         WIFI_LOGE("Get %{public}s service failed!", WIFI_SERVICE_STA);
783         return;
784     }
785     int networkId = WifiConfigCenter::GetInstance().GetLastNetworkId();
786     if (pStaService->ConnectToNetwork(networkId) != WIFI_OPT_SUCCESS) {
787         WIFI_LOGE("ConnectToNetwork failed.\n");
788     }
789 }
790 
791 /* --------------------------- state machine connection self cure state ------------------------------ */
ConnectionSelfCureState(SelfCureStateMachine * selfCureStateMachine)792 SelfCureStateMachine::ConnectionSelfCureState::ConnectionSelfCureState(SelfCureStateMachine *selfCureStateMachine)
793     : State("ConnectionSelfCureState"),
794       pSelfCureStateMachine(selfCureStateMachine)
795 {
796     WIFI_LOGD("ConnectionSelfCureState construct success.");
797 }
798 
~ConnectionSelfCureState()799 SelfCureStateMachine::ConnectionSelfCureState::~ConnectionSelfCureState() {}
800 
GoInState()801 void SelfCureStateMachine::ConnectionSelfCureState::GoInState()
802 {
803     WIFI_LOGI("ConnectionSelfCureState GoInState function.");
804     return;
805 }
806 
GoOutState()807 void SelfCureStateMachine::ConnectionSelfCureState::GoOutState()
808 {
809     WIFI_LOGI("ConnectionSelfCureState GoOutState function.");
810     return;
811 }
812 
ExecuteStateMsg(InternalMessagePtr msg)813 bool SelfCureStateMachine::ConnectionSelfCureState::ExecuteStateMsg(InternalMessagePtr msg)
814 {
815     if (msg == nullptr) {
816         return false;
817     }
818     WIFI_LOGD("ConnectionSelfCureState-msgCode=%{public}d is received.\n", msg->GetMessageName());
819     bool ret = NOT_EXECUTED;
820     switch (msg->GetMessageName()) {
821         case 0: {
822             ret = EXECUTED;
823             pSelfCureStateMachine->GetAuthType();
824             break;
825         }
826         default:
827             WIFI_LOGD("ConnectionSelfCureState-msgCode=%{public}d not handled.\n", msg->GetMessageName());
828             break;
829     }
830     return ret;
831 }
832 
833 /* --------------------------- state machine internet self cure state ------------------------------ */
InternetSelfCureState(SelfCureStateMachine * selfCureStateMachine)834 SelfCureStateMachine::InternetSelfCureState::InternetSelfCureState(SelfCureStateMachine *selfCureStateMachine)
835     : State("InternetSelfCureState"),
836       pSelfCureStateMachine(selfCureStateMachine)
837 {
838     InitSelfCureIssHandleMap();
839     WIFI_LOGD("InternetSelfCureState construct success.");
840 }
841 
~InternetSelfCureState()842 SelfCureStateMachine::InternetSelfCureState::~InternetSelfCureState() {}
843 
GoInState()844 void SelfCureStateMachine::InternetSelfCureState::GoInState()
845 {
846     WIFI_LOGI("InternetSelfCureState GoInState function.");
847     currentRssi = CURRENT_RSSI_INIT;
848     selfCureFailedCounter = 0;
849     currentAbnormalType = -1;
850     lastSelfCureLevel = -1;
851     currentSelfCureLevel = WIFI_CURE_RESET_LEVEL_IDLE;
852     hasInternetRecently = false;
853     portalUnthenEver = false;
854     userSetStaticIpConfig = false;
855     currentGateway = pSelfCureStateMachine->GetCurrentGateway();
856     testedSelfCureLevel.clear();
857     finalSelfCureUsed = false;
858     delayedReassocSelfCure = false;
859     delayedRandMacReassocSelfCure = false;
860     delayedResetSelfCure = false;
861     setStaticIp4InvalidIp = false;
862     unConflictedIp = "";
863     renewDhcpCount = 0;
864     lastMultiGwSelfFailedType = -1;
865     usedMultiGwSelfcure = false;
866     WifiConfigCenter::GetInstance().SetWifiSelfcureReset(false);
867 
868     WifiLinkedInfo linkedInfo;
869     WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo);
870     currentRssi = linkedInfo.rssi;
871     currentBssid = linkedInfo.bssid;
872     pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_PERIODIC_ARP_DETECTED, DEFAULT_ARP_DETECTED_MS);
873     pSelfCureStateMachine->String2InternetSelfCureHistoryInfo(pSelfCureStateMachine->GetSelfCureHistoryInfo(),
874                                                               selfCureHistoryInfo);
875     hasInternetRecently = NetworkStatusHistoryManager::IsInternetAccessByHistory(
876         pSelfCureStateMachine->GetNetworkStatusHistory());
877     portalUnthenEver = NetworkStatusHistoryManager::IsPortalByHistory(
878         pSelfCureStateMachine->GetNetworkStatusHistory());
879     AssignIpMethod ipAssignment;
880     pSelfCureStateMachine->GetIpAssignment(ipAssignment);
881     userSetStaticIpConfig = ipAssignment == AssignIpMethod::STATIC;
882     lastHasInetTime = pSelfCureStateMachine->GetLastHasInternetTime();
883     configAuthType = pSelfCureStateMachine->GetAuthType();
884     WIFI_LOGI("hasInternetRecently: %{public}d, portalUnthenEver: %{public}d, selfCureHistoryInfo: %{public}s",
885         hasInternetRecently, portalUnthenEver, pSelfCureStateMachine->GetSelfCureHistoryInfo().c_str());
886     return;
887 }
888 
GoOutState()889 void SelfCureStateMachine::InternetSelfCureState::GoOutState()
890 {
891     WIFI_LOGI("InternetSelfCureState GoOutState function.");
892     return;
893 }
894 
ExecuteStateMsg(InternalMessagePtr msg)895 bool SelfCureStateMachine::InternetSelfCureState::ExecuteStateMsg(InternalMessagePtr msg)
896 {
897     if (msg == nullptr) {
898         return false;
899     }
900     WIFI_LOGD("InternetSelfCureState-msgCode = %{public}d is received.\n", msg->GetMessageName());
901     auto iter = selfCureIssHandleFuncMap.find(msg->GetMessageName());
902     if (iter != selfCureIssHandleFuncMap.end()) {
903         (this->*(iter->second))(msg);
904         return EXECUTED;
905     }
906     return NOT_EXECUTED;
907 }
908 
InitSelfCureIssHandleMap()909 int SelfCureStateMachine::InternetSelfCureState::InitSelfCureIssHandleMap()
910 {
911     selfCureIssHandleFuncMap[WIFI_CURE_CMD_INTERNET_FAILED_SELF_CURE] =
912     &SelfCureStateMachine::InternetSelfCureState::HandleInternetFailedSelfCure;
913     selfCureIssHandleFuncMap[WIFI_CURE_CMD_SELF_CURE_WIFI_LINK] =
914     &SelfCureStateMachine::InternetSelfCureState::HandleSelfCureWifiLink;
915     selfCureIssHandleFuncMap[WIFI_CURE_NOTIFY_NETWORK_DISCONNECTED_RCVD] =
916     &SelfCureStateMachine::InternetSelfCureState::HandleNetworkDisconnected;
917     selfCureIssHandleFuncMap[WIFI_CURE_CMD_INTERNET_RECOVERY_CONFIRM] =
918     &SelfCureStateMachine::InternetSelfCureState::HandleInternetRecovery;
919     selfCureIssHandleFuncMap[WIFI_CURE_NOTIFY_RSSI_LEVEL_CHANGED_EVENT] =
920     &SelfCureStateMachine::InternetSelfCureState::HandleRssiChangedEvent;
921     selfCureIssHandleFuncMap[WIFI_CURE_CMD_P2P_DISCONNECTED_EVENT] =
922     &SelfCureStateMachine::InternetSelfCureState::HandleP2pDisconnected;
923     selfCureIssHandleFuncMap[WIFI_CURE_CMD_PERIODIC_ARP_DETECTED] =
924     &SelfCureStateMachine::InternetSelfCureState::HandlePeriodicArpDetecte;
925     selfCureIssHandleFuncMap[WIFI_CURE_CMD_ARP_FAILED_DETECTED] =
926     &SelfCureStateMachine::InternetSelfCureState::HandleArpFailedDetected;
927     selfCureIssHandleFuncMap[WIFI_CURE_CMD_HTTP_REACHABLE_RCV] =
928     &SelfCureStateMachine::InternetSelfCureState::HandleHttpReachableRecv;
929     selfCureIssHandleFuncMap[WIFI_CURE_CMD_RAND_MAC_SELFCURE_COMPLETE] =
930     &SelfCureStateMachine::InternetSelfCureState::HandleRandMacSelfCureComplete;
931     selfCureIssHandleFuncMap[WIFI_CURE_CMD_MULTI_GATEWAY] =
932     &SelfCureStateMachine::InternetSelfCureState::SelfcureForMultiGateway;
933     return WIFI_OPT_SUCCESS;
934 }
935 
HandleRandMacSelfCureComplete(InternalMessagePtr msg)936 void SelfCureStateMachine::InternetSelfCureState::HandleRandMacSelfCureComplete(InternalMessagePtr msg)
937 {
938     WIFI_LOGI("enter HandleRandMacSelfCureComplete.");
939     if (msg == nullptr) {
940         WIFI_LOGE("msg is nullptr.");
941         return;
942     }
943     WIFI_LOGI("rand mac selfcure complete, check if network is enable.");
944     if (pSelfCureStateMachine->IsHttpReachable()) {
945         if (pSelfCureStateMachine->IsUseFactoryMac()) {
946             HandleHttpReachableAfterSelfCure(WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC);
947         } else {
948             pSelfCureStateMachine->selfCureOnGoing = false;
949             pSelfCureStateMachine->useWithRandMacAddress = 0;
950         }
951         pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pConnectedMonitorState);
952         return;
953     }
954     HandleSelfCureFailedForRandMacReassoc();
955 }
956 
HandleInternetFailedSelfCure(InternalMessagePtr msg)957 void SelfCureStateMachine::InternetSelfCureState::HandleInternetFailedSelfCure(InternalMessagePtr msg)
958 {
959     WIFI_LOGD("enter HandleInternetFailedSelfCure.");
960     if (msg == nullptr) {
961         WIFI_LOGE("msg is nullptr.");
962         return;
963     }
964     pSelfCureStateMachine->selfCureOnGoing = false;
965     if (pSelfCureStateMachine->IsSuppOnCompletedState()) {
966         SelectSelfCureByFailedReason(msg->GetParam1());
967     }
968     return;
969 }
970 
HandleSelfCureWifiLink(InternalMessagePtr msg)971 void SelfCureStateMachine::InternetSelfCureState::HandleSelfCureWifiLink(InternalMessagePtr msg)
972 {
973     WIFI_LOGD("enter HandleSelfCureWifiLink.");
974     if (msg == nullptr) {
975         WIFI_LOGE("msg is nullptr.");
976         return;
977     }
978     if (pSelfCureStateMachine->IsSuppOnCompletedState()) {
979         currentSelfCureLevel = msg->GetParam1();
980         SelfCureWifiLink(msg->GetParam1());
981     }
982     return;
983 }
984 
HandleNetworkDisconnected(InternalMessagePtr msg)985 void SelfCureStateMachine::InternetSelfCureState::HandleNetworkDisconnected(InternalMessagePtr msg)
986 {
987     WIFI_LOGD("enter HandleNetworkDisconnected.");
988     if (msg == nullptr) {
989         WIFI_LOGE("msg is nullptr.");
990         return;
991     }
992     pSelfCureStateMachine->StopTimer(WIFI_CURE_CMD_INTERNET_RECOVERY_CONFIRM);
993     pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pDisconnectedMonitorState);
994     return;
995 }
996 
HandleInternetRecovery(InternalMessagePtr msg)997 void SelfCureStateMachine::InternetSelfCureState::HandleInternetRecovery(InternalMessagePtr msg)
998 {
999     WIFI_LOGD("enter HandleInternetRecovery.");
1000     if (msg == nullptr) {
1001         WIFI_LOGE("msg is nullptr.");
1002         return;
1003     }
1004     if (pSelfCureStateMachine->selfCureOnGoing) {
1005         HandleInternetRecoveryConfirm();
1006     }
1007     return;
1008 }
1009 
HandleRssiChangedEvent(InternalMessagePtr msg)1010 void SelfCureStateMachine::InternetSelfCureState::HandleRssiChangedEvent(InternalMessagePtr msg)
1011 {
1012     WIFI_LOGD("enter HandleRssiChangedEvent.");
1013     if (msg == nullptr) {
1014         WIFI_LOGE("msg is nullptr.");
1015         return;
1016     }
1017     currentRssi = msg->GetParam1();
1018     HandleRssiChanged();
1019     return;
1020 }
1021 
HandleP2pDisconnected(InternalMessagePtr msg)1022 void SelfCureStateMachine::InternetSelfCureState::HandleP2pDisconnected(InternalMessagePtr msg)
1023 {
1024     WIFI_LOGD("enter HandleP2pDisconnected.");
1025     if (msg == nullptr) {
1026         WIFI_LOGE("msg is nullptr.");
1027         return;
1028     }
1029     HandleRssiChanged();
1030     return;
1031 }
1032 
HandlePeriodicArpDetecte(InternalMessagePtr msg)1033 void SelfCureStateMachine::InternetSelfCureState::HandlePeriodicArpDetecte(InternalMessagePtr msg)
1034 {
1035     WIFI_LOGD("enter HandlePeriodicArpDetecte.");
1036     if (msg == nullptr) {
1037         WIFI_LOGE("msg is nullptr.");
1038         return;
1039     }
1040     pSelfCureStateMachine->PeriodicArpDetection();
1041     return;
1042 }
1043 
HandleHttpReachableRecv(InternalMessagePtr msg)1044 void SelfCureStateMachine::InternetSelfCureState::HandleHttpReachableRecv(InternalMessagePtr msg)
1045 {
1046     WIFI_LOGD("enter HandleHttpReachableRecv.");
1047     if (msg == nullptr) {
1048         WIFI_LOGE("msg is nullptr.");
1049         return;
1050     }
1051     pSelfCureStateMachine->selfCureOnGoing = false;
1052     pSelfCureStateMachine->SetSelfCureHistoryInfo(INIT_SELFCURE_HISTORY);
1053     pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pConnectedMonitorState);
1054     return;
1055 }
1056 
HandleArpFailedDetected(InternalMessagePtr msg)1057 void SelfCureStateMachine::InternetSelfCureState::HandleArpFailedDetected(InternalMessagePtr msg)
1058 {
1059     WIFI_LOGD("enter HandleArpFailedDetected.");
1060     if (pSelfCureStateMachine->ShouldTransToWifi6SelfCure(msg, currentBssid)) {
1061         return;
1062     }
1063     if (pSelfCureStateMachine->selfCureOnGoing) {
1064         return;
1065     }
1066     pSelfCureStateMachine->selfCureOnGoing = true;
1067     if (pSelfCureStateMachine->IsHttpReachable()) {
1068         WIFI_LOGI("Http Reachable.");
1069         pSelfCureStateMachine->selfCureOnGoing = false;
1070     } else {
1071         pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK, WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC);
1072     }
1073 }
1074 
SelectSelfCureByFailedReason(int internetFailedType)1075 void SelfCureStateMachine::InternetSelfCureState::SelectSelfCureByFailedReason(int internetFailedType)
1076 {
1077     WIFI_LOGI("SelectSelfCureByFailedReason, internetFailedType = %{public}d, userSetStaticIpConfig = %{public}d",
1078               internetFailedType, userSetStaticIpConfig);
1079 
1080     if (IsNeedMultiGatewaySelfcure()) {
1081         WIFI_LOGI("start multi gateway selfcure");
1082         lastMultiGwSelfFailedType = internetFailedType;
1083         pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_MULTI_GATEWAY);
1084     }
1085 
1086     if (userSetStaticIpConfig && ((internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_DNS) ||
1087                                   (internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_GATEWAY) ||
1088                                   (internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_ROAMING))) {
1089         HandleInternetFailedAndUserSetStaticIp(internetFailedType);
1090         return;
1091     }
1092     int requestSelfCureLevel = SelectBestSelfCureSolution(internetFailedType);
1093     if (requestSelfCureLevel != WIFI_CURE_RESET_LEVEL_IDLE) {
1094         currentAbnormalType = internetFailedType;
1095         pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK, requestSelfCureLevel);
1096         return;
1097     }
1098     if (pSelfCureStateMachine->SelfCureAcceptable(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_HIGH_RESET)) {
1099         WIFI_LOGI("SelectSelfCureByFailedReason, use wifi reset to cure this failed type = %{public}d",
1100                   internetFailedType);
1101         currentAbnormalType = internetFailedType;
1102         if (internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_DNS) {
1103             lastSelfCureLevel = WIFI_CURE_RESET_LEVEL_LOW_1_DNS;
1104         } else if (internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_ROAMING) {
1105             lastSelfCureLevel = WIFI_CURE_RESET_LEVEL_LOW_2_RENEW_DHCP;
1106         } else if (internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_TCP) {
1107             lastSelfCureLevel = WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC;
1108         }
1109         pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK, WIFI_CURE_RESET_LEVEL_HIGH_RESET);
1110         return;
1111     }
1112     WIFI_LOGI("SelectSelfCureByFailedReason, no usable self cure for this failed type = %{public}d",
1113               internetFailedType);
1114     HandleHttpUnreachableFinally();
1115 }
1116 
SelectBestSelfCureSolution(int internetFailedType)1117 int SelfCureStateMachine::InternetSelfCureState::SelectBestSelfCureSolution(int internetFailedType)
1118 {
1119     int bestSelfCureLevel = WIFI_CURE_RESET_LEVEL_IDLE;
1120     bool multipleDhcpServer = pSelfCureStateMachine->IsMultiDhcpOffer();
1121     bool noInternetWhenConnected =
1122         (lastHasInetTime <= 0 || lastHasInetTime < pSelfCureStateMachine->connectedTime);
1123     WIFI_LOGD("SelectBestSelfCureSolution, multipleDhcpServer = %{public}d, noInternetWhenConnected = %{public}d",
1124               multipleDhcpServer, noInternetWhenConnected);
1125 
1126     if ((multipleDhcpServer) && (noInternetWhenConnected) && (GetNextTestDhcpResults().ipAddress != 0) &&
1127         (pSelfCureStateMachine->SelfCureAcceptable(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP)) &&
1128         ((internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_DNS) ||
1129         (internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_TCP))) {
1130         bestSelfCureLevel = WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP;
1131         configStaticIp4MultiDhcpServer = true;
1132     } else if ((internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_GATEWAY) &&
1133         (multipleDhcpServer) && (GetNextTestDhcpResults().ipAddress != 0) &&
1134         (pSelfCureStateMachine->SelfCureAcceptable(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP))) {
1135         bestSelfCureLevel = WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP;
1136         configStaticIp4MultiDhcpServer = true;
1137     } else if ((internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_GATEWAY) &&
1138         pSelfCureStateMachine->IsEncryptedAuthType(configAuthType) &&
1139         (pSelfCureStateMachine->SelfCureAcceptable(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP))) {
1140         bestSelfCureLevel = WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP;
1141     } else {
1142         bestSelfCureLevel = SelectBestSelfCureSolutionExt(internetFailedType);
1143     }
1144     WIFI_LOGI("SelectBestSelfCureSolution, internetFailedType = %{public}d, bestSelfCureLevel = %{public}d",
1145               internetFailedType, bestSelfCureLevel);
1146     return bestSelfCureLevel;
1147 }
1148 
SelectBestSelfCureSolutionExt(int internetFailedType)1149 int SelfCureStateMachine::InternetSelfCureState::SelectBestSelfCureSolutionExt(int internetFailedType)
1150 {
1151     int bestSelfCureLevel = WIFI_CURE_RESET_LEVEL_IDLE;
1152     if (internetFailedType == WIFI_CURE_INTERNET_FAILED_INVALID_IP) {
1153         bestSelfCureLevel = WIFI_CURE_RESET_LEVEL_RECONNECT_4_INVALID_IP;
1154     } else if (internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_ROAMING &&
1155                pSelfCureStateMachine->SelfCureAcceptable(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_LOW_2_RENEW_DHCP)) {
1156         bestSelfCureLevel = WIFI_CURE_RESET_LEVEL_LOW_2_RENEW_DHCP;
1157     } else if (internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_DNS &&
1158                pSelfCureStateMachine->SelfCureAcceptable(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_LOW_1_DNS)) {
1159         bestSelfCureLevel = WIFI_CURE_RESET_LEVEL_LOW_1_DNS;
1160     } else if (internetFailedType == WIFI_CURE_INTERNET_FAILED_RAND_MAC &&
1161                pSelfCureStateMachine->SelfCureAcceptable(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC)) {
1162         bestSelfCureLevel = WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC;
1163     } else if (internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_TCP &&
1164                pSelfCureStateMachine->SelfCureAcceptable(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC)) {
1165         bestSelfCureLevel = WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC;
1166     }
1167     return bestSelfCureLevel;
1168 }
1169 
SelfCureWifiLink(int requestCureLevel)1170 void SelfCureStateMachine::InternetSelfCureState::SelfCureWifiLink(int requestCureLevel)
1171 {
1172     WIFI_LOGI("SelfCureWifiLink, requestCureLevel = %{public}d, currentRssi = %{public}d",
1173               requestCureLevel, currentRssi);
1174     if (requestCureLevel == WIFI_CURE_RESET_LEVEL_LOW_1_DNS) {
1175         WIFI_LOGI("SelfCureForDns");
1176         SelfCureForDns();
1177     } else if (requestCureLevel == WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP) {
1178         SelfCureForStaticIp(requestCureLevel);
1179     } else if (requestCureLevel == WIFI_CURE_RESET_LEVEL_RECONNECT_4_INVALID_IP) {
1180         SelfCureForInvalidIp();
1181     } else if (requestCureLevel == WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC) {
1182         SelfCureForReassoc(requestCureLevel);
1183     } else if (requestCureLevel == WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC) {
1184         SelfCureForRandMacReassoc(requestCureLevel);
1185     } else if (requestCureLevel == WIFI_CURE_RESET_LEVEL_HIGH_RESET) {
1186         SelfCureForReset(requestCureLevel);
1187     }
1188 }
1189 
InitDnsServer()1190 void SelfCureStateMachine::InitDnsServer()
1191 {
1192     WIFI_LOGI("InitDnsServer");
1193     std::vector<std::string> strPublicIpAddr;
1194     char dnsIpAddr[PUBLIC_DNS_SERVERS_SIZE] = {0};
1195     int ret = GetParamValue(CONST_WIFI_DNSCURE_IPCFG, "", dnsIpAddr, PUBLIC_DNS_SERVERS_SIZE);
1196     if (ret <= 0) {
1197         WIFI_LOGE("get wifi const.wifi.dnscure_ipcfg code by cache fail, ret=%{public}d", ret);
1198         return;
1199     }
1200     std::string temp = "";
1201     int publicDnsSize = sizeof(dnsIpAddr);
1202     for (int i = 0; i < publicDnsSize; i++) {
1203         if (dnsIpAddr[i] == ';') {
1204             strPublicIpAddr.push_back(temp);
1205             temp = "";
1206             continue;
1207         } else if (i == publicDnsSize - 1) {
1208             temp = temp + dnsIpAddr[i];
1209             strPublicIpAddr.push_back(temp);
1210             continue;
1211         } else {
1212             temp = temp + dnsIpAddr[i];
1213         }
1214     }
1215     if (strPublicIpAddr.size() != PUBLIC_IP_ADDR_NUM) {
1216         WIFI_LOGE("Get number of public ipaddr failed");
1217         return;
1218     }
1219     for (uint32_t i = 0; i < overseaPublicDnses.size(); i++) {
1220         overseaPublicDnses[i] = strPublicIpAddr[i];
1221     }
1222     uint32_t spaceSize = chinaPublicDnses.size();
1223     strPublicIpAddr.erase(strPublicIpAddr.begin(), strPublicIpAddr.begin() + spaceSize);
1224     for (uint32_t i = 0; i < chinaPublicDnses.size(); i++) {
1225         chinaPublicDnses[i] = strPublicIpAddr[i];
1226     }
1227     WIFI_LOGI("InitDnsServer Success");
1228 }
1229 
GetPublicDnsServers(std::vector<std::string> & publicDnsServers)1230 void SelfCureStateMachine::InternetSelfCureState::GetPublicDnsServers(std::vector<std::string>& publicDnsServers)
1231 {
1232     std::string wifiCountryCode;
1233     WifiCountryCodeManager::GetInstance().GetWifiCountryCode(wifiCountryCode);
1234     if (wifiCountryCode.compare(COUNTRY_CHINA_CAPITAL) == 0 && !chinaPublicDnses[0].empty()) {
1235         publicDnsServers = chinaPublicDnses;
1236     } else {
1237         publicDnsServers = overseaPublicDnses;
1238     }
1239 }
1240 
GetReplacedDnsServers(std::vector<std::string> & curDnses,std::vector<std::string> & replaceDnses)1241 void SelfCureStateMachine::InternetSelfCureState::GetReplacedDnsServers(
1242     std::vector<std::string>& curDnses, std::vector<std::string>& replaceDnses)
1243 {
1244     if (curDnses.empty()) {
1245         return;
1246     }
1247     std::vector<std::string> publicServer;
1248     replaceDnses = curDnses;
1249     GetPublicDnsServers(publicServer);
1250     replaceDnses[1] = publicServer[0];
1251 }
1252 
UpdateDnsServers(std::vector<std::string> & dnsServers)1253 void SelfCureStateMachine::InternetSelfCureState::UpdateDnsServers(std::vector<std::string>& dnsServers)
1254 {
1255     WifiLinkedInfo linkedInfo;
1256     WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo, pSelfCureStateMachine->m_instId);
1257     WifiDeviceConfig config;
1258     WifiSettings::GetInstance().GetDeviceConfig(linkedInfo.networkId, config);
1259     IpInfo ipInfo;
1260     IpV6Info ipV6Info;
1261     WifiConfigCenter::GetInstance().GetIpInfo(ipInfo, 0);
1262     WifiConfigCenter::GetInstance().GetIpv6Info(ipV6Info, 0);
1263     ipInfo.primaryDns = IpTools::ConvertIpv4Address(dnsServers[0]);
1264     ipInfo.secondDns = IpTools::ConvertIpv4Address(dnsServers[1]);
1265     WifiNetAgent::GetInstance().OnStaMachineUpdateNetLinkInfo(ipInfo, ipV6Info, config.wifiProxyconfig, 0);
1266 }
1267 
SelfCureForDns()1268 void SelfCureStateMachine::InternetSelfCureState::SelfCureForDns()
1269 {
1270     WIFI_LOGI("begin to self cure for internet access: dns");
1271     pSelfCureStateMachine->selfCureOnGoing = true;
1272     testedSelfCureLevel.push_back(WIFI_CURE_RESET_LEVEL_LOW_1_DNS);
1273     if (pSelfCureStateMachine->internetUnknown) {
1274         IpInfo ipInfo;
1275         WifiConfigCenter::GetInstance().GetIpInfo(ipInfo, 0);
1276         std::string ipV4PrimaryDns = IpTools::ConvertIpv4Address(ipInfo.primaryDns);
1277         std::string ipV4SecondDns = IpTools::ConvertIpv4Address(ipInfo.secondDns);
1278         std::vector<std::string> servers = {ipV4PrimaryDns, ipV4SecondDns};
1279         //backup the original dns address.
1280         AssignedDnses.push_back(ipV4PrimaryDns);
1281         AssignedDnses.push_back(ipV4SecondDns);
1282         if (ipInfo.primaryDns !=0 || ipInfo.secondDns != 0) {
1283             std::vector<std::string> replacedDnsServers;
1284             GetReplacedDnsServers(servers, replacedDnsServers);
1285             UpdateDnsServers(replacedDnsServers);
1286         } else {
1287             std::vector<std::string> publicDnsServers;
1288             GetPublicDnsServers(publicDnsServers);
1289             UpdateDnsServers(publicDnsServers);
1290         }
1291     } else {
1292         std::vector<std::string> publicDnsServers;
1293         GetPublicDnsServers(publicDnsServers);
1294         UpdateDnsServers(publicDnsServers);
1295     }
1296     WriteWifiSelfcureHisysevent(static_cast<int>(WifiSelfcureType::DNS_ABNORMAL));
1297     pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_INTERNET_RECOVERY_CONFIRM, DNS_UPDATE_CONFIRM_DELAYED_MS);
1298 }
1299 
SelfCureForInvalidIp()1300 void SelfCureStateMachine::InternetSelfCureState::SelfCureForInvalidIp()
1301 {
1302     WIFI_LOGI("begin to self cure for internet access: InvalidIp");
1303     IpInfo dhcpResults;
1304     pSelfCureStateMachine->GetLegalIpConfiguration(dhcpResults);
1305     unConflictedIp = IpTools::ConvertIpv4Address(dhcpResults.ipAddress);
1306     if (selfCureForInvalidIpCnt < MAX_SELF_CURE_CNT_INVALID_IP) {
1307         IStaService *pStaService = WifiServiceManager::GetInstance().GetStaServiceInst(0);
1308         if (pStaService == nullptr) {
1309             WIFI_LOGE("Get pStaService failed!");
1310             return;
1311         }
1312         if (pStaService->Disconnect()!=WIFI_OPT_SUCCESS) {
1313             WIFI_LOGE("Disconnect failed.\n");
1314         }
1315         selfCureForInvalidIpCnt++;
1316     }
1317 }
1318 
GetNextTestDhcpResults()1319 IpInfo SelfCureStateMachine::InternetSelfCureState::GetNextTestDhcpResults()
1320 {
1321     IpInfo ipInfo;
1322     IEnhanceService *pEnhanceService = WifiServiceManager::GetInstance().GetEnhanceServiceInst();
1323     if (pEnhanceService == nullptr) {
1324         WIFI_LOGE("GetNextTestDhcpResults get pEnhanceService service failed!");
1325         return ipInfo;
1326     }
1327     bool isMultiDhcpServer = true;
1328     bool startSelfcure = false;
1329     pEnhanceService->GetStaticIpConfig(isMultiDhcpServer, startSelfcure, ipInfo);
1330     return ipInfo;
1331 }
1332 
GetRecordDhcpResults()1333 IpInfo SelfCureStateMachine::InternetSelfCureState::GetRecordDhcpResults()
1334 {
1335     IpInfo ipInfo;
1336     IEnhanceService *pEnhanceService = WifiServiceManager::GetInstance().GetEnhanceServiceInst();
1337     if (pEnhanceService == nullptr) {
1338         WIFI_LOGE("GetRecordDhcpResults get pEnhanceService service failed!");
1339         return ipInfo;
1340     }
1341     bool isMultiDhcpServer = false;
1342     bool startSelfcure = false;
1343     pEnhanceService->GetStaticIpConfig(isMultiDhcpServer, startSelfcure, ipInfo);
1344     std::string gateway = IpTools::ConvertIpv4Address(ipInfo.gateway);
1345     if (!pSelfCureStateMachine->DoSlowArpTest(gateway)) {
1346         pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_INTERNET_RECOVERY_CONFIRM,
1347             DHCP_CONFIRM_DELAYED_MS);
1348         IpInfo dhcpResult;
1349         return dhcpResult;
1350     }
1351     return ipInfo;
1352 }
1353 
SelfCureForStaticIp(int requestCureLevel)1354 void SelfCureStateMachine::InternetSelfCureState::SelfCureForStaticIp(int requestCureLevel)
1355 {
1356     IpInfo dhcpResult;
1357     IEnhanceService *pEnhanceService = WifiServiceManager::GetInstance().GetEnhanceServiceInst();
1358     if (pEnhanceService == nullptr) {
1359         WIFI_LOGE("SelfCureForStaticIp get pEnhanceService service failed!");
1360         return;
1361     }
1362     bool isMultiDhcpServer = configStaticIp4MultiDhcpServer ? true : false;
1363     bool startSelfcure = true;
1364     pEnhanceService->GetStaticIpConfig(isMultiDhcpServer, startSelfcure, dhcpResult);
1365     if (dhcpResult.gateway == 0 || dhcpResult.ipAddress == 0) {
1366         WIFI_LOGE("%{public}s: dhcpResult is null", __FUNCTION__);
1367         return;
1368     }
1369     std::string gatewayKey = IpTools::ConvertIpv4Address(dhcpResult.gateway);
1370     WIFI_LOGI("begin to self cure for internet access: TRY_NEXT_DHCP_OFFER");
1371     pSelfCureStateMachine->selfCureOnGoing = true;
1372     WriteWifiSelfcureHisysevent(static_cast<int>(WifiSelfcureType::GATEWAY_ABNORMAL));
1373     RequestUseStaticIpConfig(dhcpResult);
1374 }
1375 
RequestUseStaticIpConfig(IpInfo & dhcpResult)1376 void SelfCureStateMachine::InternetSelfCureState::RequestUseStaticIpConfig(IpInfo &dhcpResult)
1377 {
1378     WIFI_LOGI("enter %{public}s", __FUNCTION__);
1379     WifiLinkedInfo linkedInfo;
1380     WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo, pSelfCureStateMachine->m_instId);
1381     if (linkedInfo.connState != ConnState::CONNECTED) {
1382         return;
1383     }
1384     IpV6Info wifiIpV6Info;
1385     WifiConfigCenter::GetInstance().GetIpv6Info(wifiIpV6Info, pSelfCureStateMachine->m_instId);
1386     WifiDeviceConfig config;
1387     WifiSettings::GetInstance().GetDeviceConfig(linkedInfo.networkId, config);
1388     WifiNetAgent::GetInstance().UpdateNetLinkInfo(dhcpResult, wifiIpV6Info, config.wifiProxyconfig,
1389         pSelfCureStateMachine->m_instId);
1390     linkedInfo.ipAddress = dhcpResult.ipAddress;
1391     WifiConfigCenter::GetInstance().SaveIpInfo(dhcpResult);
1392     WifiConfigCenter::GetInstance().SaveLinkedInfo(linkedInfo, pSelfCureStateMachine->m_instId);
1393     WifiEventCallbackMsg cbMsg;
1394     cbMsg.msgCode = WIFI_CBK_MSG_CONNECTION_CHANGE;
1395     cbMsg.msgData = ConnState::CONNECTED;
1396     cbMsg.linkInfo = linkedInfo;
1397     cbMsg.id = pSelfCureStateMachine->m_instId;
1398     WifiInternalEventDispatcher::GetInstance().AddBroadCastMsg(cbMsg);
1399     pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_INTERNET_RECOVERY_CONFIRM, HTTP_DETECT_TIMEOUT);
1400 }
1401 
SelfCureForReassoc(int requestCureLevel)1402 void SelfCureStateMachine::InternetSelfCureState::SelfCureForReassoc(int requestCureLevel)
1403 {
1404     if ((currentRssi < MIN_VAL_LEVEL_3) || pSelfCureStateMachine->IfP2pConnected()) {
1405         WIFI_LOGI("delayedReassocSelfCure.");
1406         delayedReassocSelfCure = true;
1407         return;
1408     }
1409     WIFI_LOGI("begin to self cure for internet access: Reassoc");
1410     WriteWifiSelfcureHisysevent(static_cast<int>(WifiSelfcureType::TCP_RX_ABNORMAL));
1411     pSelfCureStateMachine->selfCureOnGoing = true;
1412     testedSelfCureLevel.push_back(requestCureLevel);
1413     delayedReassocSelfCure = false;
1414     IStaService *pStaService = WifiServiceManager::GetInstance().GetStaServiceInst(0);
1415     if (pStaService == nullptr) {
1416         WIFI_LOGE("Get pStaService failed!");
1417         return;
1418     }
1419     if (pStaService->ReAssociate() != WIFI_OPT_SUCCESS) {
1420         WIFI_LOGE("ReAssociate failed.\n");
1421     }
1422     pSelfCureStateMachine->UpdateSelfCureHistoryInfo(selfCureHistoryInfo, requestCureLevel, false);
1423     pSelfCureStateMachine->SetSelfCureHistoryInfo(selfCureHistoryInfo.GetSelfCureHistory());
1424     pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pConnectedMonitorState);
1425 }
1426 
IsNeedMultiGatewaySelfcure()1427 bool SelfCureStateMachine::InternetSelfCureState::IsNeedMultiGatewaySelfcure()
1428 {
1429     WIFI_LOGI("usedMultiGwSelfcure is %{public}d", usedMultiGwSelfcure);
1430     if (usedMultiGwSelfcure) {
1431         return false;
1432     }
1433     return pSelfCureStateMachine->IfMultiGateway();
1434 }
1435 
SelfcureForMultiGateway(InternalMessagePtr msg)1436 void SelfCureStateMachine::InternetSelfCureState::SelfcureForMultiGateway(InternalMessagePtr msg)
1437 {
1438     WIFI_LOGI("begin to self cure for internet access: multi gateway");
1439     if (!pSelfCureStateMachine->IsSuppOnCompletedState()) {
1440         WIFI_LOGW("it is not connect, no need selfcure");
1441         return;
1442     }
1443     usedMultiGwSelfcure = true;
1444     pSelfCureStateMachine->selfCureOnGoing = true;
1445     auto pMultiGateway = DelayedSingleton<MultiGateway>::GetInstance();
1446     if (pMultiGateway == nullptr) {
1447         WIFI_LOGE("pMultiGateway is nullptr");
1448         pSelfCureStateMachine->selfCureOnGoing = false;
1449         return;
1450     }
1451     std::string ipAddr = pMultiGateway->GetGatewayIp();
1452     std::string macString = "";
1453     pMultiGateway->GetNextGatewayMac(macString);
1454     if (macString.empty() || ipAddr.empty()) {
1455         WIFI_LOGE("macString or ipAddr is nullptr");
1456         if (lastMultiGwSelfFailedType != -1) {
1457             SelectSelfCureByFailedReason(lastMultiGwSelfFailedType);
1458         }
1459         pSelfCureStateMachine->selfCureOnGoing = false;
1460         return;
1461     }
1462 
1463     std::string ifaceName = WifiConfigCenter::GetInstance().GetStaIfaceName();
1464     pMultiGateway->SetStaticArp(ifaceName, ipAddr, macString);
1465     if (!pSelfCureStateMachine->IsHttpReachable()) {
1466         pMultiGateway->DelStaticArp(ifaceName, ipAddr);
1467         pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_MULTI_GATEWAY);
1468     } else {
1469         pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pConnectedMonitorState);
1470     }
1471     pSelfCureStateMachine->selfCureOnGoing = false;
1472 }
1473 
SelfCureForRandMacReassoc(int requestCureLevel)1474 void SelfCureStateMachine::InternetSelfCureState::SelfCureForRandMacReassoc(int requestCureLevel)
1475 {
1476     if ((currentRssi < MIN_VAL_LEVEL_3) || pSelfCureStateMachine->IfP2pConnected()) {
1477         pSelfCureStateMachine->selfCureOnGoing = false;
1478         delayedReassocSelfCure = true;
1479         return;
1480     }
1481     WIFI_LOGI("begin to self cure for internet access: RandMacReassoc");
1482     pSelfCureStateMachine->selfCureOnGoing = true;
1483     delayedReassocSelfCure = false;
1484     pSelfCureStateMachine->useWithRandMacAddress = FAC_MAC_REASSOC;
1485     pSelfCureStateMachine->SetIsReassocWithFactoryMacAddress(FAC_MAC_REASSOC);
1486     WifiLinkedInfo linkedInfo;
1487     WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo);
1488     int networkId = linkedInfo.networkId;
1489     WifiConfigCenter::GetInstance().SetLastNetworkId(networkId);
1490     IStaService *pStaService = WifiServiceManager::GetInstance().GetStaServiceInst(0);
1491     if (pStaService == nullptr) {
1492         WIFI_LOGE("Get pStaService failed!");
1493         return;
1494     }
1495     if (pStaService->ConnectToNetwork(networkId) != WIFI_OPT_SUCCESS) {
1496         WIFI_LOGE("ConnectToNetwork failed.\n");
1497     }
1498     pSelfCureStateMachine->UpdateSelfCureHistoryInfo(selfCureHistoryInfo, requestCureLevel, false);
1499     pSelfCureStateMachine->SetSelfCureHistoryInfo(selfCureHistoryInfo.GetSelfCureHistory());
1500     pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_CONN_FAILED_TIMEOUT, SELF_CURE_CONN_FAILED_TIMEOUT_MS);
1501 }
1502 
SelfCureForReset(int requestCureLevel)1503 void SelfCureStateMachine::InternetSelfCureState::SelfCureForReset(int requestCureLevel)
1504 {
1505     WIFI_LOGI("enter SelfCureForReset, internetUnknown: %{public}d, hasInternetRecently: %{public}d",
1506         pSelfCureStateMachine->internetUnknown, hasInternetRecently);
1507     if ((pSelfCureStateMachine->internetUnknown) || (!hasInternetRecently) ||
1508         (pSelfCureStateMachine->IsSettingsPage())) {
1509         pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pNoInternetState);
1510         return;
1511     }
1512 
1513     if ((currentRssi < MIN_VAL_LEVEL_3_5) || pSelfCureStateMachine->IfP2pConnected() ||
1514         pSelfCureStateMachine->p2pEnhanceConnected_) {
1515         WIFI_LOGI("delay Reset self cure");
1516         delayedResetSelfCure = true;
1517         return;
1518     }
1519     WIFI_LOGI("begin to self cure for internet access: Reset");
1520     WifiConfigCenter::GetInstance().SetWifiSelfcureResetEntered(true);
1521     pSelfCureStateMachine->StopTimer(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK);
1522     delayedResetSelfCure = false;
1523     testedSelfCureLevel.push_back(requestCureLevel);
1524 
1525     WifiLinkedInfo wifiLinkedInfo;
1526     WifiConfigCenter::GetInstance().GetLinkedInfo(wifiLinkedInfo);
1527     WifiConfigCenter::GetInstance().SetLastNetworkId(wifiLinkedInfo.networkId);
1528     pSelfCureStateMachine->UpdateSelfCureHistoryInfo(selfCureHistoryInfo, requestCureLevel, false);
1529     pSelfCureStateMachine->SetSelfCureHistoryInfo(selfCureHistoryInfo.GetSelfCureHistory());
1530     pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pConnectedMonitorState);
1531 }
1532 
SelectedSelfCureAcceptable()1533 bool SelfCureStateMachine::InternetSelfCureState::SelectedSelfCureAcceptable()
1534 {
1535     if (currentAbnormalType == WIFI_CURE_INTERNET_FAILED_TYPE_DNS ||
1536         currentAbnormalType == WIFI_CURE_INTERNET_FAILED_TYPE_GATEWAY) {
1537         lastSelfCureLevel = WIFI_CURE_RESET_LEVEL_LOW_1_DNS;
1538         if (pSelfCureStateMachine->SelfCureAcceptable(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_LOW_1_DNS)) {
1539             WIFI_LOGD("HTTP unreachable, use dns replace to cure for dns failed.");
1540             pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK, WIFI_CURE_RESET_LEVEL_LOW_1_DNS, 0);
1541             return true;
1542         }
1543     } else if (currentAbnormalType == WIFI_CURE_INTERNET_FAILED_TYPE_TCP) {
1544         lastSelfCureLevel = WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC;
1545         if (pSelfCureStateMachine->SelfCureAcceptable(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC)) {
1546             WIFI_LOGD("HTTP unreachable, use reassoc to cure for no rx pkt.");
1547             pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK, WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC,
1548                                                0);
1549             return true;
1550         }
1551     }
1552     return false;
1553 }
1554 
HandleInternetFailedAndUserSetStaticIp(int internetFailedType)1555 void SelfCureStateMachine::InternetSelfCureState::HandleInternetFailedAndUserSetStaticIp(int internetFailedType)
1556 {
1557     if (hasInternetRecently &&
1558         pSelfCureStateMachine->SelfCureAcceptable(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_HIGH_RESET)) {
1559         if (internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_DNS) {
1560             lastSelfCureLevel = WIFI_CURE_RESET_LEVEL_LOW_1_DNS;
1561         } else if (internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_ROAMING) {
1562             lastSelfCureLevel = WIFI_CURE_RESET_LEVEL_LOW_2_RENEW_DHCP;
1563         } else if (internetFailedType == WIFI_CURE_INTERNET_FAILED_TYPE_GATEWAY) {
1564             lastSelfCureLevel = WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP;
1565         }
1566         pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK, WIFI_CURE_RESET_LEVEL_HIGH_RESET);
1567         return;
1568     }
1569     WIFI_LOGI("user set static ip config, ignore to update config for user.");
1570     if (!pSelfCureStateMachine->internetUnknown) {
1571         currentAbnormalType = WIFI_CURE_RESET_REJECTED_BY_STATIC_IP_ENABLED;
1572     }
1573 }
1574 
HandleIpConfigTimeout()1575 void SelfCureStateMachine::InternetSelfCureState::HandleIpConfigTimeout()
1576 {
1577     WIFI_LOGI("during self cure state. currentAbnormalType = %{public}d", currentAbnormalType);
1578     pSelfCureStateMachine->selfCureOnGoing = false;
1579     isRenewDhcpTimeout = true;
1580     std::vector<WifiScanInfo> scanResults;
1581     WifiConfigCenter::GetInstance().GetWifiScanConfig()->GetScanInfoList(scanResults);
1582     if (currentAbnormalType == WIFI_CURE_INTERNET_FAILED_TYPE_ROAMING &&
1583         pSelfCureStateMachine->IsEncryptedAuthType(configAuthType) &&
1584         pSelfCureStateMachine->GetBssidCounter(scanResults) <= DEAUTH_BSSID_CNT && !finalSelfCureUsed) {
1585         finalSelfCureUsed = true;
1586         pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK, WIFI_CURE_RESET_LEVEL_DEAUTH_BSSID);
1587     }
1588 }
1589 
HandleIpConfigCompleted()1590 void SelfCureStateMachine::InternetSelfCureState::HandleIpConfigCompleted()
1591 {
1592     WIFI_LOGI("msg removed because of ip config success.");
1593     pSelfCureStateMachine->StopTimer(WIFI_CURE_CMD_IP_CONFIG_TIMEOUT);
1594     isRenewDhcpTimeout = false;
1595     HandleIpConfigCompletedAfterRenewDhcp();
1596     if (isRenewDhcpTimeout) {
1597         HandleIpConfigCompletedAfterRenewDhcp();
1598     }
1599     WIFI_LOGI("msg removed because of rcv other dhcp offer.");
1600     pSelfCureStateMachine->StopTimer(WIFI_CURE_CMD_INVALID_DHCP_OFFER_EVENT);
1601 }
1602 
HandleIpConfigCompletedAfterRenewDhcp()1603 void SelfCureStateMachine::InternetSelfCureState::HandleIpConfigCompletedAfterRenewDhcp()
1604 {
1605     currentGateway = pSelfCureStateMachine->GetCurrentGateway();
1606     pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_INTERNET_RECOVERY_CONFIRM, IP_CONFIG_CONFIRM_DELAYED_MS);
1607 }
1608 
HandleInternetRecoveryConfirm()1609 void SelfCureStateMachine::InternetSelfCureState::HandleInternetRecoveryConfirm()
1610 {
1611     pSelfCureStateMachine->UpdateSelfCureConnectHistoryInfo(selfCureHistoryInfo, currentSelfCureLevel, true);
1612     bool success = ConfirmInternetSelfCure(currentSelfCureLevel);
1613     if (success) {
1614         currentSelfCureLevel = WIFI_CURE_RESET_LEVEL_IDLE;
1615         selfCureFailedCounter = 0;
1616         hasInternetRecently = true;
1617     }
1618 }
1619 
resetDnses(std::vector<std::string> & dnses)1620 void SelfCureStateMachine::InternetSelfCureState::resetDnses(std::vector<std::string>& dnses)
1621 {
1622     if ((!dnses[0].empty()) || (!dnses[1].empty())) {
1623         UpdateDnsServers(dnses);
1624     } else {
1625         //if the original dns address is empty, set two dnses address to empty.
1626         //2:include two string.
1627         std::vector<std::string> resetDnses(2, "");
1628         UpdateDnsServers(resetDnses);
1629     }
1630 }
1631 
ConfirmInternetSelfCure(int currentCureLevel)1632 bool SelfCureStateMachine::InternetSelfCureState::ConfirmInternetSelfCure(int currentCureLevel)
1633 {
1634     WIFI_LOGI("ConfirmInternetSelfCure, cureLevel = %{public}d ,last failed counter = %{public}d,"
1635               "finally = %{public}d",
1636               currentCureLevel, selfCureFailedCounter, finalSelfCureUsed);
1637     if (currentCureLevel == WIFI_CURE_RESET_LEVEL_IDLE) {
1638         return false;
1639     }
1640     if (pSelfCureStateMachine->IsHttpReachable()) {
1641         if (currentCureLevel == WIFI_CURE_RESET_LEVEL_LOW_1_DNS && pSelfCureStateMachine->internetUnknown) {
1642             std::vector<std::string> publicDnses;
1643             GetPublicDnsServers(publicDnses);
1644             UpdateDnsServers(publicDnses);
1645             WIFI_LOGI("RequestUpdateDnsServers");
1646         }
1647         HandleHttpReachableAfterSelfCure(currentCureLevel);
1648         pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pConnectedMonitorState);
1649         return true;
1650     }
1651     HandleConfirmInternetSelfCureFailed(currentCureLevel);
1652     return false;
1653 }
1654 
HandleConfirmInternetSelfCureFailed(int currentCureLevel)1655 void SelfCureStateMachine::InternetSelfCureState::HandleConfirmInternetSelfCureFailed(int currentCureLevel)
1656 {
1657     if (currentCureLevel == WIFI_CURE_RESET_LEVEL_LOW_1_DNS && pSelfCureStateMachine->internetUnknown) {
1658         resetDnses(AssignedDnses);
1659     }
1660     if (currentCureLevel == WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC && pSelfCureStateMachine->internetUnknown) {
1661         HandleSelfCureFailedForRandMacReassoc();
1662         return;
1663     }
1664     selfCureFailedCounter++;
1665     pSelfCureStateMachine->UpdateSelfCureHistoryInfo(selfCureHistoryInfo, currentCureLevel, false);
1666     pSelfCureStateMachine->SetSelfCureHistoryInfo(selfCureHistoryInfo.GetSelfCureHistory());
1667     WIFI_LOGI("HTTP unreachable, self cure failed for %{public}d, selfCureHistoryInfo = %{public}s", currentCureLevel,
1668               pSelfCureStateMachine->GetSelfCureHistoryInfo().c_str());
1669     pSelfCureStateMachine->selfCureOnGoing = false;
1670     if (finalSelfCureUsed) {
1671         HandleHttpUnreachableFinally();
1672         return;
1673     }
1674     if (currentCureLevel == WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC && pSelfCureStateMachine->hasTestWifi6Reassoc &&
1675         pSelfCureStateMachine->IsNeedWifiReassocUseDeviceMac()) {
1676         pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_INTERNET_FAILED_SELF_CURE, WIFI_CURE_INTERNET_FAILED_RAND_MAC);
1677         return;
1678     }
1679     if (currentCureLevel == WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP) {
1680         if (GetNextTestDhcpResults().ipAddress != 0) {
1681             lastSelfCureLevel = currentCureLevel;
1682             WIFI_LOGI("HTTP unreachable, and has next dhcp results, try next one.");
1683             pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK,
1684                 WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP, 0);
1685             return;
1686         }
1687         configStaticIp4MultiDhcpServer = false;
1688         if (SelectedSelfCureAcceptable()) {
1689             return;
1690         }
1691     }
1692     if (!HasBeenTested(WIFI_CURE_RESET_LEVEL_HIGH_RESET) &&
1693         pSelfCureStateMachine->SelfCureAcceptable(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_HIGH_RESET)) {
1694         lastSelfCureLevel = currentCureLevel;
1695         pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_INTERNET_FAILED_SELF_CURE, WIFI_CURE_RESET_LEVEL_HIGH_RESET);
1696     } else {
1697         HandleHttpUnreachableFinally();
1698     }
1699     return;
1700 }
1701 
HandleSelfCureFailedForRandMacReassoc()1702 void SelfCureStateMachine::InternetSelfCureState::HandleSelfCureFailedForRandMacReassoc()
1703 {
1704     WIFI_LOGI("enter %{public}s", __FUNCTION__);
1705     if (pSelfCureStateMachine->useWithRandMacAddress == FAC_MAC_REASSOC && pSelfCureStateMachine->IsUseFactoryMac()) {
1706         WIFI_LOGI("HTTP unreachable, factory mac failed and use rand mac instead of");
1707         pSelfCureStateMachine->useWithRandMacAddress = RAND_MAC_REASSOC;
1708         pSelfCureStateMachine->SetIsReassocWithFactoryMacAddress(RAND_MAC_REASSOC);
1709         WifiLinkedInfo linkedInfo;
1710         WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo);
1711         int networkId = linkedInfo.networkId;
1712         WifiConfigCenter::GetInstance().SetLastNetworkId(networkId);
1713         IStaService *pStaService = WifiServiceManager::GetInstance().GetStaServiceInst(0);
1714         if (pStaService == nullptr) {
1715             WIFI_LOGE("Get pStaService failed!");
1716             return;
1717         }
1718         if (pStaService->ConnectToNetwork(networkId) != WIFI_OPT_SUCCESS) {
1719             WIFI_LOGE("ConnectToNetwork failed.\n");
1720         }
1721         return;
1722     }
1723     selfCureFailedCounter++;
1724     UpdateSelfCureHistoryInfo(selfCureHistoryInfo, WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC, false);
1725     WIFI_LOGI("HTTP unreachable, self cure failed for rand mac reassoc");
1726     pSelfCureStateMachine->selfCureOnGoing = false;
1727     pSelfCureStateMachine->useWithRandMacAddress = 0;
1728     pSelfCureStateMachine->SetIsReassocWithFactoryMacAddress(0);
1729     if (pSelfCureStateMachine->IsCustNetworkSelfCure()) {
1730         return;
1731     }
1732     pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_INTERNET_FAILED_SELF_CURE, WIFI_CURE_INTERNET_FAILED_TYPE_DNS);
1733     return;
1734 }
1735 
HandleHttpReachableAfterSelfCure(int currentCureLevel)1736 void SelfCureStateMachine::InternetSelfCureState::HandleHttpReachableAfterSelfCure(int currentCureLevel)
1737 {
1738     WIFI_LOGI("HandleHttpReachableAfterSelfCure, currentCureLevel = %{public}d", currentCureLevel);
1739     pSelfCureStateMachine->UpdateSelfCureHistoryInfo(selfCureHistoryInfo, currentCureLevel, true);
1740     pSelfCureStateMachine->selfCureOnGoing = false;
1741     if (!setStaticIp4InvalidIp && currentCureLevel == WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP) {
1742         currentAbnormalType = WIFI_CURE_INTERNET_FAILED_TYPE_GATEWAY;
1743         pSelfCureStateMachine->RequestArpConflictTest();
1744         pSelfCureStateMachine->staticIpCureSuccess = true;
1745     }
1746 
1747     if (currentCureLevel == WIFI_CURE_RESET_LEVEL_LOW_1_DNS) {
1748         WriteWifiSelfcureHisysevent(static_cast<int>(WifiSelfcureType::DNS_SELFCURE_SUCC));
1749     } else if (currentCureLevel == WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP) {
1750         WriteWifiSelfcureHisysevent(static_cast<int>(WifiSelfcureType::STATIC_IP_SELFCURE_SUCC));
1751     } else if (currentCureLevel == WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC) {
1752         WriteWifiSelfcureHisysevent(static_cast<int>(WifiSelfcureType::REASSOC_SELFCURE_SUCC));
1753     } else if (currentCureLevel == WIFI_CURE_RESET_LEVEL_HIGH_RESET) {
1754         WriteWifiSelfcureHisysevent(static_cast<int>(WifiSelfcureType::RESET_SELFCURE_SUCC));
1755     }
1756 }
1757 
HandleHttpUnreachableFinally()1758 void SelfCureStateMachine::InternetSelfCureState::HandleHttpUnreachableFinally()
1759 {
1760     WIFI_LOGI("enter %{public}s", __FUNCTION__);
1761     pSelfCureStateMachine->selfCureOnGoing = false;
1762     pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pNoInternetState);
1763 }
1764 
HasBeenTested(int cureLevel)1765 bool SelfCureStateMachine::InternetSelfCureState::HasBeenTested(int cureLevel)
1766 {
1767     for (int itemTestedSelfCureLevel : testedSelfCureLevel) {
1768         if (itemTestedSelfCureLevel == cureLevel) {
1769             return true;
1770         }
1771     }
1772     return false;
1773 }
1774 
HandleRssiChanged()1775 void SelfCureStateMachine::InternetSelfCureState::HandleRssiChanged()
1776 {
1777     if (pSelfCureStateMachine->p2pEnhanceConnected_) {
1778         WIFI_LOGE("no need deal rssi change");
1779         return;
1780     }
1781     if ((currentRssi < MIN_VAL_LEVEL_3_5) && (!pSelfCureStateMachine->IfP2pConnected())) {
1782         return;
1783     }
1784     if (delayedResetSelfCure) {
1785         HandleDelayedResetSelfCure();
1786         return;
1787     }
1788     if (!pSelfCureStateMachine->selfCureOnGoing && (delayedReassocSelfCure || delayedRandMacReassocSelfCure)) {
1789         pSelfCureStateMachine->selfCureOnGoing = true;
1790         if (!pSelfCureStateMachine->IsHttpReachable()) {
1791             WIFI_LOGD("HandleRssiChanged, HTTP failed, delayedReassoc = %{public}s, delayedRandMacReassoc = %{public}s",
1792                       std::to_string(delayedReassocSelfCure).c_str(),
1793                       std::to_string(delayedRandMacReassocSelfCure).c_str());
1794             pSelfCureStateMachine->StopTimer(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK);
1795             if (delayedReassocSelfCure) {
1796                 pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK,
1797                                                    WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC, 0);
1798             } else if (delayedRandMacReassocSelfCure) {
1799                 pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK,
1800                                                    WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC, 0);
1801             }
1802         } else {
1803             pSelfCureStateMachine->selfCureOnGoing = false;
1804             delayedReassocSelfCure = false;
1805             delayedResetSelfCure = false;
1806             delayedRandMacReassocSelfCure = false;
1807             pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pConnectedMonitorState);
1808         }
1809     }
1810 }
1811 
HandleDelayedResetSelfCure()1812 void SelfCureStateMachine::InternetSelfCureState::HandleDelayedResetSelfCure()
1813 {
1814     pSelfCureStateMachine->selfCureOnGoing = true;
1815     if (!pSelfCureStateMachine->IsHttpReachable()) {
1816         WIFI_LOGD("HandleDelayedResetSelfCure, HTTP failed, delayedReset = %{public}s",
1817                   std::to_string(delayedResetSelfCure).c_str());
1818         pSelfCureStateMachine->StopTimer(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK);
1819         pSelfCureStateMachine->SendMessageAtFrontOfQueue(WIFI_CURE_CMD_SELF_CURE_WIFI_LINK,
1820                                                          WIFI_CURE_RESET_LEVEL_HIGH_RESET);
1821     } else {
1822         pSelfCureStateMachine->selfCureOnGoing = false;
1823         delayedReassocSelfCure = false;
1824         delayedResetSelfCure = false;
1825         delayedRandMacReassocSelfCure = false;
1826         pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pConnectedMonitorState);
1827     }
1828 }
1829 
1830 /* --------------------------- state machine wifi6 self cure state ------------------------------ */
Wifi6SelfCureState(SelfCureStateMachine * selfCureStateMachine)1831 SelfCureStateMachine::Wifi6SelfCureState::Wifi6SelfCureState(SelfCureStateMachine *selfCureStateMachine)
1832     : State("Wifi6SelfCureState"),
1833       pSelfCureStateMachine(selfCureStateMachine)
1834 {
1835     WIFI_LOGD("Wifi6SelfCureState construct success.");
1836 }
1837 
~Wifi6SelfCureState()1838 SelfCureStateMachine::Wifi6SelfCureState::~Wifi6SelfCureState() {}
1839 
GoInState()1840 void SelfCureStateMachine::Wifi6SelfCureState::GoInState()
1841 {
1842     WIFI_LOGI("Wifi6SelfCureState GoInState function.");
1843     wifi6HtcArpDetectionFailedCnt = 0;
1844     wifi6ArpDetectionFailedCnt = 0;
1845     return;
1846 }
1847 
GoOutState()1848 void SelfCureStateMachine::Wifi6SelfCureState::GoOutState()
1849 {
1850     WIFI_LOGI("Wifi6SelfCureState GoOutState function.");
1851     return;
1852 }
1853 
ExecuteStateMsg(InternalMessagePtr msg)1854 bool SelfCureStateMachine::Wifi6SelfCureState::ExecuteStateMsg(InternalMessagePtr msg)
1855 {
1856     if (msg == nullptr) {
1857         return false;
1858     }
1859 
1860     WIFI_LOGD("Wifi6SelfCureState-msgCode=%{public}d is received.\n", msg->GetMessageName());
1861     bool ret = NOT_EXECUTED;
1862     switch (msg->GetMessageName()) {
1863         case WIFI_CURE_CMD_WIFI6_SELFCURE:
1864             ret = EXECUTED;
1865             internetValue_ = msg->GetParam1();
1866             isForceHttpCheck_ = msg->GetParam2();
1867             pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_WIFI6_WITH_HTC_PERIODIC_ARP_DETECTED);
1868             break;
1869         case WIFI_CURE_CMD_WIFI6_BACKOFF_SELFCURE:
1870             ret = EXECUTED;
1871             internetValue_ = msg->GetParam1();
1872             isForceHttpCheck_ = msg->GetParam2();
1873             pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_WIFI6_WITHOUT_HTC_PERIODIC_ARP_DETECTED);
1874             break;
1875         case WIFI_CURE_CMD_WIFI6_WITH_HTC_PERIODIC_ARP_DETECTED:
1876             ret = EXECUTED;
1877             PeriodicWifi6WithHtcArpDetect(msg);
1878             break;
1879         case WIFI_CURE_CMD_WIFI6_WITHOUT_HTC_PERIODIC_ARP_DETECTED:
1880             ret = EXECUTED;
1881             PeriodicWifi6WithoutHtcArpDetect(msg);
1882             break;
1883         case WIFI_CURE_CMD_WIFI6_WITH_HTC_ARP_FAILED_DETECTED:
1884             ret = EXECUTED;
1885             HandleWifi6WithHtcArpFail(msg);
1886             break;
1887         case WIFI_CURE_CMD_WIFI6_WITHOUT_HTC_ARP_FAILED_DETECTED:
1888             ret = EXECUTED;
1889             HandleWifi6WithoutHtcArpFail(msg);
1890             break;
1891         default:
1892             WIFI_LOGD("Wifi6SelfCureState-msgCode=%{public}d not handled.\n", msg->GetMessageName());
1893             break;
1894     }
1895     return ret;
1896 }
1897 
PeriodicWifi6WithHtcArpDetect(InternalMessagePtr msg)1898 void SelfCureStateMachine::Wifi6SelfCureState::PeriodicWifi6WithHtcArpDetect(InternalMessagePtr msg)
1899 {
1900     if (msg == nullptr) {
1901         WIFI_LOGE("%{public}s msg is nullptr", __FUNCTION__);
1902         return;
1903     }
1904     if (!pSelfCureStateMachine->CanArpReachable()) {
1905         wifi6HtcArpDetectionFailedCnt++;
1906         WIFI_LOGI("wifi6 with htc arp detection failed, times : %{public}d", wifi6HtcArpDetectionFailedCnt);
1907         if (wifi6HtcArpDetectionFailedCnt == ARP_DETECTED_FAILED_COUNT) {
1908             pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_WIFI6_WITH_HTC_ARP_FAILED_DETECTED);
1909             return;
1910         } else if (wifi6HtcArpDetectionFailedCnt > 0 && wifi6HtcArpDetectionFailedCnt < ARP_DETECTED_FAILED_COUNT) {
1911             pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_WIFI6_WITH_HTC_PERIODIC_ARP_DETECTED,
1912                 WIFI6_HTC_ARP_DETECTED_MS);
1913             return;
1914         }
1915     } else {
1916         WIFI_LOGI("wifi6 with htc arp detect success");
1917         wifi6HtcArpDetectionFailedCnt = 0;
1918         pSelfCureStateMachine->isWifi6ArpSuccess = true;
1919         pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_INTERNET_FAILURE_DETECTED, internetValue_,
1920             isForceHttpCheck_, 0);
1921         pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pConnectedMonitorState);
1922         return;
1923     }
1924 }
1925 
PeriodicWifi6WithoutHtcArpDetect(InternalMessagePtr msg)1926 void SelfCureStateMachine::Wifi6SelfCureState::PeriodicWifi6WithoutHtcArpDetect(InternalMessagePtr msg)
1927 {
1928     if (msg == nullptr) {
1929         WIFI_LOGE("%{public}s msg is nullptr", __FUNCTION__);
1930         return;
1931     }
1932     if (!pSelfCureStateMachine->CanArpReachable()) {
1933         wifi6ArpDetectionFailedCnt++;
1934         WIFI_LOGI("wifi6 without htc arp detection failed, times : %{public}d", wifi6ArpDetectionFailedCnt);
1935         if (wifi6ArpDetectionFailedCnt == ARP_DETECTED_FAILED_COUNT) {
1936             pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_WIFI6_WITHOUT_HTC_ARP_FAILED_DETECTED);
1937             return;
1938         } else if (wifi6ArpDetectionFailedCnt > 0 && wifi6ArpDetectionFailedCnt < ARP_DETECTED_FAILED_COUNT) {
1939             pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_WIFI6_WITHOUT_HTC_PERIODIC_ARP_DETECTED,
1940                 WIFI6_HTC_ARP_DETECTED_MS);
1941             return;
1942         }
1943     } else {
1944         WIFI_LOGI("wifi6 without htc arp detect success");
1945         wifi6ArpDetectionFailedCnt = 0;
1946         pSelfCureStateMachine->isWifi6ArpSuccess = true;
1947         if (!pSelfCureStateMachine->IsHttpReachable()) {
1948             pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_INTERNET_FAILURE_DETECTED, internetValue_,
1949                 isForceHttpCheck_, SELF_CURE_DELAYED_MS);
1950         } else {
1951             pSelfCureStateMachine->selfCureOnGoing = false;
1952         }
1953         pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pConnectedMonitorState);
1954         return;
1955     }
1956 }
1957 
HandleWifi6WithHtcArpFail(InternalMessagePtr msg)1958 void SelfCureStateMachine::Wifi6SelfCureState::HandleWifi6WithHtcArpFail(InternalMessagePtr msg)
1959 {
1960     if (msg == nullptr) {
1961         WIFI_LOGE("%{public}s msg is nullptr", __FUNCTION__);
1962         return;
1963     }
1964     pSelfCureStateMachine->isWifi6ArpSuccess = false;
1965     WifiCategoryBlackListInfo wifi6BlackListInfo(ACTION_TYPE_HTC, pSelfCureStateMachine->GetNowMilliSeconds());
1966     std::string currentBssid = pSelfCureStateMachine->GetCurrentBssid();
1967     if (currentBssid.empty()) {
1968         WIFI_LOGE("%{public}s currentBssid is empty", __FUNCTION__);
1969         Wifi6ReassocSelfcure();
1970         return;
1971     }
1972     WifiConfigCenter::GetInstance().InsertWifiCategoryBlackListCache(EVENT_AX_BLA_LIST,
1973         currentBssid, wifi6BlackListInfo);
1974     WIFI_LOGI("add %{public}s to HTC bla list", MacAnonymize(currentBssid).c_str());
1975     pSelfCureStateMachine->SendBlaListToDriver(EVENT_AX_BLA_LIST);
1976     std::string param = "1";
1977     std::string ifName = "wlan0";
1978     if (WifiCmdClient::GetInstance().SendCmdToDriver(ifName, EVENT_AX_CLOSE_HTC, param) != 0) {
1979         WIFI_LOGE("%{public}s Ax Selfcure fail", __FUNCTION__);
1980         return;
1981     }
1982     pSelfCureStateMachine->SendMessage(WIFI_CURE_CMD_WIFI6_WITHOUT_HTC_PERIODIC_ARP_DETECTED);
1983 }
1984 
HandleWifi6WithoutHtcArpFail(InternalMessagePtr msg)1985 void SelfCureStateMachine::Wifi6SelfCureState::HandleWifi6WithoutHtcArpFail(InternalMessagePtr msg)
1986 {
1987     if (msg == nullptr) {
1988         WIFI_LOGE("%{public}s msg is nullptr", __FUNCTION__);
1989         return;
1990     }
1991     WIFI_LOGI("wifi6 without htc arp detect failed");
1992     std::string currentBssid = pSelfCureStateMachine->GetCurrentBssid();
1993     if (currentBssid.empty()) {
1994         WIFI_LOGE("%{public}s currentBssid is empty", __FUNCTION__);
1995         Wifi6ReassocSelfcure();
1996         return;
1997     }
1998     pSelfCureStateMachine->isWifi6ArpSuccess = false;
1999     WifiCategoryBlackListInfo wifi6BlackListInfo(ACTION_TYPE_WIFI6, pSelfCureStateMachine->GetNowMilliSeconds());
2000 
2001     WifiConfigCenter::GetInstance().InsertWifiCategoryBlackListCache(EVENT_AX_BLA_LIST,
2002         currentBssid, wifi6BlackListInfo);
2003 
2004     WIFI_LOGI("add %{public}s to wifi6 bla list", MacAnonymize(currentBssid).c_str());
2005     pSelfCureStateMachine->SendBlaListToDriver(EVENT_AX_BLA_LIST);
2006     Wifi6ReassocSelfcure();
2007 }
2008 
Wifi6ReassocSelfcure()2009 void SelfCureStateMachine::Wifi6SelfCureState::Wifi6ReassocSelfcure()
2010 {
2011     WIFI_LOGI("begin to self cure for wifi6 reassoc");
2012     pSelfCureStateMachine->hasTestWifi6Reassoc = true;
2013     pSelfCureStateMachine->MessageExecutedLater(WIFI_CURE_CMD_INTERNET_FAILED_SELF_CURE,
2014         WIFI_CURE_INTERNET_FAILED_TYPE_TCP, SELF_CURE_DELAYED_MS);
2015     pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pInternetSelfCureState);
2016 }
2017 
2018 /* --------------------------- state machine noInternet state ------------------------------ */
NoInternetState(SelfCureStateMachine * selfCureStateMachine)2019 SelfCureStateMachine::NoInternetState::NoInternetState(SelfCureStateMachine *selfCureStateMachine)
2020     : State("NoInternetState"),
2021       pSelfCureStateMachine(selfCureStateMachine)
2022 {
2023     WIFI_LOGD("NoInternetState construct success.");
2024 }
2025 
~NoInternetState()2026 SelfCureStateMachine::NoInternetState::~NoInternetState() {}
2027 
GoInState()2028 void SelfCureStateMachine::NoInternetState::GoInState()
2029 {
2030     WIFI_LOGI("NoInternetState GoInState function.");
2031     pSelfCureStateMachine->selfCureOnGoing = false;
2032     pSelfCureStateMachine->MessageExecutedLater(CMD_INTERNET_STATUS_DETECT_INTERVAL,
2033         NO_INTERNET_DETECT_INTERVAL_MS);
2034 }
2035 
GoOutState()2036 void SelfCureStateMachine::NoInternetState::GoOutState()
2037 {
2038     WIFI_LOGI("NoInternetState GoOutState function.");
2039     return;
2040 }
2041 
ExecuteStateMsg(InternalMessagePtr msg)2042 bool SelfCureStateMachine::NoInternetState::ExecuteStateMsg(InternalMessagePtr msg)
2043 {
2044     if (msg == nullptr) {
2045         return false;
2046     }
2047     WIFI_LOGD("NoInternetState-msgCode=%{public}d is received.\n", msg->GetMessageName());
2048     bool ret = NOT_EXECUTED;
2049     switch (msg->GetMessageName()) {
2050         case CMD_INTERNET_STATUS_DETECT_INTERVAL:
2051             ret = EXECUTED;
2052             pSelfCureStateMachine->StopTimer(CMD_INTERNET_STATUS_DETECT_INTERVAL);
2053             if (WifiConfigCenter::GetInstance().GetScreenState() != MODE_STATE_CLOSE) {
2054                 IpQosMonitor::GetInstance().QueryPackets();
2055             }
2056             pSelfCureStateMachine->MessageExecutedLater(CMD_INTERNET_STATUS_DETECT_INTERVAL,
2057                 NO_INTERNET_DETECT_INTERVAL_MS);
2058             break;
2059         case WIFI_CURE_CMD_HTTP_REACHABLE_RCV:
2060             ret = EXECUTED;
2061             pSelfCureStateMachine->SetSelfCureHistoryInfo(INIT_SELFCURE_HISTORY);
2062             pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pConnectedMonitorState);
2063             break;
2064         case WIFI_CURE_NOTIFY_NETWORK_DISCONNECTED_RCVD:
2065             ret = EXECUTED;
2066             pSelfCureStateMachine->SwitchState(pSelfCureStateMachine->pDisconnectedMonitorState);
2067             break;
2068         default:
2069             WIFI_LOGD("NoInternetState-msgCode=%{public}d not handled.\n", msg->GetMessageName());
2070             break;
2071     }
2072     return ret;
2073 }
2074 
GetNowMilliSeconds()2075 int64_t SelfCureStateMachine::GetNowMilliSeconds()
2076 {
2077     auto nowSys = AppExecFwk::InnerEvent::Clock::now();
2078     auto epoch = nowSys.time_since_epoch();
2079     return std::chrono::duration_cast<std::chrono::milliseconds>(epoch).count();
2080 }
2081 
SendBlaListToDriver(int blaListType)2082 void SelfCureStateMachine::SendBlaListToDriver(int blaListType)
2083 {
2084     std::map<std::string, WifiCategoryBlackListInfo> wifiBlackListCache;
2085     WifiConfigCenter::GetInstance().GetWifiCategoryBlackListCache(blaListType, wifiBlackListCache);
2086     if (wifiBlackListCache.empty()) {
2087         return;
2088     }
2089     AgeOutWifiCategoryBlack(blaListType, wifiBlackListCache);
2090     std::string param = BlackListToString(wifiBlackListCache);
2091     std::string ifName = "wlan0";
2092     if (WifiCmdClient::GetInstance().SendCmdToDriver(ifName, blaListType, param) != 0) {
2093         WIFI_LOGE("%{public}s set BlaList fail", __FUNCTION__);
2094         return;
2095     }
2096 }
2097 
BlackListToString(std::map<std::string,WifiCategoryBlackListInfo> & map)2098 std::string SelfCureStateMachine::BlackListToString(std::map<std::string, WifiCategoryBlackListInfo> &map)
2099 {
2100     std::string param;
2101     if (map.empty()) {
2102         return param;
2103     }
2104     uint32_t idx = map.size() >= WIFI_MAX_BLA_LIST_NUM ? WIFI_MAX_BLA_LIST_NUM : map.size();
2105     param.push_back(idx);
2106     for (auto iter : map) {
2107         std::string singleParam = ParseWifiCategoryBlackListInfo(iter);
2108         if (singleParam.size() != WIFI_SINGLE_ITEM_BYTE_LEN) {
2109             continue;
2110         }
2111         param.append(singleParam);
2112         if (param.size() >= WIFI_MAX_BLA_LIST_NUM * WIFI_SINGLE_ITEM_BYTE_LEN + 1) {
2113             break;
2114         }
2115     }
2116     return param;
2117 }
2118 
ParseWifiCategoryBlackListInfo(std::pair<std::string,WifiCategoryBlackListInfo> iter)2119 std::string SelfCureStateMachine::ParseWifiCategoryBlackListInfo(std::pair<std::string, WifiCategoryBlackListInfo> iter)
2120 {
2121     std::string singleParam;
2122     std::string currBssid = iter.first;
2123     WIFI_LOGI("currBssid %{public}s", MacAnonymize(currBssid).c_str());
2124     for (uint32_t i = 0; i < WIFI_SINGLE_MAC_LEN; i++) {
2125         std::string::size_type npos = currBssid.find(":");
2126         if (npos != std::string::npos) {
2127             std::string value = currBssid.substr(0, npos);
2128             singleParam.push_back(static_cast<uint8_t>(CheckDataLegalHex(value)));
2129             currBssid = currBssid.substr(npos + 1);
2130         } else {
2131             if (currBssid.empty()) {
2132                 WIFI_LOGI("currBssid is empty");
2133                 break;
2134             }
2135             singleParam.push_back(static_cast<uint8_t>(CheckDataLegalHex(currBssid)));
2136         }
2137     }
2138     singleParam.push_back(static_cast<uint8_t>(iter.second.actionType));
2139     singleParam.push_back(0);
2140     return singleParam;
2141 }
2142 
AgeOutWifiCategoryBlack(int blaListType,std::map<std::string,WifiCategoryBlackListInfo> & blackListCache)2143 void SelfCureStateMachine::AgeOutWifiCategoryBlack(int blaListType, std::map<std::string,
2144     WifiCategoryBlackListInfo> &blackListCache)
2145 {
2146     if (blaListType != EVENT_AX_BLA_LIST && blaListType != EVENT_BE_BLA_LIST) {
2147         WIFI_LOGE("AgeOutWifiCategoryBlack wrong type.");
2148         return;
2149     }
2150     for (auto iter = blackListCache.begin(); iter != blackListCache.end(); ++iter) {
2151         if (GetNowMilliSeconds() - iter->second.updateTime >= WIFI_BLA_LIST_TIME_EXPIRED) {
2152             WifiConfigCenter::GetInstance().RemoveWifiCategoryBlackListCache(blaListType, iter->first);
2153         }
2154     }
2155     if (blackListCache.size() >= WIFI_MAX_BLA_LIST_NUM) {
2156         int64_t earliestTime = std::numeric_limits<int64_t>::max();
2157         std::string delBssid;
2158         for (auto iter = blackListCache.begin(); iter != blackListCache.end(); ++iter) {
2159             if (iter->second.updateTime < earliestTime) {
2160                 delBssid = iter->first;
2161                 earliestTime = iter->second.updateTime;
2162             }
2163         }
2164         WifiConfigCenter::GetInstance().RemoveWifiCategoryBlackListCache(blaListType, delBssid);
2165     }
2166 }
2167 
AgeOutWifiConnectFailList()2168 void SelfCureStateMachine::AgeOutWifiConnectFailList()
2169 {
2170     std::map<std::string, WifiCategoryConnectFailInfo> connectFailListCache;
2171     WifiConfigCenter::GetInstance().GetWifiConnectFailListCache(connectFailListCache);
2172     for (auto iter = connectFailListCache.begin(); iter != connectFailListCache.end(); ++iter) {
2173         if (GetNowMilliSeconds() - iter->second.updateTime >= WIFI_CONNECT_FAIL_LIST_TIME_EXPIRED) {
2174             WifiConfigCenter::GetInstance().RemoveWifiConnectFailListCache(iter->first);
2175         }
2176     }
2177     if (connectFailListCache.size() >= WIFI_MAX_BLA_LIST_NUM) {
2178         int64_t earliestTime = std::numeric_limits<int64_t>::max();
2179         std::string delBssid;
2180         for (auto iter = connectFailListCache.begin(); iter != connectFailListCache.end(); ++iter) {
2181             if (iter->second.updateTime < earliestTime) {
2182                 delBssid = iter->first;
2183                 earliestTime = iter->second.updateTime;
2184             }
2185         }
2186         WifiConfigCenter::GetInstance().RemoveWifiConnectFailListCache(delBssid);
2187     }
2188 }
2189 
SetHttpMonitorStatus(bool isHttpReachable)2190 void SelfCureStateMachine::SetHttpMonitorStatus(bool isHttpReachable)
2191 {
2192     m_httpDetectResponse = true;
2193     mIsHttpReachable = isHttpReachable;
2194 }
2195 
GetCurSignalLevel()2196 int SelfCureStateMachine::GetCurSignalLevel()
2197 {
2198     WifiLinkedInfo linkedInfo;
2199     WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo);
2200     int signalLevel = WifiSettings::GetInstance().GetSignalLevel(linkedInfo.rssi, linkedInfo.band, m_instId);
2201     WIFI_LOGD("GetCurSignalLevel, signalLevel : %{public}d", signalLevel);
2202     return signalLevel;
2203 }
2204 
IsHttpReachable()2205 bool SelfCureStateMachine::IsHttpReachable()
2206 {
2207     WIFI_LOGI("IsHttpReachable network detect start");
2208     m_httpDetectResponse = false;
2209     if (mNetWorkDetect == nullptr) {
2210         WIFI_LOGI("mNetWorkDetect");
2211         return mIsHttpReachable;
2212     }
2213     mNetWorkDetect->StartWifiDetection();
2214     int64_t timeOut = GetNowMilliSeconds() + HTTP_DETECT_TIMEOUT;
2215     while (timeOut > GetNowMilliSeconds()) {
2216         if (m_httpDetectResponse) {
2217             m_httpDetectResponse = false;
2218             break;
2219         }
2220         usleep(HTTP_DETECT_USLEEP_TIME);
2221     }
2222     WIFI_LOGI("IsHttpReachable network detect end");
2223     return mIsHttpReachable;
2224 }
2225 
TransIpAddressToVec(std::string addr)2226 std::vector<uint32_t> SelfCureStateMachine::TransIpAddressToVec(std::string addr)
2227 {
2228     if (addr.empty()) {
2229         WIFI_LOGE("addr is empty");
2230         return {0, 0, 0, 0};
2231     }
2232     size_t pos = 0;
2233     std::vector<uint32_t> currAddr;
2234     while ((pos = addr.find('.')) != std::string::npos) {
2235         std::string addTmp = addr.substr(0, pos);
2236         currAddr.push_back(CheckDataLegal(addTmp));
2237         addr.erase(0, pos + 1);
2238     }
2239     currAddr.push_back(CheckDataLegal(addr));
2240     if (currAddr.size() != IP_ADDR_SIZE) {
2241         WIFI_LOGE("TransIpAddressToVec failed");
2242         return {0, 0, 0, 0};
2243     }
2244     return currAddr;
2245 }
2246 
TransVecToIpAddress(const std::vector<uint32_t> & vec)2247 std::string SelfCureStateMachine::TransVecToIpAddress(const std::vector<uint32_t>& vec)
2248 {
2249     std::string address = "";
2250     if (vec.size() != IP_ADDR_SIZE) {
2251         return address;
2252     }
2253     std::ostringstream stream;
2254     stream << vec[VEC_POS_0] << "." << vec[VEC_POS_1] << "." << vec[VEC_POS_2] << "." << vec[VEC_POS_3];
2255     address = stream.str();
2256     return address;
2257 }
2258 
GetLegalIpConfiguration(IpInfo & dhcpResults)2259 int SelfCureStateMachine::GetLegalIpConfiguration(IpInfo &dhcpResults)
2260 {
2261     WifiConfigCenter::GetInstance().GetIpInfo(dhcpResults);
2262     if ((dhcpResults.gateway != 0) && (dhcpResults.ipAddress != 0)) {
2263         std::string gateway = IpTools::ConvertIpv4Address(dhcpResults.gateway);
2264         std::string initialIpAddr = IpTools::ConvertIpv4Address(dhcpResults.ipAddress);
2265         int tryTimes = TRY_TIMES;
2266         int testCnt = 0;
2267         std::vector<std::string> conflictedIpAddr;
2268         std::string testIpAddr = initialIpAddr;
2269         /** find unconflicted ip */
2270         while (testCnt++ < tryTimes) {
2271             conflictedIpAddr.push_back(testIpAddr);
2272             testIpAddr = SelfCureStateMachine::GetNextIpAddr(gateway, initialIpAddr, conflictedIpAddr);
2273             if (DoSlowArpTest(testIpAddr)) {
2274                 WIFI_LOGI("GetLegalIpConfiguration, find a new unconflicted one.");
2275                 std::string newIpAddress = testIpAddr;
2276                 WIFI_LOGI("newIpAddress, newIpAddress = %{private}s", newIpAddress.c_str());
2277                 dhcpResults.ipAddress = IpTools::ConvertIpv4Address(newIpAddress);
2278                 return 0;
2279             }
2280         }
2281         /** there is no unconflicted ip, use 156 as static ip */
2282         uint32_t newIpAddr = STATIC_IP_ADDR;
2283         std::vector<uint32_t> oldIpAddr = TransIpAddressToVec(IpTools::ConvertIpv4Address(dhcpResults.ipAddress));
2284         if (oldIpAddr.size() != IP_ADDR_SIZE) {
2285             return -1;
2286         }
2287         oldIpAddr[VEC_POS_3] = newIpAddr;
2288         std::string newIpAddress = TransVecToIpAddress(oldIpAddr);
2289         dhcpResults.ipAddress = IpTools::ConvertIpv4Address(newIpAddress);
2290         return 0;
2291     }
2292     return -1;
2293 }
2294 
CanArpReachable()2295 bool SelfCureStateMachine::CanArpReachable()
2296 {
2297     ArpChecker arpChecker;
2298     std::string macAddress;
2299     WifiConfigCenter::GetInstance().GetMacAddress(macAddress, m_instId);
2300     IpInfo ipInfo;
2301     WifiConfigCenter::GetInstance().GetIpInfo(ipInfo, m_instId);
2302     std::string ipAddress = IpTools::ConvertIpv4Address(ipInfo.ipAddress);
2303     std::string ifName = WifiConfigCenter::GetInstance().GetStaIfaceName();
2304     if (ipInfo.gateway == 0) {
2305         WIFI_LOGE("gateway is null");
2306         return false;
2307     }
2308     std::string gateway = IpTools::ConvertIpv4Address(ipInfo.gateway);
2309     uint64_t arpRtt = 0;
2310     arpChecker.Start(ifName, macAddress, ipAddress, gateway);
2311     for (int i = 0; i < DEFAULT_SLOW_NUM_ARP_PINGS; i++) {
2312         if (arpChecker.DoArpCheck(MAX_ARP_DNS_CHECK_TIME, true, arpRtt)) {
2313             WriteArpInfoHiSysEvent(arpRtt, 0);
2314             return true;
2315         }
2316     }
2317     WriteArpInfoHiSysEvent(arpRtt, 1);
2318     return false;
2319 }
2320 
DoSlowArpTest(const std::string & testIpAddr)2321 bool SelfCureStateMachine::DoSlowArpTest(const std::string& testIpAddr)
2322 {
2323     ArpChecker arpChecker;
2324     std::string macAddress;
2325     WifiConfigCenter::GetInstance().GetMacAddress(macAddress, m_instId);
2326     std::string ipAddress = testIpAddr;
2327     std::string ifName = WifiConfigCenter::GetInstance().GetStaIfaceName();
2328     IpInfo ipInfo;
2329     std::string gateway = IpTools::ConvertIpv4Address(ipInfo.gateway);
2330     arpChecker.Start(ifName, macAddress, ipAddress, gateway);
2331     for (int i = 0; i < DEFAULT_SLOW_NUM_ARP_PINGS; i++) {
2332         if (arpChecker.DoArpCheck(MAX_ARP_DNS_CHECK_TIME, false)) {
2333             return true;
2334         }
2335     }
2336     return false;
2337 }
2338 
DoArpTest(std::string & ipAddress,std::string & gateway)2339 bool SelfCureStateMachine::DoArpTest(std::string& ipAddress, std::string& gateway)
2340 {
2341     ArpChecker arpChecker;
2342     std::string macAddress;
2343     WifiConfigCenter::GetInstance().GetMacAddress(macAddress, m_instId);
2344     std::string ifName = WifiConfigCenter::GetInstance().GetStaIfaceName();
2345     arpChecker.Start(ifName, macAddress, ipAddress, gateway);
2346     return arpChecker.DoArpCheck(MAX_ARP_DNS_CHECK_TIME, true);
2347 }
2348 
GetNextIpAddr(const std::string & gateway,const std::string & currentAddr,const std::vector<std::string> & testedAddr)2349 std::string SelfCureStateMachine::GetNextIpAddr(const std::string& gateway, const std::string& currentAddr,
2350                                                 const std::vector<std::string>& testedAddr)
2351 {
2352     std::vector<uint32_t> ipAddr;
2353     if (gateway.empty() || currentAddr.empty() || testedAddr.size() ==0) {
2354         WIFI_LOGI("gateway is empty or currentAddr is empty or testedAddr.size() == 0");
2355         return "";
2356     }
2357     uint32_t newIp = 0;
2358     uint32_t getCnt = 1;
2359     ipAddr = TransIpAddressToVec(currentAddr);
2360     uint32_t iMAX = 250;
2361     uint32_t iMIN = 101;
2362     while (getCnt++ < GET_NEXT_IP_MAC_CNT) {
2363         std::vector<uint32_t> gwAddr;
2364         bool reduplicate = false;
2365         time_t now = time(nullptr);
2366         if (now >= 0) {
2367             srand(now);
2368         }
2369         uint32_t randomNum = 0;
2370         uint32_t fd = open("/dev/random", O_RDONLY); /* Obtain the random number by reading /dev/random */
2371         if (fd > 0) {
2372             read(fd, &randomNum, sizeof(uint32_t));
2373         }
2374         close(fd);
2375         uint32_t rand = (randomNum > 0 ? randomNum : -randomNum) % 100;
2376         newIp = rand + iMIN;
2377         gwAddr = TransIpAddressToVec(gateway);
2378         if (newIp == (gwAddr[VEC_POS_3] & 0xFF) || newIp == (ipAddr[VEC_POS_3] & 0xFF)) {
2379             continue;
2380         }
2381         for (size_t i = 0; i < testedAddr.size(); i++) {
2382             std::vector<uint32_t> tmp = TransIpAddressToVec(testedAddr[i]);
2383             if (newIp == (tmp[VEC_POS_3] & 0xFF)) {
2384                 reduplicate = true;
2385                 break;
2386             }
2387         }
2388         if (newIp > 0 && !reduplicate) {
2389             break;
2390         }
2391     }
2392     if (newIp > 1 && newIp <= iMAX && getCnt < GET_NEXT_IP_MAC_CNT) {
2393         ipAddr[VEC_POS_3] = newIp;
2394         return TransVecToIpAddress(ipAddr);
2395     }
2396     return "";
2397 }
2398 
IsIpAddressInvalid()2399 bool SelfCureStateMachine::IsIpAddressInvalid()
2400 {
2401     IpInfo dhcpInfo;
2402     std::vector<uint32_t> currAddr;
2403     WifiConfigCenter::GetInstance().GetIpInfo(dhcpInfo);
2404     if (dhcpInfo.ipAddress != 0) {
2405         std::string addr = IpTools::ConvertIpv4Address(dhcpInfo.ipAddress);
2406         currAddr = TransIpAddressToVec(addr);
2407         if ((currAddr.size() == IP_ADDR_SIZE)) {
2408             uint32_t intCurrAddr3 = (currAddr[VEC_POS_3] & 0xFF);
2409             uint32_t netmaskLenth =
2410                 static_cast<uint32_t>(IpTools::GetMaskLength(IpTools::ConvertIpv4Address(dhcpInfo.netmask)));
2411             bool ipEqualsGw = (dhcpInfo.ipAddress == dhcpInfo.gateway);
2412             bool invalidIp = (intCurrAddr3 == 0 || intCurrAddr3 == 1 || intCurrAddr3 == IP_ADDR_LIMIT);
2413             if ((ipEqualsGw) || ((netmaskLenth == NET_MASK_LENGTH) && (invalidIp))) {
2414                 WIFI_LOGI("current rcvd ip is invalid, maybe no internet access, need to comfirm and cure it.");
2415                 return true;
2416             }
2417         }
2418     }
2419     return false;
2420 }
2421 
TransStrToVec(std::string str,char c)2422 std::vector<std::string> SelfCureStateMachine::TransStrToVec(std::string str, char c)
2423 {
2424     size_t pos = 0;
2425     std::vector<std::string> vec;
2426     while ((pos = str.find(c)) != std::string::npos) {
2427         vec.push_back(str.substr(0, pos));
2428         str.erase(0, pos + 1);
2429     }
2430     vec.push_back(str);
2431     return vec;
2432 }
2433 
IsUseFactoryMac()2434 bool SelfCureStateMachine::IsUseFactoryMac()
2435 {
2436     WIFI_LOGI("enter %{public}s", __FUNCTION__);
2437     WifiLinkedInfo wifiLinkedInfo;
2438     std::string currMacAddress;
2439     std::string realMacAddress;
2440     WifiConfigCenter::GetInstance().GetMacAddress(currMacAddress);
2441     WifiSettings::GetInstance().GetRealMacAddress(realMacAddress);
2442     if (!currMacAddress.empty() && !realMacAddress.empty() && currMacAddress == realMacAddress) {
2443         WIFI_LOGI("use factory mac address currently.");
2444         return true;
2445     }
2446     return false;
2447 }
2448 
IsSameEncryptType(const std::string & scanInfoKeymgmt,const std::string & deviceKeymgmt)2449 bool SelfCureStateMachine::IsSameEncryptType(const std::string& scanInfoKeymgmt, const std::string& deviceKeymgmt)
2450 {
2451     if (deviceKeymgmt == "WPA-PSK") {
2452         return scanInfoKeymgmt.find("PSK") != std::string::npos;
2453     } else if (deviceKeymgmt == "WPA-EAP") {
2454         return scanInfoKeymgmt.find("EAP") != std::string::npos;
2455     } else if (deviceKeymgmt == "SAE") {
2456         return scanInfoKeymgmt.find("SAE") != std::string::npos;
2457     } else if (deviceKeymgmt == "NONE") {
2458         return (scanInfoKeymgmt.find("PSK") == std::string::npos) &&
2459                (scanInfoKeymgmt.find("EAP") == std::string::npos) && (scanInfoKeymgmt.find("SAE") == std::string::npos);
2460     } else {
2461         return false;
2462     }
2463 }
2464 
GetBssidCounter(const std::vector<WifiScanInfo> & scanResults)2465 int SelfCureStateMachine::GetBssidCounter(const std::vector<WifiScanInfo> &scanResults)
2466 {
2467     WifiLinkedInfo wifiLinkedInfo;
2468     WifiDeviceConfig config;
2469     int counter = 0;
2470     if (scanResults.empty()) {
2471         WIFI_LOGI("scanResults ie empty.");
2472         return 0;
2473     }
2474     WifiConfigCenter::GetInstance().GetLinkedInfo(wifiLinkedInfo);
2475     std::string currentSsid = wifiLinkedInfo.ssid;
2476     WifiSettings::GetInstance().GetDeviceConfig(wifiLinkedInfo.networkId, config);
2477     std::string configKey = config.keyMgmt;
2478     if (currentSsid.empty() || configKey.empty()) {
2479         return 0;
2480     }
2481     for (WifiScanInfo nextResult : scanResults) {
2482         std::string scanSsid = nextResult.ssid;
2483         std::string capabilities = nextResult.capabilities;
2484         if (currentSsid == scanSsid && IsSameEncryptType(capabilities, configKey)) {
2485             counter += 1;
2486         }
2487     }
2488     return counter;
2489 }
2490 
IsNeedWifiReassocUseDeviceMac()2491 bool SelfCureStateMachine::IsNeedWifiReassocUseDeviceMac()
2492 {
2493     WIFI_LOGI("enter %{public}s", __FUNCTION__);
2494     WifiDeviceConfig config;
2495     if (GetCurrentWifiDeviceConfig(config) != WIFI_OPT_SUCCESS) {
2496         WIFI_LOGE("%{public}s: GetCurrentWifiDeviceConfig failed!", __FUNCTION__);
2497         return false;
2498     }
2499 #ifdef SUPPORT_LOCAL_RANDOM_MAC
2500     WIFI_LOGD("random MAC address is supported!");
2501     if (!CanArpReachable()) {
2502         WIFI_LOGI("arp is not reachable!");
2503         return false;
2504     }
2505     if (IsUseFactoryMac()) {
2506         WIFI_LOGI("use factory mac now!");
2507         return false;
2508     }
2509     std::vector<WifiScanInfo> scanResults;
2510     WifiConfigCenter::GetInstance().GetWifiScanConfig()->GetScanInfoList(scanResults);
2511     if (GetBssidCounter(scanResults) < MULTI_BSSID_NUM) {
2512         WIFI_LOGI("not multi bssid condition!");
2513         return false;
2514     }
2515     bool hasInternetEver = NetworkStatusHistoryManager::HasInternetEverByHistory(GetNetworkStatusHistory());
2516     bool isPortalNetwork = config.isPortal;
2517     if (hasInternetEver || isPortalNetwork) {
2518         WIFI_LOGI("hasinternet or portal network, don't to reassoc with factory mac!");
2519         return false;
2520     }
2521     WifiSelfCureHistoryInfo selfCureInfo;
2522     std::string internetSelfCureHistory = GetSelfCureHistoryInfo();
2523     String2InternetSelfCureHistoryInfo(internetSelfCureHistory, selfCureInfo);
2524     if (selfCureInfo.randMacSelfCureConnectFailedCnt > SELF_CURE_RAND_MAC_CONNECT_FAIL_MAX_COUNT ||
2525         selfCureInfo.randMacSelfCureFailedCnt > SELF_CURE_RAND_MAC_MAX_COUNT) {
2526         WIFI_LOGI("has connect fail three times or randMac self cure fail 20 times!");
2527         return false;
2528     }
2529     auto now = std::chrono::system_clock::now();
2530     int64_t currentMs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
2531     int64_t lastConnectFailMs = selfCureInfo.lastRandMacSelfCureConnectFailedCntTs;
2532     if ((currentMs - lastConnectFailMs) < RAND_MAC_FAIL_EXPIRATION_AGE_MILLIS) {
2533         WIFI_LOGI("Too close to the last connection failure time return");
2534         return false;
2535     }
2536     return true;
2537 #endif
2538     WIFI_LOGI("random MAC address is not supported!");
2539     return false;
2540 }
2541 
String2InternetSelfCureHistoryInfo(const std::string selfCureHistory,WifiSelfCureHistoryInfo & info)2542 int SelfCureStateMachine::String2InternetSelfCureHistoryInfo(const std::string selfCureHistory,
2543                                                              WifiSelfCureHistoryInfo &info)
2544 {
2545     WifiSelfCureHistoryInfo selfCureHistoryInfo;
2546     if (selfCureHistory.empty()) {
2547         WIFI_LOGE("InternetSelfCureHistoryInfo is empty!");
2548         info = selfCureHistoryInfo;
2549         return -1;
2550     }
2551     std::vector<std::string> histories = TransStrToVec(selfCureHistory, '|');
2552     if (histories.size() != SELFCURE_HISTORY_LENGTH) {
2553         WIFI_LOGE("self cure history length = %{public}lu", (unsigned long) histories.size());
2554         info = selfCureHistoryInfo;
2555         return -1;
2556     }
2557     if (SetSelfCureFailInfo(selfCureHistoryInfo, histories, SELFCURE_FAIL_LENGTH) != 0) {
2558         WIFI_LOGE("set self cure history information failed!");
2559     }
2560     if (SetSelfCureConnectFailInfo(selfCureHistoryInfo, histories, SELFCURE_FAIL_LENGTH) != 0) {
2561         WIFI_LOGE("set self cure connect history information failed!");
2562     }
2563     info = selfCureHistoryInfo;
2564     return 0;
2565 }
2566 
SetSelfCureFailInfo(WifiSelfCureHistoryInfo & info,std::vector<std::string> & histories,int cnt)2567 int SelfCureStateMachine::SetSelfCureFailInfo(WifiSelfCureHistoryInfo &info,
2568                                               std::vector<std::string>& histories, int cnt)
2569 {
2570     if (histories.empty() || histories.size() != SELFCURE_HISTORY_LENGTH || cnt != SELFCURE_FAIL_LENGTH) {
2571         WIFI_LOGE("SetSelfCureFailInfo return");
2572         return -1;
2573     }
2574     // 0 to 12 is history subscript, which record the selfcure failed info, covert array to calss member
2575     for (int i = 0; i < cnt; i++) {
2576         if (i == 0) {
2577             info.dnsSelfCureFailedCnt = CheckDataLegal(histories[i]);
2578         } else if (i == POS_DNS_FAILED_TS) {
2579             info.lastDnsSelfCureFailedTs = CheckDataTolonglong(histories[i]);
2580         } else if (i == POS_RENEW_DHCP_FAILED_CNT) {
2581             info.renewDhcpSelfCureFailedCnt = CheckDataLegal(histories[i]);
2582         } else if (i == POS_RENEW_DHCP_FAILED_TS) {
2583             info.lastRenewDhcpSelfCureFailedTs = CheckDataTolonglong(histories[i]);
2584         } else if (i == POS_STATIC_IP_FAILED_CNT) {
2585             info.staticIpSelfCureFailedCnt = CheckDataLegal(histories[i]);
2586         } else if (i == POS_STATIC_IP_FAILED_TS) {
2587             info.lastStaticIpSelfCureFailedTs = CheckDataTolonglong(histories[i]);
2588         } else if (i == POS_REASSOC_FAILED_CNT) {
2589             info.reassocSelfCureFailedCnt = CheckDataLegal(histories[i]);
2590         } else if (i == POS_REASSOC_FAILED_TS) {
2591             info.lastReassocSelfCureFailedTs = CheckDataTolonglong(histories[i]);
2592         } else if (i == POS_RANDMAC_FAILED_CNT) {
2593             info.randMacSelfCureFailedCnt = CheckDataLegal(histories[i]);
2594         } else if (i == POS_RANDMAC_FAILED_TS) {
2595             info.lastRandMacSelfCureFailedCntTs = CheckDataTolonglong(histories[i]);
2596         } else if (i == POS_RESET_FAILED_CNT) {
2597             info.resetSelfCureFailedCnt = CheckDataLegal(histories[i]);
2598         } else if (i == POS_RESET_FAILED_TS) {
2599             info.lastResetSelfCureFailedTs = CheckDataTolonglong(histories[i]);
2600         } else {
2601             WIFI_LOGI("exception happen.");
2602         }
2603     }
2604     return 0;
2605 }
2606 
SetSelfCureConnectFailInfo(WifiSelfCureHistoryInfo & info,std::vector<std::string> & histories,int cnt)2607 int SelfCureStateMachine::SetSelfCureConnectFailInfo(WifiSelfCureHistoryInfo &info,
2608                                                      std::vector<std::string>& histories, int cnt)
2609 {
2610     if (histories.empty() || histories.size() != SELFCURE_HISTORY_LENGTH || cnt != SELFCURE_FAIL_LENGTH) {
2611         WIFI_LOGE("SetSelfCureFailInfo return");
2612         return -1;
2613     }
2614     // 12 to 17 is history subscript, which record the selfcure connect failed info, covert array to calss member
2615     for (int i = cnt; i < SELFCURE_HISTORY_LENGTH; i++) {
2616         if (i == POS_REASSOC_CONNECT_FAILED_CNT) {
2617             info.reassocSelfCureConnectFailedCnt = CheckDataLegal(histories[i]);
2618         } else if (i == POS_REASSOC_CONNECT_FAILED_TS) {
2619             info.lastReassocSelfCureConnectFailedTs = CheckDataTolonglong(histories[i]);
2620         } else if (i == POS_RANDMAC_CONNECT_FAILED_CNT) {
2621             info.randMacSelfCureConnectFailedCnt = CheckDataLegal(histories[i]);
2622         } else if (i == POS_RANDMAC_CONNECT_FAILED_TS) {
2623             info.lastRandMacSelfCureConnectFailedCntTs = CheckDataTolonglong(histories[i]);
2624         } else if (i == POS_RESET_CONNECT_FAILED_CNT) {
2625             info.resetSelfCureConnectFailedCnt = CheckDataLegal(histories[i]);
2626         } else if (i == POS_RESET_CONNECT_FAILED_TS) {
2627             info.lastResetSelfCureConnectFailedTs = CheckDataTolonglong(histories[i]);
2628         } else {
2629             WIFI_LOGI("exception happen.");
2630         }
2631     }
2632     return 0;
2633 }
2634 
IsSuppOnCompletedState()2635 bool SelfCureStateMachine::IsSuppOnCompletedState()
2636 {
2637     WifiLinkedInfo linkedInfo;
2638     WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo);
2639     if (linkedInfo.supplicantState == SupplicantState::COMPLETED) {
2640         return true;
2641     }
2642     return false;
2643 }
2644 
IfPeriodicArpDetection()2645 bool SelfCureStateMachine::IfPeriodicArpDetection()
2646 {
2647     int curSignalLevel = GetCurSignalLevel();
2648     int state = WifiConfigCenter::GetInstance().GetScreenState();
2649     WIFI_LOGD("IfPeriodicArpDetection, GetScreenState: %{public}d", state);
2650     return (curSignalLevel >= SIGNAL_LEVEL_2) && (!selfCureOnGoing) && (IsSuppOnCompletedState()) &&
2651            (state == MODE_STATE_OPEN);
2652 }
2653 
PeriodicArpDetection()2654 void SelfCureStateMachine::PeriodicArpDetection()
2655 {
2656     StopTimer(WIFI_CURE_CMD_PERIODIC_ARP_DETECTED);
2657     if (!IfPeriodicArpDetection()) {
2658         WIFI_LOGD("PeriodicArpDetection, no need detection, just jump");
2659         MessageExecutedLater(WIFI_CURE_CMD_PERIODIC_ARP_DETECTED, DEFAULT_ARP_DETECTED_MS);
2660         return;
2661     }
2662     if (!CanArpReachable()) {
2663         arpDetectionFailedCnt++;
2664         WIFI_LOGI("Periodic Arp Detection failed, times : %{public}d", arpDetectionFailedCnt);
2665         if (arpDetectionFailedCnt == ARP_DETECTED_FAILED_COUNT) {
2666             SendMessage(WIFI_CURE_CMD_ARP_FAILED_DETECTED);
2667         } else if (arpDetectionFailedCnt > 0 && arpDetectionFailedCnt < ARP_DETECTED_FAILED_COUNT) {
2668             MessageExecutedLater(WIFI_CURE_CMD_PERIODIC_ARP_DETECTED, FAST_ARP_DETECTED_MS);
2669             return;
2670         }
2671     } else {
2672         WIFI_LOGI("Periodic Arp Detection success");
2673         arpDetectionFailedCnt = 0;
2674     }
2675     MessageExecutedLater(WIFI_CURE_CMD_PERIODIC_ARP_DETECTED, DEFAULT_ARP_DETECTED_MS);
2676 }
2677 
ShouldTransToWifi6SelfCure(InternalMessagePtr msg,std::string currConnectedBssid)2678 bool SelfCureStateMachine::ShouldTransToWifi6SelfCure(InternalMessagePtr msg, std::string currConnectedBssid)
2679 {
2680     WIFI_LOGI("enter ShouldTransToWifi6SelfCure");
2681     if (currConnectedBssid.empty() || msg== nullptr) {
2682         WIFI_LOGE("currConnectedBssid is empty or msg is nullptr");
2683         return false;
2684     }
2685     if (!IsWifi6Network(currConnectedBssid) || isWifi6ArpSuccess || GetCurrentRssi() < MIN_VAL_LEVEL_3) {
2686         return false;
2687     }
2688     int32_t arg = internetUnknown ? 1 : 0;
2689     std::map<std::string, WifiCategoryBlackListInfo> wifi6BlackListCache;
2690     WifiConfigCenter::GetInstance().GetWifiCategoryBlackListCache(EVENT_AX_BLA_LIST, wifi6BlackListCache);
2691     if (wifi6BlackListCache.find(currConnectedBssid) == wifi6BlackListCache.end()) {
2692         MessageExecutedLater(WIFI_CURE_CMD_WIFI6_SELFCURE, arg, msg->GetParam2(), SELF_CURE_DELAYED_MS);
2693         SwitchState(pWifi6SelfCureState);
2694         return true;
2695     } else {
2696         auto iter = wifi6BlackListCache.find(currConnectedBssid);
2697         if (iter->second.actionType == 0) {
2698             MessageExecutedLater(WIFI_CURE_CMD_WIFI6_BACKOFF_SELFCURE, arg, msg->GetParam2(), SELF_CURE_DELAYED_MS);
2699             SwitchState(pWifi6SelfCureState);
2700             return true;
2701         } else {
2702             WIFI_LOGD("don't need to do wifi6 selfcure");
2703         }
2704     }
2705     return false;
2706 }
2707 
GetWifi7SelfCureType(int connectFailTimes,WifiLinkedInfo & info)2708 int SelfCureStateMachine::GetWifi7SelfCureType(int connectFailTimes, WifiLinkedInfo &info)
2709 {
2710     std::vector<WifiScanInfo> scanResults;
2711     WifiConfigCenter::GetInstance().GetWifiScanConfig()->GetScanInfoList(scanResults);
2712     int scanRssi = GetScanRssi(info.bssid, scanResults);
2713     WIFI_LOGI("GetWifi7SelfCureType scanRssi %{public}d", scanRssi);
2714     if ((info.supportedWifiCategory == WifiCategory::WIFI7
2715         || info.supportedWifiCategory == WifiCategory::WIFI7_PLUS)
2716         && connectFailTimes >= SELF_CURE_WIFI7_CONNECT_FAIL_MAX_COUNT
2717         && info.rssi >= MIN_VAL_LEVEL_3) {
2718             return WIFI7_SELFCURE_DISCONNECTED;
2719     }
2720     return WIFI7_NO_SELFCURE;
2721 }
2722 
ShouldTransToWifi7SelfCure(WifiLinkedInfo & info)2723 void SelfCureStateMachine::ShouldTransToWifi7SelfCure(WifiLinkedInfo &info)
2724 {
2725     WIFI_LOGI("enter ShouldTransToWifi7SelfCure");
2726     if (info.bssid.empty()) {
2727         return;
2728     }
2729     std::map<std::string, WifiCategoryConnectFailInfo> connectFailListCache;
2730     WifiConfigCenter::GetInstance().GetWifiConnectFailListCache(connectFailListCache);
2731     auto iterConnectFail = connectFailListCache.find(info.bssid);
2732     if (iterConnectFail == connectFailListCache.end()) {
2733         WIFI_LOGE("no bssid in connectFailListCache");
2734         return;
2735     }
2736     int wifi7SelfCureType = WIFI7_NO_SELFCURE;
2737     wifi7SelfCureType = GetWifi7SelfCureType(iterConnectFail->second.connectFailTimes, info);
2738     if (wifi7SelfCureType == WIFI7_SELFCURE_DISCONNECTED) {
2739         std::map<std::string, WifiCategoryBlackListInfo> blackListCache;
2740         WifiConfigCenter::GetInstance().GetWifiCategoryBlackListCache(EVENT_BE_BLA_LIST, blackListCache);
2741         auto iterBlackList = blackListCache.find(info.bssid);
2742         if (iterBlackList == blackListCache.end()) {
2743             WIFI_LOGI("start wifi7 with mld backoff");
2744             SendMessage(WIFI_CURE_CMD_WIFI7_MLD_BACKOFF, info);
2745         } else if (iterBlackList->second.actionType == ACTION_TYPE_MLD) {
2746             WIFI_LOGI("start wifi7 without mld backoff");
2747             SendMessage(WIFI_CURE_CMD_WIFI7_NON_MLD_BACKOFF, info);
2748         } else if (iterBlackList->second.actionType == ACTION_TYPE_WIFI7
2749             && iterConnectFail->second.actionType == ACTION_TYPE_RECOVER_FAIL) {
2750             WIFI_LOGI("start wifi7 selfcure fail recover");
2751             SendMessage(WIFI_CURE_CMD_WIFI7_BACKOFF_RECOVER, info);
2752         }
2753     } else {
2754         WIFI_LOGD("don't need to do wifi7 selfcure");
2755     }
2756 }
2757 
GetScanRssi(std::string currentBssid,const std::vector<WifiScanInfo> scanResults)2758 int SelfCureStateMachine::GetScanRssi(std::string currentBssid, const std::vector<WifiScanInfo> scanResults)
2759 {
2760     for (WifiScanInfo nextResult : scanResults) {
2761         if (currentBssid == nextResult.bssid) {
2762             return nextResult.rssi;
2763         }
2764     }
2765     return CURRENT_RSSI_INIT;
2766 }
2767 
GetCurrentRssi()2768 int SelfCureStateMachine::GetCurrentRssi()
2769 {
2770     WifiLinkedInfo wifiLinkedInfo;
2771     if (WifiConfigCenter::GetInstance().GetLinkedInfo(wifiLinkedInfo) != 0) {
2772         WIFI_LOGE("Get current link info failed!");
2773     }
2774     int currentRssi = wifiLinkedInfo.rssi;
2775     return currentRssi;
2776 }
2777 
GetCurrentBssid()2778 std::string SelfCureStateMachine::GetCurrentBssid()
2779 {
2780     WifiDeviceConfig config;
2781     if (GetCurrentWifiDeviceConfig(config) != WIFI_OPT_SUCCESS) {
2782         WIFI_LOGE("Get current bssid failed!");
2783         return "";
2784     }
2785     std::string currentBssid = config.bssid;
2786     return currentBssid;
2787 }
2788 
IsWifi6Network(std::string currConnectedBssid)2789 bool SelfCureStateMachine::IsWifi6Network(std::string currConnectedBssid)
2790 {
2791     if (currConnectedBssid.empty()) {
2792         WIFI_LOGE("currConnectedBssid is empty");
2793         return false;
2794     }
2795     WifiLinkedInfo wifiLinkedInfo;
2796     if (WifiConfigCenter::GetInstance().GetLinkedInfo(wifiLinkedInfo) != 0) {
2797         WIFI_LOGE("Get current link info failed!");
2798     }
2799     if (wifiLinkedInfo.supportedWifiCategory == WifiCategory::WIFI6 ||
2800         wifiLinkedInfo.supportedWifiCategory == WifiCategory::WIFI6_PLUS) {
2801         WIFI_LOGI("current network is wifi6 network");
2802         return true;
2803     }
2804     std::map<std::string, WifiCategoryBlackListInfo> wifi7BlackListCache;
2805     WifiConfigCenter::GetInstance().GetWifiCategoryBlackListCache(EVENT_BE_BLA_LIST, wifi7BlackListCache);
2806     auto iter = wifi7BlackListCache.find(currConnectedBssid);
2807     if (iter != wifi7BlackListCache.end() &&
2808         iter->second.actionType == ACTION_TYPE_WIFI7 &&
2809         (wifiLinkedInfo.supportedWifiCategory == WifiCategory::WIFI7 ||
2810         wifiLinkedInfo.supportedWifiCategory == WifiCategory::WIFI7_PLUS)) {
2811         WIFI_LOGI("current network is wifi7 network but in wifi6 mode");
2812         return true;
2813     }
2814     return false;
2815 }
2816 
IfP2pConnected()2817 bool SelfCureStateMachine::IfP2pConnected()
2818 {
2819     WifiP2pLinkedInfo linkedInfo;
2820     WifiConfigCenter::GetInstance().GetP2pInfo(linkedInfo);
2821     WIFI_LOGI("P2p connection state : %{public}d", linkedInfo.GetConnectState());
2822     return linkedInfo.GetConnectState() == P2pConnectedState::P2P_CONNECTED;
2823 }
2824 
GetAuthType()2825 std::string SelfCureStateMachine::GetAuthType()
2826 {
2827     WifiDeviceConfig config;
2828     if (GetCurrentWifiDeviceConfig(config) != WIFI_OPT_SUCCESS) {
2829         WIFI_LOGE("GetAuthType failed!");
2830         return "";
2831     }
2832     std::string keyMgmt = config.keyMgmt;
2833     return keyMgmt;
2834 }
2835 
GetIpAssignment(AssignIpMethod & ipAssignment)2836 int SelfCureStateMachine::GetIpAssignment(AssignIpMethod &ipAssignment)
2837 {
2838     WifiDeviceConfig config;
2839     if (GetCurrentWifiDeviceConfig(config) != WIFI_OPT_SUCCESS) {
2840         WIFI_LOGE("GetIpAssignment failed!");
2841         return -1;
2842     }
2843     ipAssignment = config.wifiIpConfig.assignMethod;
2844     return 0;
2845 }
2846 
GetLastHasInternetTime()2847 time_t SelfCureStateMachine::GetLastHasInternetTime()
2848 {
2849     WifiDeviceConfig config;
2850     if (GetCurrentWifiDeviceConfig(config) != WIFI_OPT_SUCCESS) {
2851         WIFI_LOGE("GetLastHasInternetTime failed!");
2852         return -1;
2853     }
2854     time_t lastHasInternetTime = config.lastHasInternetTime;
2855     return lastHasInternetTime;
2856 }
2857 
GetNetworkStatusHistory()2858 uint32_t SelfCureStateMachine::GetNetworkStatusHistory()
2859 {
2860     WifiDeviceConfig config;
2861     if (GetCurrentWifiDeviceConfig(config) != WIFI_OPT_SUCCESS) {
2862         WIFI_LOGE("GetNetworkStatusHistory failed!");
2863         return 0;
2864     }
2865     uint32_t networkStatusHistory = config.networkStatusHistory;
2866     return networkStatusHistory;
2867 }
2868 
GetSelfCureHistoryInfo()2869 std::string SelfCureStateMachine::GetSelfCureHistoryInfo()
2870 {
2871     WifiDeviceConfig config;
2872     if (GetCurrentWifiDeviceConfig(config) != WIFI_OPT_SUCCESS) {
2873         WIFI_LOGE("GetSelfCureHistoryInfo failed!");
2874         return "";
2875     }
2876     std::string internetSelfCureHistory = config.internetSelfCureHistory;
2877     return internetSelfCureHistory;
2878 }
2879 
SetSelfCureHistoryInfo(const std::string selfCureHistory)2880 int SelfCureStateMachine::SetSelfCureHistoryInfo(const std::string selfCureHistory)
2881 {
2882     WIFI_LOGI("enter %{public}s", __FUNCTION__);
2883     if (selfCureHistory == "") {
2884         WIFI_LOGW("selfCureHistory is empty");
2885         return -1;
2886     }
2887     WifiDeviceConfig config;
2888     if (GetCurrentWifiDeviceConfig(config) != WIFI_OPT_SUCCESS) {
2889         WIFI_LOGE("SetSelfCureHistoryInfo failed!");
2890         return -1;
2891     }
2892     config.internetSelfCureHistory = selfCureHistory;
2893     WifiSettings::GetInstance().AddDeviceConfig(config);
2894     WifiSettings::GetInstance().SyncDeviceConfig();
2895     return 0;
2896 }
2897 
GetIsReassocWithFactoryMacAddress()2898 int SelfCureStateMachine::GetIsReassocWithFactoryMacAddress()
2899 {
2900     WifiDeviceConfig config;
2901     if (GetCurrentWifiDeviceConfig(config) != WIFI_OPT_SUCCESS) {
2902         WIFI_LOGE("GetIsReassocWithFactoryMacAddress failed!");
2903         return 0;
2904     }
2905     int isReassocWithFactoryMacAddress = config.isReassocSelfCureWithFactoryMacAddress;
2906     return isReassocWithFactoryMacAddress;
2907 }
2908 
IsCustNetworkSelfCure()2909 bool SelfCureStateMachine::IsCustNetworkSelfCure()
2910 {
2911     IEnhanceService *pEnhanceService = WifiServiceManager::GetInstance().GetEnhanceServiceInst();
2912     if (pEnhanceService == nullptr) {
2913         WIFI_LOGE("IsCustNetworkSelfCure get pEnhanceService service failed!");
2914         return false;
2915     }
2916     WifiDeviceConfig config;
2917     if (GetCurrentWifiDeviceConfig(config) != WIFI_OPT_SUCCESS) {
2918         return false;
2919     }
2920     if (pEnhanceService->IsHwItCustNetwork(config)) {
2921         WIFI_LOGI("dns-selfcure is not triggered on the network.");
2922         return true;
2923     }
2924     return false;
2925 }
2926 
SetIsReassocWithFactoryMacAddress(int isReassocWithFactoryMacAddress)2927 int SelfCureStateMachine::SetIsReassocWithFactoryMacAddress(int isReassocWithFactoryMacAddress)
2928 {
2929     WifiDeviceConfig config;
2930     if (GetCurrentWifiDeviceConfig(config) != WIFI_OPT_SUCCESS) {
2931         WIFI_LOGE("SetIsReassocWithFactoryMacAddress failed!");
2932         return -1;
2933     }
2934     config.isReassocSelfCureWithFactoryMacAddress = isReassocWithFactoryMacAddress;
2935     WifiSettings::GetInstance().AddDeviceConfig(config);
2936     WifiSettings::GetInstance().SyncDeviceConfig();
2937     return 0;
2938 }
2939 
GetCurrentWifiDeviceConfig(WifiDeviceConfig & config)2940 ErrCode SelfCureStateMachine::GetCurrentWifiDeviceConfig(WifiDeviceConfig &config)
2941 {
2942     WifiLinkedInfo wifiLinkedInfo;
2943     if (WifiConfigCenter::GetInstance().GetLinkedInfo(wifiLinkedInfo) != 0) {
2944         WIFI_LOGE("Get current link info failed!");
2945         return WIFI_OPT_FAILED;
2946     }
2947     if (WifiSettings::GetInstance().GetDeviceConfig(wifiLinkedInfo.networkId, config) != 0) {
2948         WIFI_LOGE("Get device config failed!");
2949         return WIFI_OPT_FAILED;
2950     }
2951     return WIFI_OPT_SUCCESS;
2952 }
2953 
AllowSelfCure(const WifiSelfCureHistoryInfo & historyInfo,int requestCureLevel)2954 bool AllowSelfCure(const WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel)
2955 {
2956     auto now = std::chrono::system_clock::now();
2957     uint64_t currentMs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
2958     if (requestCureLevel == WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC) {
2959         if ((historyInfo.reassocSelfCureConnectFailedCnt == 0) ||
2960             ((historyInfo.reassocSelfCureConnectFailedCnt >= 1) &&
2961              ((currentMs - historyInfo.lastReassocSelfCureConnectFailedTs) > DELAYED_DAYS_LOW))) {
2962             return true;
2963         }
2964     } else {
2965         if (requestCureLevel == WIFI_CURE_RESET_LEVEL_HIGH_RESET) {
2966             if ((historyInfo.resetSelfCureConnectFailedCnt == 0) ||
2967                 ((historyInfo.resetSelfCureConnectFailedCnt >= 1) &&
2968                  ((currentMs - historyInfo.lastResetSelfCureConnectFailedTs) > DELAYED_DAYS_LOW))) {
2969                 return true;
2970             }
2971         }
2972     }
2973     return false;
2974 }
2975 
DealDns(const WifiSelfCureHistoryInfo & historyInfo,int requestCureLevel,int64_t currentMs)2976 bool DealDns(const WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel, int64_t currentMs)
2977 {
2978     if (historyInfo.dnsSelfCureFailedCnt == 0 ||
2979         (historyInfo.dnsSelfCureFailedCnt == SELF_CURE_FAILED_ONE_CNT &&
2980          (currentMs - historyInfo.lastDnsSelfCureFailedTs > DELAYED_DAYS_LOW)) ||
2981         (historyInfo.dnsSelfCureFailedCnt == SELF_CURE_FAILED_TWO_CNT &&
2982          (currentMs - historyInfo.lastDnsSelfCureFailedTs > DELAYED_DAYS_MID)) ||
2983         (historyInfo.dnsSelfCureFailedCnt >= SELF_CURE_FAILED_THREE_CNT &&
2984          (currentMs - historyInfo.lastDnsSelfCureFailedTs > DELAYED_DAYS_HIGH))) {
2985         return true;
2986     }
2987     return false;
2988 }
2989 
DealRenewDhcp(const WifiSelfCureHistoryInfo & historyInfo,int requestCureLevel,int64_t currentMs)2990 bool DealRenewDhcp(const WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel, int64_t currentMs)
2991 {
2992     if (historyInfo.renewDhcpSelfCureFailedCnt >= 0) {
2993         return true;
2994     }
2995     return false;
2996 }
2997 
DealStaticIp(const WifiSelfCureHistoryInfo & historyInfo,int requestCureLevel,int64_t currentMs)2998 bool DealStaticIp(const WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel, int64_t currentMs)
2999 {
3000     if (historyInfo.staticIpSelfCureFailedCnt <= SELF_CURE_FAILED_FOUR_CNT ||
3001         (historyInfo.staticIpSelfCureFailedCnt == SELF_CURE_FAILED_FIVE_CNT &&
3002          (currentMs - historyInfo.lastStaticIpSelfCureFailedTs > DELAYED_DAYS_LOW)) ||
3003         (historyInfo.staticIpSelfCureFailedCnt == SELF_CURE_FAILED_SIX_CNT &&
3004          (currentMs - historyInfo.lastStaticIpSelfCureFailedTs > DELAYED_DAYS_MID)) ||
3005         (historyInfo.staticIpSelfCureFailedCnt >= SELF_CURE_FAILED_SEVEN_CNT &&
3006          (currentMs - historyInfo.lastStaticIpSelfCureFailedTs > DELAYED_DAYS_HIGH))) {
3007         return true;
3008     }
3009     return false;
3010 }
3011 
DealMiddleReassoc(WifiSelfCureHistoryInfo & historyInfo,int requestCureLevel,int64_t currentMs)3012 bool DealMiddleReassoc(WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel, int64_t currentMs)
3013 {
3014     if ((historyInfo.reassocSelfCureFailedCnt == 0 ||
3015         (historyInfo.reassocSelfCureFailedCnt == SELF_CURE_FAILED_ONE_CNT &&
3016          (currentMs - historyInfo.lastReassocSelfCureFailedTs > DELAYED_DAYS_LOW)) ||
3017         (historyInfo.reassocSelfCureFailedCnt == SELF_CURE_FAILED_TWO_CNT &&
3018          (currentMs - historyInfo.lastReassocSelfCureFailedTs > DELAYED_DAYS_MID)) ||
3019         (historyInfo.reassocSelfCureFailedCnt >= SELF_CURE_FAILED_THREE_CNT &&
3020          (currentMs - historyInfo.lastReassocSelfCureFailedTs > DELAYED_DAYS_HIGH))) &&
3021         AllowSelfCure(historyInfo, requestCureLevel)) {
3022         return true;
3023     }
3024     return false;
3025 }
3026 
DealRandMacReassoc(const WifiSelfCureHistoryInfo & historyInfo,int requestCureLevel,int64_t currentMs)3027 bool DealRandMacReassoc(const WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel, int64_t currentMs)
3028 {
3029     if (historyInfo.randMacSelfCureFailedCnt < SELF_CURE_RAND_MAC_MAX_COUNT) {
3030         return true;
3031     }
3032     return false;
3033 }
3034 
DealHighReset(WifiSelfCureHistoryInfo & historyInfo,int requestCureLevel,int64_t currentMs)3035 bool DealHighReset(WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel, int64_t currentMs)
3036 {
3037     if ((historyInfo.resetSelfCureFailedCnt <= SELF_CURE_FAILED_ONE_CNT ||
3038         (historyInfo.resetSelfCureFailedCnt == SELF_CURE_FAILED_TWO_CNT &&
3039          (currentMs - historyInfo.lastResetSelfCureFailedTs > DELAYED_DAYS_LOW)) ||
3040         (historyInfo.resetSelfCureFailedCnt == SELF_CURE_FAILED_THREE_CNT &&
3041          (currentMs - historyInfo.lastResetSelfCureFailedTs > DELAYED_DAYS_MID)) ||
3042         (historyInfo.resetSelfCureFailedCnt >= SELF_CURE_FAILED_FOUR_CNT &&
3043          (currentMs - historyInfo.lastResetSelfCureFailedTs > DELAYED_DAYS_HIGH))) &&
3044         AllowSelfCure(historyInfo, requestCureLevel)) {
3045         return true;
3046     }
3047     return false;
3048 }
3049 
SelfCureAcceptable(WifiSelfCureHistoryInfo & historyInfo,int requestCureLevel)3050 bool SelfCureStateMachine::SelfCureAcceptable(WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel)
3051 {
3052     auto now = std::chrono::system_clock::now();
3053     int64_t currentMs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
3054     if (currentMs <= 0) {
3055         WIFI_LOGE("Get current time error");
3056     }
3057     bool ifAcceptable = false;
3058     switch (requestCureLevel) {
3059         case WIFI_CURE_RESET_LEVEL_LOW_1_DNS:
3060             ifAcceptable = DealDns(historyInfo, WIFI_CURE_RESET_LEVEL_LOW_1_DNS, currentMs);
3061             break;
3062         case WIFI_CURE_RESET_LEVEL_LOW_2_RENEW_DHCP:
3063             ifAcceptable = DealRenewDhcp(historyInfo, WIFI_CURE_RESET_LEVEL_LOW_2_RENEW_DHCP, currentMs);
3064             break;
3065         case WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP:
3066             ifAcceptable = DealStaticIp(historyInfo, WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP, currentMs);
3067             break;
3068         case WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC:
3069             ifAcceptable = DealMiddleReassoc(historyInfo, WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC, currentMs);
3070             break;
3071         case WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC:
3072             ifAcceptable = DealRandMacReassoc(historyInfo, WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC, currentMs);
3073             break;
3074         case WIFI_CURE_RESET_LEVEL_HIGH_RESET:
3075             ifAcceptable = DealHighReset(historyInfo, WIFI_CURE_RESET_LEVEL_HIGH_RESET, currentMs);
3076             break;
3077         default:
3078             break;
3079     }
3080     return ifAcceptable;
3081 }
3082 
UpdateConnSelfCureFailedHistory()3083 bool SelfCureStateMachine::UpdateConnSelfCureFailedHistory()
3084 {
3085     return false;
3086 }
3087 
HandleNetworkConnected()3088 void SelfCureStateMachine::HandleNetworkConnected()
3089 {
3090     StopTimer(WIFI_CURE_OPEN_WIFI_SUCCEED_RESET);
3091     StopTimer(WIFI_CURE_CMD_CONN_FAILED_TIMEOUT);
3092     if (!UpdateConnSelfCureFailedHistory()) {
3093         WIFI_LOGD("Config is null for update, delay 2s to update again.");
3094         MessageExecutedLater(WIFI_CURE_CMD_UPDATE_CONN_SELF_CURE_HISTORY, SELF_CURE_MONITOR_DELAYED_MS);
3095     }
3096     noAutoConnCounter = 0;
3097     autoConnectFailedNetworksRssi.clear();
3098     connectedTime = static_cast<int64_t>(time(nullptr));
3099     {
3100         std::lock_guard<std::mutex> lock(dhcpFailedBssidLock);
3101         dhcpFailedBssids.clear();
3102         dhcpFailedConfigKeys.clear();
3103     }
3104     SwitchState(pConnectedMonitorState);
3105 }
3106 
IsEncryptedAuthType(const std::string authType)3107 bool SelfCureStateMachine::IsEncryptedAuthType(const std::string authType)
3108 {
3109     if (authType == KEY_MGMT_WPA_PSK || authType == KEY_MGMT_WAPI_PSK || authType == KEY_MGMT_SAE) {
3110         return true;
3111     }
3112     return false;
3113 }
3114 
GetCurrentGateway()3115 std::string SelfCureStateMachine::GetCurrentGateway()
3116 {
3117     std::string gateway = "";
3118     IpInfo ipInfo;
3119     WifiConfigCenter::GetInstance().GetIpInfo(ipInfo, m_instId);
3120     gateway = IpTools::ConvertIpv4Address(ipInfo.gateway);
3121     return gateway;
3122 }
3123 
UpdateSelfCureConnectHistoryInfo(WifiSelfCureHistoryInfo & historyInfo,int requestCureLevel,bool success)3124 void SelfCureStateMachine::UpdateSelfCureConnectHistoryInfo(WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel,
3125                                                             bool success)
3126 {
3127     auto now = std::chrono::system_clock::now();
3128     int64_t currentMs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
3129     if (requestCureLevel == WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC) {
3130         if (success) {
3131             historyInfo.reassocSelfCureConnectFailedCnt = 0;
3132             historyInfo.lastReassocSelfCureConnectFailedTs = 0;
3133         } else {
3134             historyInfo.reassocSelfCureConnectFailedCnt += 1;
3135             historyInfo.lastReassocSelfCureConnectFailedTs = currentMs;
3136         }
3137     } else if (requestCureLevel == WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC) {
3138         if (success) {
3139             historyInfo.randMacSelfCureConnectFailedCnt = 0;
3140             historyInfo.lastRandMacSelfCureConnectFailedCntTs = 0;
3141         } else {
3142             historyInfo.randMacSelfCureConnectFailedCnt += 1;
3143             historyInfo.lastRandMacSelfCureConnectFailedCntTs = currentMs;
3144         }
3145     } else if (requestCureLevel == WIFI_CURE_RESET_LEVEL_HIGH_RESET) {
3146         if (success) {
3147             historyInfo.resetSelfCureConnectFailedCnt = 0;
3148             historyInfo.lastResetSelfCureConnectFailedTs = 0;
3149         } else {
3150             historyInfo.resetSelfCureConnectFailedCnt += 1;
3151             historyInfo.lastResetSelfCureConnectFailedTs = currentMs;
3152         }
3153     }
3154 }
3155 
UpdateSelfCureHistoryInfo(WifiSelfCureHistoryInfo & historyInfo,int requestCureLevel,bool success)3156 void SelfCureStateMachine::UpdateSelfCureHistoryInfo(WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel,
3157                                                      bool success)
3158 {
3159     WIFI_LOGI("enter %{public}s", __FUNCTION__);
3160     auto now = std::chrono::system_clock::now();
3161     int64_t currentMs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
3162     if (requestCureLevel == WIFI_CURE_RESET_LEVEL_LOW_1_DNS) {
3163         if (success) {
3164             historyInfo.dnsSelfCureFailedCnt = 0;
3165             historyInfo.lastDnsSelfCureFailedTs = 0;
3166         } else {
3167             historyInfo.dnsSelfCureFailedCnt += 1;
3168             historyInfo.lastDnsSelfCureFailedTs = currentMs;
3169         }
3170     } else if ((requestCureLevel == WIFI_CURE_RESET_LEVEL_LOW_2_RENEW_DHCP) ||
3171                (requestCureLevel == WIFI_CURE_RESET_LEVEL_DEAUTH_BSSID)) {
3172         if (success) {
3173             historyInfo.renewDhcpSelfCureFailedCnt = 0;
3174             historyInfo.lastRenewDhcpSelfCureFailedTs = 0;
3175         } else {
3176             historyInfo.renewDhcpSelfCureFailedCnt += 1;
3177             historyInfo.lastRenewDhcpSelfCureFailedTs = currentMs;
3178         }
3179     } else if (requestCureLevel == WIFI_CURE_RESET_LEVEL_LOW_3_STATIC_IP) {
3180         if (success) {
3181             historyInfo.staticIpSelfCureFailedCnt = 0;
3182             historyInfo.lastStaticIpSelfCureFailedTs = 0;
3183         } else {
3184             historyInfo.staticIpSelfCureFailedCnt += 1;
3185             historyInfo.lastStaticIpSelfCureFailedTs = currentMs;
3186         }
3187     } else {
3188         if (requestCureLevel == WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC ||
3189             requestCureLevel == WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC ||
3190             requestCureLevel == WIFI_CURE_RESET_LEVEL_HIGH_RESET) {
3191             UpdateReassocAndResetHistoryInfo(historyInfo, requestCureLevel, success);
3192         }
3193     }
3194 }
3195 
UpdateReassocAndResetHistoryInfo(WifiSelfCureHistoryInfo & historyInfo,int requestCureLevel,bool success)3196 void SelfCureStateMachine::UpdateReassocAndResetHistoryInfo(WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel,
3197                                                             bool success)
3198 {
3199     auto now = std::chrono::system_clock::now();
3200     int64_t currentMs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
3201     if (requestCureLevel == WIFI_CURE_RESET_LEVEL_MIDDLE_REASSOC) {
3202         if (success) {
3203             historyInfo.reassocSelfCureFailedCnt = 0;
3204             historyInfo.lastReassocSelfCureFailedTs = 0;
3205         } else {
3206             historyInfo.reassocSelfCureFailedCnt += 1;
3207             historyInfo.lastReassocSelfCureFailedTs = currentMs;
3208         }
3209     } else if (requestCureLevel == WIFI_CURE_RESET_LEVEL_RAND_MAC_REASSOC) {
3210         if (success) {
3211             historyInfo.randMacSelfCureFailedCnt = 0;
3212             historyInfo.lastRandMacSelfCureFailedCntTs = 0;
3213         } else {
3214             historyInfo.randMacSelfCureFailedCnt += 1;
3215             historyInfo.lastRandMacSelfCureFailedCntTs = currentMs;
3216         }
3217     } else if (requestCureLevel == WIFI_CURE_RESET_LEVEL_HIGH_RESET) {
3218         if (success) {
3219             historyInfo.resetSelfCureFailedCnt = 0;
3220             historyInfo.lastResetSelfCureFailedTs = 0;
3221         } else {
3222             historyInfo.resetSelfCureFailedCnt += 1;
3223             historyInfo.lastResetSelfCureFailedTs = currentMs;
3224         }
3225     }
3226 }
3227 
RecoverySoftAp()3228 void SelfCureStateMachine::RecoverySoftAp()
3229 {
3230     if (WifiManager::GetInstance().GetWifiTogglerManager() == nullptr) {
3231         WIFI_LOGI("GetWifiTogglerManager is nullptr!!");
3232         return;
3233     }
3234     WifiManager::GetInstance().GetWifiTogglerManager()->SoftapToggled(0, 0);
3235     WifiManager::GetInstance().GetWifiTogglerManager()->SoftapToggled(1, 0);
3236 }
3237 
IsSoftApSsidSameWithWifi(const HotspotConfig & curApConfig)3238 bool SelfCureStateMachine::IsSoftApSsidSameWithWifi(const HotspotConfig& curApConfig)
3239 {
3240     WifiLinkedInfo linkedInfo;
3241     WifiDeviceConfig config;
3242     WifiConfigCenter::GetInstance().GetLinkedInfo(linkedInfo);
3243     WifiSettings::GetInstance().GetDeviceConfig(linkedInfo.networkId, config);
3244     bool isSameSsid = (curApConfig.GetSsid() == linkedInfo.ssid);
3245     bool isSamePassword = (curApConfig.GetPreSharedKey() == config.preSharedKey);
3246     std::string().swap(config.preSharedKey);
3247     bool isSameSecurityType = ("WPA2-PSK" == config.keyMgmt || "WPA-PSK" == config.keyMgmt);
3248     if (isSameSsid && isSameSecurityType && !isSamePassword) {
3249         return true;
3250     }
3251     return false;
3252 }
3253 
CheckConflictIpForSoftAp()3254 void SelfCureStateMachine::CheckConflictIpForSoftAp()
3255 {
3256     IpInfo ipInfo;
3257     HotspotConfig curApConfig;
3258     WifiSettings::GetInstance().GetHotspotConfig(curApConfig, 0);
3259     WifiConfigCenter::GetInstance().GetIpInfo(ipInfo);
3260     WIFI_LOGI("CheckConflictIpForSoftAp enter!");
3261     if (!WifiConfigCenter::GetInstance().GetSoftapToggledState()) {
3262         WIFI_LOGI("softap not started, return!");
3263         return;
3264     }
3265     if (WifiManager::GetInstance().GetWifiTogglerManager() == nullptr) {
3266         WIFI_LOGI("GetWifiTogglerManager is nullptr!!");
3267         return;
3268     }
3269     if (IsSoftApSsidSameWithWifi(curApConfig)) {
3270         WIFI_LOGI("sta and sofap have same ssid and PSK, close softap!");
3271         WifiManager::GetInstance().GetWifiTogglerManager()->SoftapToggled(0, 0);
3272         return;
3273     }
3274     if (IpTools::ConvertIpv4Address(ipInfo.gateway) == curApConfig.GetIpAddress()) {
3275         WIFI_LOGI("sta and sofap gateway conflict, recovery softap!");
3276         RecoverySoftAp();
3277     }
3278 }
3279 
RequestArpConflictTest()3280 void SelfCureStateMachine::RequestArpConflictTest()
3281 {
3282     IpInfo ipInfo;
3283     WifiConfigCenter::GetInstance().GetIpInfo(ipInfo);
3284     std::string ipAddr = IpTools::ConvertIpv4Address(ipInfo.ipAddress);
3285     if (ipAddr != "" && DoSlowArpTest(ipAddr)) {
3286         WIFI_LOGI("RequestArpConflictTest, Upload static ip conflicted chr!");
3287     }
3288 }
3289 
HandleP2pConnChanged(const WifiP2pLinkedInfo & info)3290 void SelfCureStateMachine::HandleP2pConnChanged(const WifiP2pLinkedInfo &info)
3291 {
3292     if (info.GetConnectState() == P2pConnectedState::P2P_CONNECTED) {
3293         p2pConnected = true;
3294         return;
3295     }
3296     p2pConnected = false;
3297     if (GetCurStateName() == pInternetSelfCureState->GetStateName()) {
3298         SendMessage(WIFI_CURE_CMD_P2P_DISCONNECTED_EVENT);
3299     }
3300 }
3301 
IfMultiGateway()3302 bool SelfCureStateMachine::IfMultiGateway()
3303 {
3304     auto pMultiGateway = DelayedSingleton<MultiGateway>::GetInstance();
3305     if (pMultiGateway == nullptr) {
3306         WIFI_LOGE("IfMultiGateway pMultiGateway is nullptr");
3307         return false;
3308     }
3309     pMultiGateway->GetGatewayAddr(m_instId);
3310     return pMultiGateway->IsMultiGateway();
3311 }
3312 
IsSettingsPage()3313 bool SelfCureStateMachine::IsSettingsPage()
3314 {
3315     std::map<std::string, std::string> variableMap;
3316     std::string page;
3317     if (WifiSettings::GetInstance().GetVariableMap(variableMap) != 0) {
3318         WIFI_LOGE("WifiSettings::GetInstance().GetVariableMap failed");
3319     }
3320     if (variableMap.find("SETTINGS") != variableMap.end()) {
3321         page = variableMap["SETTINGS"];
3322     }
3323     if (WifiAppStateAware::GetInstance().IsForegroundApp(page)) {
3324         WIFI_LOGI("settings page, do not allow reset self cure");
3325         return true;
3326     }
3327     return false;
3328 }
3329 
IsSelfCureOnGoing()3330 bool SelfCureStateMachine::IsSelfCureOnGoing()
3331 {
3332     return selfCureOnGoing;
3333 }
3334 
IsMultiDhcpOffer()3335 bool SelfCureStateMachine::IsMultiDhcpOffer()
3336 {
3337     IEnhanceService *pEnhanceService = WifiServiceManager::GetInstance().GetEnhanceServiceInst();
3338     if (pEnhanceService == nullptr) {
3339         WIFI_LOGE("IsMultiDhcpOffer get pEnhanceService service failed!");
3340         return false;
3341     }
3342     uint32_t retSize = 0;
3343     IpInfo info;
3344     pEnhanceService->DealDhcpOfferResult(OperationCmd::DHCP_OFFER_SIZE_GET, info, retSize);
3345     return retSize >= DHCP_OFFER_COUNT;
3346 }
3347 
ClearDhcpOffer()3348 void SelfCureStateMachine::ClearDhcpOffer()
3349 {
3350     IEnhanceService *pEnhanceService = WifiServiceManager::GetInstance().GetEnhanceServiceInst();
3351     if (pEnhanceService == nullptr) {
3352         WIFI_LOGE("ClearDhcpOffer get pEnhanceService service failed!");
3353         return;
3354     }
3355     uint32_t retSize = 0;
3356     IpInfo info;
3357     pEnhanceService->DealDhcpOfferResult(OperationCmd::DHCP_OFFER_CLEAR, info, retSize);
3358 }
3359 
UpdateSelfcureState(int selfcureType,bool isSelfCureOnGoing)3360 void SelfCureStateMachine::UpdateSelfcureState(int selfcureType, bool isSelfCureOnGoing)
3361 {
3362     selfCureOnGoing = isSelfCureOnGoing;
3363     int currentPid = static_cast<int>(getpid());
3364     WIFI_LOGE("UpdateSelfcureState selfcureType: %{public}d, isSelfCureOnGoing: %{public}d",
3365         selfcureType, isSelfCureOnGoing);
3366     WifiCommonEventHelper::PublishSelfcureStateChangedEvent(currentPid, selfcureType, isSelfCureOnGoing);
3367 }
3368 } // namespace Wifi
3369 } // namespace OHOS