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