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 #ifndef OHOS_SELF_CURE_STATE_MACHINE_H
17 #define OHOS_SELF_CURE_STATE_MACHINE_H
18 
19 #include "define.h"
20 #include "wifi_log.h"
21 #include "wifi_errcode.h"
22 #include "state_machine.h"
23 #include "self_cure_common.h"
24 #include "self_cure_service_callback.h"
25 #include "sta_service_callback.h"
26 #include "ista_service.h"
27 #include "ip2p_service_callbacks.h"
28 #include "wifi_scan_msg.h"
29 #include "iself_cure_service.h"
30 #include "wifi_service_manager.h"
31 #include "wifi_msg.h"
32 #include <fcntl.h>
33 #include "arp_checker.h"
34 #include "self_cure_msg.h"
35 #include "wifi_common_util.h"
36 #include "wifi_net_observer.h"
37 
38 namespace OHOS {
39 namespace Wifi {
40 constexpr int SELF_CURE_DNS_SIZE = 2;
41 constexpr int CURRENT_RSSI_INIT = -200;
42 constexpr int MAX_SELF_CURE_CNT_INVALID_IP = 3;
43 constexpr int VEC_POS_0 = 0;
44 constexpr int VEC_POS_1 = 1;
45 constexpr int VEC_POS_2 = 2;
46 constexpr int VEC_POS_3 = 3;
47 constexpr int TRY_TIMES = 3;
48 constexpr int STATIC_IP_ADDR = 156;
49 constexpr int IP_ADDR_LIMIT = 255;
50 constexpr int GET_NEXT_IP_MAC_CNT = 10;
51 constexpr int IP_ADDR_SIZE = 4;
52 constexpr int NET_MASK_LENGTH = 24;
53 constexpr int SELF_CURE_FAILED_ONE_CNT = 1;
54 constexpr int SELF_CURE_FAILED_TWO_CNT = 2;
55 constexpr int SELF_CURE_FAILED_THREE_CNT = 3;
56 constexpr int SELF_CURE_FAILED_FOUR_CNT = 4;
57 constexpr int SELF_CURE_FAILED_FIVE_CNT = 5;
58 constexpr int SELF_CURE_FAILED_SIX_CNT = 6;
59 constexpr int SELF_CURE_FAILED_SEVEN_CNT = 7;
60 constexpr int POS_DNS_FAILED_TS = 1;
61 constexpr int POS_RENEW_DHCP_FAILED_CNT = 2;
62 constexpr int POS_RENEW_DHCP_FAILED_TS = 3;
63 constexpr int POS_STATIC_IP_FAILED_CNT = 4;
64 constexpr int POS_STATIC_IP_FAILED_TS = 5;
65 constexpr int POS_REASSOC_FAILED_CNT = 6;
66 constexpr int POS_REASSOC_FAILED_TS = 7;
67 constexpr int POS_RANDMAC_FAILED_CNT = 8;
68 constexpr int POS_RANDMAC_FAILED_TS = 9;
69 constexpr int POS_RESET_FAILED_CNT = 10;
70 constexpr int POS_RESET_FAILED_TS = 11;
71 constexpr int POS_REASSOC_CONNECT_FAILED_CNT = 12;
72 constexpr int POS_REASSOC_CONNECT_FAILED_TS = 13;
73 constexpr int POS_RANDMAC_CONNECT_FAILED_CNT = 14;
74 constexpr int POS_RANDMAC_CONNECT_FAILED_TS = 15;
75 constexpr int POS_RESET_CONNECT_FAILED_CNT = 16;
76 constexpr int POS_RESET_CONNECT_FAILED_TS = 17;
77 constexpr const char* CONST_WIFI_DNSCURE_IPCFG = "const.wifi.dnscure_ipcfg";
78 
79 class SelfCureStateMachine : public StateMachine {
80     FRIEND_GTEST(SelfCureStateMachine);
81 
82 public:
83     explicit SelfCureStateMachine(int instId = 0);
84     ~SelfCureStateMachine();
85     using selfCureSmHandleFunc = void (SelfCureStateMachine::*)(InternalMessagePtr msg);
86     using SelfCureSmHandleFuncMap = std::map<int, selfCureSmHandleFunc>;
87 
88     /* *
89      * @Description  Definition of DefaultState class in SelfCureStateMachine.
90      *
91      */
92     class DefaultState : public State {
93     public:
94         explicit DefaultState(SelfCureStateMachine *selfCureStateMachine);
95         ~DefaultState() override;
96         void GoInState() override;
97         void GoOutState() override;
98         bool ExecuteStateMsg(InternalMessagePtr msg) override;
99         void HandleDhcpOfferPacketRcv(const IpInfo &info);
100         void HandleP2pEnhanceStateChange(int state);
101     private:
102         SelfCureStateMachine *pSelfCureStateMachine;
103     };
104 
105     /* *
106      * @Description  Definition of ConnectedMonitorState class in SelfCureStateMachine.
107      *
108      */
109     class ConnectedMonitorState : public State {
110     public:
111         explicit ConnectedMonitorState(SelfCureStateMachine *selfCureStateMachine);
112         ~ConnectedMonitorState() override;
113         void GoInState() override;
114         void GoOutState() override;
115         bool ExecuteStateMsg(InternalMessagePtr msg) override;
116         using selfCureCmsHandleFunc = void (SelfCureStateMachine::ConnectedMonitorState::*)(InternalMessagePtr msg);
117         using SelfCureCmsHandleFuncMap = std::map<int, selfCureCmsHandleFunc>;
118 
119     private:
120         SelfCureStateMachine *pSelfCureStateMachine;
121         int lastSignalLevel = -1;
122         std::string lastConnectedBssid;
123         bool mobileHotspot = false;
124         bool ipv4DnsEnabled = false;
125         bool gatewayInvalid = false;
126         std::string configAuthType = "-1";
127         bool hasInternetRecently = false;
128         bool portalUnthenEver = false;
129         bool userSetStaticIpConfig = false;
130         bool wifiSwitchAllowed = false;
131         SelfCureCmsHandleFuncMap selfCureCmsHandleFuncMap;
132         int InitSelfCureCmsHandleMap();
133         void HandleResetupSelfCure(InternalMessagePtr msg);
134         void HandlePeriodicArpDetection(InternalMessagePtr msg);
135         void HandleNetworkConnect(InternalMessagePtr msg);
136         void HandleNetworkDisconnect(InternalMessagePtr msg);
137         void HandleRssiLevelChange(InternalMessagePtr msg);
138         void TransitionToSelfCureState(int reason);
139         void HandleArpDetectionFailed(InternalMessagePtr msg);
140         bool SetupSelfCureMonitor();
141         void UpdateInternetAccessHistory();
142         void RequestReassocWithFactoryMac();
143         void HandleInvalidIp(InternalMessagePtr msg);
144         void HandleInternetFailedDetected(InternalMessagePtr msg);
145         void HandleTcpQualityQuery(InternalMessagePtr msg);
146         void HandleGatewayChanged(InternalMessagePtr msg);
147         bool IsGatewayChanged();
148     };
149 
150     /* *
151      * @Description  Definition of DisconnectedMonitorState class in SelfCureStateMachine.
152      *
153      */
154     class DisconnectedMonitorState : public State {
155     public:
156         explicit DisconnectedMonitorState(SelfCureStateMachine *selfCureStateMachine);
157         ~DisconnectedMonitorState() override;
158         void GoInState() override;
159         void GoOutState() override;
160         bool ExecuteStateMsg(InternalMessagePtr msg) override;
161 
162     private:
163         void HandleWifi7BlacklistRecover(InternalMessagePtr msg);
164         void HandleWifi7WithoutMldBackoff(InternalMessagePtr msg);
165         void HandleWifi7MldBackoff(InternalMessagePtr msg);
166         void HandleNetworkConnectFailCount(InternalMessagePtr msg);
167         void HandleConnectFailed(InternalMessagePtr msg);
168         void HandleResetConnectNetwork(InternalMessagePtr msg);
169         SelfCureStateMachine *pSelfCureStateMachine;
170         bool setStaticIpConfig = false;
171     };
172 
173     /* *
174      * @Description  Definition of ConnectionSelfCureState class in SelfCureStateMachine.
175      *
176      */
177     class ConnectionSelfCureState : public State {
178     public:
179         explicit ConnectionSelfCureState(SelfCureStateMachine *selfCureStateMachine);
180         ~ConnectionSelfCureState() override;
181         void GoInState() override;
182         void GoOutState() override;
183         bool ExecuteStateMsg(InternalMessagePtr msg) override;
184 
185     private:
186         SelfCureStateMachine *pSelfCureStateMachine;
187     };
188 
189     /* *
190      * @Description  Definition of InternetSelfCureState class in SelfCureStateMachine.
191      *
192      */
193     class InternetSelfCureState : public State {
194     public:
195         explicit InternetSelfCureState(SelfCureStateMachine *selfCureStateMachine);
196         ~InternetSelfCureState() override;
197         void GoInState() override;
198         void GoOutState() override;
199         bool ExecuteStateMsg(InternalMessagePtr msg) override;
200         using selfCureIssHandleFunc = void (SelfCureStateMachine::InternetSelfCureState::*)(InternalMessagePtr msg);
201         using SelfCureIssHandleFuncMap = std::map<int, selfCureIssHandleFunc>;
202 
203     private:
204         SelfCureStateMachine *pSelfCureStateMachine;
205         int currentRssi = -1;
206         std::string currentBssid = "";
207         int selfCureFailedCounter = 0;
208         int currentAbnormalType = -1;
209         int lastSelfCureLevel = -1;
210         int currentSelfCureLevel = -1;
211         int renewDhcpCount = -1;
212         bool hasInternetRecently = false;
213         bool portalUnthenEver = false;
214         bool userSetStaticIpConfig = false;
215         int64_t lastHasInetTime = 0;
216         bool delayedReassocSelfCure = false;
217         bool delayedRandMacReassocSelfCure = false;
218         bool delayedResetSelfCure = false;
219         bool setStaticIp4InvalidIp = false;
220         bool isRenewDhcpTimeout = false;
221         bool configStaticIp4MultiDhcpServer = false;
222         std::string unConflictedIp = "";
223         int lastMultiGwSelfFailedType = -1;
224         bool usedMultiGwSelfcure = false;
225         std::string configAuthType = "";
226         bool finalSelfCureUsed = false;
227         std::vector<int> testedSelfCureLevel;
228         WifiSelfCureHistoryInfo selfCureHistoryInfo;
229         std::string currentGateway = "";
230         int selfCureForInvalidIpCnt = 0;
231         SelfCureIssHandleFuncMap selfCureIssHandleFuncMap;
232         std::vector<std::string> AssignedDnses;
233         int InitSelfCureIssHandleMap();
234         void HandleRandMacSelfCureComplete(InternalMessagePtr msg);
235         void HandleInternetFailedSelfCure(InternalMessagePtr msg);
236         void HandleSelfCureWifiLink(InternalMessagePtr msg);
237         void HandleNetworkDisconnected(InternalMessagePtr msg);
238         void HandleInternetRecovery(InternalMessagePtr msg);
239         void HandleRssiChangedEvent(InternalMessagePtr msg);
240         void HandleP2pDisconnected(InternalMessagePtr msg);
241         void HandlePeriodicArpDetecte(InternalMessagePtr msg);
242         void HandleArpFailedDetected(InternalMessagePtr msg);
243         void HandleHttpReachableRecv(InternalMessagePtr msg);
244         void SelectSelfCureByFailedReason(int internetFailedType);
245         int SelectBestSelfCureSolution(int internetFailedType);
246         int SelectBestSelfCureSolutionExt(int internetFailedType);
247         void SelfCureWifiLink(int requestCureLevel);
248         bool SelectedSelfCureAcceptable();
249         void SelfCureForRandMacReassoc(int requestCureLevel);
250         void SelfCureForReset(int requestCureLevel);
251         void HandleIpConfigCompleted();
252         void HandleIpConfigCompletedAfterRenewDhcp();
253         void HandleInternetRecoveryConfirm();
254         bool ConfirmInternetSelfCure(int currentCureLevel);
255         void HandleConfirmInternetSelfCureFailed(int currentCureLevel);
256         void HandleInternetFailedAndUserSetStaticIp(int internetFailedType);
257         void HandleIpConfigTimeout();
258         bool HasBeenTested(int cureLevel);
259         void HandleHttpUnreachableFinally();
260         void HandleHttpReachableAfterSelfCure(int currentCureLevel);
261         void HandleSelfCureFailedForRandMacReassoc();
262         void HandleRssiChanged();
263         void HandleDelayedResetSelfCure();
264         void GetPublicDnsServers(std::vector<std::string>& publicDnsServers);
265         void GetReplacedDnsServers(std::vector<std::string>& curDnses, std::vector<std::string>& replacedDnses);
266         void UpdateDnsServers(std::vector<std::string>& dnsServers);
267         void SelfCureForDns();
268         void resetDnses(std::vector<std::string>& dnses);
269         void SelfCureForInvalidIp();
270         void SelfCureForReassoc(int requestCureLevel);
271         void SelfcureForMultiGateway(InternalMessagePtr msg);
272         bool IsNeedMultiGatewaySelfcure();
273         void SelfCureForStaticIp(int requestCureLevel);
274         void RequestUseStaticIpConfig(IpInfo &dhcpResult);
275         IpInfo GetNextTestDhcpResults();
276         IpInfo GetRecordDhcpResults();
277     };
278 
279     /* *
280      * @Description  Definition of Wifi6SelfCureState class in SelfCureStateMachine.
281      *
282      */
283     class Wifi6SelfCureState : public State {
284     public:
285         explicit Wifi6SelfCureState(SelfCureStateMachine *selfCureStateMachine);
286         ~Wifi6SelfCureState() override;
287         void GoInState() override;
288         void GoOutState() override;
289         bool ExecuteStateMsg(InternalMessagePtr msg) override;
290 
291     private:
292         SelfCureStateMachine *pSelfCureStateMachine;
293         int wifi6HtcArpDetectionFailedCnt = 0;
294         int wifi6ArpDetectionFailedCnt = 0;
295         int32_t internetValue_ = 0;
296         bool isForceHttpCheck_ = true;
297         void PeriodicWifi6WithHtcArpDetect(InternalMessagePtr msg);
298         void PeriodicWifi6WithoutHtcArpDetect(InternalMessagePtr msg);
299         void HandleWifi6WithHtcArpFail(InternalMessagePtr msg);
300         void HandleWifi6WithoutHtcArpFail(InternalMessagePtr msg);
301         void Wifi6ReassocSelfcure();
302     };
303 
304     /* *
305      * @Description  Definition of NoInternetState class in SelfCureStateMachine.
306      *
307      */
308     class NoInternetState : public State {
309     public:
310         explicit NoInternetState(SelfCureStateMachine *selfCureStateMachine);
311         ~NoInternetState() override;
312         void GoInState() override;
313         void GoOutState() override;
314         bool ExecuteStateMsg(InternalMessagePtr msg) override;
315 
316     private:
317         SelfCureStateMachine *pSelfCureStateMachine;
318     };
319 
320     ErrCode Initialize();
321     void SetHttpMonitorStatus(bool isHttpReachable);
322     bool IsSelfCureOnGoing();
323 
324 private:
325 
326     /* *
327      * @Description  Destruct state.
328      *
329      */
330     template <typename T>
ParsePointer(T * & pointer)331     inline void ParsePointer(T *&pointer)
332     {
333         if (pointer != nullptr) {
334             delete pointer;
335             pointer = nullptr;
336         }
337     }
338 
339     /**
340      * @Description  Build state tree
341      *
342      */
343     void BuildStateTree();
344 
345     /**
346      * @Description  Determine whether it is empty during initialization
347      *
348      */
349     template <typename T>
JudgmentEmpty(T * & pointer)350     inline ErrCode JudgmentEmpty(T *&pointer)
351     {
352         if (pointer == nullptr) {
353             return WIFI_OPT_FAILED;
354         }
355         return WIFI_OPT_SUCCESS;
356     }
357 
358     /**
359      * @Description  Initializing state of Self Cure.
360      *
361      */
362     ErrCode InitSelfCureStates();
363     int64_t GetNowMilliSeconds();
364     void SendBlaListToDriver(int blaListType);
365     std::string BlackListToString(std::map<std::string, WifiCategoryBlackListInfo> &map);
366     std::string ParseWifiCategoryBlackListInfo(std::pair<std::string, WifiCategoryBlackListInfo> iter);
367     void AgeOutWifiCategoryBlack(int blaListType, std::map<std::string, WifiCategoryBlackListInfo> &blackListCache);
368     void AgeOutWifiConnectFailList();
369     int GetCurSignalLevel();
370     bool IsHttpReachable();
371     std::string TransVecToIpAddress(const std::vector<uint32_t>& vec);
372     std::vector<uint32_t> TransIpAddressToVec(std::string addr);
373     int GetLegalIpConfiguration(IpInfo &dhcpResults);
374     bool CanArpReachable();
375     bool DoSlowArpTest(const std::string& testIpAddr);
376     std::string GetNextIpAddr(const std::string& gateway, const std::string& currentAddr,
377                               const std::vector<std::string>& testedAddr);
378     bool IsIpAddressInvalid();
379     std::vector<std::string> TransStrToVec(std::string str, char c);
380     bool IsUseFactoryMac();
381     bool IsSameEncryptType(const std::string& scanInfoKeymgmt, const std::string& deviceKeymgmt);
382     int GetBssidCounter(const std::vector<WifiScanInfo> &scanResults);
383     bool IsNeedWifiReassocUseDeviceMac();
384     int String2InternetSelfCureHistoryInfo(const std::string selfCureHistory, WifiSelfCureHistoryInfo &info);
385     int SetSelfCureFailInfo(OHOS::Wifi::WifiSelfCureHistoryInfo &info, std::vector<std::string>& histories, int cnt);
386     int SetSelfCureConnectFailInfo(WifiSelfCureHistoryInfo &info, std::vector<std::string>& histories, int cnt);
387     bool IfP2pConnected();
388     bool ShouldTransToWifi6SelfCure(InternalMessagePtr msg, std::string currConnectedBssid);
389     int GetWifi7SelfCureType(int connectFailTimes, WifiLinkedInfo &info);
390     void ShouldTransToWifi7SelfCure(WifiLinkedInfo &info);
391     int GetScanRssi(std::string currentBssid, const std::vector<WifiScanInfo> scanResults);
392     int GetCurrentRssi();
393     std::string GetCurrentBssid();
394     bool IsWifi6Network(std::string currConnectedBssid);
395     void PeriodicArpDetection();
396     bool IsSuppOnCompletedState();
397     bool IfPeriodicArpDetection();
398     std::string GetAuthType();
399     int GetIpAssignment(AssignIpMethod &ipAssignment);
400     time_t GetLastHasInternetTime();
401     uint32_t GetNetworkStatusHistory();
402     std::string GetSelfCureHistoryInfo();
403     int SetSelfCureHistoryInfo(const std::string selfCureHistory);
404     int GetIsReassocWithFactoryMacAddress();
405     int SetIsReassocWithFactoryMacAddress(int isReassocWithFactoryMacAddress);
406     bool IsCustNetworkSelfCure();
407     ErrCode GetCurrentWifiDeviceConfig(WifiDeviceConfig &config);
408     bool SelfCureAcceptable(WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel);
409     void HandleNetworkConnected();
410     bool UpdateConnSelfCureFailedHistory();
411     void RecoverySoftAp();
412     bool IsSoftApSsidSameWithWifi(const HotspotConfig& curApConfig);
413     void CheckConflictIpForSoftAp();
414     static bool IsEncryptedAuthType(const std::string authType);
415     std::string GetCurrentGateway();
416     bool DoArpTest(std::string& ipAddress, std::string& gateway);
417     void RequestArpConflictTest();
418     static void UpdateReassocAndResetHistoryInfo(WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel,
419                                                  bool success);
420     static void UpdateSelfCureHistoryInfo(WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel, bool success);
421     static void UpdateSelfCureConnectHistoryInfo(WifiSelfCureHistoryInfo &historyInfo, int requestCureLevel,
422                                                  bool success);
423     void HandleP2pConnChanged(const WifiP2pLinkedInfo &info);
424     bool IfMultiGateway();
425     void InitDnsServer();
426     bool IsSettingsPage();
427     bool IsMultiDhcpOffer();
428     void ClearDhcpOffer();
429     void UpdateSelfcureState(int selfcureType, bool isSelfCureOnGoing);
430 
431 private:
432     SelfCureSmHandleFuncMap selfCureSmHandleFuncMap;
433     std::map<std::string, SelfCureServiceCallback> mSelfCureCallback;
434     DefaultState *pDefaultState;
435     ConnectedMonitorState *pConnectedMonitorState;
436     DisconnectedMonitorState *pDisconnectedMonitorState;
437     ConnectionSelfCureState *pConnectionSelfCureState;
438     InternetSelfCureState *pInternetSelfCureState;
439     Wifi6SelfCureState *pWifi6SelfCureState;
440     NoInternetState *pNoInternetState;
441 
442     int m_instId;
443     bool mIsHttpReachable = false;
444     int useWithRandMacAddress = 0;
445     std::atomic<bool> selfCureOnGoing = false;
446     std::atomic<bool> p2pConnected = false;
447     std::atomic<bool> notAllowSelfcure = true;
448     int arpDetectionFailedCnt = 0;
449     int selfCureReason = -1;
450     int noTcpRxCounter = 0;
451     uint32_t connectNetworkRetryCnt = 0;
452     bool internetUnknown = false;
453     int noAutoConnCounter = 0;
454     int noAutoConnReason = -1;
455     bool staticIpCureSuccess = false;
456     bool isWifi6ArpSuccess = false;
457     bool hasTestWifi6Reassoc = false;
458     bool isReassocSelfCureWithRealMacAddress = false;
459     int64_t connectedTime = 0;
460     std::mutex dhcpFailedBssidLock;
461     std::vector<std::string> dhcpFailedBssids;
462     std::vector<std::string> dhcpFailedConfigKeys;
463     std::map<std::string, int> autoConnectFailedNetworksRssi;
464     std::atomic<bool> isWifiBackground = false;
465     sptr<NetStateObserver> mNetWorkDetect;
466     bool m_httpDetectResponse = false;
467     bool p2pEnhanceConnected_ = false;
468 };
469 } // namespace Wifi
470 } // namespace OHOS
471 #endif