1 /*
2  * Copyright (C) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #ifndef OHOS_WIFI_STATE_MACHINE_H
16 #define OHOS_WIFI_STATE_MACHINE_H
17 
18 #include <regex.h>
19 #include <sys/types.h>
20 #include <fstream>
21 #include <vector>
22 #include <shared_mutex>
23 #include "wifi_internal_msg.h"
24 #include "wifi_log.h"
25 #include "wifi_errcode.h"
26 #include "wifi_msg.h"
27 #include "state_machine.h"
28 #include "arp_checker.h"
29 #include "sta_service_callback.h"
30 #include "dhcp_c_api.h"
31 #include "sta_define.h"
32 #include "network_status_history_manager.h"
33 #include "wifi_native_struct.h"
34 
35 #ifndef OHOS_ARCH_LITE
36 #include "want.h"
37 #include "wifi_net_agent.h"
38 #include "wifi_net_observer.h"
39 #include "sim_state_type.h"
40 #include "core_service_client.h"
41 #include "cellular_data_client.h"
42 #include "core_manager_inner.h"
43 #include "telephony_errors.h"
44 #include "ienhance_service.h"
45 #endif
46 
47 namespace OHOS {
48 namespace Wifi {
49 #ifndef OHOS_ARCH_LITE
50 using namespace OHOS::Telephony;
51 #endif
52 constexpr int STA_CONNECT_MODE = 1;
53 constexpr int STA_SCAN_ONLY_MODE = 2;
54 constexpr int STA_CAN_ONLY_WITH_WIFI_OFF_MODE = 3;
55 constexpr int STA_DISABLED_MODE = 4;
56 constexpr int STA_RENEWAL_MIN_TIME = 120;
57 constexpr int STREAM_TXPACKET_THRESHOLD = 0;
58 constexpr int STREAM_RXPACKET_THRESHOLD = 0;
59 constexpr int STA_AP_ROAMING_TIMEOUT = 15000; // 15s->15000 ms
60 
61 constexpr int CMD_NETWORK_CONNECT_TIMEOUT = 0X01;
62 constexpr int CMD_SIGNAL_POLL = 0X02;
63 constexpr int CMD_START_NETCHECK = 0X03;
64 constexpr int CMD_START_GET_DHCP_IP_TIMEOUT = 0X04;
65 constexpr int CMD_AP_ROAMING_TIMEOUT_CHECK = 0X06;
66 
67 constexpr int STA_NETWORK_CONNECTTING_DELAY = 20 * 1000;
68 constexpr int STA_SIGNAL_POLL_DELAY = 3 * 1000;
69 constexpr int STA_SIGNAL_START_GET_DHCP_IP_DELAY = 30 * 1000;
70 
71 /* pincode length */
72 constexpr int PIN_CODE_LEN = 8;
73 
74 /* DHCP timeout interval */
75 constexpr int DHCP_TIME = 15;
76 /* rssi thresholds */
77 constexpr int INVALID_RSSI_VALUE = -127;
78 constexpr int MAX_RSSI_VALUE = 200;
79 constexpr int SIGNAL_INFO = 256;
80 constexpr int RSSI_LEVEL_3 = 3;
81 
82 /* 2.4g and 5g frequency thresholds */
83 constexpr int FREQ_2G_MIN = 2412;
84 constexpr int FREQ_2G_MAX = 2472;
85 constexpr int FREQ_5G_MIN = 5170;
86 constexpr int FREQ_5G_MAX = 5825;
87 constexpr int CHANNEL_14_FREQ = 2484;
88 constexpr int CHANNEL_14 = 14;
89 constexpr int CENTER_FREQ_DIFF = 5;
90 constexpr int CHANNEL_2G_MIN = 1;
91 constexpr int CHANNEL_5G_MIN = 34;
92 
93 constexpr int MULTI_AP = 0;
94 
95 /*
96  * During the WPS PIN connection, the WPA_SUPPLICANT blocklist is cleared every 10 seconds
97  * until the network connection is successful.
98  */
99 constexpr int BLOCK_LIST_CLEAR_TIMER = 20 * 1000;
100 
101 /* Wpa3 selfcure failreason num*/
102 constexpr int WLAN_STATUS_AUTH_TIMEOUT = 16;
103 constexpr int MAC_AUTH_RSP2_TIMEOUT = 5201;
104 constexpr int MAC_AUTH_RSP4_TIMEOUT = 5202;
105 constexpr int MAC_ASSOC_RSP_TIMEOUT = 5203;
106 constexpr int DHCP_RENEW_FAILED = 4;
107 constexpr int DHCP_RENEW_TIMEOUT = 5;
108 constexpr int DHCP_LEASE_EXPIRED = 6;
109 
110 constexpr unsigned int BIT_MLO_CONNECT = 0x80;
111 
112 #define DNS_IP_ADDR_LEN 15
113 #define WIFI_FIRST_DNS_NAME "const.wifi.wifi_first_dns"
114 #define WIFI_SECOND_DNS_NAME "const.wifi.wifi_second_dns"
115 
116 enum Wpa3ConnectFailReason {
117     WPA3_AUTH_TIMEOUT,
118     WPA3_ASSOC_TIMEOUT,
119     WPA3_FAIL_REASON_MAX
120 };
121 
122 typedef enum EnumDhcpReturnCode {
123     DHCP_RESULT,
124     DHCP_JUMP,
125     DHCP_RENEW_FAIL,
126     DHCP_IP_EXPIRED,
127     DHCP_FAIL,
128     DHCP_OFFER_REPORT,
129 } DhcpReturnCode;
130 
131 const int DETECT_TYPE_DEFAULT = 0;
132 const int DETECT_TYPE_PERIODIC = 1;
133 const int DETECT_TYPE_CHECK_PORTAL_EXPERIED = 2;
134 const int PORTAL_EXPERIED_DETECT_MAX_COUNT = 2;
135 enum PortalState {
136     UNCHECKED = 0,
137     NOT_PORTAL,
138     UNAUTHED,
139     AUTHED,
140     EXPERIED
141 };
142 
143 const std::string WPA_BSSID_ANY = "any";
144 
145 class StaStateMachine : public StateMachine {
146     FRIEND_GTEST(StaStateMachine);
147 public:
148     explicit StaStateMachine(int instId = 0);
149     ~StaStateMachine();
150     using staSmHandleFunc = std::function<void(InternalMessagePtr)>;
151     using StaSmHandleFuncMap = std::map<int, staSmHandleFunc>;
152     /**
153      * @Description  Definition of member function of State base class in StaStateMachine.
154      *
155      */
156     class RootState : public State {
157     public:
158         explicit RootState();
159         ~RootState() override;
160         void GoInState() override;
161         void GoOutState() override;
162         bool ExecuteStateMsg(InternalMessagePtr msg) override;
163     };
164     /**
165      * @Description : Definition of member function of InitState class in StaStateMachine.
166      *
167      */
168     class InitState : public State {
169     public:
170         explicit InitState(StaStateMachine *staStateMachine);
171         ~InitState() override;
172         void GoInState() override;
173         void GoOutState() override;
174         bool ExecuteStateMsg(InternalMessagePtr msg) override;
175 
176     private:
177         StaStateMachine *pStaStateMachine;
178     };
179     /**
180      * @Description : Definition of member function of WpaStartingState class in StaStateMachine.
181      *
182      */
183     class WpaStartingState : public State {
184     public:
185         explicit WpaStartingState(StaStateMachine *staStateMachine);
186         ~WpaStartingState() override;
187         void InitWpsSettings();
188         void GoInState() override;
189         void GoOutState() override;
190         bool ExecuteStateMsg(InternalMessagePtr msg) override;
191 
192     private:
193         StaStateMachine *pStaStateMachine;
194     };
195     /**
196      * @Description  Definition of member function of WpaStartedState class in StaStateMachine.
197      *
198      */
199     class WpaStartedState : public State {
200     public:
201         explicit WpaStartedState(StaStateMachine *staStateMachine);
202         ~WpaStartedState() override;
203         void GoInState() override;
204         void GoOutState() override;
205         bool ExecuteStateMsg(InternalMessagePtr msg) override;
206 
207     private:
208         StaStateMachine *pStaStateMachine;
209     };
210     /**
211      * @Description  Definition of member function of WpaStoppingState class in StaStateMachine.
212      *
213      */
214     class WpaStoppingState : public State {
215     public:
216         explicit WpaStoppingState(StaStateMachine *staStateMachine);
217         ~WpaStoppingState() override;
218         void GoInState() override;
219         void GoOutState() override;
220         bool ExecuteStateMsg(InternalMessagePtr msg) override;
221 
222     private:
223         StaStateMachine *pStaStateMachine;
224     };
225     /**
226      * @Description  Definition of member function of LinkState class in StaStateMachine.
227      *
228      */
229     class LinkState : public State {
230     public:
231         explicit LinkState(StaStateMachine *staStateMachine);
232         ~LinkState() override;
233         void GoInState() override;
234         void GoOutState() override;
235         bool ExecuteStateMsg(InternalMessagePtr msg) override;
236 
237     private:
238         StaStateMachine *pStaStateMachine;
239     };
240     /**
241      * @Description  Definition of member function of SeparatingState class in StaStateMachine.
242      *
243      */
244     class SeparatingState : public State {
245     public:
246         explicit SeparatingState();
247         ~SeparatingState() override;
248         void GoInState() override;
249         void GoOutState() override;
250         bool ExecuteStateMsg(InternalMessagePtr msg) override;
251     };
252     /**
253      * @Description  Definition of member function of SeparatedState class in StaStateMachine.
254      *
255      */
256     class SeparatedState : public State {
257     public:
258         explicit SeparatedState(StaStateMachine *staStateMachine);
259         ~SeparatedState() override;
260         void GoInState() override;
261         void GoOutState() override;
262         bool ExecuteStateMsg(InternalMessagePtr msg) override;
263 
264     private:
265         StaStateMachine *pStaStateMachine;
266     };
267     /**
268      * @Description  Definition of member function of ApLinkedState class in StaStateMachine.
269      *
270      */
271     class ApLinkedState : public State {
272     public:
273         explicit ApLinkedState(StaStateMachine *staStateMachine);
274         ~ApLinkedState() override;
275         void GoInState() override;
276         void GoOutState() override;
277         bool ExecuteStateMsg(InternalMessagePtr msg) override;
278 
279     private:
280         void HandleNetWorkConnectionEvent(InternalMessagePtr msg);
281         void HandleStaBssidChangedEvent(InternalMessagePtr msg);
282         void HandleLinkSwitchEvent(InternalMessagePtr msg);
283     private:
284         StaStateMachine *pStaStateMachine;
285     };
286     /**
287      * @Description  Definition of member function of WpsState class in StaStateMachine.
288      *
289      */
290     class StaWpsState : public State {
291     public:
292         explicit StaWpsState(StaStateMachine *staStateMachine);
293         ~StaWpsState() override;
294         void GoInState() override;
295         void GoOutState() override;
296         bool ExecuteStateMsg(InternalMessagePtr msg) override;
297 
298     private:
299         StaStateMachine *pStaStateMachine;
300     };
301     /**
302      * @Description  Definition of member function of GetIpState class in StaStateMachine.
303      *
304      */
305     class GetIpState : public State {
306     public:
307         explicit GetIpState(StaStateMachine *staStateMachine);
308         ~GetIpState() override;
309         void GoInState() override;
310         void GoOutState() override;
311         bool ExecuteStateMsg(InternalMessagePtr msg) override;
312 
313     private:
314         bool IsPublicESS();
315         bool IsProhibitUseCacheIp();
316         StaStateMachine *pStaStateMachine;
317     };
318     /**
319      * @Description  Definition of member function of LinkedState class in StaStateMachine.
320      *
321      */
322     class LinkedState : public State {
323     public:
324         explicit LinkedState(StaStateMachine *staStateMachine);
325         ~LinkedState() override;
326         void GoInState() override;
327         void GoOutState() override;
328         bool ExecuteStateMsg(InternalMessagePtr msg) override;
329 
330     private:
331 #ifndef OHOS_ARCH_LITE
332         void CheckIfRestoreWifi();
333 #endif
334         void DhcpResultNotify(InternalMessagePtr msg);
335         void NetDetectionNotify(InternalMessagePtr msg);
336         StaStateMachine *pStaStateMachine;
337     };
338     /**
339      * @Description  Definition of member function of ApRoamingState class in StaStateMachine.
340      *
341      */
342     class ApRoamingState : public State {
343     public:
344         explicit ApRoamingState(StaStateMachine *staStateMachine);
345         ~ApRoamingState() override;
346         void GoInState() override;
347         void GoOutState() override;
348         bool ExecuteStateMsg(InternalMessagePtr msg) override;
349 
350     private:
351         bool HandleNetworkConnectionEvent(InternalMessagePtr msg);
352         StaStateMachine *pStaStateMachine;
353     };
354 
355     class DhcpResultNotify {
356     public:
357         /**
358          * @Description : Construct a new dhcp result notify object
359          *
360          */
361         explicit DhcpResultNotify();
362 
363         /**
364          * @Description : Destroy the dhcp result notify object
365          *
366          */
367         ~DhcpResultNotify();
368 
369         /**
370          * @Description : Get dhcp result of specified interface success notify asynchronously
371          *
372          * @param status - int
373          * @param ifname - interface name,eg:wlan0
374          * @param result - dhcp result
375          */
376         static void OnSuccess(int status, const char *ifname, DhcpResult *result);
377 
378         /**
379          * @Description : Get dhcp offer result of specified interface success notify asynchronously
380          *
381          * @param status - int
382          * @param ifname - interface name,eg:wlan0
383          * @param result - dhcp offer
384          */
385         static void OnDhcpOfferResult(int status, const char *ifname, DhcpResult *result);
386 
387         /**
388          * @Description : deal dhcp result
389          *
390          */
391         void DealDhcpResult(int ipType);
392 
393         /**
394          * @Description : Get dhcp result of specified interface failed notify asynchronously
395          *
396          * @param status - int
397          * @param ifname - interface name,eg:wlan0
398          * @param reason - failed reason
399          */
400         static void OnFailed(int status, const char *ifname, const char *reason);
401         /**
402          * @Description : deal dhcp result failed
403          *
404          */
405         void DealDhcpResultFailed();
406         void DealDhcpOfferResult();
407         static void SetStaStateMachine(StaStateMachine *staStateMachine);
408         static void TryToSaveIpV4Result(IpInfo &ipInfo, IpV6Info &ipv6Info, DhcpResult *result);
409         static void TryToSaveIpV4ResultExt(IpInfo &ipInfo, IpV6Info &ipv6Info, DhcpResult *result);
410         static void TryToSaveIpV6Result(IpInfo &ipInfo, IpV6Info &ipv6Info, DhcpResult *result);
411         static void TryToCloseDhcpClient(int iptype);
412         static void SaveDhcpResult(DhcpResult *dest, DhcpResult *source);
413         static void SaveDhcpResultExt(DhcpResult *dest, DhcpResult *source);
414     private:
415         static StaStateMachine *pStaStateMachine;
416         static DhcpResult DhcpIpv4Result;
417         static DhcpResult DhcpIpv6Result;
418         static DhcpResult DhcpOfferInfo;
419     };
420 
421 public:
422     /**
423      * @Description  Register dhcp client CallBack
424      *
425      * @Return:  DHCP_OPT_SUCCESS - success  DHCP_OPT_FAILED - failed
426      */
427     int RegisterCallBack();
428 
429     /**
430      * @Description  Initialize StaStateMachine
431      *
432      * @Return:  WIFI_OPT_SUCCESS - success  WIFI_OPT_FAILED - failed
433      */
434     ErrCode InitStaStateMachine();
435     /**
436      * @Description  Start roaming connection.
437      *
438      * @param bssid - the mac address of network(in)
439      */
440     void StartRoamToNetwork(std::string bssid);
441     /**
442      * @Description  if it is roaming now.
443      */
444     bool IsRoaming(void);
445     /**
446      * @Description  Connecting events
447      *
448      * @param networkId - the networkId of network which is going to be connected(in)
449      * @param bssid - bssid - the mac address of wifi(in)
450      */
451     void OnNetworkConnectionEvent(int networkId, std::string bssid);
452     /**
453      * @Description  Disconnect events
454      *
455      * @param reason - the reason of wifi disconnection
456      */
457     void OnNetworkDisconnectEvent(int reason);
458     /**
459      * @Description  sta chr events
460      *
461      * @param state - the state of wifi sta
462      */
463     void OnNetworkHiviewEvent(int state);
464     /**
465      * @Description  Assoc events
466      *
467      * @param reason - the state of wifi assoc
468      */
469     void OnNetworkAssocEvent(int assocState, std::string bssid, StaStateMachine *pStaStateMachine);
470     /**
471      * @Description  Bssid change events
472      *
473      * @param reason: the reason of bssid changed(in)
474      * @param bssid: the mac address of wifi(in)
475      */
476     void OnBssidChangedEvent(std::string reason, std::string bssid);
477     /**
478      * @Description  dhcp result notify events
479      *
480      * @param result: true-success, false-fail(in)
481      */
482     void OnDhcpResultNotifyEvent(DhcpReturnCode result, int ipType = -1);
483     /**
484      * @Description Register sta callback function
485      *
486      * @param callback - Callback function pointer storage structure
487      */
488     void RegisterStaServiceCallback(const StaServiceCallback &callback);
489 
490     /**
491      * @Description unRegister sta callback function
492      *
493      * @param callback - Callback function pointer storage structure
494      */
495     void UnRegisterStaServiceCallback(const StaServiceCallback &callback);
496 
497     /**
498      * @Description  Convert the deviceConfig structure and set it to idl structure
499      *
500      * @param config -The Network info(in)
501      * @param halDeviceConfig -The Network info(in)
502      * @Return success: WIFI_OPT_SUCCESS  fail: WIFI_OPT_FAILED
503      */
504     ErrCode FillEapCfg(const WifiDeviceConfig &config, WifiHalDeviceConfig &halDeviceConfig) const;
505 
506     /**
507      * @Description  Convert the deviceConfig structure and set it to wpa_supplicant
508      *
509      * @param config -The Network info(in)
510      * @Return success: WIFI_OPT_SUCCESS  fail: WIFI_OPT_FAILED
511      */
512     ErrCode ConvertDeviceCfg(const WifiDeviceConfig &config) const;
513 
514     /**
515      * @Description Get linked info.
516      *
517      * @param linkedInfo - linked info
518      * @return int - operation result
519      */
520     int GetLinkedInfo(WifiLinkedInfo& linkedInfo);
521 
522     /**
523      * @Description Reupdate net link info
524      */
525     void ReUpdateNetLinkInfo(const WifiDeviceConfig &config);
526 
527     /**
528      * @Description On netmanager restart.
529      */
530     void OnNetManagerRestart(void);
531 
532     /**
533      * @Description : start detect timer.
534      * @param detectType - type of detect
535      */
536     void StartDetectTimer(int detectType);
537 
538     /**
539      * @Description  start browser to login portal
540      *
541      */
542     void HandlePortalNetworkPorcess();
543 
544     void SetPortalBrowserFlag(bool flag);
545     int GetInstanceId();
546     void DealApRoamingStateTimeout(InternalMessagePtr msg);
547     void DealHiLinkDataToWpa(InternalMessagePtr msg);
548     void HilinkSetMacAddress(std::string &cmd);
549     void DealWpaStateChange(InternalMessagePtr msg);
550     void DealNetworkRemoved(InternalMessagePtr msg);
551 #ifndef OHOS_ARCH_LITE
552     void SetEnhanceService(IEnhanceService* enhanceService);
553     void SyncDeviceEverConnectedState(bool hasNet);
554     void UpdateAcceptUnvalidatedState();
555 #endif
556 
557     bool SetMacToHal(const std::string &currentMac, const std::string &realMac, int instId);
558 private:
559     /**
560      * @Description  Destruct state.
561      *
562      */
563     template<typename T>
ParsePointer(T * & pointer)564     inline void ParsePointer(T *&pointer)
565     {
566         if (pointer != nullptr) {
567             delete pointer;
568             pointer = nullptr;
569         }
570     }
571     /**
572      * @Description  Build state tree
573      *
574      */
575     void BuildStateTree();
576     /**
577      * @Description  Determine whether it is empty during initialization
578      *
579      */
580     template<typename T>
JudgmentEmpty(T * & pointer)581     inline ErrCode JudgmentEmpty(T *&pointer)
582     {
583         if (pointer == nullptr) {
584             return WIFI_OPT_FAILED;
585         }
586         return WIFI_OPT_SUCCESS;
587     }
588     /**
589      * @Description  Initializing state of Sta.
590      *
591      */
592     ErrCode InitStaStates();
593     /**
594      * @Description  The process of initializing connected wifi information.
595      *
596      */
597     void InitWifiLinkedInfo();
598     /**
599      * @Description  The process of initializing the last connected wifi information.
600      *
601      */
602     void InitLastWifiLinkedInfo();
603     /**
604      * @Description  Get device config information.
605      *
606      * @param bassid - the mac address of wifi(in).
607      * @param deviceConfig - the device config(out).
608      */
609     void GetDeviceCfgInfo(const std::string& bssid, WifiDeviceConfig &deviceConfig);
610     /**
611      * @Description  Setting linkedInfo in case of when wpa connects
612                      automatically there isn't any connection information.
613      *
614      * @param networkId - the nerworkId of network which is saved in the WifiLinkedInfo.(in)
615      */
616     void SetWifiLinkedInfo(int networkId);
617 
618     /**
619      * @Description  Save the current connected state into WifiLinkedInfo.
620      *
621      * @param state - current connecting state(in)
622      * @param detailState - the current detail state of StaStateMachine.(in)
623      */
624     void SaveLinkstate(ConnState state, DetailedState detailState);
625 
626     /**
627      * @Description  Save the disconnected reason.
628      *
629      * @param discReason - disconnected reason(in)
630      */
631     void SaveDiscReason(DisconnectedReason discReason);
632 
633     /**
634      * @Description  Translate frequency to band(2.4G or 5G).
635      *
636      * @param freQuency -the frequency needed to be translted into band.(in)
637      */
638     void GetBandFromFreQuencies(const int &freQuency);
639 
640     /**
641      * @Description  Processing after a success response is returned after Wi-Fi
642                      is enabled successfully, such as setting the MAC address and
643                      saving the connection information.
644      *
645      */
646     void StartWifiProcess();
647 
648     /**
649      * @Description  Update wifi status and save connection information.
650      *
651      * @param bssid - the mac address of wifi(in)
652      */
653     void ConnectToNetworkProcess(std::string bssid);
654 
655     /**
656      * @Description  Update wifi device config after wifi connected.
657      *
658      * @param deviceConfig - deviceConfig
659      * @param bssid - the mac address of wifi(in)
660      */
661     void UpdateDeviceConfigAfterWifiConnected(WifiDeviceConfig &deviceConfig, const std::string &bssid);
662 
663     /**
664      * @Description On connect fail.
665      *
666      * @param networkId - the networkId of network which is going to be connected.(in)
667      */
668     void OnConnectFailed(int networkId);
669 
670     /**
671      * @Description  Start to connect to network.
672      *
673      * @param networkId - the networkId of network which is going to be connected.(in)
674      * @param bssid - the bssid of network which is going to be connected.
675      * @Return success: WIFI_OPT_SUCCESS  fail: WIFI_OPT_FAILED
676      */
677     ErrCode StartConnectToNetwork(int networkId, const std::string &bssid);
678 
679     /**
680      * @Description  Disconnect network
681      *
682      */
683     void DisConnectProcess();
684 
685     /**
686      * @Description  Disable wifi process.
687      *
688      */
689     void StopWifiProcess();
690     /**
691      * @Description  Setting statemachine status during the process of enable or disable wifi.
692      *
693      * @param mode - operating mode(in)
694      */
695     void SetOperationalMode(int mode);
696     void SetSuspendMode(bool enabled);
697     void SetPowerMode(bool mode);
698     void SetPowerSave(bool enabled);
699 
700     /**
701      * @Description  Configure static ipaddress.
702      *
703      * @param staticIpAddress- static ip address(in)
704      */
705     bool ConfigStaticIpAddress(StaticIpAddress &staticIpAddress);
706 
707     /**
708      * @Description  the process of handling network check results.
709      *
710      * @param netState the state of connecting network(in)
711      * @param portalUrl portal network redirection address
712      */
713     void HandleNetCheckResult(SystemNetWorkState netState, const std::string &portalUrl);
714 
715     /**
716      * @Description  update portalState
717      *
718      * @param netState the state of connecting network(in)
719      * @param updatePortalAuthTime need update portalAuthTime or not [out]
720      */
721     void UpdatePortalState(SystemNetWorkState netState, bool &updatePortalAuthTime);
722 
723     /**
724      * @Description  start detection if portalState is expired
725      */
726     void PortalExpiredDetect();
727 
728     /**
729      * @Description implementation of the network detection callback function
730      *
731      * @param netState the state of connecting network
732      * @param url portal network redirection address
733      */
734     void NetStateObserverCallback(SystemNetWorkState netState, std::string url);
735 
736     /**
737      * @Description  the process of handling arp check results.
738      *
739      * @param arpState - the state of arp proto(in)
740      */
741     void HandleArpCheckResult(StaArpState arpState);
742 
743     /**
744      * @Description  the process of handling network check results.
745      *
746      * @param dnsState - the state of dns protol(in)
747      */
748     void HandleDnsCheckResult(StaDnsState dnsState);
749 
750     /**
751      * @Description  notification portal network.
752      *
753      */
754     void PublishPortalNetworkNotification();
755 
756     /**
757      * @Description  Remove all device configurations before enabling WPS.
758      *
759      */
760     void RemoveAllDeviceConfigs();
761 
762     /**
763      * @Description  Initialize the connection state processing message map
764      *
765      */
766     int InitStaSMHandleMap();
767 
768     /**
769      * @Description : Update RSSI to LinkedInfo.
770      *
771      * @param  inRssi - Rssi get from SignalPoll Result
772      */
773     int UpdateLinkInfoRssi(int inRssi);
774 
775     /**
776      * @Description : Deal SignalPoll Result.
777      */
778     void DealSignalPollResult();
779 
780     /**
781      * @Description : Update RSSI to LinkedInfo and public rssi changed broadcast.
782      *
783      * @param  signalInfo - SignalPoll Result
784      */
785     void UpdateLinkRssi(const WifiHalWpaSignalInfo &signalInfo);
786 
787     /**
788      * @Description : Converting frequencies to channels.
789      *
790      */
791     void ConvertFreqToChannel();
792 
793     /**
794      * @Description : send packet direction to hisysevent
795      *
796      */
797     void DealSignalPacketChanged(int txPackets, int rxPackets);
798 
799     /**
800      * @Description  Connect to selected network.
801      *
802      * @param  msg - Message body received by the state machine[in]
803      */
804     void DealConnectToSelectedNetCmd(InternalMessagePtr msg);
805 
806     /**
807      * @Description : Ready to connect to the network selected by user.
808      *
809      * @param msg - Message body received by the state machine[in]
810      */
811     void DealConnectToUserSelectedNetwork(InternalMessagePtr msg);
812 
813     /**
814      * @Description  Operations after the disconnection Event is reported.
815      *
816      * @param msg - Message body received by the state machine[in]
817      */
818     void DealDisconnectEvent(InternalMessagePtr msg);
819 
820     /**
821      * @Description  Operations after the Connection Event is reported.
822      *
823      * @param msg - Message body received by the state machine[in]
824      */
825     void DealConnectionEvent(InternalMessagePtr msg);
826 
827     /**
828      * @Description  Operations after Disable specified network commands.
829      *
830      * @param msg - Message body received by the state machine[in]
831      */
832     void DealConnectTimeOutCmd(InternalMessagePtr msg);
833 
834     /**
835      * @Description  Operations after Clear blocklist is reported.
836      *
837      * @param msg - Message body received by the state machine[in]
838      */
839     void DealWpaBlockListClearEvent(InternalMessagePtr msg);
840 
841     /**
842      * @Description  Operations after StartWps commands.
843      *
844      * @param msg - Message body received by the state machine[in]
845      */
846     void DealStartWpsCmd(InternalMessagePtr msg);
847 
848     /**
849      * @Description  Operations after the Wps Connect TimeOut Event is reported.
850      *
851      * @param msg - Message body received by the state machine[in]
852      */
853     void DealWpsConnectTimeOutEvent(InternalMessagePtr msg);
854 
855     /**
856      * @Description  Cancel wps connection
857      *
858      * @param msg - Message body received by the state machine[in]
859      */
860     void DealCancelWpsCmd(InternalMessagePtr msg);
861 
862     /**
863      * @Description  Reconnect network
864      *
865      * @param msg - Message body received by the state machine[in]
866      */
867     void DealReConnectCmd(InternalMessagePtr msg);
868 
869     /**
870      * @Description  Operations after the Reassociate lead is issued
871      *
872      * @param msg - Message body received by the state machine[in]
873      */
874     void DealReassociateCmd(InternalMessagePtr msg);
875 
876     /**
877      * @Description  Roaming connection.
878      *
879      * @param msg - Message body received by the state machine[in]
880      */
881     void DealStartRoamCmd(InternalMessagePtr msg);
882 
883     /**
884      * @Description  Operation after the password error is reported
885      *
886      * @param msg - Message body received by the state machine[in]
887      */
888     void DealWpaLinkFailEvent(InternalMessagePtr msg);
889 
890     /**
891      * @Description  set sta connect failed count
892      *@Return void
893      */
894     void DealSetStaConnectFailedCount(int count, bool set);
895 
896     /**
897      * @Description  Wps mode is ON
898      *
899      * @param msg - Message body received by the state machine[in]
900      */
901     void StartWpsMode(InternalMessagePtr msg);
902 
903     /**
904      * @Description  Reassociate network.
905      *
906      */
907     void ReassociateProcess();
908 
909     /**
910      * @Description  Set value of randomMacInfo.
911      *
912      * @param deviceConfig - deviceConfig[in]
913      * @param bssid - bssid[in]
914      * @param deviceConfig - randomMacInfo[out]
915      */
916     void InitRandomMacInfo(const WifiDeviceConfig &deviceConfig, const std::string &bssid,
917         WifiStoreRandomMac &randomMacInfo);
918 
919     /**
920      * @Description  Set a random MAC address.
921      *
922      * @param networkId - network id[in]
923      */
924     bool SetRandomMac(int networkId, const std::string &bssid);
925 
926     /**
927      * @Description  check whether the current bssid are consistent.
928      *
929      * @param bssid - bssid
930      */
931     bool CheckRoamingBssidIsSame(std::string bssid);
932 
933     /**
934      * @Description  Generate a random MAC address.
935      *
936      * @param strMac - Randomly generated MAC address[out]
937      */
938     void MacAddressGenerate(WifiStoreRandomMac &randomMacInfo);
939 
940     /**
941      * @Description  Compare the encryption mode of the current network with that of the network in the scanning result.
942      *
943      * @param scanInfoKeymgmt - Network encryption mode in the scanning result[in]
944      * @param deviceKeymgmt - Encryption mode of the current network[in]
945      */
946     bool ComparedKeymgmt(const std::string scanInfoKeymgmt, const std::string deviceKeymgmt);
947 
948     /**
949      * @Description : Deal network check cmd.
950      *
951      * @param msg - Message body received by the state machine[in]
952      */
953     void DealNetworkCheck(InternalMessagePtr msg);
954 
955     /**
956      * @Description : Deal get dhcp ip timeout.
957      *
958      * @param msg - Message body received by the state machine[in]
959      */
960     void DealGetDhcpIpTimeout(InternalMessagePtr msg);
961 
962     /**
963      * @Description : is wpa3 transition mode.
964      *
965      * @param ssid - ssid
966      */
967     bool IsWpa3Transition(std::string ssid) const;
968 
969     /**
970      * @Description : get wpa3 failreason connect fail count
971      *
972      * @param failreason - auth or assoc fail
973      * @param ssid - ssid
974      */
975     int GetWpa3FailCount(int failreason, std::string ssid) const;
976 
977     /**
978      * @Description : add wpa3 failreason connect fail count
979      *
980      * @param failreason - auth or assoc fail
981      * @param ssid - ssid
982      */
983     void AddWpa3FailCount(int failreason, std::string ssid);
984 
985     /**
986      * @Description : add wpa3 black map
987      *
988      * @param ssid - ssid
989      */
990     void AddWpa3BlackMap(std::string ssid);
991 
992     /**
993      * @Description : is in wpa3 black map
994      *
995      * @param ssid - ssid
996      */
997     bool IsInWpa3BlackMap(std::string ssid) const;
998 
999     /**
1000      * @Description : wpa3 transition selfcure
1001      *
1002      * @param failreason - auth or assoc fail
1003      * @param networkId - networkId
1004      */
1005     void OnWifiWpa3SelfCure(int failreason, int networkId);
1006 
1007     /**
1008      * @Description : Deal screen state change event.
1009      *
1010      * @param msg - Message body received by the state machine[in]
1011      */
1012     void DealScreenStateChangedEvent(InternalMessagePtr msg);
1013 
1014     /**
1015      * @Description set external sim
1016      *
1017      * @param ifName - port name(in)
1018      * @param eap - eap method(in)
1019      * @Return success: 0  fail: others
1020      */
1021     ErrCode SetExternalSim(const std::string ifName, const std::string &eap, int value) const;
1022 
1023     /**
1024      * @Description : should sta connect use factory mac address.
1025      *
1026      * @param networkId - networkId.
1027      */
1028     bool ShouldUseFactoryMac(const WifiDeviceConfig &deviceConfig);
1029 
1030     /**
1031      * @Description : Check Current Connect is used randomized mac or not.
1032      *
1033      * @param networkId - networkId.
1034      * @Return true: used randomized mac address.
1035      */
1036     bool CurrentIsRandomizedMac();
1037 
1038     /**
1039      * @Description : Check wpa report DisConnect reason is should stoptimer.
1040      *
1041      * @param reason - reason.
1042      * @Return true: need stop timer.
1043      */
1044     bool IsDisConnectReasonShouldStopTimer(int reason);
1045 
1046     /**
1047      * @Description : Hilink Save Data To Device Config.
1048      *
1049      */
1050     void HilinkSaveConfig(void);
1051 
1052     /**
1053      * @Description operation before dhcp
1054      */
1055     void HandlePreDhcpSetup();
1056 
1057     /**
1058      * @Description operation after dhcp
1059      */
1060     void HandlePostDhcpSetup();
1061 
1062 #ifndef OHOS_ARCH_LITE
1063     /**
1064      * @Description Get slot id.
1065      * @Return int32_t - 0:success, other value:failed
1066      */
1067     int32_t GetDataSlotId(int32_t slotId);
1068 
1069     /**
1070      * @Description Get card type.
1071      * @param cardType - card type
1072      * @Return int32_t - 0:success, other value:failed
1073      */
1074     int32_t GetCardType(CardType &cardType);
1075 
1076     /**
1077      * @Description Get default slot id.
1078      * @param slotId - slot id
1079      * @Return int32_t - 0 success, other value:failed
1080      */
1081     int32_t GetDefaultId(int32_t slotId);
1082 
1083     /**
1084      * @Description Get card state.
1085      * @param slotId - slot id
1086      * @Return int32_t - card state
1087      */
1088     int32_t GetSimCardState(int32_t slotId);
1089 
1090     /**
1091      * @Description verify simId.
1092      * @param simId - sim id
1093      * @Return int32_t - true: success, false: failed
1094      */
1095     bool IsValidSimId(int32_t simId);
1096 
1097     /**
1098      * @Description Check whether the SIM card is a multi-SIM card.
1099      * @Return int32_t - true: success, false: failed
1100      */
1101     bool IsMultiSimEnabled();
1102 
1103     /**
1104      * @Description sim authenticate
1105      * @param nonce - sim id
1106      * @Return int32_t - 0:success, other value:failed
1107      */
1108     std::string SimAkaAuth(const std::string &nonce, AuthType authType);
1109 
1110     /**
1111      * @Description Get SIM card authentication information.
1112      * @param param - authentication information
1113      * @Return int32_t - 0:success, other value:failed
1114      */
1115     std::string GetGsmAuthResponseWithLength(EapSimGsmAuthParam param);
1116 
1117     /**
1118      * @Description Get SIM card authentication information.
1119      * @param param - authentication information
1120      * @Return int32_t - 0:success, other value:failed
1121      */
1122     std::string GetGsmAuthResponseWithoutLength(EapSimGsmAuthParam param);
1123 
1124     /**
1125      * @Description sim authentication notify events
1126      *
1127      * @param msg: authentication data
1128      */
1129     void DealWpaEapSimAuthEvent(InternalMessagePtr msg);
1130 
1131     /**
1132      * @Description aka/aka' authentication Pre-process
1133      *
1134      */
1135     bool PreWpaEapUmtsAuthEvent();
1136 
1137     /**
1138      * @Description fill aka/aka' authentication request message
1139      *
1140      * @param param: authentication data
1141      */
1142     std::vector<uint8_t> FillUmtsAuthReq(EapSimUmtsAuthParam &param);
1143 
1144     /**
1145      * @Description fill aka/aka' authentication request message
1146      *
1147      * @param nonce: authentication data
1148      */
1149     std::string ParseAndFillUmtsAuthParam(std::vector<uint8_t> &nonce);
1150 
1151     /**
1152      * @Description Get aka/aka' card authentication information
1153      *
1154      * @param param: authentication data
1155      */
1156     std::string GetUmtsAuthResponse(EapSimUmtsAuthParam &param);
1157 
1158     /**
1159      * @Description aka/aka' authentication notify events
1160      *
1161      * @param msg: authentication data
1162      */
1163     void DealWpaEapUmtsAuthEvent(InternalMessagePtr msg);
1164 
1165     /**
1166      * @Description Get the SIM card ID.
1167      *
1168      */
1169     int32_t GetSimId();
1170 
1171     /**
1172      * @Description Set the SIM card ID.
1173      *
1174      * @param id - Sim card id
1175      */
1176     void SetSimId(int32_t simId);
1177 
1178     /**
1179      * @Description Subscribe system ability changed.
1180      */
1181     void SubscribeSystemAbilityChanged(void);
1182 
1183     /**
1184      * @Description save wificonfig for update mode.
1185      *
1186      * @param networkId - current connected networkId;
1187      */
1188     void SaveWifiConfigForUpdate(int networkId);
1189 #endif // OHOS_ARCH_LITE
1190 
1191 private:
1192     StaSmHandleFuncMap staSmHandleFuncMap;
1193     std::shared_mutex m_staCallbackMutex;
1194     std::map<std::string, StaServiceCallback> m_staCallback;
1195     bool m_hilinkFlag = false;
1196     WifiDeviceConfig m_hilinkDeviceConfig;
1197 #ifndef OHOS_ARCH_LITE
1198     sptr<NetManagerStandard::NetSupplierInfo> NetSupplierInfo;
1199     sptr<NetStateObserver> m_NetWorkState;
1200     IEnhanceService *enhanceService_ = nullptr;        /* EnhanceService handle */
1201 #endif
1202 
1203     int lastNetworkId;
1204     int operationalMode;
1205     int targetNetworkId;
1206     int pinCode;
1207     SetupMethod wpsState;
1208     int lastSignalLevel_;
1209     std::string targetRoamBssid;
1210     int currentTpType;
1211     IsWpsConnected isWpsConnect;
1212     int getIpSucNum;
1213     int getIpFailNum;
1214     bool enableSignalPoll;
1215     bool isRoam;
1216     int64_t lastTimestamp;
1217     bool portalFlag;
1218     PortalState portalState;
1219     int detectNum;
1220     int portalExpiredDetectCount;
1221     bool mIsWifiInternetCHRFlag;
1222     bool networkStatusHistoryInserted;
1223     WifiLinkedInfo linkedInfo;
1224     WifiLinkedInfo lastLinkedInfo;
1225     DhcpResultNotify *pDhcpResultNotify;
1226     ClientCallBack clientCallBack;
1227     DhcpClientReport dhcpClientReport_;
1228     RootState *pRootState;
1229     InitState *pInitState;
1230     WpaStartingState *pWpaStartingState; /* Starting wpa_supplicant state. */
1231     WpaStartedState *pWpaStartedState;   /* Started wpa_supplicant state. */
1232     WpaStoppingState *pWpaStoppingState; /* Stopping wpa_supplicant state. */
1233     LinkState *pLinkState;
1234     SeparatingState *pSeparatingState;
1235     SeparatedState *pSeparatedState;
1236     ApLinkedState *pApLinkedState;
1237     StaWpsState *pWpsState;
1238     GetIpState *pGetIpState;
1239     LinkedState *pLinkedState;
1240     ApRoamingState *pApRoamingState;
1241     int m_instId;
1242     std::map<std::string, time_t> wpa3BlackMap;
1243     std::map<std::string, int> wpa3ConnectFailCountMapArray[WPA3_FAIL_REASON_MAX];
1244     std::string mPortalUrl;
1245     int mLastConnectNetId;      /* last request connect netword id */
1246     int mConnectFailedCnt;      /* mLastConnectNetId connect failed count */
1247     /**
1248      * @Description Replace empty dns
1249      */
1250     void ReplaceEmptyDns(DhcpResult *result);
1251     void InvokeOnStaConnChanged(OperateResState state, const WifiLinkedInfo &info);
1252     void InvokeOnWpsChanged(WpsStartState state, const int code);
1253     void InvokeOnStaStreamChanged(StreamDirection direction);
1254     void InvokeOnStaRssiLevelChanged(int level);
1255     void InvokeOnDhcpOfferReport(IpInfo ipInfo);
1256     WifiDeviceConfig getCurrentWifiDeviceConfig();
1257     void InsertOrUpdateNetworkStatusHistory(const NetworkStatus &networkStatus, bool updatePortalAuthTime);
1258     bool CanArpReachable();
1259     void AddRandomMacCure();
1260     ErrCode ConfigRandMacSelfCure(const int networkId);
1261 #ifndef OHOS_ARCH_LITE
1262     void ShowPortalNitification();
1263     void SetSupportedWifiCategory();
1264     void UpdateWifiCategory();
1265 #endif
1266     void SetConnectMethod(int connectMethod);
1267     void FillSuiteB192Cfg(WifiHalDeviceConfig &halDeviceConfig) const;
1268     void FillWapiCfg(const WifiDeviceConfig &config, WifiHalDeviceConfig &halDeviceConfig) const;
1269     void TransHalDeviceConfig(WifiHalDeviceConfig &halDeviceConfig, const WifiDeviceConfig &config) const;
1270     void SetRandomMacConfig(WifiStoreRandomMac &randomMacInfo, const WifiDeviceConfig &deviceConfig,
1271     std::string &currentMac);
1272     bool IsGoodSignalQuality();
1273     void AppendFastTransitionKeyMgmt(const WifiScanInfo &scanInfo, WifiHalDeviceConfig &halDeviceConfig) const;
1274     void ConvertSsidToOriginalSsid(const WifiDeviceConfig &config, WifiHalDeviceConfig &halDeviceConfig) const;
1275 };
1276 }  // namespace Wifi
1277 }  // namespace OHOS
1278 #endif
1279