• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "wifi_internal_msg.h"
23 #include "wifi_log.h"
24 #include "wifi_errcode.h"
25 #include "wifi_msg.h"
26 #include "state_machine.h"
27 #include "sta_network_check.h"
28 #include "i_dhcp_result_notify.h"
29 #include "sta_service_callback.h"
30 #include "i_dhcp_service.h"
31 #include "sta_define.h"
32 #include "wifi_net_agent.h"
33 
34 namespace OHOS {
35 namespace Wifi {
36 constexpr int STA_CONNECT_MODE = 1;
37 constexpr int STA_SCAN_ONLY_MODE = 2;
38 constexpr int STA_CAN_ONLY_WITH_WIFI_OFF_MODE = 3;
39 constexpr int STA_DISABLED_MODE = 4;
40 
41 constexpr int CMD_NETWORK_CONNECT_TIMEOUT = 0X01;
42 constexpr int STA_NETWORK_CONNECTTING_DELAY = 30 * 1000;
43 
44 constexpr int CMD_SIGNAL_POLL = 0X02;
45 constexpr int STA_SIGNAL_POLL_DELAY = 3 * 1000;
46 
47 /* pincode length */
48 constexpr int PIN_CODE_LEN = 8;
49 
50 /* DHCP timeout interval */
51 constexpr int DHCP_TIME = 15;
52 /* rssi thresholds */
53 constexpr int INVALID_RSSI_VALUE = -127;
54 constexpr int MAX_RSSI_VALUE = 200;
55 constexpr int SIGNAL_INFO = 256;
56 
57 /* 2.4g and 5g frequency thresholds */
58 constexpr int FREQ_2G_MIN = 2412;
59 constexpr int FREQ_2G_MAX = 2472;
60 constexpr int FREQ_5G_MIN = 5170;
61 constexpr int FREQ_5G_MAX = 5825;
62 constexpr int CHANNEL_14_FREQ = 2484;
63 constexpr int CHANNEL_14 = 14;
64 constexpr int CENTER_FREQ_DIFF = 5;
65 constexpr int CHANNEL_2G_MIN = 1;
66 constexpr int CHANNEL_5G_MIN = 34;
67 
68 constexpr int MULTI_AP = 0;
69 
70 /*
71  * During the WPS PIN connection, the WPA_SUPPLICANT blocklist is cleared every 10 seconds
72  * until the network connection is successful.
73  */
74 constexpr int BLOCK_LIST_CLEAR_TIMER = 20 * 1000;
75 
76 /* Signal levels are classified into: 0 1 2 3 4 ,the max is 4. */
77 constexpr int MAX_LEVEL = 4;
78 const std::string WPA_BSSID_ANY = "any";
79 const std::string IF_NAME = "wlan0";
80 
81 class StaStateMachine : public StateMachine {
82     FRIEND_GTEST(StaStateMachine);
83 public:
84     StaStateMachine();
85     ~StaStateMachine();
86     using staSmHandleFunc = void (StaStateMachine::*)(InternalMessage *msg);
87     using StaSmHandleFuncMap = std::map<int, staSmHandleFunc>;
88     /**
89      * @Description  Definition of member function of State base class in StaStateMachine.
90      *
91      */
92     class RootState : public State {
93     public:
94         explicit RootState();
95         ~RootState() override;
96         void GoInState() override;
97         void GoOutState() override;
98         bool ExecuteStateMsg(InternalMessage *msg) override;
99     };
100     /**
101      * @Description : Definition of member function of InitState class in StaStateMachine.
102      *
103      */
104     class InitState : public State {
105     public:
106         explicit InitState(StaStateMachine *pStaStateMachine);
107         ~InitState() override;
108         void GoInState() override;
109         void GoOutState() override;
110         bool ExecuteStateMsg(InternalMessage *msg) override;
111 
112     private:
113         StaStateMachine *pStaStateMachine;
114     };
115     /**
116      * @Description : Definition of member function of WpaStartingState class in StaStateMachine.
117      *
118      */
119     class WpaStartingState : public State {
120     public:
121         explicit WpaStartingState(StaStateMachine *pStaStateMachine);
122         ~WpaStartingState() override;
123         void InitWpsSettings();
124         void GoInState() override;
125         void GoOutState() override;
126         bool ExecuteStateMsg(InternalMessage *msg) override;
127 
128     private:
129         StaStateMachine *pStaStateMachine;
130     };
131     /**
132      * @Description  Definition of member function of WpaStartedState class in StaStateMachine.
133      *
134      */
135     class WpaStartedState : public State {
136     public:
137         explicit WpaStartedState(StaStateMachine *pStaStateMachine);
138         ~WpaStartedState() override;
139         void GoInState() override;
140         void GoOutState() override;
141         bool ExecuteStateMsg(InternalMessage *msg) override;
142 
143     private:
144         StaStateMachine *pStaStateMachine;
145     };
146     /**
147      * @Description  Definition of member function of WpaStoppingState class in StaStateMachine.
148      *
149      */
150     class WpaStoppingState : public State {
151     public:
152         explicit WpaStoppingState(StaStateMachine *pStaStateMachine);
153         ~WpaStoppingState() override;
154         void GoInState() override;
155         void GoOutState() override;
156         bool ExecuteStateMsg(InternalMessage *msg) override;
157 
158     private:
159         StaStateMachine *pStaStateMachine;
160     };
161     /**
162      * @Description  Definition of member function of LinkState class in StaStateMachine.
163      *
164      */
165     class LinkState : public State {
166     public:
167         explicit LinkState(StaStateMachine *pStaStateMachine);
168         ~LinkState() override;
169         void GoInState() override;
170         void GoOutState() override;
171         bool ExecuteStateMsg(InternalMessage *msg) override;
172 
173     private:
174         StaStateMachine *pStaStateMachine;
175     };
176     /**
177      * @Description  Definition of member function of SeparatingState class in StaStateMachine.
178      *
179      */
180     class SeparatingState : public State {
181     public:
182         explicit SeparatingState();
183         ~SeparatingState() override;
184         void GoInState() override;
185         void GoOutState() override;
186         bool ExecuteStateMsg(InternalMessage *msg) override;
187     };
188     /**
189      * @Description  Definition of member function of SeparatedState class in StaStateMachine.
190      *
191      */
192     class SeparatedState : public State {
193     public:
194         explicit SeparatedState(StaStateMachine *pStaStateMachine);
195         ~SeparatedState() override;
196         void GoInState() override;
197         void GoOutState() override;
198         bool ExecuteStateMsg(InternalMessage *msg) override;
199 
200     private:
201         StaStateMachine *pStaStateMachine;
202     };
203     /**
204      * @Description  Definition of member function of ApLinkedState class in StaStateMachine.
205      *
206      */
207     class ApLinkedState : public State {
208     public:
209         explicit ApLinkedState(StaStateMachine *pStaStateMachine);
210         ~ApLinkedState() override;
211         void GoInState() override;
212         void GoOutState() override;
213         bool ExecuteStateMsg(InternalMessage *msg) override;
214 
215     private:
216         StaStateMachine *pStaStateMachine;
217     };
218     /**
219      * @Description  Definition of member function of WpsState class in StaStateMachine.
220      *
221      */
222     class StaWpsState : public State {
223     public:
224         explicit StaWpsState(StaStateMachine *pStaStateMachine);
225         ~StaWpsState() override;
226         void GoInState() override;
227         void GoOutState() override;
228         bool ExecuteStateMsg(InternalMessage *msg) override;
229 
230     private:
231         StaStateMachine *pStaStateMachine;
232     };
233     /**
234      * @Description  Definition of member function of GetIpState class in StaStateMachine.
235      *
236      */
237     class GetIpState : public State {
238     public:
239         explicit GetIpState(StaStateMachine *pStaStateMachine);
240         ~GetIpState() override;
241         void GoInState() override;
242         void GoOutState() override;
243         bool ExecuteStateMsg(InternalMessage *msg) override;
244 
245     private:
246         StaStateMachine *pStaStateMachine;
247     };
248     /**
249      * @Description  Definition of member function of LinkedState class in StaStateMachine.
250      *
251      */
252     class LinkedState : public State {
253     public:
254         explicit LinkedState();
255         ~LinkedState() override;
256         void GoInState() override;
257         void GoOutState() override;
258         bool ExecuteStateMsg(InternalMessage *msg) override;
259     };
260     /**
261      * @Description  Definition of member function of ApRoamingState class in StaStateMachine.
262      *
263      */
264     class ApRoamingState : public State {
265     public:
266         explicit ApRoamingState(StaStateMachine *pStaStateMachine);
267         ~ApRoamingState() override;
268         void GoInState() override;
269         void GoOutState() override;
270         bool ExecuteStateMsg(InternalMessage *msg) override;
271 
272     private:
273         StaStateMachine *pStaStateMachine;
274     };
275 
276     class DhcpResultNotify : public IDhcpResultNotify {
277     public:
278         /**
279          * @Description : Construct a new dhcp result notify object
280          *
281          */
282         explicit DhcpResultNotify(StaStateMachine *pStaStateMachine);
283 
284         /**
285          * @Description : Destroy the dhcp result notify object
286          *
287          */
288         ~DhcpResultNotify() override;
289 
290         /**
291          * @Description : Get dhcp result of specified interface success notify asynchronously
292          *
293          * @param status - int
294          * @param ifname - interface name,eg:wlan0
295          * @param result - dhcp result
296          */
297         void OnSuccess(int status, const std::string &ifname, DhcpResult &result) override;
298 
299         /**
300          * @Description : Get dhcp result of specified interface failed notify asynchronously
301          *
302          * @param status - int
303          * @param ifname - interface name,eg:wlan0
304          * @param reason - failed reason
305          */
306         void OnFailed(int status, const std::string &ifname, const std::string &reason) override;
307 
308         /**
309         * @Description : Get the abnormal exit notify of dhcp server process.
310         *
311         * @param ifname - interface name,eg:wlan0
312         */
313         void OnSerExitNotify(const std::string& ifname) override;
314     private:
315         StaStateMachine *pStaStateMachine;
316     };
317 
318 public:
319     /**
320      * @Description  Initialize StaStateMachine
321      *
322      * @Return:  WIFI_OPT_SUCCESS - success  WIFI_OPT_FAILED - failed
323      */
324     ErrCode InitStaStateMachine();
325     /**
326      * @Description  Start roaming connection.
327      *
328      * @param bssid - the mac address of network(in)
329      */
330     void StartRoamToNetwork(std::string bssid);
331     /**
332      * @Description  Connecting events
333      *
334      * @param networkId - the networkId of network which is going to be connected(in)
335      * @param bssid - bssid - the mac address of wifi(in)
336      */
337     void OnNetworkConnectionEvent(int networkId, std::string bssid);
338 
339     /**
340      * @Description Register sta callback function
341      *
342      * @param callbacks - Callback function pointer storage structure
343      */
344     void RegisterStaServiceCallback(const StaServiceCallback &callbacks);
345 
346     /**
347      * @Description  Convert the deviceConfig structure and set it to wpa_supplicant
348      *
349      * @param config -The Network info(in)
350      * @Return success: WIFI_OPT_SUCCESS  fail: WIFI_OPT_FAILED
351      */
352     ErrCode ConvertDeviceCfg(const WifiDeviceConfig &config) const;
353 
354     /**
355      * @Description Get linked info.
356      *
357      * @param linkedInfo - linked info
358      * @return int - operation result
359      */
360     int GetLinkedInfo(WifiLinkedInfo& linkedInfo);
361 
362 private:
363     /**
364      * @Description  Destruct state.
365      *
366      */
367     template<typename T>
ParsePointer(T * & pointer)368     inline void ParsePointer(T *&pointer)
369     {
370         if (pointer != nullptr) {
371             delete pointer;
372             pointer = nullptr;
373         }
374     }
375     /**
376      * @Description  Build state tree
377      *
378      */
379     void BuildStateTree();
380     /**
381      * @Description  Determine whether it is empty during initialization
382      *
383      */
384     template<typename T>
JudgmentEmpty(T * & pointer)385     inline ErrCode JudgmentEmpty(T *&pointer)
386     {
387         if (pointer == nullptr) {
388             return WIFI_OPT_FAILED;
389         }
390         return WIFI_OPT_SUCCESS;
391     }
392     /**
393      * @Description  Initializing state of Sta.
394      *
395      */
396     ErrCode InitStaStates();
397     /**
398      * @Description  The process of initializing connected wifi information.
399      *
400      */
401     void InitWifiLinkedInfo();
402     /**
403      * @Description  The process of initializing the last connected wifi information.
404      *
405      */
406     void InitLastWifiLinkedInfo();
407     /**
408      * @Description  Setting linkedInfo in case of when wpa connects
409                      automatically there isn't any connection information.
410      *
411      * @param networkId - the nerworkId of network which is saved in the WifiLinkedInfo.(in)
412      */
413     void SetWifiLinkedInfo(int networkId);
414     /**
415      * @Description  Save the current connected state into WifiLinkedInfo.
416      *
417      * @param state - current connecting state(in)
418      * @param detailState - the current detail state of StaStateMachine.(in)
419      */
420     void SaveLinkstate(ConnState state, DetailedState detailState);
421     /**
422      * @Description  Translate frequency to band(2.4G or 5G).
423      *
424      * @param freQuency -the frequency needed to be translted into band.(in)
425      */
426     void GetBandFromFreQuencies(const int &freQuency);
427 
428     /**
429      * @Description  Processing after a success response is returned after Wi-Fi
430                      is enabled successfully, such as setting the MAC address and
431                      saving the connection information.
432      *
433      */
434     void StartWifiProcess();
435     /**
436      * @Description  Synchronize the deviceConfig structure to wpa_supplicant
437      */
438     void SyncDeviceConfigToWpa() const;
439     /**
440      * @Description  Update wifi status and save connection information.
441      *
442      * @param networkId - the networkId of selected network which is going to be connected(in)
443      * @param bssid - the mac address of wifi(in)
444      */
445     void ConnectToNetworkProcess(InternalMessage *msg);
446 
447     /**
448      * @Description On connect fail.
449      *
450      * @param networkId - the networkId of network which is going to be connected.(in)
451      */
452     void OnConnectFailed(int networkId);
453 
454     /**
455      * @Description  Start to connect to network.
456      *
457      * @param networkId - the networkId of network which is going to be connected.(in)
458      * @Return success: WIFI_OPT_SUCCESS  fail: WIFI_OPT_FAILED
459      */
460     ErrCode StartConnectToNetwork(int networkId);
461     /**
462      * @Description  Disable network
463      *
464      * @param networkId - the networkId of network which is going to be disabled.(in)
465      */
466     ErrCode DisableNetwork(int networkId);
467     /**
468      * @Description  Disconnect network
469      *
470      */
471     void DisConnectProcess();
472     /**
473      * @Description  Disable wifi process.
474      *
475      */
476     void StopWifiProcess();
477     /**
478      * @Description  Setting statemachine status during the process of enable or disable wifi.
479      *
480      * @param mode - operating mode(in)
481      */
482     void SetOperationalMode(int mode);
483     void SetSuspendMode(bool enabled);
484     void SetPowerSave(bool enabled);
485     /**
486      * @Description  Configure static ipaddress.
487      *
488      * @param staticIpAddress- static ip address(in)
489      */
490     bool ConfigStaticIpAddress(StaticIpAddress &staticIpAddress);
491     int PortalHttpDetection();
492     /**
493      * @Description  the process of handling network check results.
494      *
495      * @param netState - the state of connecting network(in)
496      */
497     void HandleNetCheckResult(StaNetState netState, const std::string portalUrl);
498     /**
499      * @Description  Remove all device configurations before enabling WPS.
500      *
501      */
502     void RemoveAllDeviceConfigs();
503     /**
504      * @Description  Synchronize all networks saved in the configuration center to the WPA.
505      *
506      */
507     void SyncAllDeviceConfigs();
508     /**
509      * @Description  Initialize the connection state processing message map
510      *
511      */
512     int InitStaSMHandleMap();
513     /**
514      * @Description : Deal SignalPoll Result.
515      *
516      * @param  msg - Message body received by the state machine[in]
517      */
518     void DealSignalPollResult(InternalMessage *msg);
519     /**
520      * @Description : Converting frequencies to channels.
521      *
522      */
523     void ConvertFreqToChannel();
524     /**
525      * @Description  Connect to selected network.
526      *
527      * @param  msg - Message body received by the state machine[in]
528      */
529     void DealConnectToSelectedNetCmd(InternalMessage *msg);
530     /**
531      * @Description : Ready to connect to the network selected by user.
532      *
533      * @param msg - Message body received by the state machine[in]
534      */
535     void DealConnectToUserSelectedNetwork(InternalMessage *msg);
536     /**
537      * @Description  Operations after the disconnection Event is reported.
538      *
539      * @param msg - Message body received by the state machine[in]
540      */
541     void DealDisconnectEvent(InternalMessage *msg);
542     /**
543      * @Description  Operations after the Connection Event is reported.
544      *
545      * @param msg - Message body received by the state machine[in]
546      */
547     void DealConnectionEvent(InternalMessage *msg);
548     /**
549      * @Description  Operations after Disable specified network commands.
550      *
551      * @param msg - Message body received by the state machine[in]
552      */
553     void DealConnectTimeOutCmd(InternalMessage *msg);
554     /**
555      * @Description  Operations after Clear blocklist is reported.
556      *
557      * @param msg - Message body received by the state machine[in]
558      */
559     void DealWpaBlockListClearEvent(InternalMessage *msg);
560     /**
561      * @Description  Operations after StartWps commands.
562      *
563      * @param msg - Message body received by the state machine[in]
564      */
565     void DealStartWpsCmd(InternalMessage *msg);
566     /**
567      * @Description  Operations after the Wps Connect TimeOut Event is reported.
568      *
569      * @param msg - Message body received by the state machine[in]
570      */
571     void DealWpsConnectTimeOutEvent(InternalMessage *msg);
572     /**
573      * @Description  Cancel wps connection
574      *
575      * @param msg - Message body received by the state machine[in]
576      */
577     void DealCancelWpsCmd(InternalMessage *msg);
578     /**
579      * @Description  Reconnect network
580      *
581      * @param msg - Message body received by the state machine[in]
582      */
583     void DealReConnectCmd(InternalMessage *msg);
584     /**
585      * @Description  Operations after the Reassociate lead is issued
586      *
587      * @param msg - Message body received by the state machine[in]
588      */
589     void DealReassociateCmd(InternalMessage *msg);
590     /**
591      * @Description  Roaming connection.
592      *
593      * @param msg - Message body received by the state machine[in]
594      */
595     void DealStartRoamCmd(InternalMessage *msg);
596     /**
597      * @Description  Operation after the password error is reported
598      *
599      * @param msg - Message body received by the state machine[in]
600      */
601     void DealWpaLinkFailEvent(InternalMessage *msg);
602     /**
603      * @Description  Wps mode is ON
604      *
605      * @param msg - Message body received by the state machine[in]
606      */
607     void StartWpsMode(InternalMessage *msg);
608     /**
609      * @Description  Reassociate network.
610      *
611      */
612     void ReassociateProcess();
613 
614     /**
615      * @Description  Set a random MAC address.
616      *
617      * @param networkId - network id[in]
618      */
619     bool SetRandomMac(int networkId);
620     /**
621      * @Description  Generate a random MAC address.
622      *
623      * @param strMac - Randomly generated MAC address[out]
624      */
625     void MacAddressGenerate(std::string &strMac);
626     /**
627      * @Description  Compare the encryption mode of the current network with that of the network in the scanning result.
628      *
629      * @param scanInfoKeymgmt - Network encryption mode in the scanning result[in]
630      * @param deviceKeymgmt - Encryption mode of the current network[in]
631      */
632     bool ComparedKeymgmt(const std::string scanInfoKeymgmt, const std::string deviceKeymgmt);
633 
634 private:
635     StaSmHandleFuncMap staSmHandleFuncMap;
636     StaServiceCallback staCallback;
637     sptr<NetManagerStandard::NetSupplierInfo> NetSupplierInfo;
638 
639     int lastNetworkId;
640     int operationalMode;
641     int targetNetworkId;
642     int pinCode;
643     SetupMethod wpsState;
644     int lastSignalLevel;
645     std::string targetRoamBssid;
646     int currentTpType;
647     IsWpsConnected isWpsConnect;
648     int getIpSucNum;
649     int getIpFailNum;
650     bool isRoam;
651     WifiLinkedInfo linkedInfo;
652     WifiLinkedInfo lastLinkedInfo;
653     IDhcpService *pDhcpService;
654     DhcpResultNotify *pDhcpResultNotify;
655     StaNetworkCheck *pNetcheck;
656 
657     RootState *pRootState;
658     InitState *pInitState;
659     WpaStartingState *pWpaStartingState; /* Starting wpa_supplicant state. */
660     WpaStartedState *pWpaStartedState;   /* Started wpa_supplicant state. */
661     WpaStoppingState *pWpaStoppingState; /* Stopping wpa_supplicant state. */
662     LinkState *pLinkState;
663     SeparatingState *pSeparatingState;
664     SeparatedState *pSeparatedState;
665     ApLinkedState *pApLinkedState;
666     StaWpsState *pWpsState;
667     GetIpState *pGetIpState;
668     LinkedState *pLinkedState;
669     ApRoamingState *pApRoamingState;
670 };
671 }  // namespace Wifi
672 }  // namespace OHOS
673 #endif
674