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 
16 #ifndef OHOS_WIFI_GLOBAL_FUNC_H
17 #define OHOS_WIFI_GLOBAL_FUNC_H
18 
19 #include <vector>
20 #include <random>
21 #include <string>
22 #include "wifi_errcode.h"
23 #include "wifi_ap_msg.h"
24 #include "wifi_internal_msg.h"
25 #include "wifi_msg.h"
26 #include "wifi_scan_msg.h"
27 
28 namespace OHOS {
29 namespace Wifi {
30 constexpr int MAC_STRING_SIZE = 17;
31 constexpr int MIN_SSID_LEN = 1;
32 constexpr int MAX_SSID_LEN = 32;
33 constexpr int MIN_PSK_LEN = 8;
34 constexpr int MAX_PSK_LEN = 63;
35 constexpr int HEX_TYPE_LEN = 3; /* 3 hex type: 0 a A */
36 constexpr int MAX_AP_CONN = 32;
37 constexpr int MAX_CONFIGS_NUM = 1000;
38 typedef void (*ParameterChgPtr)(const char *key, const char *value, void *context);
39 
40 /**
41  * @Description Get a random string
42  *
43  * @param len - Random string length
44  * @return std::string - Random String
45  */
46 std::string GetRandomStr(int len);
47 
48 /**
49  * @Description get a random num
50  *
51  * @param start - The lower limit of the range of random numbers
52  * @param end - The upper limit of the range of random numbers
53  * @return random num
54  */
55 int GetRandomInt(int start, int end);
56 
57 /**
58  * @Description If allowed scan always according the scan control policy
59  *
60  * @param info - ScanControlInfo object
61  * @return true - allowed
62  * @return false - not allowed
63  */
64 bool IsAllowScanAnyTime(const ScanControlInfo &info);
65 
66 /**
67  * @Description Internal transition from OperateResState struct to ConnState
68  *
69  * @param resState - OperateResState state
70  * @param isReport - true : need report; flase : not report
71  * @return ConnState - convert output connection state
72  */
73 ConnState ConvertConnStateInternal(OperateResState resState, bool &isReport);
74 
75 /**
76  * @Description Check whether the MAC address is valid
77  *
78  * @param macStr - input the mac address
79  * @return int - 0 Valid; -1 Invalid
80  */
81 int CheckMacIsValid(const std::string &macStr);
82 
83 /**
84  * @Description Split string to vector accord split
85  *
86  * @param str - input string
87  * @param split - split string
88  * @param vec - return string vector
89  */
90 void SplitString(const std::string &str, const std::string &split, std::vector<std::string> &vec);
91 
92 /**
93  * @Description Converts a numeric vector to a character array.
94  *
95  * @param vec - Input numeric vector.[in]
96  * @param pChar - Character array.[out]
97  * @param len - Length of character array.[out]
98  * @param memSize - Character array's memory size.[in]
99  * @return int - 0 Valid; -1 Invalid
100  */
101 template <typename T>
Vec2Char(const std::vector<T> & vec,T * pChar,int & len,int memSize)102 int Vec2Char(const std::vector<T> &vec, T *pChar, int& len, int memSize)
103 {
104     if (pChar == nullptr) {
105         len = 0;
106         return -1;
107     }
108 
109     const int vecSize = static_cast<int>(vec.size());
110     if (vecSize > memSize) {
111         pChar = nullptr;
112         len = 0;
113         return -1;
114     }
115 
116     for (int i = 0; i < vecSize; i++) {
117         pChar[i] = vec[i];
118     }
119     len = vecSize;
120     return 0;
121 }
122 
123 /**
124  * @Description Converts a character array to a numeric vector.
125  *
126  * @param pChar - Character array.[in]
127  * @param len - Length of character array.[in]
128  * @param vec - Input numeric vector.[out]
129  * @return int - 0 Valid; -1 Invalid
130  */
131 template <typename T>
Char2Vec(const T * pChar,int len,std::vector<T> & vec)132 int Char2Vec(const T *pChar, int len, std::vector<T> &vec)
133 {
134     vec.clear();
135     if (pChar == nullptr || len < 0) {
136         return -1;
137     }
138 
139     for (int i = 0; i < len; i++) {
140         vec.push_back(pChar[i]);
141     }
142 
143     return 0;
144 }
145 
146 /**
147  * @Description Converts a char/unsigned char/byte/int8 vector to a hexadecimal character array. A numeric
148  * value is converted to two characters. e.g. 0x3F -> '3' 'F'
149  *
150  * @param vec - Input numeric vector.
151  * @param pHexChar - Character array.
152  * @param memSize - Character array's memory size.
153  * @return int - 0 Valid; -1 Invalid
154  */
155 template<typename T>
Val2HexChar(const std::vector<T> & vec,char * pHexChar,unsigned memSize)156 int Val2HexChar(const std::vector<T> &vec, char *pHexChar, unsigned memSize)
157 {
158     unsigned size = vec.size();
159     unsigned doubleSize = (size << 1);
160     if (doubleSize >= memSize) {
161         return -1;
162     }
163     const std::string hexStr = "0123456789ABCDEF";
164     const unsigned highBit = 4;
165     int pos = 0;
166     for (unsigned i = 0; i < size; ++i) {
167         unsigned char tmp = vec[i];
168         pHexChar[pos] = hexStr[(tmp >> highBit) & 0x0F];
169         ++pos;
170         pHexChar[pos] = hexStr[tmp & 0x0F];
171         ++pos;
172     }
173     pHexChar[pos] = '\0';
174     return 0;
175 }
176 
177 template <typename T>
JoinVecToString(const std::vector<T> & vec,const std::string & delimiter)178 std::string JoinVecToString(const std::vector<T> &vec, const std::string &delimiter)
179 {
180     std::stringstream ss;
181     std::copy(vec.begin(), vec.end(), std::ostream_iterator<T>(ss, delimiter.c_str()));
182     std::string joinedStr = ss.str();
183     if (joinedStr.size() > delimiter.size()) {
184         joinedStr.erase(joinedStr.size() - delimiter.size());
185     }
186     return joinedStr;
187 }
188 
189 /**
190  * @Description splitting numeric strings based on characters
191  *
192  * @param str - split string
193  * @param split - characters used for splitting
194  * @return number vector
195  */
196 std::vector<int> SplitStringToIntVector(const std::string &str, const std::string &split);
197 
198 /**
199  * @Description  Output vecChar to stream.
200  * @param prefix  - prefix string[in]
201  * @param vecChar - vector char[in]
202  * @param suffix  - suffix string[in]
203  */
204 std::string Vec2Stream(const std::string &prefix, const std::vector<char> &vecChar, const std::string &sufffix = "");
205 
206 /**
207  * @Description Convert a hex type string to vector.
208  *
209  * @param str - input hex string, eg: 010203...
210  * @param vec - output vector result, eg: [1,2,3,...]
211  * @return int - convert result, 0 success, -1 failed
212  */
213 int HexStringToVec(const std::string &str, std::vector<char> &vec);
214 
215 /**
216  * @Description Convert a hex type string to uint8_t*.
217  *
218  * @param str - input hex string, eg: 010203...
219  * @param plainText - output uint8_t* result, eg: [1,2,3,...]
220  * @param plainLength - input maxLength of uint8_t* result, eg: 256
221  * @param resultLength - output Length of uint8_t* result, eg: 16
222  * @return int - convert result, 0 success, -1 failed
223  */
224 int HexStringToVec(const std::string &str, uint8_t plainText[], uint32_t plainLength, uint32_t &resultLength);
225 
226 /**
227  * @Description Convert a uint8_t* to Hex string.
228  *
229  * @param plainText - input uint8_t*, eg: [1,2,3,...]
230  * @param size - input uint8_t* size, eg: 16
231  * @return string - convert Hex string, eg: 010203...
232  */
233 std::string ConvertArrayToHex(const uint8_t plainText[], uint32_t size);
234 
235 /**
236  * @Description Convert a string to validate string for write.
237  *
238  * @param str - input string
239  * @return string - validate string wrapped by ""
240  */
241 std::string ValidateString(const std::string  &str);
242 
243 /**
244  * @Description is unm
245  *
246  * @param str - input string
247  * @return result
248  */
249 bool IsValidateNum(const std::string &str);
250 
251 /**
252  * @Description transform freq to bandType
253  *
254  * @param freq - freq
255  * @return BandType
256  */
257 BandType TransformFreqToBand(int freq);
258 
259 /**
260  * @Description transform channel to bandType
261  *
262  * @param channel - channel
263  * @return BandType
264  */
265 BandType TransformChannelToBand(int channel);
266 
267 /**
268  * @Description Check is a valid 5G frequency.
269  *
270  * @param freq - Frequency input
271  * @return true - valid
272  * @return false - invalid
273  */
274 bool IsValid5GHz(int freq);
275 
276 /**
277  * @Description Check is a valid 2.4G frequency.
278  *
279  * @param freq - Frequency input
280  * @return true - valid
281  * @return false - invalid
282  */
283 bool IsValid24GHz(int freq);
284 
285 /**
286  * @Description Check is a valid 2.4G channel.
287  *
288  * @param channel - channel input
289  * @return true - valid
290  * @return false - invalid
291  */
292 bool IsValid24GChannel(int channel);
293 
294 /**
295  * @Description Check is a valid 5G channel.
296  *
297  * @param channel - channel input
298  * @return true - valid
299  * @return false - invalid
300  */
301 bool IsValid5GChannel(int channel);
302 
303 /**
304  * @Description  Convert frequency to channel number.
305  * @param freq - frequency to convert
306  * @return success: channel num    failed: -1
307  */
308 int TransformFrequencyIntoChannel(int freq);
309 
310 /**
311  * @Description Convert the frequency in the container into a channel.
312  *
313  * @param freqVector - frequency vector input
314  * @param chanVector - Channel vector output
315  */
316 void TransformFrequencyIntoChannel(const std::vector<int> &freqVector, std::vector<int> &chanVector);
317 
318 /**
319  * @Description transform freq to band
320  *
321  * @param freq - freq
322  * @return band
323  */
324 BandType TransformFreqToBand(int freq);
325 
326 /**
327  * @Description transform channel to band
328  *
329  * @param channel - channel
330  * @return band
331  */
332 BandType TransformChannelToBand(int channel);
333 
334 #ifndef OHOS_ARCH_LITE
335 /**
336  * @Description Check whether the country code is valid.
337  *
338  * @param wifiCountryCode - country code to be determined
339  * @return true - valid
340  * @return false - invalid
341  */
342 bool IsValidCountryCode(const std::string &wifiCountryCode);
343 
344 /**
345  * @Description Convert the country code from mnc to iso.
346  *
347  * @param wifiCountryCode - country code to be convert
348  * @return true - convert success
349  * @return false - convert fail
350  */
351 bool ConvertMncToIso(int mnc, std::string &wifiCountryCode);
352 #endif
353 
354 /**
355  * @Description Convert the letters to upper.
356  *
357  * @param str - input lowercase letters and output upper letters
358  */
359 void StrToUpper(std::string &str);
360 
361 /**
362  * @Description Converting char to numbers
363  *
364  * @param c - char
365  * @return numbers
366  */
367 int ConvertCharToInt(const char &c);
368 
369 /**
370  * @Description Converting string to numbers
371  *
372  * @param str - string
373  * @return numbers
374  */
375 int ConvertStringToInt(const std::string str);
376 
377 /**
378  * @Description Obtains a system parameter matching the specified key.
379  *
380  * @param key - Indicates the key for the system parameter to query.
381  * The value can contain lowercase letters, digits, underscores (_), and dots (.).
382  * Its length cannot exceed 32 bytes (including the end-of-text character in the string).
383  * @param def - Indicates the default value to return when no query result is found.
384  * This parameter is specified by the caller.
385  * @param value - Indicates the data buffer that stores the query result.
386  * This parameter is applied for and released by the caller and can be used as an output parameter.
387  * @param len - Indicates the length of the data in the buffer.
388  * @return Returns the number of bytes of the system parameter if the operation is successful;
389  * returns -9 if a parameter is incorrect; returns -1 in other scenarios.
390  */
391 int GetParamValue(const char *key, const char *def, char *value, uint32_t len);
392 
393 /**
394  * @Description Sets or updates a system parameter.
395  *
396  * @param key Indicates the key for the parameter to set or update.
397  * The value can contain lowercase letters, digits, underscores (_), and dots (.).
398  * Its length cannot exceed 32 bytes (including the end-of-text character in the string).
399  * @param value Indicates the system parameter value.
400  * Its length cannot exceed 128 bytes (including the end-of-text character in the string).
401  * @return Returns 0 if the operation is successful;
402  * returns -9 if a parameter is incorrect; returns -1 in other scenarios.
403  */
404 int SetParamValue(const char *key, const char *value);
405 
406 /**
407  * @Description Watch for system parameter values.
408  *
409  * @param keyPrefix - Indicates the key prefix for the parameter to be watched.
410  * If keyPrefix is not a full name, "A.B." for example, it means to watch for all parameter started with "A.B.".
411  * @param callback - Indicates value change callback.
412  * If callback is NULL, it means to cancel the watch.
413  * @param context - context.
414  * @return Returns 0 if the operation is successful;
415  */
416 int WatchParamValue(const char *keyprefix, ParameterChgPtr callback, void *context);
417 
418 /**
419  * @Description are the two frequencies dbac
420  *
421  * @param freqA - one freq
422  * @param freqB - other freq
423  * @return true - dbac
424  * @return false - not dbac
425  */
426 bool IsFreqDbac(int freqA, int freqB);
427 
428 /**
429  * @Description are the two channels dbac
430  *
431  * @param freqA - one channel
432  * @param freqB - other channel
433  * @return true - dbac
434  * @return false - not dbac
435  */
436 bool IsChannelDbac(int channelA, int channelB);
437 
438 /**
439  * @Description check the keyMgmnt is Psk
440  *
441  * @param keyMgmt - in data
442  * @return true - isPsk
443  */
444 bool IsPskEncryption(const std::string &keyMgmt);
445 
446 /**
447  * @Description is factory mode
448  *
449  * @return true - factory mode
450  * @return false - not factory mode
451  */
452 bool IsFactoryMode();
453 
454 /**
455  * @Description is wifi support opening automatically when first start up
456  *
457  * @return true - open
458  * @return false - close
459  */
460 bool IsStartUpWifiEnableSupport();
461 
462 #ifndef OHOS_ARCH_LITE
463 /**
464  * @Description Parse json string, find key by type, get value by key
465  *
466  * @param jsonString - json string
467  * @param type - key at group named type
468  * @param key - key
469  * @param value - value
470  * @return true - parse json success
471  */
472 bool ParseJson(const std::string &jsonString, const std::string &type, const std::string &key, std::string &value);
473 
474 /**
475  * @Description used for string(1,2,3,...,255) to hexstring
476  *
477  * @param inData - string(1,2,3,...,255)
478  * @param outData - hexstring
479  */
480 void ConvertDecStrToHexStr(const std::string &inData, std::string &outData);
481 
482 /**
483  * @Description Split string by substrings
484  *
485  * @param inData - in data
486  * @param outData - out data
487  * @param subBegin - find substring begin
488  * @param subEnd - find substring end
489  */
490 void SplitStringBySubstring(const std::string &inData, std::string &outData, const std::string &subBegin,
491     const std::string &subEnd);
492 #endif
493 }  // namespace Wifi
494 }  // namespace OHOS
495 #endif