1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Portions copyright (C) 2024 Broadcom Limited
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 
19 #include <stdint.h>
20 #include <stdlib.h>
21 #ifndef ANDROID
22 #include <stddef.h>
23 #endif
24 
25 #define LOG_TAG  "WifiHAL"
26 
27 #define NAN_MAX_SIDS_IN_BEACONS 127u
28 #define MAX_WIFI_USABLE_CHANNELS 256u
29 #include <utils/Log.h>
30 #ifndef ANDROID
31 #include <cutils/memory.h>
32 #endif
33 #include <inttypes.h>
34 #include <sys/socket.h>
35 #ifdef ANDROID
36 #include <linux/if.h>
37 #endif
38 #include <ctype.h>
39 #include <stdarg.h>
40 #include <semaphore.h>
41 #include <fcntl.h>
42 #include <string.h>
43 #include <errno.h>
44 #include "netinet/in.h"
45 #include "arpa/inet.h"
46 #ifndef ANDROID
47 #include <sys/ioctl.h>
48 #include <net/if.h>
49 #endif
50 #include <sys/ioctl.h>
51 #include <linux/netlink.h>
52 #include <hardware_legacy/wifi_hal.h>
53 #include <hardware_legacy/wifi_nan.h>
54 #include <hardware_legacy/wifi_twt.h>
55 
56 #include "common.h"
57 
58 #define EVENT_COUNT 256
59 #define MAC2STR(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5]
60 #define MACSTR "%02x:%02x:%02x:%02x:%02x:%02x"
61 
62 #define NMR2STR(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5], (a)[6], (a)[7]
63 #define NMRSTR "%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x"
64 #define NAN_DISC_MAC_RAND_INTVL 30
65 pthread_mutex_t printMutex;
66 static u8 enab_for_chre = 0;
67 static u8 disab_for_chre = 0;
68 
69 static wifi_hal_fn hal_fn;
70 static char* frequency_to_channel(int center_freq);
71 
72 /* API to spawn a hal instance from halutil CLI to capture events */
73 wifi_error  nan_event_check_request(transaction_id id,
74         wifi_interface_handle handle);
75 
76 /* API to spawn a hal instance from halutil CLI to capture events */
77 wifi_error twt_event_check_request(transaction_id id,
78         wifi_interface_handle handle);
79 static int set_interface_params(char *p_info, char *val_p, int len);
80 static wifi_interface_handle wifi_get_iface_handle_by_iface_name(char *val_p);
81 static void printApfUsage();
82 static void printTxPowerUsage();
83 
printMsg(const char * fmt,...)84 void printMsg(const char *fmt, ...)
85 {
86     pthread_mutex_lock(&printMutex);
87     va_list l;
88     va_start(l, fmt);
89 
90     vprintf(fmt, l);
91     va_end(l);
92     pthread_mutex_unlock(&printMutex);
93 }
94 
95 /* pretty hex print a contiguous buffer */
prhex_msg(const char * msg,u8 * buf,u32 nbytes)96 static void prhex_msg(const char *msg, u8 *buf, u32 nbytes)
97 {
98     char line[128];
99     char *p;
100     int len = sizeof(line);
101     int nchar;
102     u32 i;
103 
104     if (msg && (msg[0] != '\0')) {
105         printf("%s: len %d\n", msg, nbytes);
106     }
107 
108     p = line;
109     for (i = 0; i < nbytes; i++) {
110         if (i % 16 == 0) {
111             nchar = snprintf(p, len, "  %04d: ", i);    /* line prefix */
112             p += nchar;
113             len -= nchar;
114         }
115 
116         if (len > 0) {
117             nchar = snprintf(p, len, "%02x ", buf[i]);
118             p += nchar;
119             len -= nchar;
120         }
121 
122         if (i % 16 == 15) {
123             printf("%s\n", line);       /* flush line */
124             p = line;
125             len = sizeof(line);
126         }
127     }
128 
129     /* flush last partial line */
130     if (p != line) {
131         printf("%s\n", line);
132     }
133 }
134 
135 template<typename T, unsigned N>
countof(T (& rgt)[N])136 unsigned countof(T (&rgt)[N]) {
137     return N;
138 }
139 
140 #define NBBY    8  /* number of bits/byte */
141 
142 /* Bit map related macros. */
143 #define setbit(a,i) ((a)[(i)/NBBY] |= 1<<((i)%NBBY))
144 #define clrbit(a,i) ((a)[(i)/NBBY] &= ~(1<<((i)%NBBY)))
145 #define isset(a,i)  ((a)[(i)/NBBY] & (1<<((i)%NBBY)))
146 #define isclr(a,i)  (((a)[(i)/NBBY] & (1<<((i)%NBBY))) == 0)
147 #define CEIL(x, y)  (((x) + ((y) - 1)) / (y))
148 
149 /* TLV defines */
150 #define TLV_TAG_OFF     0   /* tag offset */
151 #define TLV_LEN_OFF     1   /* length offset */
152 #define TLV_HDR_LEN     2   /* header length */
153 #define TLV_BODY_OFF    2   /* body offset */
154 #define TLV_BODY_LEN_MAX 255  /* max body length */
155 
156 
157 /* Information Element IDs */
158 #define WIFI_EID_SSID 0
159 #define WIFI_EID_SUPP_RATES 1
160 #define WIFI_EID_FH_PARAMS 2
161 #define WIFI_EID_DS_PARAMS 3
162 #define WIFI_EID_CF_PARAMS 4
163 #define WIFI_EID_TIM 5
164 #define WIFI_EID_IBSS_PARAMS 6
165 #define WIFI_EID_COUNTRY 7
166 #define WIFI_EID_BSS_LOAD 11
167 #define WIFI_EID_CHALLENGE 16
168 /* EIDs defined by IEEE 802.11h - START */
169 #define WIFI_EID_PWR_CONSTRAINT 32
170 #define WIFI_EID_PWR_CAPABILITY 33
171 #define WIFI_EID_TPC_REQUEST 34
172 #define WIFI_EID_TPC_REPORT 35
173 #define WIFI_EID_SUPPORTED_CHANNELS 36
174 #define WIFI_EID_CHANNEL_SWITCH 37
175 #define WIFI_EID_MEASURE_REQUEST 38
176 #define WIFI_EID_MEASURE_REPORT 39
177 #define WIFI_EID_QUITE 40
178 #define WIFI_EID_IBSS_DFS 41
179 /* EIDs defined by IEEE 802.11h - END */
180 #define WIFI_EID_ERP_INFO 42
181 #define WIFI_EID_HT_CAP 45
182 #define WIFI_EID_QOS 46
183 #define WIFI_EID_RSN 48
184 #define WIFI_EID_EXT_SUPP_RATES 50
185 #define WIFI_EID_NEIGHBOR_REPORT 52
186 #define WIFI_EID_MOBILITY_DOMAIN 54
187 #define WIFI_EID_FAST_BSS_TRANSITION 55
188 #define WIFI_EID_TIMEOUT_INTERVAL 56
189 #define WIFI_EID_RIC_DATA 57
190 #define WIFI_EID_SUPPORTED_OPERATING_CLASSES 59
191 #define WIFI_EID_HT_OPERATION 61
192 #define WIFI_EID_SECONDARY_CHANNEL_OFFSET 62
193 #define WIFI_EID_WAPI 68
194 #define WIFI_EID_TIME_ADVERTISEMENT 69
195 #define WIFI_EID_20_40_BSS_COEXISTENCE 72
196 #define WIFI_EID_20_40_BSS_INTOLERANT 73
197 #define WIFI_EID_OVERLAPPING_BSS_SCAN_PARAMS 74
198 #define WIFI_EID_MMIE 76
199 #define WIFI_EID_SSID_LIST 84
200 #define WIFI_EID_BSS_MAX_IDLE_PERIOD 90
201 #define WIFI_EID_TFS_REQ 91
202 #define WIFI_EID_TFS_RESP 92
203 #define WIFI_EID_WNMSLEEP 93
204 #define WIFI_EID_TIME_ZONE 98
205 #define WIFI_EID_LINK_ID 101
206 #define WIFI_EID_INTERWORKING 107
207 #define WIFI_EID_ADV_PROTO 108
208 #define WIFI_EID_QOS_MAP_SET 110
209 #define WIFI_EID_ROAMING_CONSORTIUM 111
210 #define WIFI_EID_EXT_CAPAB 127
211 #define WIFI_EID_CCKM 156
212 #define WIFI_EID_VHT_CAP 191
213 #define WIFI_EID_VHT_OPERATION 192
214 #define WIFI_EID_VHT_EXTENDED_BSS_LOAD 193
215 #define WIFI_EID_VHT_WIDE_BW_CHSWITCH  194
216 #define WIFI_EID_VHT_TRANSMIT_POWER_ENVELOPE 195
217 #define WIFI_EID_VHT_CHANNEL_SWITCH_WRAPPER 196
218 #define WIFI_EID_VHT_AID 197
219 #define WIFI_EID_VHT_QUIET_CHANNEL 198
220 #define WIFI_EID_VHT_OPERATING_MODE_NOTIFICATION 199
221 #define WIFI_EID_VENDOR_SPECIFIC 221
222 
223 
224 /* Extended capabilities IE bitfields */
225 /* 20/40 BSS Coexistence Management support bit position */
226 #define DOT11_EXT_CAP_OBSS_COEX_MGMT        0
227 /* Extended Channel Switching support bit position */
228 #define DOT11_EXT_CAP_EXT_CHAN_SWITCHING    2
229 /* scheduled PSMP support bit position */
230 #define DOT11_EXT_CAP_SPSMP         6
231 /*  Flexible Multicast Service */
232 #define DOT11_EXT_CAP_FMS           11
233 /* proxy ARP service support bit position */
234 #define DOT11_EXT_CAP_PROXY_ARP     12
235 /* Civic Location */
236 #define DOT11_EXT_CAP_CIVIC_LOC     14
237 /* Geospatial Location */
238 #define DOT11_EXT_CAP_LCI           15
239 /* Traffic Filter Service */
240 #define DOT11_EXT_CAP_TFS           16
241 /* WNM-Sleep Mode */
242 #define DOT11_EXT_CAP_WNM_SLEEP     17
243 /* TIM Broadcast service */
244 #define DOT11_EXT_CAP_TIMBC         18
245 /* BSS Transition Management support bit position */
246 #define DOT11_EXT_CAP_BSSTRANS_MGMT 19
247 /* Direct Multicast Service */
248 #define DOT11_EXT_CAP_DMS           26
249 /* Interworking support bit position */
250 #define DOT11_EXT_CAP_IW            31
251 /* QoS map support bit position */
252 #define DOT11_EXT_CAP_QOS_MAP       32
253 /* service Interval granularity bit position and mask */
254 #define DOT11_EXT_CAP_SI            41
255 #define DOT11_EXT_CAP_SI_MASK       0x0E
256 /* WNM notification */
257 #define DOT11_EXT_CAP_WNM_NOTIF     46
258 /* Operating mode notification - VHT (11ac D3.0 - 8.4.2.29) */
259 #define DOT11_EXT_CAP_OPER_MODE_NOTIF  62
260 /* Fine timing measurement - D3.0 */
261 #define DOT11_EXT_CAP_FTM_RESPONDER    70
262 #define DOT11_EXT_CAP_FTM_INITIATOR    71 /* tentative 11mcd3.0 */
263 
264 #define DOT11_EXT_CH_MASK   0x03 /* extension channel mask */
265 #define DOT11_EXT_CH_UPPER  0x01 /* ext. ch. on upper sb */
266 #define DOT11_EXT_CH_LOWER  0x03 /* ext. ch. on lower sb */
267 #define DOT11_EXT_CH_NONE   0x00 /* no extension ch.  */
268 
269 enum vht_op_chan_width {
270     VHT_OP_CHAN_WIDTH_20_40 = 0,
271     VHT_OP_CHAN_WIDTH_80    = 1,
272     VHT_OP_CHAN_WIDTH_160   = 2,
273     VHT_OP_CHAN_WIDTH_80_80 = 3
274 };
275 /**
276  * Channel Factor for the starting frequence of 2.4 GHz channels.
277  * The value corresponds to 2407 MHz.
278  */
279 #define CHAN_FACTOR_2_4_G 4814 /* 2.4 GHz band, 2407 MHz */
280 
281 /**
282  * Channel Factor for the starting frequence of 5 GHz channels.
283  * The value corresponds to 5000 MHz.
284  */
285 #define CHAN_FACTOR_5_G 10000 /* 5 GHz band, 5000 MHz */
286 
287 
288 /* ************* HT definitions. ************* */
289 #define MCSSET_LEN 16       /* 16-bits per 8-bit set to give 128-bits bitmap of MCS Index */
290 #define MAX_MCS_NUM (128)   /* max mcs number = 128 */
291 
292 struct ht_op_ie {
293     u8  ctl_ch;         /* control channel number */
294     u8  chan_info;      /* ext ch,rec. ch. width, RIFS support */
295     u16 opmode;         /* operation mode */
296     u16 misc_bits;      /* misc bits */
297     u8  basic_mcs[MCSSET_LEN];  /* required MCS set */
298 } __attribute__ ((packed));
299 struct vht_op_ie {
300     u8  chan_width;
301     u8  chan1;
302     u8  chan2;
303     u16 supp_mcs; /* same def as above in vht cap */
304 } __attribute__ ((packed));
305 
306 #define EVENT_BUF_SIZE 2048
307 #define MAX_EVENT_MSG_LEN 256
308 #define MAX_CH_BUF_SIZE  256
309 #define MAX_FEATURE_SET  8
310 #define MAX_RADIO_COMBO	5
311 #define MAX_CORE 2
312 #define HOTLIST_LOST_WINDOW  5
313 
314 static wifi_handle halHandle;
315 static wifi_interface_handle *ifaceHandles;
316 static wifi_interface_handle wlan0Handle;
317 static wifi_interface_handle p2p0Handle;
318 static int numIfaceHandles;
319 static int cmdId = 1; /* Start with TxId of 1 */
320 static int ioctl_sock = 0;
321 static int max_event_wait = 5;
322 static int stest_max_ap = 10;
323 static int stest_base_period = 5000;
324 static int stest_threshold_percent = 80;
325 static int stest_threshold_num_scans = 10;
326 static int swctest_rssi_sample_size =  3;
327 static int swctest_rssi_lost_ap =  3;
328 static int swctest_rssi_min_breaching =  2;
329 static int swctest_rssi_ch_threshold =  1;
330 static int htest_low_threshold =  90;
331 static int htest_high_threshold =  10;
332 static int rssi_monitor = 0;
333 static signed char min_rssi = 0;
334 static signed char max_rssi = 0;
335 static size_t n_requested_pkt_fate = 0;
336 
337 #define FILE_NAME_LEN 128
338 #define FILE_MAX_SIZE (1 * 1024 * 1024)
339 #define MAX_RING_NAME_SIZE 32
340 
341 #define NUM_ALERT_DUMPS 10
342 #define ETHER_ADDR_LEN 6
343 #define MAX_NAN_MSG_BUF_SIZE 256
344 
345 #define NAN_MAX_CLUST_VALUE_RANGE 0xFFFF
346 #define MAX_CH_AVOID 128
347 
348 /*
349  * Host can send Post Connectivity Capability attributes
350  * to be included in Service Discovery frames transmitted.
351  */
352 enum post_connectivity_capability {
353     FEATURE_NOT_SUPPORTED   = 0,
354     FEATURE_SUPPORTED       = 1
355 };
356 
357 
358 /////////////////////////////////////////////////////////////////
359 // Logger related.
360 
361 #define DEFAULT_MEMDUMP_FILE "/data/memdump.bin"
362 #define ALERT_MEMDUMP_PREFIX "/data/alertdump"
363 #define RINGDATA_PREFIX "/data/ring-"
364 #define DEFAULT_TX_PKT_FATE_FILE "/data/txpktfate.txt"
365 #define DEFAULT_RX_PKT_FATE_FILE "/data/rxpktfate.txt"
366 
367 static char mem_dump_file[FILE_NAME_LEN] = DEFAULT_MEMDUMP_FILE;
368 static char tx_pkt_fate_file[FILE_NAME_LEN] = DEFAULT_TX_PKT_FATE_FILE;
369 static char rx_pkt_fate_file[FILE_NAME_LEN] = DEFAULT_RX_PKT_FATE_FILE;
370 
371 struct LoggerParams {
372     u32 verbose_level;
373     u32 flags;
374     u32 max_interval_sec;
375     u32 min_data_size;
376     wifi_ring_buffer_id ring_id;
377     char ring_name[MAX_RING_NAME_SIZE];
378 };
379 struct LoggerParams default_logger_param = {0, 0 , 0 , 0, 0, {0}};
380 
381 char default_ring_name[MAX_RING_NAME_SIZE] = "fw_event";
382 
383 typedef enum {
384     LOG_INVALID = -1,
385     LOG_START,
386     LOG_GET_MEMDUMP,
387     LOG_GET_FW_VER,
388     LOG_GET_DRV_VER,
389     LOG_GET_RING_STATUS,
390     LOG_GET_RINGDATA,
391     LOG_GET_FEATURE,
392     LOG_GET_RING_DATA,
393     LOG_MONITOR_PKTFATE,
394     LOG_GET_TXPKTFATE,
395     LOG_GET_RXPKTFATE,
396     LOG_SET_LOG_HANDLER,
397     LOG_SET_ALERT_HANDLER,
398 } LoggerCmd;
399 
400 LoggerCmd log_cmd = LOG_INVALID;
401 wifi_ring_buffer_id ringId = -1;
402 
403 #define C2S(x)  case x: return #x;
404 
RBentryTypeToString(int cmd)405 static const char *RBentryTypeToString(int cmd) {
406     switch (cmd) {
407         C2S(ENTRY_TYPE_CONNECT_EVENT)
408         C2S(ENTRY_TYPE_PKT)
409         C2S(ENTRY_TYPE_WAKE_LOCK)
410         C2S(ENTRY_TYPE_POWER_EVENT)
411         C2S(ENTRY_TYPE_DATA)
412         default:
413             return "ENTRY_TYPE_UNKNOWN";
414     }
415 }
416 
RBconnectEventToString(int cmd)417 static const char *RBconnectEventToString(int cmd)
418 {
419     switch (cmd) {
420         C2S(WIFI_EVENT_ASSOCIATION_REQUESTED)
421         C2S(WIFI_EVENT_AUTH_COMPLETE)
422         C2S(WIFI_EVENT_ASSOC_COMPLETE)
423         C2S(WIFI_EVENT_FW_AUTH_STARTED)
424         C2S(WIFI_EVENT_FW_ASSOC_STARTED)
425         C2S(WIFI_EVENT_FW_RE_ASSOC_STARTED)
426         C2S(WIFI_EVENT_DRIVER_SCAN_REQUESTED)
427         C2S(WIFI_EVENT_DRIVER_SCAN_RESULT_FOUND)
428         C2S(WIFI_EVENT_DRIVER_SCAN_COMPLETE)
429         C2S(WIFI_EVENT_G_SCAN_STARTED)
430         C2S(WIFI_EVENT_G_SCAN_COMPLETE)
431         C2S(WIFI_EVENT_DISASSOCIATION_REQUESTED)
432         C2S(WIFI_EVENT_RE_ASSOCIATION_REQUESTED)
433         C2S(WIFI_EVENT_ROAM_REQUESTED)
434         C2S(WIFI_EVENT_BEACON_RECEIVED)
435         C2S(WIFI_EVENT_ROAM_SCAN_STARTED)
436         C2S(WIFI_EVENT_ROAM_SCAN_COMPLETE)
437         C2S(WIFI_EVENT_ROAM_SEARCH_STARTED)
438         C2S(WIFI_EVENT_ROAM_SEARCH_STOPPED)
439         C2S(WIFI_EVENT_CHANNEL_SWITCH_ANOUNCEMENT)
440         C2S(WIFI_EVENT_FW_EAPOL_FRAME_TRANSMIT_START)
441         C2S(WIFI_EVENT_FW_EAPOL_FRAME_TRANSMIT_STOP)
442         C2S(WIFI_EVENT_DRIVER_EAPOL_FRAME_TRANSMIT_REQUESTED)
443         C2S(WIFI_EVENT_FW_EAPOL_FRAME_RECEIVED)
444         C2S(WIFI_EVENT_DRIVER_EAPOL_FRAME_RECEIVED)
445         C2S(WIFI_EVENT_BLOCK_ACK_NEGOTIATION_COMPLETE)
446         C2S(WIFI_EVENT_BT_COEX_BT_SCO_START)
447         C2S(WIFI_EVENT_BT_COEX_BT_SCO_STOP)
448         C2S(WIFI_EVENT_BT_COEX_BT_SCAN_START)
449         C2S(WIFI_EVENT_BT_COEX_BT_SCAN_STOP)
450         C2S(WIFI_EVENT_BT_COEX_BT_HID_START)
451         C2S(WIFI_EVENT_BT_COEX_BT_HID_STOP)
452         C2S(WIFI_EVENT_ROAM_AUTH_STARTED)
453         C2S(WIFI_EVENT_ROAM_AUTH_COMPLETE)
454         C2S(WIFI_EVENT_ROAM_ASSOC_STARTED)
455         C2S(WIFI_EVENT_ROAM_ASSOC_COMPLETE)
456         C2S(WIFI_EVENT_DRIVER_PNO_ADD)
457         C2S(WIFI_EVENT_DRIVER_PNO_REMOVE)
458         C2S(WIFI_EVENT_DRIVER_PNO_NETWORK_FOUND)
459         C2S(WIFI_EVENT_DRIVER_PNO_SCAN_REQUESTED)
460         C2S(WIFI_EVENT_DRIVER_PNO_SCAN_RESULT_FOUND)
461         C2S(WIFI_EVENT_DRIVER_PNO_SCAN_COMPLETE)
462         default:
463             return "WIFI_EVENT_UNKNOWN";
464     }
465 }
466 
RBTlvTagToString(int cmd)467 static const char *RBTlvTagToString(int cmd) {
468     switch (cmd) {
469         C2S(WIFI_TAG_VENDOR_SPECIFIC)
470         C2S(WIFI_TAG_BSSID)
471         C2S(WIFI_TAG_ADDR)
472         C2S(WIFI_TAG_SSID)
473         C2S(WIFI_TAG_STATUS)
474         C2S(WIFI_TAG_CHANNEL_SPEC)
475         C2S(WIFI_TAG_WAKE_LOCK_EVENT)
476         C2S(WIFI_TAG_ADDR1)
477         C2S(WIFI_TAG_ADDR2)
478         C2S(WIFI_TAG_ADDR3)
479         C2S(WIFI_TAG_ADDR4)
480         C2S(WIFI_TAG_IE)
481         C2S(WIFI_TAG_INTERFACE)
482         C2S(WIFI_TAG_REASON_CODE)
483         C2S(WIFI_TAG_RATE_MBPS)
484         C2S(WIFI_TAG_CHANNEL)
485         C2S(WIFI_TAG_RSSI)
486         default:
487             return "WIFI_TAG_UNKNOWN";
488     }
489 }
490 
RBchanWidthToString(int cmd)491 static const char *RBchanWidthToString(int cmd) {
492     switch (cmd) {
493         C2S(WIFI_CHAN_WIDTH_20)
494         C2S(WIFI_CHAN_WIDTH_40)
495         C2S(WIFI_CHAN_WIDTH_80)
496         C2S(WIFI_CHAN_WIDTH_160)
497         C2S(WIFI_CHAN_WIDTH_80P80)
498         C2S(WIFI_CHAN_WIDTH_5)
499         C2S(WIFI_CHAN_WIDTH_10)
500         C2S(WIFI_CHAN_WIDTH_INVALID)
501         default:
502             return "WIFI_CHAN_WIDTH_INVALID";
503     }
504 }
505 
BandToString(wlan_mac_band cmd)506 static const char *BandToString(wlan_mac_band cmd) {
507     switch (cmd) {
508         C2S(WLAN_MAC_2_4_BAND)
509         C2S(WLAN_MAC_5_0_BAND)
510         C2S(WLAN_MAC_6_0_BAND)
511         C2S(WLAN_MAC_60_0_BAND)
512         default:
513         return "INVALID";
514     }
515 }
516 
AntennCfgToString(wifi_antenna_configuration cmd)517 static const char *AntennCfgToString(wifi_antenna_configuration cmd) {
518     switch (cmd) {
519         C2S(WIFI_ANTENNA_1X1)
520         C2S(WIFI_ANTENNA_2X2)
521         C2S(WIFI_ANTENNA_3X3)
522         C2S(WIFI_ANTENNA_4X4)
523         default:
524         return "WIFI_ANTENNA_INVALID";
525     }
526 }
527 
528 /////////////////////////////////////////////////////////////////
529 // RTT related to configuration
530 #define MAX_SSID_LEN (32 + 1)
531 /* 18-bytes of Ethernet address buffer length */
532 #define ETHER_ADDR_STR_LEN      18
533 #define ETHER_ADDR_LEN          6
RttTypeToString(wifi_rtt_type type)534 static const char *RttTypeToString(wifi_rtt_type type)
535 {
536     switch (type) {
537         C2S(RTT_TYPE_1_SIDED)
538         C2S(RTT_TYPE_2_SIDED)
539         /* C2S(RTT_TYPE_2_SIDED_11MC) is same as above */
540         C2S(RTT_TYPE_2_SIDED_11AZ_NTB)
541         default:
542             return "UNKNOWN TYPE";
543     }
544 }
545 
convert_channel_width_to_rtt_bw(int channel_width)546 wifi_rtt_bw convert_channel_width_to_rtt_bw(int channel_width)
547 {
548     wifi_rtt_bw rtt_bw = WIFI_RTT_BW_5;
549 
550     switch (channel_width) {
551         case WIFI_CHAN_WIDTH_20:
552             rtt_bw = WIFI_RTT_BW_20;
553             break;
554         case WIFI_CHAN_WIDTH_40:
555             rtt_bw = WIFI_RTT_BW_40;
556             break;
557         case WIFI_CHAN_WIDTH_80:
558             rtt_bw = WIFI_RTT_BW_80;
559             break;
560         case WIFI_CHAN_WIDTH_160:
561             rtt_bw = WIFI_RTT_BW_160;
562             break;
563         case WIFI_CHAN_WIDTH_5:
564             rtt_bw = WIFI_RTT_BW_5;
565             break;
566         case WIFI_CHAN_WIDTH_10:
567             rtt_bw = WIFI_RTT_BW_10;
568             break;
569         case WIFI_CHAN_WIDTH_80P80:
570             rtt_bw = WIFI_RTT_BW_5;
571             break;
572         default:
573 	    ALOGE("Unsupported channel_width: %d\n", channel_width);
574             break;
575     }
576     ALOGI("rtt_bw: %x, channel_width: %d\n", rtt_bw, channel_width);
577     return rtt_bw;
578 }
579 
580 #define DEFAULT_RTT_FILE "/data/rtt-ap.list"
581 static int rtt_from_file = 0;
582 static int rtt_to_file = 0;
583 static wifi_band band = WIFI_BAND_UNSPECIFIED;
584 static wifi_interface_handle ifHandle = NULL;
585 static int max_ap = 256; // the maximum count of  ap for RTT test
586 static char rtt_aplist[FILE_NAME_LEN] = DEFAULT_RTT_FILE;
587 static mac_addr responder_addr;
588 static wifi_channel responder_channel;
589 static int channel_width = 0;
590 static wifi_rtt_type type = RTT_TYPE_2_SIDED;
591 static u64 ntb_min_meas_time = 0;
592 static u64 ntb_max_meas_time = 0;
593 static bool rtt_sta = false;
594 static bool rtt_nan = false;
595 static bool is_6g = false;
596 struct rtt_params {
597     u32 burst_period;
598     u32 num_burst;
599     u32 num_frames_per_burst;
600     u32 num_retries_per_ftm;
601     u32 num_retries_per_ftmr;
602     u32 burst_duration;
603     u8 LCI_request;
604     u8 LCR_request;
605     u8 preamble;
606     u8 bw;
607     wifi_rtt_type type;
608 };
609 
610 struct rtt_params_v3 {
611     u64 ntb_min_measurement_time;
612     u64 ntb_max_measurement_time;
613     u32 num_frames_per_burst;
614 };
615 
616 struct rtt_params default_rtt_param = {0, 0, 0, 0, 0, 15, 0, 0, 0, 0, RTT_TYPE_2_SIDED};
617 struct rtt_params_v3 default_rtt_param_v3 = {5000, 500, 5};
618 
619 mac_addr hotlist_bssids[16];
620 mac_addr blacklist_bssids[16];
621 char whitelist_ssids[MAX_WHITELIST_SSID][MAX_SSID_LEN] = {{0}};
622 unsigned char mac_oui[3];
623 wifi_epno_params epno_cfg;
624 int channel_list[16];
625 int num_hotlist_bssids = 0;
626 int num_channels = 0;
627 mac_addr pref_bssids[16];
628 int rssi_modifier[16];
629 int num_pref_bssids = -1;
630 int num_blacklist_bssids = -1;
631 int num_whitelist_ssids = -1;
632 bool set_roaming_configuration = false;
633 
634 #define EPNO_HIDDEN               (1 << 0)
635 #define EPNO_A_BAND_TRIG          (1 << 1)
636 #define EPNO_BG_BAND_TRIG         (1 << 2)
637 #define EPNO_ABG_BAND_TRIG        (EPNO_A_BAND_TRIG | EPNO_BG_BAND_TRIG)
638 #define EPNO_FLAG_STRICT_MATCH    (1 << 3)
639 #define EPNO_FLAG_SAME_NETWORK    (1 << 4)
640 
641 void parseMacAddress(const char *str, mac_addr addr);
642 
linux_set_iface_flags(int sock,const char * ifname,int dev_up)643 int linux_set_iface_flags(int sock, const char *ifname, int dev_up)
644 {
645     struct ifreq ifr;
646     int ret;
647 
648     ALOGD("setting interface %s flags (%s)\n", ifname, dev_up ? "UP" : "DOWN");
649 
650     if (sock < 0) {
651         printMsg("Bad socket: %d\n", sock);
652         return -1;
653     }
654 
655     memset(&ifr, 0, sizeof(ifr));
656 #ifdef ANDROID
657     strlcpy(ifr.ifr_name, ifname, IFNAMSIZ);
658 #else
659     strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
660 #endif
661     ALOGD("reading old value\n");
662 
663     if (ioctl(sock, SIOCGIFFLAGS, &ifr) != 0) {
664         ret = errno ? -errno : -999;
665         printMsg("Could not read interface %s flags: %d\n", ifname, errno);
666         return ret;
667     } else {
668         ALOGD("writing new value\n");
669     }
670 
671     if (dev_up) {
672         if (ifr.ifr_flags & IFF_UP) {
673             ALOGD("interface %s is already up\n", ifname);
674             return 0;
675         }
676         ifr.ifr_flags |= IFF_UP;
677     } else {
678         if (!(ifr.ifr_flags & IFF_UP)) {
679             printMsg("interface %s is already down\n", ifname);
680             return 0;
681         }
682         ifr.ifr_flags &= ~IFF_UP;
683     }
684 
685     if (ioctl(sock, SIOCSIFFLAGS, &ifr) != 0) {
686         ret = errno ? -errno : -999;
687         printMsg("Could not set interface %s flags \n", ifname);
688         return ret;
689     } else {
690         ALOGD("set interface %s flags (%s)\n", ifname, dev_up ? "UP" : "DOWN");
691     }
692     ALOGD("Done\n");
693     return 0;
694 }
695 
696 
init()697 static int init() {
698 
699     wifi_error res = init_wifi_vendor_hal_func_table(&hal_fn);
700     if (res != WIFI_SUCCESS) {
701         ALOGD("Can not initialize the vendor function pointer table");
702         return -1;
703     }
704 
705     ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
706     if (ioctl_sock < 0) {
707         printMsg("Bad socket: %d\n", ioctl_sock);
708         return errno;
709     } else {
710         ALOGD("Good socket: %d\n", ioctl_sock);
711     }
712 
713     int ret = linux_set_iface_flags(ioctl_sock, "wlan0", 1);
714     if (ret < 0) {
715         return ret;
716     }
717 
718     res = hal_fn.wifi_initialize(&halHandle);
719     if (res < 0) {
720         return res;
721     }
722 
723     res = hal_fn.wifi_get_ifaces(halHandle, &numIfaceHandles, &ifaceHandles);
724     if (res < 0) {
725         return res;
726     }
727 
728     char buf[EVENT_BUF_SIZE];
729     for (int i = 0; i < numIfaceHandles; i++) {
730         if (hal_fn.wifi_get_iface_name(ifaceHandles[i], buf, sizeof(buf)) == WIFI_SUCCESS) {
731             if (strcmp(buf, "wlan0") == 0) {
732                 printMsg("found interface %s\n", buf);
733                 wlan0Handle = ifaceHandles[i];
734             } else if (strcmp(buf, "p2p0") == 0) {
735                 printMsg("found interface %s\n", buf);
736                 p2p0Handle = ifaceHandles[i];
737             }
738         }
739     }
740 
741     return res;
742 }
743 
cleaned_up_handler(wifi_handle handle)744 static void cleaned_up_handler(wifi_handle handle) {
745     printMsg("HAL cleaned up handler\n");
746     halHandle = NULL;
747     ifaceHandles = NULL;
748 }
749 
cleanup()750 static void cleanup() {
751     printMsg("cleaning up HAL\n");
752     hal_fn.wifi_cleanup(halHandle, cleaned_up_handler);
753 }
754 
755 sem_t event_thread_mutex;
756 
eventThreadFunc(void * context)757 static void *eventThreadFunc(void *context) {
758 
759     printMsg("starting wifi event loop\n");
760     sem_post( &event_thread_mutex );
761     hal_fn.wifi_event_loop(halHandle);
762     printMsg("out of wifi event loop\n");
763 
764     return NULL;
765 }
766 
767 
getNewCmdId()768 static int getNewCmdId() {
769     return cmdId++;
770 }
771 
772 /* pretty hex print a contiguous buffer to file */
773 void
fprhex(FILE * f_wp,char * buf,uint nbytes,bool prefix)774 fprhex(FILE *f_wp, char *buf, uint nbytes, bool prefix)
775 {
776     char line[128], *p;
777     int rem_len = sizeof(line);
778     int nchar = 0;
779     uint i;
780 
781     p = line;
782     for (i = 0; i < nbytes; i++) {
783         if ((i % 16 == 0) && prefix) {
784             nchar = snprintf(p, rem_len, "  %04x: ", i); /* line prefix */
785             p += nchar;
786             rem_len -= nchar;
787         }
788 
789         if (rem_len > 0) {
790             nchar = snprintf(p, rem_len, "%02x ", (unsigned char)buf[i]);
791             p += nchar;
792             rem_len -= nchar;
793         }
794 
795         if (i % 16 == 15) {
796             fprintf(f_wp, "%s\n", line); /* flush line */
797             p = line;
798             rem_len = sizeof(line);
799         }
800     }
801 
802     /* flush last partial line */
803     if (p != line) {
804         fprintf(f_wp, "%s\n", line);
805     }
806 }
807 
808 
809 /* -------------------------------------------  */
810 /* helpers                                      */
811 /* -------------------------------------------  */
812 
printScanHeader()813 void printScanHeader() {
814     printMsg("SSID\t\t\t\t\tBSSID\t\t  RSSI\tchannel\ttimestamp\tRTT\tRTT SD\n");
815     printMsg("----\t\t\t\t\t-----\t\t  ----\t-------\t---------\t---\t------\n");
816 }
817 
printScanResult(wifi_scan_result result)818 void printScanResult(wifi_scan_result result) {
819 
820     printMsg("%-32s\t", result.ssid);
821 
822     printMsg("%02x:%02x:%02x:%02x:%02x:%02x ", result.bssid[0], result.bssid[1],
823             result.bssid[2], result.bssid[3], result.bssid[4], result.bssid[5]);
824 
825     printMsg("%d\t", result.rssi);
826     printMsg("%d\t", result.channel);
827     printMsg("%lld\t", result.ts);
828     printMsg("%lld\t", result.rtt);
829     printMsg("%lld\n", result.rtt_sd);
830 }
831 
printSignificantChangeResult(wifi_significant_change_result * res)832 void printSignificantChangeResult(wifi_significant_change_result *res) {
833 
834     wifi_significant_change_result &result = *res;
835     printMsg("%02x:%02x:%02x:%02x:%02x:%02x ", result.bssid[0], result.bssid[1],
836             result.bssid[2], result.bssid[3], result.bssid[4], result.bssid[5]);
837 
838     printMsg("%d\t", result.channel);
839 
840     for (int i = 0; i < result.num_rssi; i++) {
841         printMsg("%d,", result.rssi[i]);
842     }
843     printMsg("\n");
844 }
845 
printScanCapabilities(wifi_gscan_capabilities capabilities)846 void printScanCapabilities(wifi_gscan_capabilities capabilities)
847 {
848     printMsg("Scan Capabililites\n");
849     printMsg("  max_scan_cache_size = %d\n", capabilities.max_scan_cache_size);
850     printMsg("  max_scan_buckets = %d\n", capabilities.max_scan_buckets);
851     printMsg("  max_ap_cache_per_scan = %d\n", capabilities.max_ap_cache_per_scan);
852     printMsg("  max_rssi_sample_size = %d\n", capabilities.max_rssi_sample_size);
853     printMsg("  max_scan_reporting_threshold = %d\n", capabilities.max_scan_reporting_threshold);
854     printMsg("  max_hotlist_bssids = %d\n", capabilities.max_hotlist_bssids);
855     printMsg("  max_significant_wifi_change_aps = %d\n",
856             capabilities.max_significant_wifi_change_aps);
857     printMsg("  max_number_epno_networks = %d\n", capabilities.max_number_epno_networks);
858 }
859 
860 
861 /* -------------------------------------------  */
862 /* commands and events                          */
863 /* -------------------------------------------  */
864 
865 typedef enum {
866     EVENT_TYPE_SCAN_FAILED                        = 1000,
867     EVENT_TYPE_HOTLIST_AP_FOUND                   = 1001,
868     EVENT_TYPE_SIGNIFICANT_WIFI_CHANGE            = 1002,
869     EVENT_TYPE_RTT_RESULTS                        = 1003,
870     EVENT_TYPE_SCAN_COMPLETE                      = 1004,
871     EVENT_TYPE_HOTLIST_AP_LOST                    = 1005,
872     EVENT_TYPE_EPNO_SSID                          = 1006,
873     EVENT_TYPE_LOGGER_RINGBUFFER_DATA             = 1007,
874     EVENT_TYPE_LOGGER_MEMDUMP_DATA                = 1008,
875     EVENT_TYPE_LOGGER_ALERT_DATA                  = 1009,
876     EVENT_TYPE_RSSI_MONITOR                       = 1010,
877     EVENT_TYPE_SCAN_RESULTS_THRESHOLD             = 1011,
878     EVENT_TYPE_NAN_PUBLISH_REPLIED                = 1012,
879     EVENT_TYPE_SUBSCRIBE_MATCHED                  = 1013,
880     EVENT_TYPE_NAN_FOLLOWUP_RECIEVE               = 1014,
881     EVENT_TYPE_NAN_PUBLISH_TERMINATED             = 1015,
882     EVENT_TYPE_NAN_DISABLED                       = 1016,
883     EVENT_TYPE_NAN_SUBSCRIBE_TERMINATED           = 1017,
884     EVENT_TYPE_NAN_ENABLED                        = 1018,
885     EVENT_TYPE_NAN_DATA_REQUEST_INDICATION        = 1019,
886     EVENT_TYPE_NAN_DATA_CONFIRMATION              = 1020,
887     EVENT_TYPE_NAN_DATA_END_INDICAION             = 1021,
888     EVENT_TYPE_NAN_TRANSMIT_FOLLOWUP_INDICATION   = 1022,
889     EVENT_TYPE_RTT_RESULTS_DETAIL                 = 1023,
890     EVENT_TYPE_CHRE_NAN_RTT_STATE_UPDATED         = 1024,
891     EVENT_TYPE_NAN_PAIRING_REQUEST_INDICATION     = 1025,
892     EVENT_TYPE_NAN_PAIRING_CONFIRMATION           = 1026,
893     EVENT_TYPE_NAN_BOOTSTRAP_REQUEST_INDICATION   = 1027,
894     EVENT_TYPE_NAN_BOOTSTRAP_CONFIRMATION         = 1028,
895 
896 } EventType;
897 
898 typedef struct {
899     int type;
900     char buf[MAX_EVENT_MSG_LEN];
901 } EventInfo;
902 
903 const int MAX_EVENTS_IN_CACHE = 256;
904 EventInfo eventCache[256];
905 int eventsInCache = 0;
906 pthread_cond_t eventCacheCondition;
907 pthread_mutex_t eventCacheMutex;
908 
putEventInCache(int type,const char * msg)909 void putEventInCache(int type, const char *msg) {
910     pthread_mutex_lock(&eventCacheMutex);
911     if (eventsInCache + 1 < MAX_EVENTS_IN_CACHE) {
912         eventCache[eventsInCache].type = type;
913         strncpy(eventCache[eventsInCache].buf, msg, (MAX_EVENT_MSG_LEN - 1));
914         eventCache[eventsInCache].buf[MAX_EVENT_MSG_LEN - 1] = '\0';
915         eventsInCache++;
916         pthread_cond_signal(&eventCacheCondition);
917     } else {
918         printMsg("Too many events in the cache\n");
919     }
920     pthread_mutex_unlock(&eventCacheMutex);
921 }
922 
getEventFromCache(EventInfo & info)923 void getEventFromCache(EventInfo& info) {
924     pthread_mutex_lock(&eventCacheMutex);
925     while (true) {
926         if (eventsInCache > 0) {
927             info.type = eventCache[0].type;
928             strncpy(info.buf, eventCache[0].buf, (MAX_EVENT_MSG_LEN - 1));
929             eventCache[0].buf[MAX_EVENT_MSG_LEN - 1] = '\0';
930             eventsInCache--;
931             memmove(&eventCache[0], &eventCache[1], sizeof(EventInfo) * eventsInCache);
932             pthread_mutex_unlock(&eventCacheMutex);
933             return;
934         } else {
935             pthread_cond_wait(&eventCacheCondition, &eventCacheMutex);
936         }
937     }
938 }
939 
on_scan_event(wifi_request_id id,wifi_scan_event event)940 static void on_scan_event(wifi_request_id id, wifi_scan_event event) {
941     EventType internal_event;
942     printMsg("Received scan event\n");
943     if (event == WIFI_SCAN_THRESHOLD_PERCENT || event == WIFI_SCAN_THRESHOLD_NUM_SCANS) {
944         printMsg("Received buffer events - %d \n", event);
945         internal_event = EVENT_TYPE_SCAN_RESULTS_THRESHOLD;
946     } else if(event == WIFI_SCAN_RESULTS_AVAILABLE) {
947         printMsg("Received scan complete event  - WIFI_SCAN_RESULTS_AVAILABLE!!\n");
948         internal_event = EVENT_TYPE_SCAN_COMPLETE;
949     } else if (event == WIFI_SCAN_FAILED) {
950         printMsg("Received scan event - WIFI_SCAN_FAILED \n");
951         internal_event = EVENT_TYPE_SCAN_FAILED;
952     } else {
953         /* set to default value */
954         internal_event = EVENT_TYPE_SCAN_FAILED;
955     }
956     putEventInCache(internal_event, "New scan event");
957 }
958 
959 static int scanCmdId;
960 static int rssiMonId;
961 static int hotlistCmdId;
962 static int rttCmdId;
963 static int epnoCmdId;
964 static int loggerCmdId;
965 static u16 nanCmdId;
966 static u16 twtCmdId;
967 static wifi_error twt_init_handlers(void);
968 
startScan(int max_ap_per_scan,int base_period,int threshold_percent,int threshold_num_scans)969 static bool startScan(int max_ap_per_scan, int base_period, int threshold_percent,
970         int threshold_num_scans) {
971 
972     /* Get capabilties */
973     wifi_gscan_capabilities capabilities;
974     int result = hal_fn.wifi_get_gscan_capabilities(wlan0Handle, &capabilities);
975     if (result < 0) {
976         printMsg("failed to get scan capabilities - %d\n", result);
977         printMsg("trying scan anyway ..\n");
978     } else {
979         printScanCapabilities(capabilities);
980     }
981 
982     wifi_scan_cmd_params params;
983     memset(&params, 0, sizeof(params));
984 
985     if(num_channels > 0){
986         params.max_ap_per_scan = max_ap_per_scan;
987         params.base_period = base_period;                      // 5 second by default
988         params.report_threshold_percent = threshold_percent;
989         params.report_threshold_num_scans = threshold_num_scans;
990         params.num_buckets = 1;
991 
992         params.buckets[0].bucket = 0;
993         params.buckets[0].band = WIFI_BAND_UNSPECIFIED;
994         params.buckets[0].period = base_period;
995         params.buckets[0].num_channels = num_channels;
996 
997         for(int i = 0; i < num_channels; i++){
998             params.buckets[0].channels[i].channel = channel_list[i];
999         }
1000 
1001     } else {
1002 
1003         /* create a schedule to scan channels 1, 6, 11 every 5 second and
1004          * scan 36, 40, 44, 149, 153, 157, 161 165 every 10 second */
1005         params.max_ap_per_scan = max_ap_per_scan;
1006         params.base_period = base_period;                      // 5 second
1007         params.report_threshold_percent = threshold_percent;
1008         params.report_threshold_num_scans = threshold_num_scans;
1009         params.num_buckets = 4;
1010 
1011         params.buckets[0].bucket = 0;
1012         params.buckets[0].band = WIFI_BAND_BG;
1013         params.buckets[0].period = 5000;                // 5 second
1014         params.buckets[0].report_events = 0;
1015         params.buckets[0].num_channels = 3;     // driver should ignore list since band is specified
1016 
1017         params.buckets[0].channels[0].channel = 2412;
1018         params.buckets[0].channels[1].channel = 2437;
1019         params.buckets[0].channels[2].channel = 2462;
1020 
1021         params.buckets[1].bucket = 1;
1022         params.buckets[1].band = WIFI_BAND_UNSPECIFIED;
1023         params.buckets[1].period = 10000;               // 10 second
1024         params.buckets[1].report_events = 0;
1025         params.buckets[1].num_channels = 6;
1026 
1027 
1028         params.buckets[1].channels[0].channel = 5180;
1029         params.buckets[1].channels[1].channel = 5200;
1030         params.buckets[1].channels[2].channel = 5220;
1031         params.buckets[1].channels[3].channel = 5745;
1032         params.buckets[1].channels[4].channel = 5765;
1033         params.buckets[1].channels[5].channel = 5785;
1034 
1035         params.buckets[2].bucket = 2;
1036         params.buckets[2].band = WIFI_BAND_UNSPECIFIED;
1037         params.buckets[2].period = 15000;                // 15 second
1038         params.buckets[2].report_events = 0;
1039         params.buckets[2].num_channels = 3;
1040 
1041         params.buckets[2].channels[0].channel = 2462;
1042         params.buckets[2].channels[1].channel = 5805;
1043         params.buckets[2].channels[2].channel = 5825;
1044 
1045         params.buckets[3].bucket = 3;
1046         params.buckets[3].band = WIFI_BAND_A;
1047         params.buckets[3].period = 35000;       // 35 second
1048         params.buckets[3].report_events = 1;
1049         params.buckets[3].num_channels = 3;     // driver should ignore list since band is specified
1050 
1051         params.buckets[3].channels[0].channel = 2462;
1052         params.buckets[3].channels[1].channel = 5805;
1053         params.buckets[3].channels[2].channel = 5825;
1054     }
1055 
1056     wifi_scan_result_handler handler;
1057     memset(&handler, 0, sizeof(handler));
1058 
1059     handler.on_scan_event = on_scan_event;
1060 
1061     scanCmdId = getNewCmdId();
1062     printMsg("Starting scan --->\n");
1063     printMsg("Number of buckets = %d\n", params.num_buckets);
1064     return hal_fn.wifi_start_gscan(scanCmdId, wlan0Handle, params, handler) == WIFI_SUCCESS;
1065 }
1066 
stopScan()1067 static void stopScan() {
1068     wifi_request_id id = scanCmdId;
1069     if (id == 0)
1070         id = -1;
1071 
1072     hal_fn.wifi_stop_gscan(id, wlan0Handle);
1073     scanCmdId = 0;
1074 }
1075 
1076 wifi_scan_result **saved_scan_results;
1077 unsigned max_saved_scan_results;
1078 unsigned num_saved_scan_results;
1079 
on_single_shot_scan_event(wifi_request_id id,wifi_scan_event event)1080 static void on_single_shot_scan_event(wifi_request_id id, wifi_scan_event event) {
1081     if(event == WIFI_SCAN_RESULTS_AVAILABLE || event == WIFI_SCAN_THRESHOLD_NUM_SCANS ||
1082             event == WIFI_SCAN_THRESHOLD_PERCENT) {
1083         printMsg("Received scan complete event: %d\n", event);
1084         putEventInCache(EVENT_TYPE_SCAN_COMPLETE, "One scan completed");
1085     }
1086     else if (event == WIFI_SCAN_FAILED) {
1087         printMsg("Received scan event - WIFI_SCAN_FAILED \n");
1088         putEventInCache(EVENT_TYPE_SCAN_FAILED, "Scan failed");
1089     }
1090     else {
1091         printMsg("Received unknown scan event: %d \n", event);
1092     }
1093 }
1094 
on_full_scan_result(wifi_request_id id,wifi_scan_result * r,unsigned buckets_scanned)1095 static void on_full_scan_result(wifi_request_id id, wifi_scan_result *r, unsigned buckets_scanned) {
1096     if (num_saved_scan_results < max_saved_scan_results) {
1097         int alloc_len = offsetof(wifi_scan_result, ie_data) + r->ie_length;
1098         wifi_scan_result **result = &(saved_scan_results[num_saved_scan_results]);
1099         *result = (wifi_scan_result *)malloc(alloc_len);
1100         memcpy(*result, r, alloc_len);
1101         printMsg("buckets_scanned - %x\n", buckets_scanned);
1102         num_saved_scan_results++;
1103     }
1104 }
1105 
scanOnce(wifi_band band,wifi_scan_result ** results,int num_results)1106 static int scanOnce(wifi_band band, wifi_scan_result **results, int num_results) {
1107 
1108     saved_scan_results = results;
1109     max_saved_scan_results = num_results;
1110     num_saved_scan_results = 0;
1111 
1112     wifi_scan_cmd_params params;
1113     memset(&params, 0, sizeof(params));
1114 
1115     params.max_ap_per_scan = 10;
1116     params.base_period = 5000;                        // 5 second by default
1117     params.report_threshold_percent = 90;
1118     params.report_threshold_num_scans = 1;
1119     params.num_buckets = 1;
1120 
1121     params.buckets[0].bucket = 0;
1122     params.buckets[0].band = band;
1123     params.buckets[0].period = 5000;                  // 5 second
1124     params.buckets[0].report_events = 2;              // REPORT_EVENTS_AFTER_EACH_SCAN
1125     params.buckets[0].num_channels = 0;
1126 
1127     wifi_scan_result_handler handler;
1128     memset(&handler, 0, sizeof(handler));
1129     handler.on_scan_event = on_single_shot_scan_event;
1130     handler.on_full_scan_result = on_full_scan_result;
1131 
1132     int scanCmdId = getNewCmdId();
1133     printMsg("Starting scan --->\n");
1134     if (hal_fn.wifi_start_gscan(scanCmdId, wlan0Handle, params, handler) == WIFI_SUCCESS) {
1135         while (true) {
1136             EventInfo info;
1137             memset(&info, 0, sizeof(info));
1138             getEventFromCache(info);
1139             if (info.type == EVENT_TYPE_SCAN_RESULTS_THRESHOLD
1140                     || info.type == EVENT_TYPE_SCAN_COMPLETE) {
1141                 int retrieved_num_results = num_saved_scan_results;
1142                 if (retrieved_num_results == 0) {
1143                     printMsg("fetched 0 scan results, waiting for more..\n");
1144                     continue;
1145                 } else {
1146                     printMsg("fetched %d scan results\n", retrieved_num_results);
1147 
1148                     printMsg("Scan once completed, stopping scan\n");
1149                     hal_fn.wifi_stop_gscan(scanCmdId, wlan0Handle);
1150                     saved_scan_results = NULL;
1151                     max_saved_scan_results = 0;
1152                     num_saved_scan_results = 0;
1153                     return retrieved_num_results;
1154                 }
1155             }
1156         }
1157     } else {
1158         return 0;
1159     }
1160 }
1161 
retrieveScanResults()1162 static int retrieveScanResults() {
1163 
1164     int num_results = 64;
1165     wifi_cached_scan_results *results;
1166     results = (wifi_cached_scan_results *)malloc(num_results * sizeof(wifi_cached_scan_results));
1167     if (!results) {
1168         printMsg("%s:Malloc failed\n",__FUNCTION__);
1169         return WIFI_ERROR_OUT_OF_MEMORY;
1170     }
1171     memset(results, 0, sizeof(wifi_cached_scan_results) * num_results);
1172     printMsg("Retrieve Scan results available -->\n");
1173     int result = hal_fn.wifi_get_cached_gscan_results(wlan0Handle, 1, num_results, results, &num_results);
1174     if (result < 0) {
1175         printMsg("failed to fetch scan results : %d\n", result);
1176         goto exit;
1177     } else {
1178         printMsg("fetched %d scan results\n", num_results);
1179     }
1180 
1181     printScanHeader();
1182     for (int i = 0; i < num_results; i++) {
1183         printMsg("ScanId = %d, Scanned buckets 0x%x, Flags = %x, num results = %d\n",
1184             results[i].scan_id, results[i].buckets_scanned, results[i].flags,
1185             results[i].num_results);
1186         for (int j = 0; j < results[i].num_results; j++) {
1187             printScanResult(results[i].results[j]);
1188         }
1189         printMsg("\n");
1190     }
1191 
1192 exit:
1193     if (results) {
1194         free(results);
1195     }
1196     return WIFI_SUCCESS;
1197 }
1198 
1199 
compareScanResultsByRssi(const void * p1,const void * p2)1200 static int compareScanResultsByRssi(const void *p1, const void *p2) {
1201     const wifi_scan_result *result1 = *(const wifi_scan_result **)(p1);
1202     const wifi_scan_result *result2 = *(const wifi_scan_result **)(p2);
1203 
1204     /* RSSI is -ve, so lower one wins */
1205     if (result1->rssi < result2->rssi) {
1206         return 1;
1207     } else if (result1->rssi == result2->rssi) {
1208         return 0;
1209     } else {
1210         return -1;
1211     }
1212 }
1213 
sortScanResultsByRssi(wifi_scan_result ** results,int num_results)1214 static void sortScanResultsByRssi(wifi_scan_result **results, int num_results) {
1215     qsort(results, num_results, sizeof(wifi_scan_result*), &compareScanResultsByRssi);
1216 }
1217 
removeDuplicateScanResults(wifi_scan_result ** results,int num)1218 static int removeDuplicateScanResults(wifi_scan_result **results, int num) {
1219     /* remove duplicates by BSSID */
1220     int num_results = num;
1221     wifi_scan_result *tmp;
1222     for (int i = 0; i < num_results; i++) {
1223         for (int j = i + 1; j < num_results; ) {
1224             if (memcmp((*results[i]).bssid, (*results[j]).bssid, sizeof(mac_addr)) == 0) {
1225                 int num_to_move = num_results - j - 1;
1226                 tmp = results[j];
1227                 memmove(&results[j], &results[j+1], num_to_move * sizeof(wifi_scan_result *));
1228                 free(tmp);
1229                 num_results--;
1230             } else {
1231                 j++;
1232             }
1233         }
1234     }
1235     return num_results;
1236 }
1237 
onRTTResultsV3(wifi_request_id id,unsigned num_results,wifi_rtt_result_v3 * result[])1238 static void onRTTResultsV3(wifi_request_id id, unsigned num_results,
1239     wifi_rtt_result_v3 *result[]) {
1240 
1241     printMsg("RTT results: num_results %d\n", num_results);
1242     wifi_rtt_result_v3 *rtt_result_v3;
1243     mac_addr addr = {0};
1244 
1245     for (unsigned i = 0; i < num_results; i++) {
1246         rtt_result_v3 = result[i];
1247         if (memcmp(addr, rtt_result_v3->rtt_result.rtt_result.addr, sizeof(mac_addr))) {
1248             printMsg("Target mac : %02x:%02x:%02x:%02x:%02x:%02x\n",
1249                     rtt_result_v3->rtt_result.rtt_result.addr[0],
1250                     rtt_result_v3->rtt_result.rtt_result.addr[1],
1251                     rtt_result_v3->rtt_result.rtt_result.addr[2],
1252                     rtt_result_v3->rtt_result.rtt_result.addr[3],
1253                     rtt_result_v3->rtt_result.rtt_result.addr[4],
1254                     rtt_result_v3->rtt_result.rtt_result.addr[5]);
1255             memcpy(addr, rtt_result_v3->rtt_result.rtt_result.addr, sizeof(mac_addr));
1256         }
1257 
1258         printMsg("\tburst_num : %d, measurement_number : %d,\n"
1259                 "\tsuccess_number : %d, number_per_burst_peer : %d,\n"
1260                 "\tstatus : %d, retry_after_duration : %ds,\n"
1261                 "\ttype : %d, rssi : %d dbm, rx_rate : %d Kbps, rtt : %lu ps,\n"
1262                 "\trtt_sd : %lu ps, distance : %d mm, burst_duration : %d ms,\n"
1263                 "\tnegotiated_burst_num : %d, frequency : %d, packet_bw : %d\n",
1264                 rtt_result_v3->rtt_result.rtt_result.burst_num,
1265                 rtt_result_v3->rtt_result.rtt_result.measurement_number,
1266                 rtt_result_v3->rtt_result.rtt_result.success_number,
1267                 rtt_result_v3->rtt_result.rtt_result.number_per_burst_peer,
1268                 rtt_result_v3->rtt_result.rtt_result.status,
1269                 rtt_result_v3->rtt_result.rtt_result.retry_after_duration,
1270                 rtt_result_v3->rtt_result.rtt_result.type,
1271                 rtt_result_v3->rtt_result.rtt_result.rssi,
1272                 rtt_result_v3->rtt_result.rtt_result.rx_rate.bitrate * 100,
1273                 (unsigned long)rtt_result_v3->rtt_result.rtt_result.rtt,
1274                 (unsigned long)rtt_result_v3->rtt_result.rtt_result.rtt_sd,
1275                 rtt_result_v3->rtt_result.rtt_result.distance_mm,
1276                 rtt_result_v3->rtt_result.rtt_result.burst_duration,
1277                 rtt_result_v3->rtt_result.rtt_result.negotiated_burst_num,
1278                 rtt_result_v3->rtt_result.frequency,
1279                 rtt_result_v3->rtt_result.packet_bw);
1280 
1281         if (rtt_result_v3->rtt_result.rtt_result.LCI) {
1282             printMsg("LCI id %d\n", rtt_result_v3->rtt_result.rtt_result.LCI->id);
1283             printMsg("LCI Len %d\n", rtt_result_v3->rtt_result.rtt_result.LCI->len);
1284             prhex_msg("LCI data",
1285                     rtt_result_v3->rtt_result.rtt_result.LCI->data,
1286                     rtt_result_v3->rtt_result.rtt_result.LCI->len);
1287         }
1288 
1289         if (rtt_result_v3->rtt_result.rtt_result.LCR) {
1290             printMsg("LCR id %d\n", rtt_result_v3->rtt_result.rtt_result.LCR->id);
1291             printMsg("LCR Len %d\n", rtt_result_v3->rtt_result.rtt_result.LCR->len);
1292             prhex_msg("LCR data",
1293                     rtt_result_v3->rtt_result.rtt_result.LCR->data,
1294                     rtt_result_v3->rtt_result.rtt_result.LCR->len);
1295         }
1296 
1297         if (rtt_result_v3->rtt_result.rtt_result.type == RTT_TYPE_2_SIDED_11AZ_NTB) {
1298             printMsg("\t i2r_tx_ltf_repetition_cnt: %u,\n"
1299                     " \t r2i_tx_ltf_repetition_cnt: %u,\n"
1300                     " \t ntb min meas_time: %lu units of 100us,\n"
1301                     " \t ntb max meas_time: %lu units of 10ms\n",
1302                     rtt_result_v3->i2r_tx_ltf_repetition_count,
1303                     rtt_result_v3->r2i_tx_ltf_repetition_count,
1304                     rtt_result_v3->ntb_min_measurement_time,
1305                     rtt_result_v3->ntb_max_measurement_time);
1306         }
1307     }
1308 
1309     putEventInCache(EVENT_TYPE_RTT_RESULTS, "RTT results");
1310 }
1311 
onHotlistAPFound(wifi_request_id id,unsigned num_results,wifi_scan_result * results)1312 static void onHotlistAPFound(wifi_request_id id, unsigned num_results, wifi_scan_result *results) {
1313 
1314     printMsg("Found hotlist APs\n");
1315     for (unsigned i = 0; i < num_results; i++) {
1316         printScanResult(results[i]);
1317     }
1318     putEventInCache(EVENT_TYPE_HOTLIST_AP_FOUND, "Found a hotlist AP");
1319 }
1320 
onHotlistAPLost(wifi_request_id id,unsigned num_results,wifi_scan_result * results)1321 static void onHotlistAPLost(wifi_request_id id, unsigned num_results, wifi_scan_result *results) {
1322 
1323     printMsg("Lost hotlist APs\n");
1324     for (unsigned i = 0; i < num_results; i++) {
1325         printScanResult(results[i]);
1326     }
1327     putEventInCache(EVENT_TYPE_HOTLIST_AP_LOST, "Lost event Hotlist APs");
1328 }
1329 
onePnoSsidFound(wifi_request_id id,unsigned num_results,wifi_scan_result * results)1330 static void onePnoSsidFound(wifi_request_id id, unsigned num_results, wifi_scan_result *results) {
1331 
1332     printMsg("Found ePNO SSID\n");
1333     for (unsigned i = 0; i < num_results; i++) {
1334         printMsg("SSID %s, %02x:%02x:%02x:%02x:%02x:%02x, channel %d, rssi %d\n",
1335             results[i].ssid, results[i].bssid[0], results[i].bssid[1],
1336             results[i].bssid[2], results[i].bssid[3], results[i].bssid[4],
1337             results[i].bssid[5], results[i].channel, (signed char)results[i].rssi);
1338     }
1339     putEventInCache(EVENT_TYPE_EPNO_SSID, "Found ePNO SSID");
1340 }
1341 
onRssiThresholdbreached(wifi_request_id id,u8 * cur_bssid,s8 cur_rssi)1342 static void onRssiThresholdbreached(wifi_request_id id, u8 *cur_bssid, s8 cur_rssi) {
1343 
1344     printMsg("RSSI threshold breached, cur RSSI - %d!!\n", cur_rssi);
1345     printMsg("BSSID %02x:%02x:%02x:%02x:%02x:%02x\n",
1346                 cur_bssid[0], cur_bssid[1], cur_bssid[2],
1347                 cur_bssid[3], cur_bssid[4], cur_bssid[5]);
1348     putEventInCache(EVENT_TYPE_RSSI_MONITOR, "RSSI monitor Event");
1349 }
1350 
bss_get_ie(u8 id,const char * ie,const s32 ie_len)1351 static const u8 *bss_get_ie(u8 id, const char* ie, const s32 ie_len)
1352 {
1353     const u8 *end, *pos;
1354 
1355     pos = (const u8 *)ie;
1356     end = pos + ie_len;
1357 
1358     while (pos + 1 < end) {
1359         if (pos + 2 + pos[1] > end)
1360             break;
1361         if (pos[0] == id)
1362             return pos;
1363         pos += 2 + pos[1];
1364     }
1365 
1366     return NULL;
1367 }
1368 
is11mcAP(const char * ie,const s32 ie_len)1369 static bool is11mcAP(const char* ie, const s32 ie_len)
1370 {
1371     const u8 *ext_cap_ie, *ptr_ie;
1372     u8 ext_cap_length = 0;
1373     ptr_ie = bss_get_ie(WIFI_EID_EXT_CAPAB, ie, ie_len);
1374     if (ptr_ie) {
1375         ext_cap_length = *(ptr_ie + TLV_LEN_OFF);
1376         ext_cap_ie = ptr_ie + TLV_BODY_OFF;
1377         if ((ext_cap_length >= CEIL(DOT11_EXT_CAP_FTM_RESPONDER, NBBY)) &&
1378                 (isset(ext_cap_ie, DOT11_EXT_CAP_FTM_RESPONDER) ||
1379                  isset(ext_cap_ie, DOT11_EXT_CAP_FTM_INITIATOR))) {
1380             return true;
1381         }
1382     }
1383     return false;
1384 }
1385 
1386 #define CHAN_FACTOR_6_G 11900u   /* 6   GHz band, 5950 MHz */
channel2mhz_6g(uint ch)1387 int channel2mhz_6g(uint ch)
1388 {
1389      int freq;
1390      freq = (ch * 5) + (CHAN_FACTOR_6_G / 2);
1391      return freq;
1392 }
1393 
channel2mhz(uint ch)1394 int channel2mhz(uint ch)
1395 {
1396     int freq;
1397     int start_factor = (ch > 14)? CHAN_FACTOR_5_G : CHAN_FACTOR_2_4_G;
1398     if ((start_factor == CHAN_FACTOR_2_4_G && (ch < 1 || ch > 14)) ||
1399             (ch > 200))
1400         freq = -1;
1401     else if ((start_factor == CHAN_FACTOR_2_4_G) && (ch == 14))
1402         freq = 2484;
1403     else
1404         freq = ch * 5 + start_factor / 2;
1405 
1406     return freq;
1407 }
1408 
read_ht_oper_ie(const char * ie,const s32 ie_len)1409 struct ht_op_ie *read_ht_oper_ie(const char* ie, const s32 ie_len)
1410 {
1411     const u8 *ptr_ie;
1412     ptr_ie = bss_get_ie(WIFI_EID_HT_OPERATION, ie, ie_len);
1413     if (ptr_ie) {
1414         return (struct ht_op_ie *)(ptr_ie + TLV_BODY_OFF);
1415     }
1416     return NULL;
1417 }
1418 
read_vht_oper_ie(const char * ie,const s32 ie_len)1419 struct vht_op_ie *read_vht_oper_ie(const char* ie, const s32 ie_len)
1420 {
1421     const u8 *ptr_ie;
1422     ptr_ie = bss_get_ie(WIFI_EID_VHT_OPERATION, ie, ie_len);
1423     if (ptr_ie) {
1424         return (struct vht_op_ie *)(ptr_ie + TLV_BODY_OFF);
1425     }
1426     return NULL;
1427 }
1428 
convert_channel(int ch,int chan_width,bool is_6g)1429 wifi_channel_info convert_channel(int ch, int chan_width, bool is_6g)
1430 {
1431     wifi_channel_info chan_info;
1432     memset(&chan_info, 0, sizeof(wifi_channel_info));
1433 
1434     chan_info.width = (wifi_channel_width)chan_width;
1435     if (is_6g) {
1436         chan_info.center_freq = channel2mhz_6g(ch);
1437         return chan_info;
1438     } else {
1439         chan_info.center_freq = channel2mhz(ch);
1440     }
1441     if (chan_width == WIFI_CHAN_WIDTH_160) {
1442         if ((ch >= 36) && (ch <= 64))
1443             chan_info.center_freq0 = 5250;
1444         if ((ch >= 100) && (ch <= 128))
1445             chan_info.center_freq0 = 5570;
1446         if ((ch >= 149) && (ch <= 177))
1447             chan_info.center_freq0 = 5815;
1448     } else if (chan_width == WIFI_CHAN_WIDTH_80) {
1449         /*primary is the lowest channel*/
1450         if ((ch >= 36) && (ch <= 48))
1451             chan_info.center_freq0 = 5210;
1452         else if ((ch >= 52) && (ch <= 64))
1453             chan_info.center_freq0 = 5290;
1454         else if ((ch >= 100) && (ch <= 112))
1455             chan_info.center_freq0 = 5530;
1456         else if ((ch >= 116) && (ch <= 128))
1457             chan_info.center_freq0 = 5610;
1458         else if ((ch >= 132) && (ch <= 144))
1459             chan_info.center_freq0 = 5690;
1460         else if ((ch >= 149) && (ch <= 161))
1461             chan_info.center_freq0 = 5775;
1462     } else {
1463         if (chan_width == WIFI_CHAN_WIDTH_40) {
1464             if ((ch >= 36) && (ch <= 40))
1465                 chan_info.center_freq0 = 5190;
1466             else if ((ch >= 44) && (ch <= 48))
1467                 chan_info.center_freq0 = 5230;
1468             else if ((ch >= 52) && (ch <= 56))
1469                 chan_info.center_freq0 = 5270;
1470             else if ((ch >= 60) && (ch <= 64))
1471                 chan_info.center_freq0 = 5310;
1472             else if ((ch >= 100) && (ch <= 104))
1473                 chan_info.center_freq0 = 5510;
1474             else if ((ch >= 108) && (ch <= 112))
1475                 chan_info.center_freq0 = 5550;
1476             else if ((ch >= 116) && (ch <= 120))
1477                 chan_info.center_freq0 = 5590;
1478             else if ((ch >= 124) && (ch <= 128))
1479                 chan_info.center_freq0 = 5630;
1480             else if ((ch >= 132) && (ch <= 136))
1481                 chan_info.center_freq0 = 5670;
1482             else if ((ch >= 140) && (ch <= 144))
1483                 chan_info.center_freq0 = 5710;
1484             else if ((ch >= 149) && (ch <= 153))
1485                 chan_info.center_freq0 = 5755;
1486             else if ((ch >= 157) && (ch <= 161))
1487                 chan_info.center_freq0 = 5795;
1488         }
1489     }
1490     return chan_info;
1491 }
1492 
get_channel_of_ie(const char * ie,const s32 ie_len)1493 wifi_channel_info get_channel_of_ie(const char* ie, const s32 ie_len)
1494 {
1495     struct vht_op_ie *vht_op;
1496     struct ht_op_ie *ht_op;
1497     const u8 *ptr_ie;
1498     wifi_channel_info chan_info;
1499     memset(&chan_info, 0, sizeof(wifi_channel_info));
1500     vht_op = read_vht_oper_ie(ie, ie_len);
1501     if ((vht_op = read_vht_oper_ie(ie, ie_len)) &&
1502             ((ht_op = (read_ht_oper_ie(ie, ie_len))))) {
1503         /* VHT mode */
1504         if (vht_op->chan_width == VHT_OP_CHAN_WIDTH_80) {
1505             chan_info.width = WIFI_CHAN_WIDTH_80;
1506             /* primary channel */
1507             chan_info.center_freq = channel2mhz(ht_op->ctl_ch);
1508             /* center frequency */
1509             chan_info.center_freq0 = channel2mhz(vht_op->chan1);
1510             return chan_info;
1511         }
1512     }
1513     if ((ht_op = (read_ht_oper_ie(ie, ie_len)))) {
1514         /* HT mode */
1515         /* control channel */
1516         chan_info.center_freq = channel2mhz(ht_op->ctl_ch);
1517         chan_info.width = WIFI_CHAN_WIDTH_20;
1518         switch (ht_op->chan_info & DOT11_EXT_CH_MASK) {
1519             chan_info.center_freq = channel2mhz(ht_op->ctl_ch);
1520             case DOT11_EXT_CH_UPPER:
1521                 chan_info.width = WIFI_CHAN_WIDTH_40;
1522                 break;
1523             case DOT11_EXT_CH_LOWER:
1524                 chan_info.width = WIFI_CHAN_WIDTH_40;
1525                 break;
1526             case DOT11_EXT_CH_NONE:
1527                 break;
1528         }
1529     } else {
1530         chan_info.width = WIFI_CHAN_WIDTH_20;
1531         ptr_ie = bss_get_ie(WIFI_EID_DS_PARAMS, ie, ie_len);
1532         if (ptr_ie) {
1533             chan_info.center_freq = channel2mhz(ptr_ie[TLV_BODY_OFF]);
1534         }
1535     }
1536     return chan_info;
1537 }
1538 
testRTT()1539 static void testRTT()
1540 {
1541     wifi_scan_result *results[max_ap];
1542     wifi_scan_result *scan_param;
1543     u32 num_ap = 0;
1544     /*For STA-STA RTT */
1545     u32 num_sta = 0;
1546     int result = 0;
1547     /* Run by a provided rtt-ap-list file */
1548     FILE* w_fp = NULL;
1549     wifi_rtt_config_v3 params[max_ap];
1550 
1551     if (!rtt_from_file && !rtt_sta && !rtt_nan) {
1552         /* band filter for a specific band */
1553         if (band == WIFI_BAND_UNSPECIFIED)
1554             band = WIFI_BAND_ABG;
1555         int num_results = scanOnce(band, results, max_ap);
1556         if (num_results == 0) {
1557             printMsg("RTT aborted because of no scan results\n");
1558             return;
1559         } else {
1560             printMsg("Retrieved %d scan results\n", num_results);
1561         }
1562 
1563         num_results = removeDuplicateScanResults(results, num_results);
1564 
1565         sortScanResultsByRssi(results, num_results);
1566         printMsg("Sorted scan results -\n");
1567         for (int i = 0; i < num_results; i++) {
1568             printScanResult(*results[i]);
1569         }
1570 
1571         if (rtt_to_file) {
1572             /* Write a RTT AP list to a file */
1573             w_fp = fopen(rtt_aplist, "w");
1574             if (w_fp == NULL) {
1575                 printMsg("failed to open the file : %s\n", rtt_aplist);
1576                 return;
1577             }
1578             fprintf(w_fp, "|SSID|BSSID|Primary Freq|Center Freq|Channel BW(0=20MHZ,1=40MZ,2=80MHZ)\n"
1579                     "|rtt_type(1=1WAY,2=2WAY,3=auto)|Peer Type(STA=0, AP=1)|burst period|\n"
1580                     "Num of Burst|FTM retry count|FTMR retry count|LCI|LCR|\n"
1581                     "Burst Duration|Preamble|BW||NTB Min Meas Time in units of 100us|\n"
1582                     "NTB Max Meas Time in units of 10ms\n");
1583         }
1584 
1585         for (int i = 0; i < min(num_results, max_ap); i++) {
1586             scan_param = results[i];
1587             if(is11mcAP(&scan_param->ie_data[0], scan_param->ie_length)) {
1588                 memcpy(params[num_ap].rtt_config.addr, scan_param->bssid,
1589                         sizeof(mac_addr));
1590                 mac_addr &addr = params[num_ap].rtt_config.addr;
1591                 printMsg("Adding %s(%02x:%02x:%02x:%02x:%02x:%02x) on Freq (%d) for %s type RTT\n",
1592                         scan_param->ssid, addr[0], addr[1],
1593                         addr[2], addr[3], addr[4], addr[5],
1594                         scan_param->channel, RttTypeToString(type));
1595                 params[num_ap].rtt_config.type = type;
1596                 params[num_ap].rtt_config.channel = get_channel_of_ie(&scan_param->ie_data[0],
1597                         scan_param->ie_length);
1598                 params[num_ap].rtt_config.peer = RTT_PEER_AP;
1599                 params[num_ap].rtt_config.num_burst = default_rtt_param.num_burst;
1600                 params[num_ap].rtt_config.num_frames_per_burst =
1601                         default_rtt_param.num_frames_per_burst;
1602                 params[num_ap].rtt_config.num_retries_per_rtt_frame =
1603                         default_rtt_param.num_retries_per_ftm;
1604                 params[num_ap].rtt_config.num_retries_per_ftmr =
1605                         default_rtt_param.num_retries_per_ftmr;
1606                 params[num_ap].rtt_config.burst_period = default_rtt_param.burst_period;
1607                 params[num_ap].rtt_config.burst_duration = default_rtt_param.burst_duration;
1608                 params[num_ap].rtt_config.LCI_request = default_rtt_param.LCI_request;
1609                 params[num_ap].rtt_config.LCR_request = default_rtt_param.LCR_request;
1610                 params[num_ap].rtt_config.preamble = (wifi_rtt_preamble)default_rtt_param.preamble;
1611                 params[num_ap].rtt_config.bw = convert_channel_width_to_rtt_bw(channel_width);
1612                 if (params[num_ap].rtt_config.bw == WIFI_RTT_BW_5) {
1613                     printf("Unsupported rtt bw %x \n",
1614                             params[num_ap].rtt_config.bw);
1615                     return;
1616                 }
1617                 if (params[num_ap].rtt_config.type == RTT_TYPE_2_SIDED_11AZ_NTB) {
1618                     params[num_ap].rtt_config.num_frames_per_burst =
1619                             default_rtt_param_v3.num_frames_per_burst;
1620                     printf("num_frames_per_burst %d \n",
1621                             params[num_ap].rtt_config.num_frames_per_burst);
1622                     if (!ntb_min_meas_time) {
1623                         params[num_ap].ntb_min_measurement_time =
1624                                 default_rtt_param_v3.ntb_min_measurement_time;
1625                     } else {
1626                         params[num_ap].ntb_min_measurement_time =
1627                                 ntb_min_meas_time;
1628                     }
1629                     if (!ntb_max_meas_time) {
1630                          params[num_ap].ntb_max_measurement_time =
1631                                 default_rtt_param_v3.ntb_max_measurement_time;
1632                     } else {
1633                         params[num_ap].ntb_max_measurement_time =
1634                                 ntb_max_meas_time;
1635                     }
1636                 }
1637                 if (rtt_to_file) {
1638                     fprintf(w_fp, "%s %02x:%02x:%02x:%02x:%02x:%02x"
1639                             " %d %d %d %d %d %d %d %d %d "
1640                             "%d %d %d %d %d %d %lu %lu\n",
1641                             scan_param->ssid,
1642                             params[num_ap].rtt_config.addr[0],
1643                             params[num_ap].rtt_config.addr[1],
1644                             params[num_ap].rtt_config.addr[2],
1645                             params[num_ap].rtt_config.addr[3],
1646                             params[num_ap].rtt_config.addr[4],
1647                             params[num_ap].rtt_config.addr[5],
1648                             params[num_ap].rtt_config.channel.center_freq,
1649                             params[num_ap].rtt_config.channel.center_freq0,
1650                             params[num_ap].rtt_config.channel.width,
1651                             params[num_ap].rtt_config.type,
1652                             params[num_ap].rtt_config.peer,
1653                             params[num_ap].rtt_config.burst_period,
1654                             params[num_ap].rtt_config.num_burst,
1655                             params[num_ap].rtt_config.num_frames_per_burst,
1656                             params[num_ap].rtt_config.num_retries_per_rtt_frame,
1657                             params[num_ap].rtt_config.num_retries_per_ftmr,
1658                             params[num_ap].rtt_config.LCI_request,
1659                             params[num_ap].rtt_config.LCR_request,
1660                             params[num_ap].rtt_config.burst_duration,
1661                             params[num_ap].rtt_config.preamble,
1662                             params[num_ap].rtt_config.bw,
1663                             params[num_ap].ntb_min_measurement_time,
1664                             params[num_ap].ntb_max_measurement_time);
1665                 }
1666                 num_ap++;
1667             } else {
1668                 /* legacy AP */
1669             }
1670         }
1671         /* free the results data */
1672         for (int i = 0; i < num_results; i++) {
1673             free(results[i]);
1674             results[i] = NULL;
1675         }
1676         if (w_fp)
1677             fclose(w_fp);
1678     } else if (rtt_sta || rtt_nan) {
1679         printf(" Run initiator rtt sta/nan, rtt_sta = %d, rtt_nan = %d \n",
1680                 rtt_sta, rtt_nan);
1681         /* As we have only one target */
1682         memcpy(params[num_sta].rtt_config.addr, responder_addr, sizeof(mac_addr));
1683         params[num_sta].rtt_config.channel =
1684                 convert_channel(responder_channel, channel_width, is_6g);
1685         printMsg("Adding(" MACSTR ") on Freq (%d) for %s RTT\n",
1686                 MAC2STR(responder_addr),
1687                 params[num_sta].rtt_config.channel.center_freq,
1688                 RttTypeToString(type));
1689         /*As we are doing STA-STA RTT */
1690         params[num_sta].rtt_config.type = type;
1691         if (rtt_nan) {
1692             params[num_sta].rtt_config.peer = RTT_PEER_NAN;
1693         } else if (rtt_sta) {
1694             params[num_sta].rtt_config.peer = RTT_PEER_STA;
1695         }
1696         params[num_sta].rtt_config.num_burst = default_rtt_param.num_burst;
1697         params[num_sta].rtt_config.num_frames_per_burst = default_rtt_param.num_frames_per_burst;
1698         params[num_sta].rtt_config.num_retries_per_rtt_frame =
1699             default_rtt_param.num_retries_per_ftm;
1700         params[num_sta].rtt_config.num_retries_per_ftmr = default_rtt_param.num_retries_per_ftmr;
1701         params[num_sta].rtt_config.burst_period = default_rtt_param.burst_period;
1702         params[num_sta].rtt_config.burst_duration = default_rtt_param.burst_duration;
1703         params[num_sta].rtt_config.LCI_request = default_rtt_param.LCI_request;
1704         params[num_sta].rtt_config.LCR_request = default_rtt_param.LCR_request;
1705         params[num_sta].rtt_config.preamble = (wifi_rtt_preamble)default_rtt_param.preamble;
1706         params[num_sta].rtt_config.bw = convert_channel_width_to_rtt_bw(channel_width);
1707         if (params[num_sta].rtt_config.bw == WIFI_RTT_BW_5) {
1708             printf("Unsupported rtt bw %x \n",
1709                     params[num_sta].rtt_config.bw);
1710             return;
1711         }
1712 
1713         if (params[num_sta].rtt_config.type == RTT_TYPE_2_SIDED_11AZ_NTB) {
1714             params[num_sta].rtt_config.num_frames_per_burst =
1715                     default_rtt_param_v3.num_frames_per_burst;
1716 
1717             printf("num_frames_per_burst %d \n",
1718                     params[num_sta].rtt_config.num_frames_per_burst);
1719             if (!ntb_min_meas_time) {
1720                 params[num_sta].ntb_min_measurement_time =
1721                         default_rtt_param_v3.ntb_min_measurement_time;
1722                 } else {
1723                     params[num_sta].ntb_min_measurement_time =
1724                             ntb_min_meas_time;
1725                 }
1726                 if (!ntb_max_meas_time) {
1727                     params[num_sta].ntb_max_measurement_time =
1728                             default_rtt_param_v3.ntb_max_measurement_time;
1729                 } else {
1730                     params[num_sta].ntb_max_measurement_time =
1731                             ntb_max_meas_time;
1732                 }
1733         }
1734 
1735         num_sta++;
1736 
1737     } else {
1738         /* Run by a provided rtt-ap-list file */
1739         FILE* fp;
1740         char bssid[ETHER_ADDR_STR_LEN];
1741         char ssid[MAX_SSID_LEN];
1742         char first_char;
1743         memset(bssid, 0, sizeof(bssid));
1744         memset(ssid, 0, sizeof(ssid));
1745         memset(params, 0, sizeof(params));
1746 
1747         /* Read a RTT AP list from a file */
1748         fp = fopen(rtt_aplist, "r");
1749         if (fp == NULL) {
1750             printMsg("\nRTT AP list file does not exist on %s.\n"
1751                     "Please specify correct full path or use default one, %s, \n"
1752                     "  by following order in file, such as:\n"
1753                     "SSID | BSSID | chan_num |Channel BW(0=20MHZ,1=40MZ,2=80MHZ)|"
1754                     " RTT_Type(1=1WAY,2=2WAY,3=auto) |Peer Type(STA=0, AP=1)| Burst Period|"
1755                     " No of Burst| No of FTM Burst| FTM Retry Count| FTMR Retry Count| LCI| LCR|"
1756                     " Burst Duration| Preamble|Channel_Bandwith|"
1757                     " NTB Min Meas Time in units of 100us|\n",
1758                     " NTB Max Meas Time in units of 10ms\n",
1759                     rtt_aplist, DEFAULT_RTT_FILE);
1760             return;
1761         }
1762         int i = 0;
1763         while (!feof(fp)) {
1764             if ((fscanf(fp, "%c", &first_char) == 1) && (first_char != '|')) {
1765                 result = fseek(fp, -1, SEEK_CUR);
1766                 if (result != 0) {
1767                     printMsg("fseek failed %d\n", result);
1768                     break;
1769                 }
1770 
1771                 result = fscanf(fp,"%s %s %u %u %u\n",
1772                         ssid, bssid, (unsigned int*)&responder_channel,
1773                         (unsigned int*)&channel_width,
1774                         (unsigned int*)&params[i].rtt_config.type);
1775                 if (result != 5) {
1776                     printMsg("fscanf failed to read ssid, bssid, channel, type: %d\n", result);
1777                     break;
1778                 }
1779 
1780                 result = fscanf(fp, "%u %u %u %u %u %u %hhu %hhu %u %hhu %u\n",
1781                         (unsigned int*)&params[i].rtt_config.peer,
1782                         &params[i].rtt_config.burst_period,
1783                         &params[i].rtt_config.num_burst,
1784                         &params[i].rtt_config.num_frames_per_burst,
1785                         (unsigned int*)&params[i].rtt_config.num_retries_per_rtt_frame,
1786                         (unsigned int*)&params[i].rtt_config.num_retries_per_ftmr,
1787                         (unsigned char*)&params[i].rtt_config.LCI_request,
1788                         (unsigned char*)&params[i].rtt_config.LCR_request,
1789                         (unsigned int*)&params[i].rtt_config.burst_duration,
1790                         (unsigned char*)&params[i].rtt_config.preamble, &channel_width);
1791                 if (result != 11) {
1792                     printMsg("fscanf failed to read mc params %d\n", result);
1793                     break;
1794                 }
1795                 params[i].rtt_config.bw = convert_channel_width_to_rtt_bw(channel_width);
1796                 if (params[i].rtt_config.bw == WIFI_RTT_BW_5) {
1797                     printf("Unsupported rtt bw %x \n", params[i].rtt_config.bw);
1798                     break;
1799                 }
1800 
1801                 if (params[i].rtt_config.type == RTT_TYPE_2_SIDED_11AZ_NTB) {
1802                     result = fscanf(fp, "%14lu %14lu\n",
1803                             &params[i].ntb_min_measurement_time,
1804                             &params[i].ntb_max_measurement_time);
1805                     if (result != 2) {
1806                         printMsg("fscanf failed to read az params %d\n", result);
1807                         break;
1808                     }
1809                 }
1810 
1811                 params[i].rtt_config.channel = convert_channel(responder_channel,
1812                         channel_width, is_6g);
1813                 parseMacAddress(bssid, params[i].rtt_config.addr);
1814 
1815                 printMsg("Target: [%d]: ssid: %-16s\n"
1816                         " BSSID:%-20s\n"
1817                         " center freq: %-8u\n"
1818                         " center freq0:%-14u\n"
1819                         " channel_width: %-12d\n"
1820                         " Type:%-15s\n"
1821                         " peer:%-10u\n"
1822                         " burst_period:%-16u\n"
1823                         " num_burst:%-10u\n"
1824                         " num_frames_per_burst:%-14u\n"
1825                         " num_retries_per_rtt_frame:%-11u\n"
1826                         " num_retries_per_ftmr:%-5hhu\n"
1827                         " LCI_request: %-5hhu\n"
1828                         " LCR_request: %-15u\n"
1829                         " burst_duration: %-10hhu\n"
1830                         " preamble:%-10hhu\n"
1831                         " bw:%-10hhu\n"
1832                         " ntb_min_measurement_time: %-14lu\n"
1833                         " ntb_max_measurement_time: %-14lu\n",
1834                         i+1, ssid, bssid,
1835                         params[i].rtt_config.channel.center_freq,
1836                         params[i].rtt_config.channel.center_freq0,
1837                         params[i].rtt_config.channel.width,
1838                         RttTypeToString(params[i].rtt_config.type),
1839                         params[i].rtt_config.peer,
1840                         params[i].rtt_config.burst_period,
1841                         params[i].rtt_config.num_burst,
1842                         params[i].rtt_config.num_frames_per_burst,
1843                         params[i].rtt_config.num_retries_per_rtt_frame,
1844                         params[i].rtt_config.num_retries_per_ftmr,
1845                         params[i].rtt_config.LCI_request,
1846                         params[i].rtt_config.LCR_request,
1847                         params[i].rtt_config.burst_duration,
1848                         params[i].rtt_config.preamble,
1849                         params[i].rtt_config.bw,
1850                         params[i].ntb_min_measurement_time,
1851                         params[i].ntb_max_measurement_time);
1852 
1853                 i++;
1854             } else {
1855                 /* Ignore the rest of the line. */
1856                 result = fscanf(fp, "%*[^\n]");
1857                 if (result != 1) {
1858                     printMsg("fscanf failed to read the next line %d\n", result);
1859                     break;
1860                 }
1861 
1862                 result = fscanf(fp, "\n");
1863                 if (result != 1) {
1864                     printMsg("fscanf failed after reading next line%d\n", result);
1865                     break;
1866                 }
1867             }
1868         }
1869         num_ap = i;
1870         fclose(fp);
1871         fp = NULL;
1872     }
1873 
1874     wifi_rtt_event_handler_v3 handler;
1875     memset(&handler, 0, sizeof(handler));
1876     handler.on_rtt_results_v3 = &onRTTResultsV3;
1877 
1878     if (!rtt_to_file || rtt_sta || rtt_nan)  {
1879         if (num_ap || num_sta) {
1880             if (num_ap) {
1881                 printMsg("Configuring RTT for %d APs\n", num_ap);
1882                 result = hal_fn.wifi_rtt_range_request_v3(rttCmdId, wlan0Handle,
1883                         num_ap, params, handler);
1884             } else if (num_sta) {
1885                 printMsg("Configuring RTT for %d sta \n", num_sta);
1886                 result = hal_fn.wifi_rtt_range_request_v3(rttCmdId, wlan0Handle,
1887                         num_sta, params, handler);
1888             }
1889 
1890             if (result == WIFI_SUCCESS) {
1891                 printMsg("\nWaiting for RTT results\n");
1892                 while (true) {
1893                     EventInfo info;
1894                     memset(&info, 0, sizeof(info));
1895                     getEventFromCache(info);
1896                     if (info.type == EVENT_TYPE_RTT_RESULTS ||
1897                         info.type == EVENT_TYPE_RTT_RESULTS_DETAIL) {
1898                         break;
1899                     }
1900                 }
1901             } else {
1902                 printMsg("Could not set setRTTAPs : %d\n", result);
1903             }
1904         } else {
1905             printMsg("no candidate for RTT\n");
1906         }
1907     } else {
1908         printMsg("written AP info into file %s successfully\n", rtt_aplist);
1909     }
1910 }
1911 
cancelRTT()1912 static int cancelRTT()
1913 {
1914     int ret;
1915     ret = hal_fn.wifi_rtt_range_cancel(rttCmdId, wlan0Handle, 0, NULL);
1916     if (ret == WIFI_SUCCESS) {
1917         printMsg("Successfully cancelled the RTT\n");
1918     }
1919     return ret;
1920 }
1921 
getRTTCapability()1922 static void getRTTCapability()
1923 {
1924     int ret;
1925     wifi_rtt_capabilities_v3 rtt_capability;
1926     ret = hal_fn.wifi_get_rtt_capabilities_v3(wlan0Handle, &rtt_capability);
1927     if (ret == WIFI_SUCCESS) {
1928         printMsg("Supported Capabilites of RTT :\n");
1929         if (rtt_capability.rtt_capab.rtt_one_sided_supported)
1930             printMsg("One side RTT is supported\n");
1931         if (rtt_capability.rtt_capab.rtt_ftm_supported)
1932             printMsg("FTM(11mc) RTT is supported\n");
1933         if (rtt_capability.rtt_capab.lci_support)
1934             printMsg("LCI is supported\n");
1935         if (rtt_capability.rtt_capab.lcr_support)
1936             printMsg("LCR is supported\n");
1937         if (rtt_capability.rtt_capab.bw_support) {
1938             printMsg("BW(%s %s %s %s) are supported\n",
1939                     (rtt_capability.rtt_capab.bw_support & BW_20_SUPPORT) ? "20MHZ" : "",
1940                     (rtt_capability.rtt_capab.bw_support & BW_40_SUPPORT) ? "40MHZ" : "",
1941                     (rtt_capability.rtt_capab.bw_support & BW_80_SUPPORT) ? "80MHZ" : "",
1942                     (rtt_capability.rtt_capab.bw_support & BW_160_SUPPORT) ? "160MHZ" : "");
1943         }
1944         if (rtt_capability.rtt_capab.preamble_support) {
1945             printMsg("Preamble(%s %s %s) are supported\n",
1946                     (rtt_capability.rtt_capab.preamble_support & PREAMBLE_LEGACY) ? "Legacy" : "",
1947                     (rtt_capability.rtt_capab.preamble_support & PREAMBLE_HT) ? "HT" : "",
1948                     (rtt_capability.rtt_capab.preamble_support & PREAMBLE_VHT) ? "VHT" : "");
1949 
1950         }
1951 
1952         if (rtt_capability.az_preamble_support) {
1953             printMsg("AZ preamble is supported\n");
1954         }
1955 
1956         if (rtt_capability.az_bw_support) {
1957             printMsg("AZ bw is supported\n");
1958         }
1959 
1960         if (rtt_capability.ntb_initiator_supported) {
1961             printMsg("NTB initiator is supported\n");
1962         }
1963 
1964         if (rtt_capability.ntb_responder_supported) {
1965             printMsg("NTB responder is supported\n");
1966         }
1967     } else {
1968         printMsg("Could not get the rtt capabilities : %d\n", ret);
1969     }
1970 
1971 }
1972 
1973 /* TWT related apis */
setupTwtRequest(char * argv[])1974 static void setupTwtRequest(char *argv[]) {
1975     TwtSetupRequest msg;
1976     wifi_error ret = WIFI_SUCCESS;
1977     char *endptr, *param, *val_p;
1978 
1979     /* Set Default twt setup request params */
1980     memset(&msg, 0, sizeof(msg));
1981 
1982     /* Parse args for twt params */
1983     /* skip utility */
1984     argv++;
1985     /* skip command */
1986     argv++;
1987     /* skip command */
1988     argv++;
1989 
1990     while ((param = *argv++) != NULL) {
1991         val_p = *argv++;
1992         if (!val_p || *val_p == '-') {
1993             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
1994             ret = WIFI_ERROR_NOT_SUPPORTED;
1995             goto exit;
1996         }
1997         if (strcmp(param, "-iface") == 0) {
1998             ifHandle = wifi_get_iface_handle_by_iface_name(val_p);
1999         } else if (strcmp(param, "-config_id") == 0) {
2000             msg.config_id = atoi(val_p);
2001         } else if (strcmp(param, "-neg_type") == 0) {
2002             msg.negotiation_type = atoi(val_p);
2003         } else if (strcmp(param, "-trigger_type") == 0) {
2004             msg.trigger_type = atoi(val_p);
2005         } else if (strcmp(param, "-wake_dur_us") == 0) {
2006             msg.wake_dur_us = strtoul(val_p, &endptr, 0);
2007         } else if (strcmp(param, "-wake_int_us") == 0) {
2008             msg.wake_int_us = strtoul(val_p, &endptr, 0);
2009         } else if (strcmp(param, "-wake_int_min_us") == 0) {
2010             msg.wake_int_min_us = strtoul(val_p, &endptr, 0);
2011         } else if (strcmp(param, "-wake_int_max_us") == 0) {
2012             msg.wake_int_max_us = strtoul(val_p, &endptr, 0);
2013         } else if (strcmp(param, "-wake_dur_min_us") == 0) {
2014             msg.wake_dur_min_us = strtoul(val_p, &endptr, 0);
2015         } else if (strcmp(param, "-wake_dur_max_us") == 0) {
2016             msg.wake_dur_max_us = strtoul(val_p, &endptr, 0);
2017         } else if (strcmp(param, "-avg_pkt_size") == 0) {
2018             msg.avg_pkt_size = strtoul(val_p, &endptr, 0);
2019         } else if (strcmp(param, "-avg_pkt_num") == 0) {
2020             msg.avg_pkt_num = strtoul(val_p, &endptr, 0);
2021         } else if (strcmp(param, "-wake_time_off_us") == 0) {
2022             msg.wake_time_off_us = strtoul(val_p, &endptr, 0);
2023         } else {
2024             printMsg("%s:Unsupported Parameter for twt setup request\n", __FUNCTION__);
2025             ret = WIFI_ERROR_INVALID_ARGS;
2026             goto exit;
2027         }
2028     }
2029 
2030     if (ifHandle == NULL) {
2031         printMsg("-iface <> is mandatory\n");
2032         goto exit;
2033     }
2034 
2035     ret = twt_init_handlers();
2036     if (ret != WIFI_SUCCESS) {
2037         printMsg("Failed to initialize twt handlers %d\n", ret);
2038         goto exit;
2039     }
2040 
2041     ret = twt_setup_request(ifHandle, &msg);
2042 
2043 exit:
2044     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
2045     return;
2046 }
2047 
TeardownTwt(char * argv[])2048 static void TeardownTwt(char *argv[]) {
2049     TwtTeardownRequest msg;
2050     wifi_error ret = WIFI_SUCCESS;
2051     char *param, *val_p;
2052 
2053     /* Set Default twt teardown params */
2054     memset(&msg, 0, sizeof(msg));
2055 
2056     /* Parse args for twt params */
2057     /* skip utility */
2058     argv++;
2059     /* skip command */
2060     argv++;
2061     /* skip command */
2062     argv++;
2063 
2064     while ((param = *argv++) != NULL) {
2065         val_p = *argv++;
2066         if (!val_p || *val_p == '-') {
2067             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
2068             ret = WIFI_ERROR_NOT_SUPPORTED;
2069             goto exit;
2070         }
2071         if (strcmp(param, "-iface") == 0) {
2072             ifHandle = wifi_get_iface_handle_by_iface_name(val_p);
2073         } else if (strcmp(param, "-config_id") == 0) {
2074             msg.config_id = atoi(val_p);
2075         } else if (strcmp(param, "-all_twt") == 0) {
2076             msg.all_twt = atoi(val_p);
2077         } else if (strcmp(param, "-neg_type") == 0) {
2078             msg.negotiation_type = atoi(val_p);
2079         } else {
2080             printMsg("%s:Unsupported Parameter for twt teardown request\n", __FUNCTION__);
2081             ret = WIFI_ERROR_INVALID_ARGS;
2082             goto exit;
2083         }
2084     }
2085 
2086     if (ifHandle == NULL) {
2087         printMsg("-iface <> is mandatory\n");
2088         goto exit;
2089     }
2090 
2091     ret = twt_init_handlers();
2092     if (ret != WIFI_SUCCESS) {
2093         printMsg("Failed to initialize twt handlers %d\n", ret);
2094         goto exit;
2095     }
2096 
2097     ret = twt_teardown_request(ifHandle, &msg);
2098 
2099 exit:
2100     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
2101     return;
2102 }
2103 
InfoFrameTwt(char * argv[])2104 static void InfoFrameTwt(char *argv[]) {
2105     TwtInfoFrameRequest msg;
2106     wifi_error ret = WIFI_SUCCESS;
2107     char *param, *val_p;
2108 
2109     /* Set Default twt info frame params */
2110     memset(&msg, 0, sizeof(msg));
2111 
2112     /* Parse args for twt params */
2113     /* skip utility */
2114     argv++;
2115     /* skip command */
2116     argv++;
2117     /* skip command */
2118     argv++;
2119 
2120     while ((param = *argv++) != NULL) {
2121         val_p = *argv++;
2122         if (!val_p || *val_p == '-') {
2123             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
2124             ret = WIFI_ERROR_NOT_SUPPORTED;
2125             goto exit;
2126         }
2127         if (strcmp(param, "-iface") == 0) {
2128             ifHandle = wifi_get_iface_handle_by_iface_name(val_p);
2129         } else if (strcmp(param, "-config_id") == 0) {
2130             msg.config_id = atoi(val_p);
2131         } else if (strcmp(param, "-all_twt") == 0) {
2132             msg.all_twt = atoi(val_p);
2133         } else if (strcmp(param, "-resume_time_us") == 0) {
2134             msg.resume_time_us = atoi(val_p);
2135         } else {
2136             printMsg("%s:Unsupported Parameter for twt info request\n", __FUNCTION__);
2137             ret = WIFI_ERROR_INVALID_ARGS;
2138             goto exit;
2139         }
2140     }
2141 
2142     if (ifHandle == NULL) {
2143         printMsg("-iface <> is mandatory\n");
2144         goto exit;
2145     }
2146 
2147     ret = twt_init_handlers();
2148     if (ret != WIFI_SUCCESS) {
2149         printMsg("Failed to initialize twt handlers %d\n", ret);
2150         goto exit;
2151     }
2152 
2153     ret = twt_info_frame_request(ifHandle, &msg);
2154 
2155 exit:
2156     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
2157     return;
2158 }
2159 
GetTwtStats(char * argv[])2160 static void GetTwtStats(char *argv[]) {
2161     wifi_error ret = WIFI_SUCCESS;
2162     char *param, *val_p;
2163     u8 config_id = 1;
2164     TwtStats twt_stats;
2165 
2166     /* Parse args for twt params */
2167     /* skip utility */
2168     argv++;
2169     /* skip command */
2170     argv++;
2171     /* skip command */
2172     argv++;
2173 
2174     while ((param = *argv++) != NULL) {
2175         val_p = *argv++;
2176         if (!val_p || *val_p == '-') {
2177             printMsg("%s:Need value following %s\n", __FUNCTION__, param);
2178             ret = WIFI_ERROR_NOT_SUPPORTED;
2179             goto exit;
2180         }
2181         if (strcmp(param, "-iface") == 0) {
2182             ifHandle = wifi_get_iface_handle_by_iface_name(val_p);
2183         } else if (strcmp(param, "-config_id") == 0) {
2184             config_id = atoi(val_p);
2185         } else {
2186             printMsg("%s:Unsupported Parameter for get stats request\n", __FUNCTION__);
2187             ret = WIFI_ERROR_INVALID_ARGS;
2188             goto exit;
2189         }
2190     }
2191 
2192     if (ifHandle == NULL) {
2193         printMsg("-iface <> is mandatory\n");
2194         goto exit;
2195     }
2196 
2197     memset(&twt_stats, 0, sizeof(twt_stats));
2198 
2199     ret = twt_get_stats(ifHandle, config_id, &twt_stats);
2200 
2201     if (ret == WIFI_SUCCESS) {
2202         printMsg("TWT stats :\n");
2203         if (twt_stats.config_id)
2204             printMsg("config id = %d\n", twt_stats.config_id);
2205         if (twt_stats.avg_pkt_num_tx)
2206             printMsg("avg_pkt_num_tx = %d\n", twt_stats.avg_pkt_num_tx);
2207         if (twt_stats.avg_pkt_num_rx)
2208             printMsg("avg_pkt_num_rx = %d\n", twt_stats.avg_pkt_num_rx);
2209         if (twt_stats.avg_tx_pkt_size)
2210             printMsg("avg_tx_pkt_size = %d\n", twt_stats.avg_tx_pkt_size);
2211         if (twt_stats.avg_rx_pkt_size)
2212             printMsg("avg_rx_pkt_size = %d\n", twt_stats.avg_rx_pkt_size);
2213         if (twt_stats.avg_eosp_dur_us)
2214             printMsg("avg_eosp_dur_us = %d\n", twt_stats.avg_eosp_dur_us);
2215         if (twt_stats.eosp_count)
2216             printMsg("eosp_count = %d\n", twt_stats.eosp_count);
2217 
2218         return;
2219     }
2220 exit:
2221     printMsg("Could not get the twt stats : err %d\n", ret);
2222     return;
2223 }
2224 
ClearTwtStats(char * argv[])2225 void ClearTwtStats(char *argv[]) {
2226     wifi_error ret = WIFI_SUCCESS;
2227     char *param, *val_p;
2228     u8 config_id = 1;
2229 
2230     /* Parse args for twt params */
2231     /* skip utility */
2232     argv++;
2233     /* skip command */
2234     argv++;
2235     /* skip command */
2236     argv++;
2237 
2238     while ((param = *argv++) != NULL) {
2239         val_p = *argv++;
2240         if (!val_p || *val_p == '-') {
2241             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
2242             ret = WIFI_ERROR_NOT_SUPPORTED;
2243             goto exit;
2244         }
2245         if (strcmp(param, "-iface") == 0) {
2246             ifHandle = wifi_get_iface_handle_by_iface_name(val_p);
2247         } else if (strcmp(param, "-config_id") == 0) {
2248             config_id = atoi(val_p);
2249         } else {
2250             printMsg("%s:Unsupported Parameter for twt info request\n", __FUNCTION__);
2251             ret = WIFI_ERROR_INVALID_ARGS;
2252             goto exit;
2253         }
2254     }
2255 
2256     if (ifHandle == NULL) {
2257         printMsg("-iface <> is mandatory\n");
2258         goto exit;
2259     }
2260 
2261     ret = twt_init_handlers();
2262     if (ret != WIFI_SUCCESS) {
2263         printMsg("Failed to initialize twt handlers %d\n", ret);
2264         goto exit;
2265     }
2266     ret = twt_clear_stats(ifHandle, config_id);
2267 
2268 exit:
2269     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
2270     return;
2271 }
2272 
getTWTCapability(char * argv[])2273 static void getTWTCapability(char *argv[]) {
2274     wifi_error ret = WIFI_SUCCESS;
2275     char *param, *val_p;
2276 
2277     /* skip utility */
2278     argv++;
2279     /* skip command */
2280     argv++;
2281 
2282     while ((param = *argv++) != NULL) {
2283         val_p = *argv++;
2284         if (!val_p || *val_p == '-') {
2285             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
2286             ret = WIFI_ERROR_NOT_SUPPORTED;
2287             goto exit;
2288         }
2289         if (strcmp(param, "-iface") == 0) {
2290             ifHandle = wifi_get_iface_handle_by_iface_name(val_p);
2291         } else {
2292             printMsg("%s:Unsupported Parameter for twt capability request\n", __FUNCTION__);
2293             ret = WIFI_ERROR_INVALID_ARGS;
2294             goto exit;
2295         }
2296     }
2297 
2298     if (ifHandle == NULL) {
2299         printMsg("-iface <> is mandatory\n");
2300         goto exit;
2301     }
2302 
2303     TwtCapabilitySet twt_capability;
2304 
2305     ret = twt_get_capability(ifHandle, &twt_capability);
2306     if (ret == WIFI_SUCCESS) {
2307         printMsg("Supported Capabilites of TWT :\n");
2308         if (twt_capability.device_capability.requester_supported)
2309             printMsg("Device Requester supported\n");
2310         if (twt_capability.device_capability.responder_supported)
2311             printMsg("Device Responder supported\n");
2312         if (twt_capability.device_capability.broadcast_twt_supported)
2313             printMsg("Device Broadcast twt supported\n");
2314         if (twt_capability.device_capability.flexibile_twt_supported)
2315             printMsg("Device Flexibile twt supported\n");
2316         if (twt_capability.peer_capability.requester_supported)
2317             printMsg("Peer Requester supported\n");
2318         if (twt_capability.peer_capability.responder_supported)
2319             printMsg("Peer Responder supported\n");
2320         if (twt_capability.peer_capability.broadcast_twt_supported)
2321             printMsg("Peer Broadcast twt supported\n");
2322         if (twt_capability.peer_capability.flexibile_twt_supported)
2323             printMsg("Peer Flexibile twt supported\n");
2324     } else {
2325         printMsg("Could not get the twt capabilities : %d\n", ret);
2326     }
2327 exit:
2328     return;
2329 }
2330 
showResponderCapability(wifi_rtt_responder responder_info)2331 static void showResponderCapability(wifi_rtt_responder responder_info)
2332 {
2333     wifi_channel_info channel_info;
2334     channel_info = responder_info.channel;
2335     printMsg("Centre freq = %d \n",channel_info.center_freq);
2336     if (channel_info.width == WIFI_CHAN_WIDTH_20) {
2337         printMsg("channel width = 20 \n");
2338     } else if (channel_info.width == WIFI_CHAN_WIDTH_40) {
2339         printMsg("channel width = 40 \n");
2340     } else if (channel_info.width == WIFI_CHAN_WIDTH_80) {
2341         printMsg("channel width = 80 \n");
2342     }
2343     if (channel_info.width == WIFI_CHAN_WIDTH_40 || channel_info.width == WIFI_CHAN_WIDTH_80) {
2344         printMsg("CentreFreq0 = %d \n",channel_info.center_freq0);
2345     }
2346     if (responder_info.preamble & WIFI_RTT_PREAMBLE_HT) {
2347         printMsg("Responder preamble = %d \n",responder_info.preamble);
2348     }
2349     if (responder_info.preamble & WIFI_RTT_PREAMBLE_VHT) {
2350         printMsg("Responder preamble = %d \n",responder_info.preamble);
2351     }
2352     if (responder_info.preamble & WIFI_RTT_PREAMBLE_LEGACY) {
2353         printMsg("Responder preamble = %d \n",responder_info.preamble);
2354     }
2355 }
2356 
getRttResponderInfo()2357 static int getRttResponderInfo()
2358 {
2359     int ret;
2360     wifi_rtt_responder responder_info;
2361     ret = hal_fn.wifi_rtt_get_responder_info(wlan0Handle, &responder_info);
2362     if (ret == WIFI_SUCCESS) {
2363         showResponderCapability(responder_info);
2364     }
2365     return ret;
2366 }
2367 
RttEnableResponder()2368 static int RttEnableResponder()
2369 {
2370     int ret = 0;
2371     wifi_request_id id = 0;
2372     wifi_channel_info channel_hint;
2373     memset(&channel_hint, 0, sizeof(wifi_channel_info));
2374     wifi_rtt_responder responder_info;
2375     unsigned int max_duration_sec = 0;
2376 
2377     ret = hal_fn.wifi_enable_responder(id, wlan0Handle, channel_hint,
2378         max_duration_sec, &responder_info);
2379     if (ret == WIFI_SUCCESS) {
2380         showResponderCapability(responder_info);
2381     }
2382     return ret;
2383 }
2384 
cancelRttResponder()2385 static int cancelRttResponder()
2386 {
2387     int ret = 0;
2388     wifi_request_id id = 0;
2389 
2390     ret = hal_fn.wifi_disable_responder(id, wlan0Handle);
2391     return ret;
2392 }
2393 
printCachedScanResults(wifi_cached_scan_report * cache_report)2394 static void printCachedScanResults(wifi_cached_scan_report *cache_report) {
2395     int scanned_channel[MAX_CH_BUF_SIZE] = {0};
2396     wifi_cached_scan_result cached_results[MAX_CACHED_SCAN_RESULT];
2397     memset(&cached_results, 0, sizeof(cached_results));
2398 
2399     if (cache_report->ts) {
2400         printMsg("Printing scan results were queried at (%lu) (in microseconds):\n",
2401             cache_report->ts);
2402     }
2403     printMsg("--------------------------------------\n");
2404     if (cache_report->scanned_freq_num > MAX_CH_BUF_SIZE ) {
2405         cache_report->scanned_freq_num = MAX_CH_BUF_SIZE;
2406     }
2407 
2408     if (cache_report->scanned_freq_num && cache_report->scanned_freq_list) {
2409         memcpy(scanned_channel, cache_report->scanned_freq_list,
2410             cache_report->scanned_freq_num * sizeof(u32));
2411     }
2412 
2413     if (cache_report->result_cnt > MAX_CACHED_SCAN_RESULT) {
2414          cache_report->result_cnt = MAX_CACHED_SCAN_RESULT;
2415     }
2416 
2417     if (cache_report->result_cnt && cache_report->results) {
2418         memcpy(cached_results, cache_report->results,
2419            cache_report->result_cnt * sizeof(wifi_cached_scan_result));
2420     }
2421 
2422     printMsg("(%d) channels were scanned:\n", cache_report->scanned_freq_num);
2423     for (int i = 0; i < cache_report->scanned_freq_num; i++) {
2424          printMsg("%d, ", scanned_channel[i]);
2425     }
2426     printMsg("\n");
2427     printMsg("(%d) results reported:\n", cache_report->result_cnt);
2428     for (int i = 0; i < cache_report->result_cnt; i++) {
2429         printMsg("ssid:%s,bssid: %02x:%02x:%02x:%02x:%02x:%02x,"
2430                 "rssi: %d, primary_freq: %d, bw: %d, capability: 0x%x,"
2431                 "flags: 0x%x, age_ms: %d\n",
2432                 cached_results[i].ssid,
2433                 cached_results[i].bssid[0], cached_results[i].bssid[1],
2434                 cached_results[i].bssid[2], cached_results[i].bssid[3],
2435                 cached_results[i].bssid[4], cached_results[i].bssid[5],
2436                 cached_results[i].rssi,
2437                 cached_results[i].chanspec.primary_frequency,
2438                 cached_results[i].chanspec.width,
2439                 cached_results[i].capability, cached_results[i].flags,
2440                 cached_results[i].age_ms);
2441     }
2442 }
2443 
on_cached_scan_results(wifi_cached_scan_report * cache_report)2444 static void on_cached_scan_results(wifi_cached_scan_report *cache_report) {
2445     if (!cache_report) {
2446         printf("Scan results not found! Issue scan first\n");
2447         return;
2448     }
2449 
2450     printf("onCachedScanResult scanned_freq_num = %d result_cnt %d \n",
2451             cache_report->scanned_freq_num, cache_report->result_cnt);
2452     printCachedScanResults(cache_report);
2453 }
2454 
getWifiCachedScanResults(void)2455 static void getWifiCachedScanResults(void) {
2456     wifi_cached_scan_result_handler handler;
2457     handler.on_cached_scan_results = on_cached_scan_results;
2458 
2459     wifi_error ret = hal_fn.wifi_get_cached_scan_results(wlan0Handle, handler);
2460     if (ret != WIFI_SUCCESS) {
2461         printMsg("Failed to get cached scan results: %d\n", ret);
2462     }
2463     return;
2464 }
2465 
2466 /* CHRA NAN RTT related */
OnChreNanRttStateChanged(chre_nan_rtt_state state)2467 static void OnChreNanRttStateChanged(chre_nan_rtt_state state) {
2468     printMsg("CHRE NAN RTT state update : %d\n", state);
2469     putEventInCache(EVENT_TYPE_CHRE_NAN_RTT_STATE_UPDATED, "CHRE NAN RTT state updated");
2470 }
2471 
enableChreNanRtt()2472 static void enableChreNanRtt() {
2473     wifi_error ret = WIFI_SUCCESS;
2474     ret = hal_fn.wifi_nan_rtt_chre_enable_request(0, wlan0Handle, NULL);
2475     if (ret != WIFI_SUCCESS) {
2476         printMsg("Failed to enable CHRE NAN RTT: %d\n", ret);
2477     }
2478 
2479     return;
2480 }
2481 
disableChreNanRtt()2482 static void disableChreNanRtt() {
2483     wifi_error ret = WIFI_SUCCESS;
2484     ret = hal_fn.wifi_nan_rtt_chre_disable_request(0, wlan0Handle);
2485     if (ret != WIFI_SUCCESS) {
2486         printMsg("Failed to disable CHRE NAN RTT: %d\n", ret);
2487     }
2488 
2489     return;
2490 }
2491 
registerChreCallback()2492 static void registerChreCallback() {
2493     wifi_error ret = WIFI_SUCCESS;
2494     EventInfo info;
2495     wifi_chre_handler handler;
2496     handler.on_chre_nan_rtt_change = OnChreNanRttStateChanged;
2497     ret = hal_fn.wifi_chre_register_handler(wlan0Handle, handler);
2498     if (ret != WIFI_SUCCESS) {
2499         printMsg("Failed to register CHRE callback: %d\n", ret);
2500     } else {
2501         while (true) {
2502             memset(&info, 0, sizeof(info));
2503             getEventFromCache(info);
2504             if (info.type == EVENT_TYPE_CHRE_NAN_RTT_STATE_UPDATED) {
2505                 printMsg("Received CHRE NAN RTT state, end the CHRE NAN RTT monitor!!\n");
2506                 break;
2507             }
2508         }
2509     }
2510     return;
2511 }
GetCachedGScanResults(int max,wifi_scan_result * results,int * num)2512 static int GetCachedGScanResults(int max, wifi_scan_result *results, int *num)
2513 {
2514     int num_results = 64;
2515     wifi_cached_scan_results *results2;
2516     results2 = (wifi_cached_scan_results *)malloc(num_results * sizeof(wifi_cached_scan_results));
2517     memset(results2, 0, sizeof(wifi_cached_scan_results) * num_results);
2518     int ret = hal_fn.wifi_get_cached_gscan_results(wlan0Handle, 1, num_results, results2,
2519         &num_results);
2520     if (ret < 0) {
2521         printMsg("failed to fetch scan results : %d\n", ret);
2522         goto exit;
2523     } else {
2524         printMsg("fetched %d scan data\n", num_results);
2525     }
2526 
2527     *num = 0;
2528     for (int i = 0; i < num_results; i++) {
2529         for (int j = 0; j < results2[i].num_results; j++, (*num)++) {
2530             memcpy(&(results[*num]), &(results2[i].results[j]), sizeof(wifi_scan_result));
2531         }
2532     }
2533 
2534 exit:
2535     if (results2) {
2536         free(results2);
2537     }
2538     return ret;
2539 }
2540 
2541 
setHotlistAPsUsingScanResult(wifi_bssid_hotlist_params * params)2542 static wifi_error setHotlistAPsUsingScanResult(wifi_bssid_hotlist_params *params)
2543 {
2544     printMsg("testHotlistAPs Scan started, waiting for event ...\n");
2545     EventInfo info;
2546     memset(&info, 0, sizeof(info));
2547     getEventFromCache(info);
2548 
2549     wifi_scan_result *results;
2550     results = (wifi_scan_result *)malloc(256 * sizeof(wifi_scan_result));
2551     memset(results, 0, sizeof(wifi_scan_result) * 256);
2552 
2553     printMsg("Retrieving scan results for Hotlist AP setting\n");
2554     int num_results = 256;
2555     int result = GetCachedGScanResults(num_results, results, &num_results);
2556     if (result < 0) {
2557         printMsg("failed to fetch scan results : %d\n", result);
2558         if (results) {
2559             free(results);
2560         }
2561         return WIFI_ERROR_UNKNOWN;
2562     } else {
2563         printMsg("fetched %d scan results\n", num_results);
2564     }
2565 
2566     for (int i = 0; i < num_results; i++) {
2567         printScanResult(results[i]);
2568     }
2569 
2570     for (int i = 0; i < stest_max_ap; i++) {
2571         memcpy(params->ap[i].bssid, results[i].bssid, sizeof(mac_addr));
2572         params->ap[i].low  = -htest_low_threshold;
2573         params->ap[i].high = -htest_high_threshold;
2574     }
2575     params->num_bssid = stest_max_ap;
2576 
2577     if (results) {
2578         free(results);
2579     }
2580 
2581     return WIFI_SUCCESS;
2582 }
2583 
setHotlistAPs()2584 static wifi_error setHotlistAPs() {
2585     wifi_bssid_hotlist_params params;
2586     memset(&params, 0, sizeof(params));
2587 
2588     params.lost_ap_sample_size = HOTLIST_LOST_WINDOW;
2589     if (num_hotlist_bssids > 0) {
2590         for (int i = 0; i < num_hotlist_bssids; i++) {
2591             memcpy(params.ap[i].bssid, hotlist_bssids[i], sizeof(mac_addr));
2592             params.ap[i].low  = -htest_low_threshold;
2593             params.ap[i].high = -htest_high_threshold;
2594         }
2595         params.num_bssid = num_hotlist_bssids;
2596     } else {
2597         setHotlistAPsUsingScanResult(&params);
2598     }
2599 
2600     printMsg("BSSID\t\t\tHIGH\tLOW\n");
2601     for (int i = 0; i < params.num_bssid; i++) {
2602         mac_addr &addr = params.ap[i].bssid;
2603         printMsg("%02x:%02x:%02x:%02x:%02x:%02x\t%d\t%d\n", addr[0],
2604                 addr[1], addr[2], addr[3], addr[4], addr[5],
2605                 params.ap[i].high, params.ap[i].low);
2606     }
2607 
2608     wifi_hotlist_ap_found_handler handler;
2609     handler.on_hotlist_ap_found = &onHotlistAPFound;
2610     handler.on_hotlist_ap_lost = &onHotlistAPLost;
2611     hotlistCmdId = getNewCmdId();
2612     printMsg("Setting hotlist APs threshold\n");
2613     return hal_fn.wifi_set_bssid_hotlist(hotlistCmdId, wlan0Handle, params, handler);
2614 }
2615 
resetHotlistAPs()2616 static void resetHotlistAPs() {
2617     printMsg(", stoping Hotlist AP scanning\n");
2618     hal_fn.wifi_reset_bssid_hotlist(hotlistCmdId, wlan0Handle);
2619 }
2620 
setPnoMacOui()2621 static void setPnoMacOui() {
2622     hal_fn.wifi_set_scanning_mac_oui(wlan0Handle, mac_oui);
2623 }
2624 
testHotlistAPs()2625 static void testHotlistAPs(){
2626 
2627     EventInfo info;
2628     memset(&info, 0, sizeof(info));
2629 
2630     printMsg("starting Hotlist AP scanning\n");
2631     bool startScanResult = startScan(stest_max_ap,
2632             stest_base_period, stest_threshold_percent, stest_threshold_num_scans);
2633     if (!startScanResult) {
2634         printMsg("testHotlistAPs failed to start scan!!\n");
2635         return;
2636     }
2637 
2638     int result = setHotlistAPs();
2639     if (result == WIFI_SUCCESS) {
2640         printMsg("Waiting for Hotlist AP event\n");
2641         while (true) {
2642             memset(&info, 0, sizeof(info));
2643             getEventFromCache(info);
2644 
2645             if (info.type == EVENT_TYPE_SCAN_COMPLETE) {
2646                 retrieveScanResults();
2647             } else if (info.type == EVENT_TYPE_HOTLIST_AP_FOUND ||
2648                     info.type == EVENT_TYPE_HOTLIST_AP_LOST) {
2649                 printMsg("Hotlist APs");
2650                 if (--max_event_wait > 0)
2651                     printMsg(", waiting for more event ::%d\n", max_event_wait);
2652                 else
2653                     break;
2654             }
2655         }
2656         resetHotlistAPs();
2657     } else {
2658         printMsg("Could not set AP hotlist : %d\n", result);
2659     }
2660 }
2661 
testPNO(bool clearOnly,bool scan)2662 static void testPNO(bool clearOnly, bool scan){
2663 
2664     EventInfo info;
2665     int result;
2666     wifi_epno_handler handler;
2667     handler.on_network_found = &onePnoSsidFound;
2668     memset(&info, 0, sizeof(info));
2669     if (clearOnly) {
2670         result = wifi_reset_epno_list(-1, wlan0Handle);
2671         if (result != WIFI_SUCCESS) {
2672             printMsg("Failed to reset ePNO!!\n");
2673         }
2674         return;
2675     }
2676     epnoCmdId = getNewCmdId();
2677     printMsg("configuring ePNO SSIDs num %u\n", epno_cfg.num_networks);
2678     result = hal_fn.wifi_set_epno_list(epnoCmdId, wlan0Handle, &epno_cfg, handler);
2679     if (result == WIFI_SUCCESS && scan) {
2680         bool startScanResult = startScan(stest_max_ap,
2681             stest_base_period, stest_threshold_percent, stest_threshold_num_scans);
2682         if (!startScanResult) {
2683             printMsg("testPNO failed to start scan!!\n");
2684             return;
2685         }
2686         printMsg("Waiting for ePNO events\n");
2687         while (true) {
2688             memset(&info, 0, sizeof(info));
2689             getEventFromCache(info);
2690 
2691             if (info.type == EVENT_TYPE_SCAN_COMPLETE) {
2692                 retrieveScanResults();
2693             } else if (info.type == EVENT_TYPE_EPNO_SSID) {
2694                 printMsg("FOUND ePNO event");
2695                 if (--max_event_wait > 0)
2696                   printMsg(", waiting for more event ::%d\n", max_event_wait);
2697                 else
2698                   break;
2699             }
2700         }
2701         //wifi_reset_epno_list(epnoCmdId, wlan0Handle);
2702     } else if (result != WIFI_SUCCESS) {
2703         printMsg("Could not set ePNO : %d\n", result);
2704     }
2705 }
2706 
onSignificantWifiChange(wifi_request_id id,unsigned num_results,wifi_significant_change_result ** results)2707 static void onSignificantWifiChange(wifi_request_id id,
2708         unsigned num_results, wifi_significant_change_result **results)
2709 {
2710     printMsg("Significant wifi change for %d\n", num_results);
2711     for (unsigned i = 0; i < num_results; i++) {
2712         printSignificantChangeResult(results[i]);
2713     }
2714     putEventInCache(EVENT_TYPE_SIGNIFICANT_WIFI_CHANGE, "significant wifi change noticed");
2715 }
2716 
SelectSignificantAPsFromScanResults()2717 static int SelectSignificantAPsFromScanResults() {
2718     wifi_scan_result *results;
2719     results = (wifi_scan_result *)malloc(256 * sizeof(wifi_scan_result));
2720     memset(results, 0, sizeof(wifi_scan_result) * 256);
2721     printMsg("Retrieving scan results for significant wifi change setting\n");
2722     int num_results = 256;
2723     int result = GetCachedGScanResults(num_results, results, &num_results);
2724     if (result < 0) {
2725         printMsg("failed to fetch scan results : %d\n", result);
2726         if (results) {
2727             free(results);
2728         }
2729         return WIFI_ERROR_UNKNOWN;
2730     } else {
2731         printMsg("fetched %d scan results\n", num_results);
2732     }
2733 
2734     for (int i = 0; i < num_results; i++) {
2735         printScanResult(results[i]);
2736     }
2737 
2738     wifi_significant_change_params params;
2739     memset(&params, 0, sizeof(params));
2740 
2741     params.rssi_sample_size = swctest_rssi_sample_size;
2742     params.lost_ap_sample_size = swctest_rssi_lost_ap;
2743     params.min_breaching = swctest_rssi_min_breaching;
2744 
2745     for (int i = 0; i < stest_max_ap; i++) {
2746         memcpy(params.ap[i].bssid, results[i].bssid, sizeof(mac_addr));
2747         params.ap[i].low  = results[i].rssi - swctest_rssi_ch_threshold;
2748         params.ap[i].high = results[i].rssi + swctest_rssi_ch_threshold;
2749     }
2750     params.num_bssid = stest_max_ap;
2751 
2752     printMsg("Settting Significant change params rssi_sample_size#%d lost_ap_sample_size#%d"
2753             " and min_breaching#%d\n", params.rssi_sample_size,
2754             params.lost_ap_sample_size , params.min_breaching);
2755     printMsg("BSSID\t\t\tHIGH\tLOW\n");
2756     for (int i = 0; i < params.num_bssid; i++) {
2757         mac_addr &addr = params.ap[i].bssid;
2758         printMsg("%02x:%02x:%02x:%02x:%02x:%02x\t%d\t%d\n", addr[0],
2759                 addr[1], addr[2], addr[3], addr[4], addr[5],
2760                 params.ap[i].high, params.ap[i].low);
2761     }
2762     wifi_significant_change_handler handler;
2763     memset(&handler, 0, sizeof(handler));
2764     handler.on_significant_change = &onSignificantWifiChange;
2765 
2766     int id = getNewCmdId();
2767     if (results) {
2768         free(results);
2769     }
2770     return hal_fn.wifi_set_significant_change_handler(id, wlan0Handle, params, handler);
2771 
2772 }
2773 
untrackSignificantChange()2774 static void untrackSignificantChange() {
2775     printMsg(", Stop tracking SignificantChange\n");
2776     hal_fn.wifi_reset_bssid_hotlist(hotlistCmdId, wlan0Handle);
2777 }
2778 
trackSignificantChange()2779 static void trackSignificantChange() {
2780     printMsg("starting trackSignificantChange\n");
2781 
2782     if (!startScan(stest_max_ap,
2783                 stest_base_period, stest_threshold_percent, stest_threshold_num_scans)) {
2784         printMsg("trackSignificantChange failed to start scan!!\n");
2785         return;
2786     } else {
2787         printMsg("trackSignificantChange Scan started, waiting for event ...\n");
2788     }
2789 
2790     EventInfo info;
2791     memset(&info, 0, sizeof(info));
2792     getEventFromCache(info);
2793 
2794     int result = SelectSignificantAPsFromScanResults();
2795     if (result == WIFI_SUCCESS) {
2796         printMsg("Waiting for significant wifi change event\n");
2797         while (true) {
2798             memset(&info, 0, sizeof(info));
2799             getEventFromCache(info);
2800 
2801             if (info.type == EVENT_TYPE_SCAN_COMPLETE) {
2802                 retrieveScanResults();
2803             } else if(info.type == EVENT_TYPE_SIGNIFICANT_WIFI_CHANGE) {
2804                 printMsg("Received significant wifi change");
2805                 if (--max_event_wait > 0)
2806                     printMsg(", waiting for more event ::%d\n", max_event_wait);
2807                 else
2808                     break;
2809             }
2810         }
2811         untrackSignificantChange();
2812     } else {
2813         printMsg("Failed to set significant change  ::%d\n", result);
2814     }
2815 }
2816 
2817 
testScan()2818 void testScan() {
2819     printf("starting scan with max_ap_per_scan#%d  base_period#%d  threshold#%d \n",
2820             stest_max_ap,stest_base_period, stest_threshold_percent);
2821     if (!startScan(stest_max_ap,
2822                 stest_base_period, stest_threshold_percent, stest_threshold_num_scans)) {
2823         printMsg("failed to start scan!!\n");
2824         return;
2825     } else {
2826         EventInfo info;
2827         memset(&info, 0, sizeof(info));
2828 
2829         while (true) {
2830             getEventFromCache(info);
2831             printMsg("retrieved event %d : %s\n", info.type, info.buf);
2832             if (info.type == EVENT_TYPE_SCAN_COMPLETE)
2833                 continue;
2834             retrieveScanResults();
2835             if(--max_event_wait > 0)
2836                 printMsg("Waiting for more :: %d event \n", max_event_wait);
2837             else
2838                 break;
2839         }
2840 
2841         stopScan();
2842         printMsg("stopped scan\n");
2843     }
2844 }
2845 
testStopScan()2846 void testStopScan() {
2847     stopScan();
2848     printMsg("stopped scan\n");
2849 }
2850 
2851 
2852 ///////////////////////////////////////////////////////////////////////////////
2853 // Logger feature set
2854 
onRingBufferData(char * ring_name,char * buffer,int buffer_size,wifi_ring_buffer_status * status)2855 static void onRingBufferData(char *ring_name, char *buffer, int buffer_size,
2856                                 wifi_ring_buffer_status *status)
2857 {
2858     // helper for LogHandler
2859 
2860     static int cnt = 1;
2861     FILE* w_fp;
2862     static int f_count = 0;
2863     char ring_file[FILE_NAME_LEN];
2864     char *pBuff;
2865 
2866     if (!buffer || buffer_size <= 0) {
2867         printMsg("No data in dump buffer\n");
2868         return;
2869     }
2870 
2871     printMsg("\n%d) RingId=%d, Name=%s, Flags=%u, DebugLevel=%u, "
2872             "wBytes=%u, rBytes=%u, RingSize=%u, wRecords=%u\n",
2873             cnt++, status->ring_id, status->name, status->flags,
2874             status->verbose_level, status->written_bytes,
2875             status->read_bytes, status->ring_buffer_byte_size,
2876             status->written_records);
2877 
2878     wifi_ring_buffer_entry *buffer_entry = (wifi_ring_buffer_entry *) buffer;
2879 
2880     printMsg("Format: (%d) ", buffer_entry->flags);
2881     if (buffer_entry->flags & RING_BUFFER_ENTRY_FLAGS_HAS_BINARY)
2882         printMsg("\"BINARY\" ");
2883     if (buffer_entry->flags & RING_BUFFER_ENTRY_FLAGS_HAS_TIMESTAMP)
2884         printMsg("\"TIMESTAMP\"");
2885 
2886     printMsg(", Type: %s (%d)", RBentryTypeToString(buffer_entry->type), buffer_entry->type);
2887     printMsg(", TS: %llu ms", buffer_entry->timestamp);
2888     printMsg(", Size: %d bytes\n", buffer_entry->entry_size);
2889 
2890     pBuff = (char *) (buffer_entry + 1);
2891     snprintf(ring_file, FILE_NAME_LEN, "%s%s-%d.bin", RINGDATA_PREFIX, ring_name, f_count);
2892     w_fp = fopen(ring_file, "a");
2893     if (w_fp == NULL) {
2894         printMsg("Failed to open a file: %s\n", ring_file);
2895         return;
2896     }
2897 
2898     fwrite(pBuff, 1, buffer_entry->entry_size, w_fp);
2899     if (ftell(w_fp) >= FILE_MAX_SIZE) {
2900         f_count++;
2901         if (f_count >= NUM_ALERT_DUMPS)
2902             f_count = 0;
2903     }
2904     fclose(w_fp);
2905     w_fp = NULL;
2906 
2907     printMsg("Data: ");
2908     if (buffer_entry->flags & RING_BUFFER_ENTRY_FLAGS_HAS_BINARY) {
2909         for (int i = 0; i < buffer_size; i++)
2910             printMsg("%02x ", buffer[i]);
2911         printMsg("\n");
2912     } else {
2913         printMsg("%s\n", pBuff);
2914     }
2915 
2916     /*
2917      * Parsing Wake Lock event
2918      */
2919     if (buffer_entry->type == ENTRY_TYPE_WAKE_LOCK) {
2920         const char *strStatus[] = {"Taken", "Released", "Timeout"};
2921         wake_lock_event *wlock_event = (wake_lock_event *) pBuff;
2922 
2923         printMsg("Wakelock Event: Status=%s (%02x), Name=%s, Reason=%s (%02x)\n",
2924             strStatus[wlock_event->status], wlock_event->status,
2925             wlock_event->name, "\"TO BE\"", wlock_event->reason);
2926         return;
2927     }
2928 
2929     /*
2930      * Parsing TLV data
2931      */
2932     if (buffer_entry->type == ENTRY_TYPE_CONNECT_EVENT) {
2933         wifi_ring_buffer_driver_connectivity_event *connect_event =
2934             (wifi_ring_buffer_driver_connectivity_event *) (pBuff);
2935 
2936         tlv_log *tlv_data = (tlv_log *) (connect_event + 1);
2937         printMsg("Event type: %s (%u)\n", RBconnectEventToString(connect_event->event),
2938                 connect_event->event);
2939 
2940         char *pos = (char *)tlv_data;
2941         char *end = (char *)connect_event + buffer_entry->entry_size;
2942         while (pos < end) {
2943             printMsg("TLV.type: %s (%d), TLV.len=%d (%02x)\n",
2944                     RBTlvTagToString(tlv_data->tag),
2945                     tlv_data->tag, tlv_data->length, tlv_data->length);
2946 
2947             switch (tlv_data->tag) {
2948                 case WIFI_TAG_VENDOR_SPECIFIC:
2949                     break;
2950 
2951                 case WIFI_TAG_BSSID:
2952                 case WIFI_TAG_ADDR:
2953                 case WIFI_TAG_ADDR1:
2954                 case WIFI_TAG_ADDR2:
2955                 case WIFI_TAG_ADDR3:
2956                 case WIFI_TAG_ADDR4:
2957                 {
2958                     if (tlv_data->length == sizeof(mac_addr)) {
2959                         mac_addr addr;
2960                         memcpy(&addr, tlv_data->value, sizeof(mac_addr));
2961                         printMsg("Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
2962                             addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
2963                     } else
2964                         printMsg("wrong lenght of address\n");
2965                     break;
2966                 }
2967 
2968                 case WIFI_TAG_SSID:
2969                 {
2970                     char ssid[MAX_SSID_LEN];
2971                     memset(ssid, 0, sizeof(ssid));
2972                     if (tlv_data->length > MAX_SSID_LEN)
2973                         tlv_data->length = MAX_SSID_LEN;
2974                     memcpy(ssid, tlv_data->value, tlv_data->length);
2975                     printMsg("SSID = %s\n", ssid);
2976                     break;
2977                 }
2978 
2979                 case WIFI_TAG_STATUS:
2980                 {
2981                     unsigned int tag_status = 0;
2982                     memcpy(&tag_status, tlv_data->value, tlv_data->length);
2983                     printMsg("tag_Status = %u\n", tag_status);
2984                     break;
2985                 }
2986 
2987                 case WIFI_TAG_CHANNEL_SPEC:
2988                 {
2989                     wifi_channel_info *ch_spec = (wifi_channel_info *) tlv_data->value;
2990                     printMsg("Channel Info: center_freq=%d, freq0=%d, freq1=%d, width=%s\n",
2991                         ch_spec->center_freq, ch_spec->center_freq0,
2992                         ch_spec->center_freq1, RBchanWidthToString(ch_spec->width));
2993                     break;
2994                 }
2995 
2996                 case WIFI_TAG_WAKE_LOCK_EVENT:
2997                 {
2998                     printMsg("Wake lock event = \"TO BE DONE LATER\"\n");
2999                     break;
3000                 }
3001 
3002                 case WIFI_TAG_TSF:
3003                 {
3004                     u64 tsf = 0;
3005                     memcpy(&tsf, tlv_data->value, tlv_data->length);
3006                     printMsg("TSF value = %llu\n", tsf);
3007                     break;
3008                 }
3009 
3010                 case WIFI_TAG_IE:
3011                 {
3012                     printMsg("Information Element = \"TO BE\"\n");
3013                     break;
3014                 }
3015 
3016                 case WIFI_TAG_INTERFACE:
3017                 {
3018                     const int len = 32;
3019                     char inf_name[len];
3020 
3021                     if (tlv_data->length > len)
3022                         tlv_data->length = len;
3023                     memset(inf_name, 0, 32);
3024                     memcpy(inf_name, tlv_data->value, tlv_data->length);
3025                     printMsg("Interface = %s\n", inf_name);
3026                     break;
3027                 }
3028 
3029                 case WIFI_TAG_REASON_CODE:
3030                 {
3031                     u16 reason = 0;
3032                     memcpy(&reason, tlv_data->value, 2);
3033                     printMsg("Reason code = %d\n", reason);
3034                     break;
3035                 }
3036 
3037                 case WIFI_TAG_RATE_MBPS:
3038                 {
3039                     u32 rate = 0;
3040                     memcpy(&rate, tlv_data->value, tlv_data->length);
3041                     printMsg("Rate = %.1f Mbps\n", rate * 0.5);    // rate unit is 500 Kbps.
3042                     break;
3043                 }
3044 
3045                 case WIFI_TAG_CHANNEL:
3046                 {
3047                     u16 channel = 0;
3048                     memcpy(&channel, tlv_data->value, tlv_data->length);
3049                     printMsg("Channel = %d\n", channel);
3050                     break;
3051                 }
3052 
3053                 case WIFI_TAG_RSSI:
3054                 {
3055                     short rssi = 0;
3056                     memcpy(&rssi, tlv_data->value, tlv_data->length);
3057                     printMsg("RSSI = %d\n", rssi);
3058                     break;
3059                 }
3060             }
3061             pos = (char *)(tlv_data + 1);
3062             pos += tlv_data->length;
3063             tlv_data = (tlv_log *) pos;
3064         }
3065     }
3066 }
3067 
onAlert(wifi_request_id id,char * buffer,int buffer_size,int err_code)3068 static void onAlert(wifi_request_id id, char *buffer, int buffer_size, int err_code)
3069 {
3070 
3071     // helper for AlertHandler
3072 
3073     printMsg("Getting FW Memory dump: (%d bytes), err code: %d\n", buffer_size, err_code);
3074 
3075     FILE* w_fp = NULL;
3076     static int f_count = 0;
3077     char dump_file[FILE_NAME_LEN];
3078 
3079     if (!buffer || buffer_size <= 0) {
3080         printMsg("No data in alert buffer\n");
3081         return;
3082     }
3083 
3084     snprintf(dump_file, FILE_NAME_LEN, "%s-%d.bin", ALERT_MEMDUMP_PREFIX, f_count++);
3085     if (f_count >= NUM_ALERT_DUMPS)
3086         f_count = 0;
3087 
3088     w_fp = fopen(dump_file, "w");
3089     if (w_fp == NULL) {
3090         printMsg("Failed to create a file: %s\n", dump_file);
3091         return;
3092     }
3093 
3094     printMsg("Write to \"%s\"\n", dump_file);
3095     fwrite(buffer, 1, buffer_size, w_fp);
3096     fclose(w_fp);
3097     w_fp = NULL;
3098 
3099 }
3100 
onFirmwareMemoryDump(char * buffer,int buffer_size)3101 static void onFirmwareMemoryDump(char *buffer, int buffer_size)
3102 {
3103     // helper for LoggerGetMemdump()
3104 
3105     printMsg("Getting FW Memory dump: (%d bytes)\n", buffer_size);
3106 
3107     // Write a raw dump data into default local file or specified name
3108     FILE* w_fp = NULL;
3109 
3110     if (!buffer || buffer_size <= 0) {
3111         printMsg("No data in dump buffer\n");
3112         return;
3113     }
3114 
3115     w_fp = fopen(mem_dump_file, "w");
3116     if (w_fp == NULL) {
3117         printMsg("Failed to create a file: %s\n", mem_dump_file);
3118         return;
3119     }
3120 
3121     printMsg("Write to \"%s\"\n", mem_dump_file);
3122     fwrite(buffer, 1, buffer_size, w_fp);
3123     fclose(w_fp);
3124     w_fp = NULL;
3125 
3126     putEventInCache(EVENT_TYPE_LOGGER_MEMDUMP_DATA, "Memdump data");
3127 }
3128 
LoggerStart()3129 static wifi_error LoggerStart()
3130 {
3131     int ret;
3132 
3133     ret = hal_fn.wifi_start_logging(wlan0Handle,
3134         default_logger_param.verbose_level, default_logger_param.flags,
3135         default_logger_param.max_interval_sec, default_logger_param.min_data_size,
3136         default_logger_param.ring_name);
3137 
3138     if (ret != WIFI_SUCCESS) {
3139         printMsg("Failed to start Logger: %d\n", ret);
3140         return WIFI_ERROR_UNKNOWN;
3141     }
3142 
3143     /*
3144      * debug mode (0) which means no more debug events will be triggered.
3145      *
3146      * Hopefully, need to extend this functionality by additional interfaces such as
3147      * set verbose level to each ring buffer.
3148      */
3149     return WIFI_SUCCESS;
3150 }
3151 
LoggerGetMemdump()3152 static wifi_error LoggerGetMemdump()
3153 {
3154     wifi_firmware_memory_dump_handler handler;
3155     handler.on_firmware_memory_dump = &onFirmwareMemoryDump;
3156 
3157     printMsg("Create Memdump event\n");
3158     int result = hal_fn.wifi_get_firmware_memory_dump(wlan0Handle, handler);
3159 
3160     if (result == WIFI_SUCCESS) {
3161         EventInfo info;
3162         while (true) {
3163             memset(&info, 0, sizeof(info));
3164             getEventFromCache(info);
3165             if (info.type == EVENT_TYPE_LOGGER_MEMDUMP_DATA)
3166                 break;
3167             else
3168                 printMsg("Could not get memdump data: %d\n", result);
3169         }
3170     }
3171     return WIFI_SUCCESS;
3172 }
3173 
LoggerGetRingData()3174 static wifi_error LoggerGetRingData()
3175 {
3176     int result = hal_fn.wifi_get_ring_data(wlan0Handle, default_ring_name);
3177 
3178     if (result == WIFI_SUCCESS)
3179         printMsg("Get Ring data command success\n");
3180     else
3181         printMsg("Failed to execute get ring data command\n");
3182 
3183     return WIFI_SUCCESS;
3184 }
3185 
LoggerGetFW()3186 static wifi_error LoggerGetFW()
3187 {
3188     int ret;
3189     const int BSIZE = 256;
3190     int buffer_size = BSIZE;
3191 
3192     char buffer[BSIZE];
3193     memset(buffer, 0, BSIZE);
3194 
3195     if (ifHandle == NULL) {
3196         printMsg("-iface <> is mandatory\n");
3197         return WIFI_ERROR_INVALID_ARGS;
3198     }
3199 
3200     ret = hal_fn.wifi_get_firmware_version(ifHandle, buffer, buffer_size);
3201 
3202     if (ret == WIFI_SUCCESS)
3203         printMsg("FW version (len=%lu):\n%s\n", strlen(buffer), buffer);
3204     else
3205         printMsg("Failed to get FW version\n");
3206 
3207     return WIFI_SUCCESS;
3208 }
3209 
LoggerGetDriver()3210 static wifi_error LoggerGetDriver()
3211 {
3212     int ret;
3213     const int BSIZE = 256;
3214     int buffer_size = BSIZE;
3215 
3216     char buffer[BSIZE];
3217     memset(buffer, 0, BSIZE);
3218 
3219     if (ifHandle == NULL) {
3220         printMsg("-iface <> is mandatory\n");
3221         return WIFI_ERROR_INVALID_ARGS;
3222     }
3223 
3224     ret = hal_fn.wifi_get_driver_version(ifHandle, buffer, buffer_size);
3225 
3226     if (ret == WIFI_SUCCESS)
3227         printMsg("Driver version (len=%lu):\n%s\n", strlen(buffer), buffer);
3228     else
3229         printMsg("Failed to get driver version\n");
3230 
3231     return WIFI_SUCCESS;
3232 }
3233 
LoggerGetRingbufferStatus()3234 static wifi_error LoggerGetRingbufferStatus()
3235 {
3236     int ret;
3237     const int NRING = 10;
3238     u32 num_rings = NRING;
3239 
3240     wifi_ring_buffer_status *status =
3241         (wifi_ring_buffer_status *)malloc(sizeof(wifi_ring_buffer_status) * num_rings);
3242 
3243     if (status == NULL)
3244         return WIFI_ERROR_OUT_OF_MEMORY;
3245     memset(status, 0, sizeof(wifi_ring_buffer_status) * num_rings);
3246 
3247     ret = hal_fn.wifi_get_ring_buffers_status(wlan0Handle, &num_rings, status);
3248 
3249     if (ret == WIFI_SUCCESS) {
3250         printMsg("RingBuffer status: [%d ring(s)]\n", num_rings);
3251 
3252         for (unsigned int i = 0; i < num_rings; i++) {
3253             printMsg("[%d] RingId=%d, Name=%s, Flags=%u, DebugLevel=%u, "
3254                     "wBytes=%u, rBytes=%u, RingSize=%u, wRecords=%u, status_addr=%p\n",
3255                     i+1,
3256                     status->ring_id,
3257                     status->name,
3258                     status->flags,
3259                     status->verbose_level,
3260                     status->written_bytes,
3261                     status->read_bytes,
3262                     status->ring_buffer_byte_size,
3263                     status->written_records, status);
3264             status++;
3265         }
3266     } else {
3267         printMsg("Failed to get Ringbuffer status\n");
3268     }
3269 
3270     free(status);
3271     status = NULL;
3272 
3273     return WIFI_SUCCESS;
3274 }
3275 
LoggerGetFeature()3276 static wifi_error LoggerGetFeature()
3277 {
3278     int ret;
3279     unsigned int support = 0;
3280 
3281     const char *mapFeatures[] = {
3282         "MEMORY_DUMP",
3283         "PER_PACKET_TX_RX_STATUS",
3284         "CONNECT_EVENT",
3285         "POWER_EVENT",
3286         "WAKE_LOCK",
3287         "VERBOSE",
3288         "WATCHDOG_TIMER",
3289         "DRIVER_DUMP",
3290         "PACKET_FATE"
3291     };
3292 
3293     ret = hal_fn.wifi_get_logger_supported_feature_set(wlan0Handle, &support);
3294 
3295     if (ret == WIFI_SUCCESS) {
3296         printMsg("Logger supported features: %02x  [", support);
3297 
3298         if (support & WIFI_LOGGER_MEMORY_DUMP_SUPPORTED)
3299             printMsg(" \"%s\" ", mapFeatures[0]);
3300         if (support & WIFI_LOGGER_PER_PACKET_TX_RX_STATUS_SUPPORTED)
3301             printMsg(" \"%s\" ", mapFeatures[1]);
3302         if (support & WIFI_LOGGER_CONNECT_EVENT_SUPPORTED)
3303             printMsg(" \"%s\" ", mapFeatures[2]);
3304         if (support & WIFI_LOGGER_POWER_EVENT_SUPPORTED)
3305             printMsg(" \"%s\" ", mapFeatures[3]);
3306         if (support & WIFI_LOGGER_WAKE_LOCK_SUPPORTED)
3307             printMsg(" \"%s\" ", mapFeatures[4]);
3308         if (support & WIFI_LOGGER_VERBOSE_SUPPORTED)
3309             printMsg(" \"%s\" ", mapFeatures[5]);
3310         if (support & WIFI_LOGGER_WATCHDOG_TIMER_SUPPORTED)
3311             printMsg(" \"%s\" ", mapFeatures[6]);
3312         if (support & WIFI_LOGGER_DRIVER_DUMP_SUPPORTED)
3313             printMsg(" \"%s\" ", mapFeatures[7]);
3314         if (support & WIFI_LOGGER_PACKET_FATE_SUPPORTED)
3315             printMsg(" \"%s\" ", mapFeatures[8]);
3316         printMsg("]\n");
3317     } else {
3318         printMsg("Failed to get Logger supported features\n");
3319     }
3320 
3321     return WIFI_SUCCESS;
3322 }
3323 
LoggerSetLogHandler()3324 static wifi_error LoggerSetLogHandler()
3325 {
3326     wifi_ring_buffer_data_handler handler;
3327     handler.on_ring_buffer_data = &onRingBufferData;
3328 
3329     printMsg("Setting log handler\n");
3330     int result = hal_fn.wifi_set_log_handler(loggerCmdId, wlan0Handle, handler);
3331 
3332     if (result == WIFI_SUCCESS) {
3333         EventInfo info;
3334         while (true) {
3335             memset(&info, 0, sizeof(info));
3336             getEventFromCache(info);
3337             if (info.type == EVENT_TYPE_LOGGER_RINGBUFFER_DATA)
3338                 break;
3339         }
3340     } else {
3341         printMsg("Failed set Log handler: %d\n", result);
3342     }
3343     return WIFI_SUCCESS;
3344 }
3345 
LoggerSetAlertHandler()3346 static wifi_error LoggerSetAlertHandler()
3347 {
3348     loggerCmdId = getNewCmdId();
3349     wifi_alert_handler handler;
3350     handler.on_alert = &onAlert;
3351 
3352     printMsg("Create alert handler\n");
3353     int result = hal_fn.wifi_set_alert_handler(loggerCmdId, wlan0Handle, handler);
3354 
3355     if (result == WIFI_SUCCESS) {
3356         EventInfo info;
3357         while (true) {
3358             memset(&info, 0, sizeof(info));
3359             getEventFromCache(info);
3360             if (info.type == EVENT_TYPE_LOGGER_ALERT_DATA)
3361                 break;
3362         }
3363     } else {
3364         printMsg("Failed set Alert handler: %d\n", result);
3365     }
3366     return WIFI_SUCCESS;
3367 }
3368 
LoggerMonitorPktFate()3369 static wifi_error LoggerMonitorPktFate()
3370 {
3371     printMsg("Start packet fate monitor \n");
3372     wifi_error result = hal_fn.wifi_start_pkt_fate_monitoring(wlan0Handle);
3373 
3374     if (result == WIFI_SUCCESS) {
3375         printMsg("Start packet fate monitor command successful\n");
3376     } else {
3377         printMsg("Start packet fate monitor command failed, err = %d\n", result);
3378     }
3379     return result;
3380 }
3381 
LoggerGetTxPktFate()3382 static wifi_error LoggerGetTxPktFate()
3383 {
3384     wifi_tx_report *tx_report, *report_ptr;
3385     size_t frame_len, n_provided_fates = 0;
3386     wifi_error result = WIFI_SUCCESS;
3387     FILE *w_fp = NULL;
3388 
3389     printMsg("Logger get tx pkt fate command\n");
3390     if (!n_requested_pkt_fate || n_requested_pkt_fate > MAX_FATE_LOG_LEN) {
3391         n_requested_pkt_fate = MAX_FATE_LOG_LEN;
3392     }
3393 
3394     tx_report = (wifi_tx_report *)malloc(n_requested_pkt_fate * sizeof(*tx_report));
3395     if (!tx_report) {
3396         printMsg("%s: Memory allocation failed\n",__FUNCTION__);
3397         return WIFI_ERROR_OUT_OF_MEMORY;
3398     }
3399     memset(tx_report, 0, n_requested_pkt_fate * sizeof(*tx_report));
3400 
3401     if (ifHandle == NULL) {
3402         printMsg("-iface <> is mandatory\n");
3403         result = WIFI_ERROR_INVALID_ARGS;
3404         goto exit;
3405     }
3406 
3407     result = hal_fn.wifi_get_tx_pkt_fates(ifHandle, tx_report,
3408             n_requested_pkt_fate, &n_provided_fates);
3409     if (result != WIFI_SUCCESS) {
3410         printMsg("Logger get tx pkt fate command failed, err = %d\n", result);
3411         goto exit;
3412     }
3413 
3414     if (!n_provided_fates) {
3415         printMsg("Got empty pkt fates\n");
3416         result = WIFI_ERROR_NOT_AVAILABLE;
3417         goto exit;
3418     }
3419 
3420     printMsg("No: of tx pkt fates provided = %zu\n", n_provided_fates);
3421 
3422     w_fp = fopen(tx_pkt_fate_file, "w");
3423     if (!w_fp) {
3424         printMsg("Failed to create file: %s\n", tx_pkt_fate_file);
3425         result = WIFI_ERROR_NOT_AVAILABLE;
3426         goto exit;
3427     }
3428 
3429     fprintf(w_fp, "--- BEGIN ---\n\n");
3430     fprintf(w_fp, "No: of pkt fates provided = %zd\n\n", n_provided_fates);
3431     report_ptr = tx_report;
3432     for (size_t i = 0; i < n_provided_fates; i++) {
3433         fprintf(w_fp, "--- REPORT : %zu ---\n\n", (i + 1));
3434         if (report_ptr->frame_inf.frame_len == 0 ||
3435                 report_ptr->frame_inf.payload_type == FRAME_TYPE_UNKNOWN) {
3436             fprintf(w_fp, "Invalid frame...!!!\n\n");
3437         }
3438         fprintf(w_fp, "MD5 Prefix                 :  ");
3439         fprhex(w_fp, report_ptr->md5_prefix, MD5_PREFIX_LEN, false);
3440         fprintf(w_fp, "Packet Fate                :  %d\n", report_ptr->fate);
3441         fprintf(w_fp, "Frame Type                 :  %d\n", report_ptr->frame_inf.payload_type);
3442         fprintf(w_fp, "Frame Len                  :  %zu\n", report_ptr->frame_inf.frame_len);
3443         fprintf(w_fp, "Driver Timestamp           :  %u\n",
3444             report_ptr->frame_inf.driver_timestamp_usec);
3445         fprintf(w_fp, "Firmware Timestamp         :  %u\n",
3446             report_ptr->frame_inf.firmware_timestamp_usec);
3447         if (report_ptr->frame_inf.payload_type == FRAME_TYPE_ETHERNET_II) {
3448             frame_len = min(report_ptr->frame_inf.frame_len, (size_t)MAX_FRAME_LEN_ETHERNET);
3449             fprintf(w_fp, "Frame Content (%04zu bytes) :  \n", frame_len);
3450             fprhex(w_fp, report_ptr->frame_inf.frame_content.ethernet_ii_bytes, frame_len, true);
3451         } else {
3452             frame_len = min(report_ptr->frame_inf.frame_len, (size_t)MAX_FRAME_LEN_80211_MGMT);
3453             fprintf(w_fp, "Frame Content (%04zu bytes) :  \n", frame_len);
3454             fprhex(w_fp, report_ptr->frame_inf.frame_content.ieee_80211_mgmt_bytes,
3455                 frame_len, true);
3456         }
3457         fprintf(w_fp, "\n--- END OF REPORT ---\n\n");
3458 
3459         report_ptr++;
3460     }
3461     fprintf(w_fp, "--- EOF ---\n");
3462 
3463 exit:
3464     if (w_fp) {
3465         fclose(w_fp);
3466     }
3467     if (tx_report) {
3468         free(tx_report);
3469     }
3470 
3471     return result;
3472 }
3473 
LoggerGetRxPktFate()3474 static wifi_error LoggerGetRxPktFate()
3475 {
3476     wifi_rx_report *rx_report, *report_ptr;
3477     size_t frame_len, n_provided_fates = 0;
3478     wifi_error result = WIFI_SUCCESS;
3479     FILE *w_fp = NULL;
3480 
3481     printMsg("Logger get rx pkt fate command\n");
3482     if (!n_requested_pkt_fate || n_requested_pkt_fate > MAX_FATE_LOG_LEN) {
3483         n_requested_pkt_fate = MAX_FATE_LOG_LEN;
3484     }
3485 
3486     rx_report = (wifi_rx_report *)malloc(n_requested_pkt_fate * sizeof(*rx_report));
3487     if (!rx_report) {
3488         printMsg("%s: Memory allocation failed\n",__FUNCTION__);
3489         return WIFI_ERROR_OUT_OF_MEMORY;
3490     }
3491     memset(rx_report, 0, n_requested_pkt_fate * sizeof(*rx_report));
3492 
3493     if (ifHandle == NULL) {
3494         printMsg("-iface <> is mandatory\n");
3495         result = WIFI_ERROR_INVALID_ARGS;
3496         goto exit;
3497     }
3498 
3499     result = hal_fn.wifi_get_rx_pkt_fates(ifHandle, rx_report,
3500             n_requested_pkt_fate, &n_provided_fates);
3501     if (result != WIFI_SUCCESS) {
3502         printMsg("Logger get rx pkt fate command failed, err = %d\n", result);
3503         goto exit;
3504     }
3505 
3506     if (!n_provided_fates) {
3507         printMsg("Got empty pkt fates\n");
3508         result = WIFI_ERROR_NOT_AVAILABLE;
3509         goto exit;
3510     }
3511 
3512     printMsg("No: of rx pkt fates provided = %zu\n", n_provided_fates);
3513 
3514     w_fp = fopen(rx_pkt_fate_file, "w");
3515     if (!w_fp) {
3516         printMsg("Failed to create file: %s\n", rx_pkt_fate_file);
3517         result = WIFI_ERROR_NOT_AVAILABLE;
3518         goto exit;
3519     }
3520 
3521     fprintf(w_fp, "--- BEGIN ---\n\n");
3522     fprintf(w_fp, "No: of pkt fates provided = %zd\n\n", n_provided_fates);
3523     report_ptr = rx_report;
3524     for (size_t i = 0; i < n_provided_fates; i++) {
3525         fprintf(w_fp, "--- REPORT : %zu ---\n\n", (i + 1));
3526         if (report_ptr->frame_inf.frame_len == 0 ||
3527                 report_ptr->frame_inf.payload_type == FRAME_TYPE_UNKNOWN) {
3528             fprintf(w_fp, "Invalid frame...!!!\n\n");
3529         }
3530         fprintf(w_fp, "MD5 Prefix                 :  ");
3531         fprhex(w_fp, report_ptr->md5_prefix, MD5_PREFIX_LEN, false);
3532         fprintf(w_fp, "Packet Fate                :  %d\n", report_ptr->fate);
3533         fprintf(w_fp, "Frame Type                 :  %d\n", report_ptr->frame_inf.payload_type);
3534         fprintf(w_fp, "Frame Len                  :  %zu\n", report_ptr->frame_inf.frame_len);
3535         fprintf(w_fp, "Driver Timestamp           :  %u\n", report_ptr->frame_inf.driver_timestamp_usec);
3536         fprintf(w_fp, "Firmware Timestamp         :  %u\n", report_ptr->frame_inf.firmware_timestamp_usec);
3537         if (report_ptr->frame_inf.payload_type == FRAME_TYPE_ETHERNET_II) {
3538             frame_len = min(report_ptr->frame_inf.frame_len, (size_t)MAX_FRAME_LEN_ETHERNET);
3539             fprintf(w_fp, "Frame Content (%04zu bytes) :  \n", frame_len);
3540             fprhex(w_fp, report_ptr->frame_inf.frame_content.ethernet_ii_bytes, frame_len,
3541                 true);
3542         } else {
3543             frame_len = min(report_ptr->frame_inf.frame_len, (size_t)MAX_FRAME_LEN_80211_MGMT);
3544             fprintf(w_fp, "Frame Content (%04zu bytes) :  \n", frame_len);
3545             fprhex(w_fp, report_ptr->frame_inf.frame_content.ieee_80211_mgmt_bytes, frame_len,
3546                 true);
3547         }
3548         fprintf(w_fp, "\n--- END OF REPORT ---\n\n");
3549 
3550         report_ptr++;
3551     }
3552     fprintf(w_fp, "--- EOF ---\n");
3553 
3554 exit:
3555     if (w_fp) {
3556         fclose(w_fp);
3557     }
3558     if (rx_report) {
3559         free(rx_report);
3560     }
3561 
3562     return result;
3563 }
3564 
runLogger()3565 static void runLogger()
3566 {
3567     switch (log_cmd) {
3568         case LOG_GET_FW_VER:
3569             LoggerGetFW();
3570             break;
3571         case LOG_GET_DRV_VER:
3572             LoggerGetDriver();
3573             break;
3574         case LOG_GET_RING_STATUS:
3575             LoggerGetRingbufferStatus();
3576             break;
3577         case LOG_GET_FEATURE:
3578             LoggerGetFeature();
3579             break;
3580         case LOG_GET_MEMDUMP:
3581             LoggerGetMemdump();
3582             break;
3583         case LOG_GET_RING_DATA:
3584             LoggerGetRingData();
3585             break;
3586         case LOG_START:
3587             LoggerStart();
3588             break;
3589         case LOG_SET_LOG_HANDLER:
3590             LoggerSetLogHandler();
3591             break;
3592         case LOG_SET_ALERT_HANDLER:
3593             LoggerSetAlertHandler();
3594             break;
3595         case LOG_MONITOR_PKTFATE:
3596             LoggerMonitorPktFate();
3597             break;
3598         case LOG_GET_TXPKTFATE:
3599             LoggerGetTxPktFate();
3600             break;
3601         case LOG_GET_RXPKTFATE:
3602             LoggerGetRxPktFate();
3603             break;
3604         default:
3605             break;
3606     }
3607 }
3608 
start_mkeep_alive(int index,u32 period_msec,u16 ether_type,u8 * src_mac,u8 * dst_mac,u8 * ip_pkt,u16 ip_pkt_len)3609 static wifi_error start_mkeep_alive(int index, u32 period_msec, u16 ether_type,
3610                                         u8* src_mac, u8* dst_mac, u8* ip_pkt,
3611                                         u16 ip_pkt_len)
3612 {
3613     int ret;
3614 
3615     ret = hal_fn.wifi_start_sending_offloaded_packet(index, wlan0Handle, ether_type, ip_pkt,
3616           ip_pkt_len, src_mac, dst_mac, period_msec);
3617 
3618     if (ret == WIFI_SUCCESS) {
3619         printMsg("Start mkeep_alive with ID %d, %u period(msec), src(" MACSTR "), "
3620             "dst(" MACSTR ")\n", index, period_msec, MAC2STR(src_mac), MAC2STR(dst_mac));
3621     } else {
3622         printMsg("Failed to start mkeep_alive by ID %d: %d\n", index, ret);
3623         return WIFI_ERROR_NOT_AVAILABLE;
3624     }
3625     return WIFI_SUCCESS;
3626 }
3627 
stop_mkeep_alive(int index)3628 static wifi_error stop_mkeep_alive(int index)
3629 {
3630     int ret;
3631 
3632     ret = hal_fn.wifi_stop_sending_offloaded_packet(index, wlan0Handle);
3633 
3634     if (ret == WIFI_SUCCESS) {
3635         printMsg("Stop mkeep_alive with ID %d\n", index);
3636     } else {
3637         printMsg("Failed to stop mkeep_alive by ID %d: %d\n", index, ret);
3638         return WIFI_ERROR_NOT_AVAILABLE;
3639     }
3640     return WIFI_SUCCESS;
3641 }
3642 
parseHexChar(char ch)3643 byte parseHexChar(char ch) {
3644     if (isdigit(ch))
3645         return ch - '0';
3646     else if ('A' <= ch && ch <= 'F')
3647         return ch - 'A' + 10;
3648     else if ('a' <= ch && ch <= 'f')
3649         return ch - 'a' + 10;
3650     else {
3651         printMsg("invalid character in bssid %c\n", ch);
3652         return 0;
3653     }
3654 }
3655 
parseHexByte(char ch1,char ch2)3656 byte parseHexByte(char ch1, char ch2) {
3657     return (parseHexChar(ch1) << 4) | parseHexChar(ch2);
3658 }
3659 
parseMacAddress(const char * str,mac_addr addr)3660 void parseMacAddress(const char *str, mac_addr addr) {
3661     addr[0] = parseHexByte(str[0], str[1]);
3662     addr[1] = parseHexByte(str[3], str[4]);
3663     addr[2] = parseHexByte(str[6], str[7]);
3664     addr[3] = parseHexByte(str[9], str[10]);
3665     addr[4] = parseHexByte(str[12], str[13]);
3666     addr[5] = parseHexByte(str[15], str[16]);
3667 }
3668 
parseMacOUI(char * str,unsigned char * addr)3669 void parseMacOUI(char *str, unsigned char *addr) {
3670     addr[0] = parseHexByte(str[0], str[1]);
3671     addr[1] = parseHexByte(str[3], str[4]);
3672     addr[2] = parseHexByte(str[6], str[7]);
3673     printMsg("read mac OUI: %02x:%02x:%02x\n", addr[0],
3674             addr[1], addr[2]);
3675 }
3676 
3677 int
ether_atoe(const char * a,u8 * addr)3678 ether_atoe(const char *a, u8 *addr)
3679 {
3680     char *c = NULL;
3681     int i = 0;
3682     memset(addr, 0, ETHER_ADDR_LEN);
3683     for (; i < ETHER_ADDR_LEN; i++) {
3684         addr[i] = (u8)strtoul(a, &c, 16);
3685         if (*c != ':' && *c != '\0') {
3686             return 0;
3687         }
3688         a = ++c;
3689     }
3690     return (i == ETHER_ADDR_LEN);
3691 }
3692 
readTestOptions(int argc,char * argv[])3693 void readTestOptions(int argc, char *argv[]) {
3694 
3695     printf("Total number of argc #%d\n", argc);
3696     wifi_epno_network *epno_ssid = epno_cfg.networks;
3697     for (int j = 1; j < argc-1; j++) {
3698         if (strcmp(argv[j], "-max_ap") == 0 && isdigit(argv[j+1][0])) {
3699             stest_max_ap = atoi(argv[++j]);
3700             printf(" max_ap #%d\n", stest_max_ap);
3701         } else if (strcmp(argv[j], "-base_period") == 0 && isdigit(argv[j+1][0])) {
3702             stest_base_period = atoi(argv[++j]);
3703             printf(" base_period #%d\n", stest_base_period);
3704         } else if (strcmp(argv[j], "-threshold") == 0 && isdigit(argv[j+1][0])) {
3705             stest_threshold_percent = atoi(argv[++j]);
3706             printf(" threshold #%d\n", stest_threshold_percent);
3707         } else if (strcmp(argv[j], "-avg_RSSI") == 0 && isdigit(argv[j+1][0])) {
3708             swctest_rssi_sample_size = atoi(argv[++j]);
3709             printf(" avg_RSSI #%d\n", swctest_rssi_sample_size);
3710         } else if (strcmp(argv[j], "-ap_loss") == 0 && isdigit(argv[j+1][0])) {
3711             swctest_rssi_lost_ap = atoi(argv[++j]);
3712             printf(" ap_loss #%d\n", swctest_rssi_lost_ap);
3713         } else if (strcmp(argv[j], "-ap_breach") == 0 && isdigit(argv[j+1][0])) {
3714             swctest_rssi_min_breaching = atoi(argv[++j]);
3715             printf(" ap_breach #%d\n", swctest_rssi_min_breaching);
3716         } else if (strcmp(argv[j], "-ch_threshold") == 0 && isdigit(argv[j+1][0])) {
3717             swctest_rssi_ch_threshold = atoi(argv[++j]);
3718             printf(" ch_threshold #%d\n", swctest_rssi_ch_threshold);
3719         } else if (strcmp(argv[j], "-wt_event") == 0 && isdigit(argv[j+1][0])) {
3720             max_event_wait = atoi(argv[++j]);
3721             printf(" wt_event #%d\n", max_event_wait);
3722         } else if (strcmp(argv[j], "-low_th") == 0 && isdigit(argv[j+1][0])) {
3723             htest_low_threshold = atoi(argv[++j]);
3724             printf(" low_threshold #-%d\n", htest_low_threshold);
3725         } else if (strcmp(argv[j], "-high_th") == 0 && isdigit(argv[j+1][0])) {
3726             htest_high_threshold = atoi(argv[++j]);
3727             printf(" high_threshold #-%d\n", htest_high_threshold);
3728         } else if (strcmp(argv[j], "-hotlist_bssids") == 0 && isxdigit(argv[j+1][0])) {
3729             j++;
3730             for (num_hotlist_bssids = 0; j < argc && isxdigit(argv[j][0]);
3731                 j++, num_hotlist_bssids++) {
3732                     parseMacAddress(argv[j], hotlist_bssids[num_hotlist_bssids]);
3733             }
3734             j -= 1;
3735         } else if (strcmp(argv[j], "-channel_list") == 0 && isxdigit(argv[j+1][0])) {
3736             j++;
3737             for (num_channels = 0; j < argc && isxdigit(argv[j][0]); j++, num_channels++) {
3738                 channel_list[num_channels] = atoi(argv[j]);
3739             }
3740             j -= 1;
3741         } else if ((strcmp(argv[j], "-get_ch_list") == 0)) {
3742             if(strcmp(argv[j + 1], "a") == 0) {
3743                 band = WIFI_BAND_A_WITH_DFS;
3744             } else if(strcmp(argv[j + 1], "bg") == 0) {
3745                 band = WIFI_BAND_BG;
3746             } else if(strcmp(argv[j + 1], "abg") == 0) {
3747                 band = WIFI_BAND_ABG_WITH_DFS;
3748             } else if(strcmp(argv[j + 1], "a_nodfs") == 0) {
3749                 band = WIFI_BAND_A;
3750             } else if(strcmp(argv[j + 1], "dfs") == 0) {
3751                 band = WIFI_BAND_A_DFS;
3752             } else if(strcmp(argv[j + 1], "abg_nodfs") == 0) {
3753                 band = WIFI_BAND_ABG;
3754             }
3755             j++;
3756         } else if ((strcmp(argv[j], "-iface") == 0)) {
3757             ifHandle = wifi_get_iface_handle_by_iface_name(argv[j + 1]);
3758         } else if (strcmp(argv[j], "-scan_mac_oui") == 0 && isxdigit(argv[j+1][0])) {
3759             parseMacOUI(argv[++j], mac_oui);
3760         } else if ((strcmp(argv[j], "-ssid") == 0)) {
3761             epno_cfg.num_networks++;
3762             if (epno_cfg.num_networks < (int)MAX_EPNO_NETWORKS) {
3763                 memcpy(epno_ssid[epno_cfg.num_networks].ssid, argv[j + 1], (size_t)(MAX_SSID_LEN));
3764                 printf(" SSID %s\n", epno_ssid[epno_cfg.num_networks].ssid);
3765                 j++;
3766             }
3767         } else if ((strcmp(argv[j], "-auth") == 0)) {
3768             if (epno_cfg.num_networks < (int)MAX_EPNO_NETWORKS) {
3769                epno_ssid[epno_cfg.num_networks].auth_bit_field = atoi(argv[++j]);
3770                printf(" auth %d\n", epno_ssid[epno_cfg.num_networks].auth_bit_field);
3771             }
3772         } else if ((strcmp(argv[j], "-hidden") == 0)) {
3773             if (epno_cfg.num_networks < (int)MAX_EPNO_NETWORKS) {
3774                epno_ssid[epno_cfg.num_networks].flags |= atoi(argv[++j]) ? EPNO_HIDDEN: 0;
3775                printf(" flags %d\n", epno_ssid[epno_cfg.num_networks].flags);
3776             }
3777         } else if ((strcmp(argv[j], "-strict") == 0)) {
3778             if (epno_cfg.num_networks < (int)MAX_EPNO_NETWORKS) {
3779                epno_ssid[epno_cfg.num_networks].flags |= atoi(argv[++j]) ? EPNO_FLAG_STRICT_MATCH: 0;
3780                printf(" flags %d\n", epno_ssid[epno_cfg.num_networks].flags);
3781             }
3782         } else if ((strcmp(argv[j], "-same_network") == 0)) {
3783             if (epno_cfg.num_networks < (int)MAX_EPNO_NETWORKS) {
3784                epno_ssid[epno_cfg.num_networks].flags |= atoi(argv[++j]) ? EPNO_FLAG_SAME_NETWORK: 0;
3785                printf(" flags %d\n", epno_ssid[epno_cfg.num_networks].flags);
3786             }
3787         } else if (strcmp(argv[j], "-min5g_rssi") == 0 && isdigit(argv[j+1][0])) {
3788             epno_cfg.min5GHz_rssi = -atoi(argv[++j]);
3789             printf(" min5g_rssi %d\n", epno_cfg.min5GHz_rssi);
3790         } else if (strcmp(argv[j], "-min2g_rssi") == 0 && isdigit(argv[j+1][0])) {
3791             epno_cfg.min24GHz_rssi = -atoi(argv[++j]);
3792             printf(" min2g_rssi %d\n", epno_cfg.min24GHz_rssi);
3793         } else if (strcmp(argv[j], "-init_score_max") == 0 && isdigit(argv[j+1][0])) {
3794             epno_cfg.initial_score_max = atoi(argv[++j]);
3795             printf(" initial_score_max %d\n", epno_cfg.initial_score_max);
3796         } else if (strcmp(argv[j], "-cur_conn_bonus") == 0 && isdigit(argv[j+1][0])) {
3797             epno_cfg.current_connection_bonus = atoi(argv[++j]);
3798             printf(" cur_conn_bonus %d\n", epno_cfg.current_connection_bonus);
3799         } else if (strcmp(argv[j], "-same_network_bonus") == 0 && isdigit(argv[j+1][0])) {
3800             epno_cfg.same_network_bonus = atoi(argv[++j]);
3801             printf(" same_network_bonus %d\n", epno_cfg.same_network_bonus);
3802         } else if (strcmp(argv[j], "-secure_bonus") == 0 && isdigit(argv[j+1][0])) {
3803             epno_cfg.secure_bonus = atoi(argv[++j]);
3804             printf(" secure_bonus %d\n", epno_cfg.secure_bonus);
3805         } else if (strcmp(argv[j], "-band5g_bonus") == 0 && isdigit(argv[j+1][0])) {
3806             epno_cfg.band5GHz_bonus = atoi(argv[++j]);
3807             printf(" band5GHz_bonus %d\n", epno_cfg.band5GHz_bonus);
3808         } else if ((strcmp(argv[j], "-trig") == 0)) {
3809             if (epno_cfg.num_networks < (int)MAX_EPNO_NETWORKS) {
3810                 if ((strcmp(argv[j + 1], "a") == 0)) {
3811                    epno_ssid[epno_cfg.num_networks].flags |= EPNO_A_BAND_TRIG;
3812                 } else if ((strcmp(argv[j + 1], "bg") == 0)) {
3813                    epno_ssid[epno_cfg.num_networks].flags |= EPNO_BG_BAND_TRIG;
3814                 } else if ((strcmp(argv[j + 1], "abg") == 0)) {
3815                    epno_ssid[epno_cfg.num_networks].flags |= EPNO_ABG_BAND_TRIG;
3816                 }
3817                printf(" flags %d\n", epno_ssid[epno_cfg.num_networks].flags);
3818             }
3819             j++;
3820         } else if (strcmp(argv[j], "-blacklist_bssids") == 0 && isxdigit(argv[j+1][0])) {
3821             j++;
3822             for (num_blacklist_bssids = 0;
3823                 j < argc && isxdigit(argv[j][0]) &&
3824                 num_blacklist_bssids < MAX_BLACKLIST_BSSID;
3825                 j++, num_blacklist_bssids++) {
3826                 parseMacAddress(argv[j], blacklist_bssids[num_blacklist_bssids]);
3827             }
3828             j -= 1;
3829         } else if (strcmp(argv[j], "-whitelist_ssids") == 0) {
3830             j++;
3831             for (num_whitelist_ssids = 0;
3832                 j < argc && (num_whitelist_ssids < MAX_WHITELIST_SSID);
3833                 j++, num_whitelist_ssids++) {
3834                    if ((strcmp(argv[j], "-blacklist_bssids") == 0) ||
3835                         isxdigit(argv[j][0])) {
3836                         num_whitelist_ssids--;
3837                         continue;
3838                     }
3839                 strncpy(whitelist_ssids[num_whitelist_ssids], argv[j],
3840                 min(strlen(argv[j]), (size_t)(MAX_SSID_LEN-1)));
3841             }
3842             /* Setting this flag to true here as -blacklist_bssids has already existing explicit handler */
3843             set_roaming_configuration = true;
3844             j -= 1;
3845         } else if (strcmp(argv[j], "-rssi_monitor") == 0 && isdigit(argv[j+1][0])) {
3846             rssi_monitor = atoi(argv[++j]);
3847             printf(" rssi_monitor #%d\n", rssi_monitor);
3848         } else if (strcmp(argv[j], "-max_rssi") == 0 && isdigit(argv[j+1][0])) {
3849             max_rssi = -atoi(argv[++j]);
3850             printf(" max_rssi #%d\n", max_rssi);
3851         } else if (strcmp(argv[j], "-min_rssi") == 0 && isdigit(argv[j+1][0])) {
3852             min_rssi = -atoi(argv[++j]);
3853             printf(" min_rssi #%d\n", min_rssi);
3854         }
3855     }
3856 }
3857 
readRTTOptions(int argc,char * argv[])3858 void readRTTOptions(int argc, char *argv[]) {
3859     for (int j = 1; j < argc-1; j++) {
3860         if ((strcmp(argv[j], "-get_ch_list") == 0)) {
3861             if(strcmp(argv[j + 1], "a") == 0) {
3862                 band = WIFI_BAND_A_WITH_DFS;
3863             } else if(strcmp(argv[j + 1], "bg") == 0) {
3864                 band = WIFI_BAND_BG;
3865             } else if(strcmp(argv[j + 1], "abg") == 0) {
3866                 band = WIFI_BAND_ABG_WITH_DFS;
3867             } else if(strcmp(argv[j + 1], "a_nodfs") == 0) {
3868                 band = WIFI_BAND_A;
3869             } else if(strcmp(argv[j + 1], "dfs") == 0) {
3870                 band = WIFI_BAND_A_DFS;
3871             } else if(strcmp(argv[j + 1], "abg_nodfs") == 0) {
3872                 band = WIFI_BAND_ABG;
3873             }
3874             ALOGE("band chosen = %s[band = %d]\n", argv[j + 1], band);
3875             j++;
3876         } else if ((strcmp(argv[j], "-l") == 0)) {
3877             /*
3878              * If this option is specified but there is no file name,
3879              * use a default file from rtt_aplist.
3880              */
3881             if (++j != argc-1) {
3882                 strncpy(rtt_aplist, argv[j], (FILE_NAME_LEN -1));
3883                 rtt_aplist[FILE_NAME_LEN -1] = '\0';
3884             }
3885             rtt_from_file = 1;
3886         } else if ((strcmp(argv[j], "-n") == 0) && isdigit(argv[j+1][0])) {
3887             default_rtt_param.num_burst = atoi(argv[++j]);
3888         } else if ((strcmp(argv[j], "-f") == 0) && isdigit(argv[j+1][0])) {
3889             default_rtt_param.num_frames_per_burst = atoi(argv[++j]);
3890         } else if ((strcmp(argv[j], "-r") == 0) && isdigit(argv[j+1][0])) {
3891             default_rtt_param.num_retries_per_ftm = atoi(argv[++j]);
3892         } else if ((strcmp(argv[j], "-m") == 0) && isdigit(argv[j+1][0])) {
3893             default_rtt_param.num_retries_per_ftmr = atoi(argv[++j]);
3894         } else if ((strcmp(argv[j], "-b") == 0) && isdigit(argv[j+1][0])) {
3895             default_rtt_param.burst_duration = atoi(argv[++j]);
3896         } else if ((strcmp(argv[j], "-max_ap") == 0) && isdigit(argv[j+1][0])) {
3897             max_ap = atoi(argv[++j]);
3898         } else if ((strcmp(argv[j], "-lci") == 0) && isdigit(argv[j+1][0])) {
3899             default_rtt_param.LCI_request = atoi(argv[++j]);
3900         } else if ((strcmp(argv[j], "-lcr") == 0) && isdigit(argv[j+1][0])) {
3901             default_rtt_param.LCR_request = atoi(argv[++j]);
3902         } else if ((strcmp(argv[j], "-type") == 0) && isdigit(argv[j+1][0])) {
3903             u8 rtt_type = atoi(argv[++j]);
3904             if (rtt_type == 1) {
3905                 printf("RTT Type is ONE-SIDED\n");
3906                 type = RTT_TYPE_1_SIDED;
3907             }
3908         } else if ((strcmp(argv[j], "-o") == 0)) {
3909             /*
3910              * If this option is specified but there is no file name,
3911              * use a default file from rtt_aplist.
3912              */
3913             if (++j != argc-1) {
3914                 strncpy(rtt_aplist, argv[j], (FILE_NAME_LEN -1));
3915                 rtt_aplist[FILE_NAME_LEN -1] = '\0';
3916             }
3917             rtt_to_file = 1;
3918         } else if ((strcmp(argv[j], "-sta") == 0) ||
3919             (strcmp(argv[j], "-nan") == 0)) {
3920             if (strcmp(argv[j], "-sta") == 0) {
3921                 rtt_sta = true;
3922             } else {
3923                 rtt_nan = true;
3924             }
3925             if (isxdigit(argv[j+1][0])) {
3926                 j++;
3927                 parseMacAddress(argv[j], responder_addr);
3928                 printMsg("Target mac(" MACSTR ")", MAC2STR(responder_addr));
3929             }
3930             /* Read channel if present */
3931             if (argv[j+1]) {
3932                 if (isdigit(argv[j+1][0])) {
3933                     j++;
3934                     responder_channel = atoi(argv[j]);
3935                     printf("Channel set as %d \n", responder_channel);
3936                 }
3937                 /* Read band width if present */
3938                 if (argv[j+1]) {
3939                     if (isdigit(argv[j+1][0])) {
3940                         j++;
3941                         channel_width = atoi(argv[j]);
3942                         printf("channel_width as %d \n", channel_width);
3943                     }
3944                 }
3945                 /* check its 6g channel */
3946                 if (argv[j+1]) {
3947                     if (isdigit(argv[j+1][0])) {
3948                         j++;
3949                         if(atoi(argv[j]) == 1) {
3950                             printf(" IS 6G CHANNEL \n");
3951                             is_6g = true;
3952                         }
3953                     }
3954                 }
3955 
3956                 /* Read rtt_type if present */
3957                 if (argv[j+1]) {
3958                     if (isdigit(argv[j+1][0])) {
3959                         j++;
3960                         type = (wifi_rtt_type)atoi(argv[j]);
3961                         printf("rtt_type %d \n", type);
3962                     }
3963                 }
3964 
3965                 /* Read ntb_min_meas_time if present */
3966                 if (argv[j+1] && (type == RTT_TYPE_2_SIDED_11AZ_NTB)) {
3967                     if (isdigit(argv[j+1][0])) {
3968                         j++;
3969                         ntb_min_meas_time = atoi(argv[j]);
3970                         printf("ntb_min_meas_time as %lu \n", ntb_min_meas_time);
3971                     }
3972                 }
3973 
3974                 /* Read ntb_max_meas_time if present */
3975                 if (argv[j+1] && (type == RTT_TYPE_2_SIDED_11AZ_NTB)) {
3976                     if (isdigit(argv[j+1][0])) {
3977                         j++;
3978                         ntb_max_meas_time = atoi(argv[j]);
3979                         printf("ntb_max_meas_time as %lu \n", ntb_max_meas_time);
3980                     }
3981                 }
3982             }
3983         }
3984     }
3985 }
3986 
readLoggerOptions(int argc,char * argv[])3987 void readLoggerOptions(int argc, char *argv[])
3988 {
3989     void printUsage();          // declaration for below printUsage()
3990     int j = 1;
3991 
3992     if (argc < 3) {
3993         printUsage();
3994         return;
3995     }
3996 
3997     if ((strcmp(argv[j], "-start") == 0)) {
3998         if ((strcmp(argv[j+1], "pktmonitor") == 0)){
3999             log_cmd = LOG_MONITOR_PKTFATE;
4000             return;
4001         } else if (argc != 13) {
4002             printf("\nUse correct logger option:\n");
4003             printUsage();
4004             return;
4005         }
4006         log_cmd = LOG_START;
4007         memset(&default_logger_param, 0, sizeof(default_logger_param));
4008 
4009         j++;
4010         if ((strcmp(argv[j], "-d") == 0) && isdigit(argv[j+1][0]))
4011             default_logger_param.verbose_level = (unsigned int)atoi(argv[++j]);
4012         if ((strcmp(argv[++j], "-f") == 0) && isdigit(argv[j+1][0]))
4013             default_logger_param.flags = atoi(argv[++j]);
4014         if ((strcmp(argv[++j], "-i") == 0) && isdigit(argv[j+1][0]))
4015             default_logger_param.max_interval_sec = atoi(argv[++j]);
4016         if ((strcmp(argv[++j], "-s") == 0) && isdigit(argv[j+1][0]))
4017             default_logger_param.min_data_size = atoi(argv[++j]);
4018         if ((strcmp(argv[++j], "-n") == 0))
4019             memcpy(default_logger_param.ring_name, argv[j+1], (MAX_RING_NAME_SIZE));
4020         return;
4021     } else if ((strcmp(argv[j], "-get") == 0) && (argc > 3)) {
4022         if ((strcmp(argv[j+1], "fw") == 0)) {
4023             log_cmd = LOG_GET_FW_VER;
4024             j++;
4025             while (j+1 < argc-1) {
4026                 if (strcmp(argv[j+1], "-iface") == 0) {
4027                     j++;
4028                     if (j+1 < argc-1) {
4029                         ifHandle = wifi_get_iface_handle_by_iface_name(argv[j+1]);
4030                     }
4031                 }
4032                 j++;
4033             }
4034         } else if ((strcmp(argv[j+1], "driver") == 0)) {
4035             log_cmd = LOG_GET_DRV_VER;
4036             j++;
4037             while (j+1 < argc-1) {
4038                 if (strcmp(argv[j+1], "-iface") == 0) {
4039                     j++;
4040                     if (j+1 < argc-1) {
4041                         ifHandle = wifi_get_iface_handle_by_iface_name(argv[j+1]);
4042                     }
4043                 }
4044                 j++;
4045             }
4046         } else if ((strcmp(argv[j+1], "memdump") == 0)) {
4047             log_cmd = LOG_GET_MEMDUMP;
4048             j++;
4049             if ((j+1 < argc-1) && (strcmp(argv[j+1], "-o") == 0)) {
4050                 // If this option is specified but there is no file name,
4051                 // use a default file from DEFAULT_MEMDUMP_FILE.
4052                 j++;
4053                 if (j+1 < argc-1) {
4054                     strncpy(mem_dump_file, argv[j+1] , (FILE_NAME_LEN -1));
4055                     mem_dump_file[FILE_NAME_LEN -1] = '\0';
4056                 }
4057             }
4058         } else if ((strcmp(argv[j+1], "ringstatus") == 0)) {
4059             log_cmd = LOG_GET_RING_STATUS;
4060         } else if ((strcmp(argv[j+1], "feature") == 0)) {
4061             log_cmd = LOG_GET_FEATURE;
4062         } else if ((strcmp(argv[j+1], "ringdata") == 0)) {
4063             log_cmd = LOG_GET_RING_DATA;
4064             j+=2;
4065             if ((strcmp(argv[j], "-n") == 0))
4066                 memcpy(default_ring_name, argv[j+1], MAX_RING_NAME_SIZE);
4067         } else if ((strcmp(argv[j+1], "txfate") == 0)) {
4068             log_cmd = LOG_GET_TXPKTFATE;
4069             j++;
4070             while (j+1 < argc-1) {
4071                 if (strcmp(argv[j+1], "-n") == 0) {
4072                     j++;
4073                     if (j+1 < argc-1) {
4074                         n_requested_pkt_fate = atoi(argv[j+1]);
4075                     }
4076                 } else if (strcmp(argv[j+1], "-f") == 0) {
4077                     j++;
4078                     if (j+1 < argc-1) {
4079                         size_t len = min(strlen(argv[j+1]), (size_t)(FILE_NAME_LEN - 1));
4080                         strncpy(tx_pkt_fate_file, argv[j+1], len);
4081                         tx_pkt_fate_file[len] = '\0';
4082                     }
4083                 } else if (strcmp(argv[j+1], "-iface") == 0) {
4084                     j++;
4085                     if (j+1 < argc-1) {
4086                         ifHandle = wifi_get_iface_handle_by_iface_name(argv[j+1]);
4087                     }
4088                 }
4089                 j++;
4090             }
4091         } else if ((strcmp(argv[j+1], "rxfate") == 0)) {
4092             log_cmd = LOG_GET_RXPKTFATE;
4093             j++;
4094             while (j+1 < argc-1) {
4095                 if (strcmp(argv[j+1], "-n") == 0) {
4096                     j++;
4097                     if (j+1 < argc-1) {
4098                         n_requested_pkt_fate = atoi(argv[j+1]);
4099                     }
4100                 } else if (strcmp(argv[j+1], "-f") == 0) {
4101                     j++;
4102                     if (j+1 < argc-1) {
4103                         size_t len = min(strlen(argv[j+1]), (size_t)(FILE_NAME_LEN - 1));
4104                         strncpy(rx_pkt_fate_file, argv[j+1], len);
4105                         rx_pkt_fate_file[len] = '\0';
4106                     }
4107                 } else if (strcmp(argv[j+1], "-iface") == 0) {
4108                     j++;
4109                     if (j+1 < argc-1) {
4110                         ifHandle = wifi_get_iface_handle_by_iface_name(argv[j+1]);
4111                     }
4112                 }
4113                 j++;
4114             }
4115         } else {
4116             printf("\nUse correct logger option:\n");
4117             printUsage();
4118         }
4119         return;
4120     } else if ((strcmp(argv[j], "-set") == 0) && (argc > 3)) {
4121         if ((strcmp(argv[j+1], "loghandler") == 0)) {
4122             log_cmd = LOG_SET_LOG_HANDLER;
4123         } else if ((strcmp(argv[j+1], "alerthandler") == 0)) {
4124             log_cmd = LOG_SET_ALERT_HANDLER;
4125         }
4126     } else {
4127         printf("\nUse correct logger option:\n");
4128         printUsage();
4129 
4130         return;
4131     }
4132 }
4133 
str2hex(char * src,char * dst)4134 static int str2hex(char *src, char *dst)
4135 {
4136     int i;
4137     if (strlen(src) % 2 != 0) {
4138         printMsg(("Mask invalid format. Needs to be of even length\n"));
4139         return -1;
4140     }
4141 
4142     if (strncmp(src, "0x", 2) == 0 || strncmp(src, "0X", 2) == 0) {
4143         src = src + 2; /* Skip past 0x */
4144     }
4145 
4146     for (i = 0; *src != '\0'; i++) {
4147         char num[3];
4148         strncpy(num, src, 2);
4149         num[2] = '\0';
4150         dst[i] = (u8)strtoul(num, NULL, 16);
4151         src += 2;
4152     }
4153     return i;
4154 }
4155 
readKeepAliveOptions(int argc,char * argv[])4156 void readKeepAliveOptions(int argc, char *argv[])
4157 {
4158     void printUsage();          // declaration for below printUsage()
4159 
4160     int index = 0;
4161     u32 period_msec = 0;
4162     mac_addr src_mac;                           // byte array of src mac address
4163     mac_addr dst_mac;                           // byte array of dest mac address
4164     u8 ip_pkt[MKEEP_ALIVE_IP_PKT_MAX] = {0};    // IP pkt including UDP and headers
4165     u16 ip_pkt_len = 0, ether_type = 0;
4166     int j = 1;
4167     int ret = 0;
4168 
4169     /**
4170      * For example,
4171      *
4172      * u8 ip_pkt[] =
4173      * "0014a54b164f000f66f45b7e08004500001e000040004011c52a0a8830700a88302513c413c4000a00000a0d"
4174      *
4175      *  length: 44 bytes
4176      *
4177      *  Ethernet header
4178      *       0014a54b164f   - dest addr
4179      *       000f66f45b7e   - src addr
4180      *       0800           - ether-type    ETHERTYPE_IP (IP protocol) or
4181      *       86dd           - ether-type    ETHERTYPE_IPV6 (IPv6 protocol)
4182      *  IP header
4183      *       4500001e       - Version, IHL, TOS, Total length
4184      *       00004000       - Identification, fragment
4185      *       4011c52a       - TTL, Protocol, Checksum
4186      *       0a883070       - src addr
4187      *       0a883025       - dest addr
4188      *  UDP header
4189      *       13c4           - src port
4190      *       13c4           - dest port
4191      *       000a           - UDP length
4192      *       0000           - checksum
4193      *  UDP payload
4194      *       0a0d
4195      */
4196 
4197     if ((argc == 9) && (strcmp(argv[j], "-start") == 0)) {
4198         // Mapping index
4199         index = atoi(argv[++j]);
4200         if (index < 1 || index > N_AVAIL_ID) {
4201             printMsg("Select proper index number (1 to 3) for mkeep_alive.\n");
4202             return;
4203         }
4204 
4205         // Mapping period
4206         period_msec = atoi(argv[++j]);
4207         if (period_msec <= 0) {
4208             printMsg("Select proper retransmission period for mkeep_alive, great than zero\n");
4209             return;
4210         }
4211 
4212         // Mapping mac addresses
4213         if ((str2hex(argv[++j], (char *)src_mac) != ETHER_ADDR_LEN)
4214                 || (str2hex(argv[++j], (char *)dst_mac) != ETHER_ADDR_LEN)) {
4215             printMsg("Source or destination mac address is not correct. Please make sure.\n");
4216             return;
4217         }
4218 
4219         // Mapping ether_type
4220         ether_type = atoi(argv[++j]);
4221         if (!((ether_type == ETHERTYPE_IP) ||
4222             (ether_type == ETHERTYPE_IPV6))) {
4223             printMsg("Select proper ether_type, valid values 0x0800(2048) for IP or 0x86dd(34525) IP6\n");
4224             return;
4225         }
4226 
4227         // Mapping string pkt length by hexa byte
4228         ip_pkt_len = strlen(argv[++j])/2;
4229         if (ip_pkt_len > MKEEP_ALIVE_IP_PKT_MAX) {
4230             printMsg("IP pkt size is bigger than max_len (%d) for mkeep_alive. "
4231                      "Please check up the size of IP packet contents.\n",
4232                 MKEEP_ALIVE_IP_PKT_MAX);
4233                 return;
4234         }
4235 
4236         // Mapping pkt contents by hexa format
4237         memset(ip_pkt, 0, MKEEP_ALIVE_IP_PKT_MAX);
4238         if (str2hex(argv[j], (char *)ip_pkt) != ip_pkt_len) {
4239             printMsg("Conversion of hexa byte on IP pkt has been failed.\n");
4240             return;
4241         }
4242 
4243         ret = start_mkeep_alive(index, period_msec, ether_type, src_mac,
4244                 dst_mac, ip_pkt, ip_pkt_len);
4245         if (ret == WIFI_SUCCESS)
4246             printMsg("Success to register mkeep_alive by ID %d\n", index);
4247     } else if ((argc == 4) && (strcmp(argv[j], "-stop") == 0)) {
4248         // mapping index
4249         index = atoi(argv[++j]);
4250         if (index < 1 || index > N_AVAIL_ID) {
4251             printMsg("Select proper index number (1 to 3) for mkeep_alive.\n");
4252             return;
4253         }
4254 
4255         ret = stop_mkeep_alive(index);
4256         if (ret == WIFI_SUCCESS)
4257             printMsg("Success to stop mkeep_alive by ID %d\n", index);
4258     } else {
4259         printf("Use correct mkeep_alive option:\n");
4260     }
4261 }
4262 
4263 const char *eht_rates[] = {
4264     "OFDM/LEGACY 1Mbps               ",
4265     "OFDM/LEGACY 2Mbps               ",
4266     "OFDM/LEGACY 5.5Mbps             ",
4267     "OFDM/LEGACY 6Mbps               ",
4268     "OFDM/LEGACY 9Mbps               ",
4269     "OFDM/LEGACY 11Mbps              ",
4270     "OFDM/LEGACY 12Mbps              ",
4271     "OFDM/LEGACY 18Mbps              ",
4272     "OFDM/LEGACY 24Mbps              ",
4273     "OFDM/LEGACY 36Mbps              ",
4274     "OFDM/LEGACY 48Mbps              ",
4275     "OFDM/LEGACY 54Mbps              ",
4276     "HT MCS0  | VHT/HE/EHT MCS0  NSS1",
4277     "HT MCS1  | VHT/HE/EHT MCS1  NSS1",
4278     "HT MCS2  | VHT/HE/EHT MCS2  NSS1",
4279     "HT MCS3  | VHT/HE/EHT MCS3  NSS1",
4280     "HT MCS4  | VHT/HE/EHT MCS4  NSS1",
4281     "HT MCS5  | VHT/HE/EHT MCS5  NSS1",
4282     "HT MCS6  | VHT/HE/EHT MCS6  NSS1",
4283     "HT MCS7  | VHT/HE/EHT MCS7  NSS1",
4284     "HT MCS8  | VHT/HE/EHT MCS8  NSS1",
4285     "HT MCS9  | VHT/HE/EHT MCS9  NSS1",
4286     "HT MCS10 | VHT/HE/EHT MCS10 NSS1",
4287     "HT MCS11 | VHT/HE/EHT MCS11 NSS1",
4288     "HT MCS12 |        EHT MCS12 NSS1",
4289     "HT MCS13 |        EHT MCS13 NSS1",
4290     "HT MCS14 |        EHT MCS14 NSS1",
4291     "HT MCS15 |        EHT MCS15 NSS1",
4292     "HT N/A   | VHT/HE/EHT MCS0  NSS2",
4293     "HT N/A   | VHT/HE/EHT MCS1  NSS2",
4294     "HT N/A   | VHT/HE/EHT MCS2  NSS2",
4295     "HT N/A   | VHT/HE/EHT MCS3  NSS2",
4296     "HT N/A   | VHT/HE/EHT MCS4  NSS2",
4297     "HT N/A   | VHT/HE/EHT MCS5  NSS2",
4298     "HT N/A   | VHT/HE/EHT MCS6  NSS2",
4299     "HT N/A   | VHT/HE/EHT MCS7  NSS2",
4300     "HT N/A   | VHT/HE/EHT MCS8  NSS2",
4301     "HT N/A   | VHT/HE/EHT MCS9  NSS2",
4302     "HT N/A   | VHT/HE/EHT MCS10 NSS2",
4303     "HT N/A   | VHT/HE/EHT MCS11 NSS2",
4304     "HT N/A   |        EHT MCS12 NSS2",
4305     "HT N/A   |        EHT MCS13 NSS2",
4306     "HT N/A   |        EHT MCS14 NSS2",
4307     "HT N/A   |        EHT MCS15 NSS2",
4308 };
4309 
4310 const char *rates[] = {
4311     "OFDM/LEGACY 1Mbps",
4312     "OFDM/LEGACY 2Mbps",
4313     "OFDM/LEGACY 5.5Mbps",
4314     "OFDM/LEGACY 6Mbps",
4315     "OFDM/LEGACY 9Mbps",
4316     "OFDM/LEGACY 11Mbps",
4317     "OFDM/LEGACY 12Mbps",
4318     "OFDM/LEGACY 18Mbps",
4319     "OFDM/LEGACY 24Mbps",
4320     "OFDM/LEGACY 36Mbps",
4321     "OFDM/LEGACY 48Mbps",
4322     "OFDM/LEGACY 54Mbps",
4323     "HT MCS0  | VHT/HE MCS0  NSS1",
4324     "HT MCS1  | VHT/HE MCS1  NSS1",
4325     "HT MCS2  | VHT/HE MCS2  NSS1",
4326     "HT MCS3  | VHT/HE MCS3  NSS1",
4327     "HT MCS4  | VHT/HE MCS4  NSS1",
4328     "HT MCS5  | VHT/HE MCS5  NSS1",
4329     "HT MCS6  | VHT/HE MCS6  NSS1",
4330     "HT MCS7  | VHT/HE MCS7  NSS1",
4331     "HT MCS8  | VHT/HE MCS8  NSS1",
4332     "HT MCS9  | VHT/HE MCS9  NSS1",
4333     "HT MCS10 | VHT/HE MCS10 NSS1",
4334     "HT MCS11 | VHT/HE MCS11 NSS1",
4335     "HT MCS12 | VHT/HE MCS0  NSS2",
4336     "HT MCS13 | VHT/HE MCS1  NSS2",
4337     "HT MCS14 | VHT/HE MCS2  NSS2",
4338     "HT MCS15 | VHT/HE MCS3  NSS2",
4339     "HT N/A   | VHT/HE MCS4  NSS2",
4340     "HT N/A   | VHT/HE MCS5  NSS2",
4341     "HT N/A   | VHT/HE MCS6  NSS2",
4342     "HT N/A   | VHT/HE MCS7  NSS2",
4343     "HT N/A   | VHT/HE MCS8  NSS2",
4344     "HT N/A   | VHT/HE MCS9  NSS2",
4345     "HT N/A   | VHT/HE MCS10 NSS2",
4346     "HT N/A   | VHT/HE MCS11 NSS2",
4347 };
4348 
4349 /* Legacy rates */
4350 #define NUM_RATES (sizeof(rates)/sizeof(rates[0]))
4351 #define NUM_EHT_RATES (sizeof(eht_rates)/sizeof(eht_rates[0]))
4352 
4353 #define RATE_SPEC_STR_LEN       10
4354 #define RATE_SPEC_CHECK_INDEX   27
4355 const char rate_stat_preamble[][RATE_SPEC_STR_LEN] = {
4356     "OFDM",
4357     "CCK",
4358     "HT",
4359     "VHT",
4360     "HE",
4361     "EHT"
4362 };
4363 
4364 const short int rate_stat_bandwidth[] = {
4365     20,
4366     40,
4367     80,
4368     160,
4369     320
4370 };
4371 
4372 int radios = 0;
4373 int ml_links = 0;
4374 
4375 wifi_radio_stat rx_stat[MAX_NUM_RADIOS];
4376 wifi_channel_stat cca_stat[MAX_CH_BUF_SIZE];
4377 
updateRateStats(u8 ** buf,int num_rates)4378 void updateRateStats(u8 **buf, int num_rates) {
4379     printMsg("\nPrinting rate statistics: ");
4380     printMsg("------------------------------------------------------\n");
4381     printMsg("%40s %12s %14s %15s\n", "TX",  "RX", "LOST", "RETRIES");
4382     for (int k = 0; k < num_rates; k++) {
4383         if (!*buf) {
4384             ALOGE("No valid buf of rate_stats for index %d\n", k);
4385             continue;
4386         }
4387         wifi_rate_stat *local_ratestat_ptr = (wifi_rate_stat*)(*buf);
4388         if (!local_ratestat_ptr) {
4389             printMsg("rate stat data of index %d not found\n", k);
4390             continue;
4391         }
4392         if (num_rates == NUM_EHT_RATES) {
4393             printMsg("%-28s  %10d   %10d     %10d      %10d\n",
4394                 eht_rates[k], local_ratestat_ptr->tx_mpdu, local_ratestat_ptr->rx_mpdu,
4395                     local_ratestat_ptr->mpdu_lost, local_ratestat_ptr->retries);
4396         } else if (num_rates == NUM_RATES) {
4397             printMsg("%-28s  %10d   %10d     %10d      %10d\n",
4398                 rates[k], local_ratestat_ptr->tx_mpdu, local_ratestat_ptr->rx_mpdu,
4399                     local_ratestat_ptr->mpdu_lost, local_ratestat_ptr->retries);
4400         } else {
4401             printMsg("num_rates %d value is not supported\n", num_rates);
4402             continue;
4403         }
4404         *buf += sizeof(wifi_rate_stat);
4405     }
4406 }
4407 
printPeerinfoStats(wifi_peer_info * local_peer_ptr)4408 void printPeerinfoStats(wifi_peer_info *local_peer_ptr) {
4409     printMsg("Peer type = %d\n", local_peer_ptr->type);
4410     printMsg("Peer mac address: ( " MACSTR " )\n",
4411         MAC2STR(local_peer_ptr->peer_mac_address));
4412     printMsg("Peer Capabilities = %d\n", local_peer_ptr->capabilities);
4413     printMsg("Load_info(Station Count) = %d\n", local_peer_ptr->bssload.sta_count);
4414     printMsg("CCA_level(Channel Utilization) = %d\n", local_peer_ptr->bssload.chan_util);
4415     printMsg("Num rate %d \n", local_peer_ptr->num_rate);
4416     return;
4417 }
4418 
update_peer_info_per_link(u8 ** buf)4419 void update_peer_info_per_link(u8 **buf) {
4420     wifi_peer_info *local_peer_ptr = (wifi_peer_info*)(*buf);
4421     if (!local_peer_ptr) {
4422         printMsg("peer data not found, skip\n");
4423         return;
4424     }
4425 
4426     if ((local_peer_ptr->num_rate == NUM_RATES) ||
4427         (local_peer_ptr->num_rate == NUM_EHT_RATES)) {
4428         printPeerinfoStats(local_peer_ptr);
4429         *buf += offsetof(wifi_peer_info, rate_stats);
4430         if (!*buf) {
4431             ALOGE("No valid rate_stats\n");
4432             return;
4433         }
4434         updateRateStats(buf, local_peer_ptr->num_rate);
4435     }
4436 }
4437 
printPerLinkStats(wifi_link_stat * local_link_ptr,int link_id)4438 void printPerLinkStats(wifi_link_stat *local_link_ptr, int link_id) {
4439     printMsg("Printing link statistics of the link:%d\n", link_id);
4440     printMsg("Identifier for the link = %d\n", local_link_ptr->link_id);
4441     printMsg("State of the link = %d\n", local_link_ptr->state);
4442     printMsg("Radio on which link stats are sampled. = %d\n", local_link_ptr->radio);
4443     printMsg("Frequency on which link is operating. = %d MHz\n", local_link_ptr->frequency);
4444     printMsg("beacon_rx = %d\n", local_link_ptr->beacon_rx);
4445     printMsg("average_tsf_offset= %llu\n", local_link_ptr->average_tsf_offset);
4446     printMsg("leaky_ap_detected= %d\n", local_link_ptr->leaky_ap_detected);
4447     printMsg("leaky_ap_avg_num_frames_leaked= %d\n",
4448         local_link_ptr->leaky_ap_avg_num_frames_leaked);
4449     printMsg("leaky_ap_guard_time= %d\n", local_link_ptr->leaky_ap_guard_time);
4450     printMsg("mgmt_rx= %d\n", local_link_ptr->mgmt_rx);
4451     printMsg("mgmt_action_rx= %d\n", local_link_ptr->mgmt_action_rx);
4452     printMsg("mgmt_action_tx= %d\n", local_link_ptr->mgmt_action_tx);
4453     printMsg("RSSI mgmt = %d\n", local_link_ptr->rssi_mgmt);
4454     printMsg("RSSI data = %d\n", local_link_ptr->rssi_data);
4455     printMsg("RSSI ack = %d\n", local_link_ptr->rssi_ack);
4456     printMsg("AC_BE:\n");
4457     printMsg("txmpdu = %d\n", local_link_ptr->ac[WIFI_AC_BE].tx_mpdu);
4458     printMsg("rxmpdu = %d\n", local_link_ptr->ac[WIFI_AC_BE].rx_mpdu);
4459     printMsg("mpdu_lost = %d\n", local_link_ptr->ac[WIFI_AC_BE].mpdu_lost);
4460     printMsg("retries = %d\n", local_link_ptr->ac[WIFI_AC_BE].retries);
4461     printMsg("AC_BK:\n");
4462     printMsg("txmpdu = %d\n", local_link_ptr->ac[WIFI_AC_BK].tx_mpdu);
4463     printMsg("rxmpdu = %d\n", local_link_ptr->ac[WIFI_AC_BK].rx_mpdu);
4464     printMsg("mpdu_lost = %d\n", local_link_ptr->ac[WIFI_AC_BK].mpdu_lost);
4465     printMsg("AC_VI:\n");
4466     printMsg("txmpdu = %d\n", local_link_ptr->ac[WIFI_AC_VI].tx_mpdu);
4467     printMsg("rxmpdu = %d\n", local_link_ptr->ac[WIFI_AC_VI].rx_mpdu);
4468     printMsg("mpdu_lost = %d\n", local_link_ptr->ac[WIFI_AC_VI].mpdu_lost);
4469     printMsg("AC_VO:\n");
4470     printMsg("txmpdu = %d\n", local_link_ptr->ac[WIFI_AC_VO].tx_mpdu);
4471     printMsg("rxmpdu = %d\n", local_link_ptr->ac[WIFI_AC_VO].rx_mpdu);
4472     printMsg("mpdu_lost = %d\n", local_link_ptr->ac[WIFI_AC_VO].mpdu_lost);
4473     printMsg("time slicing duty_cycle = %d\n", local_link_ptr->time_slicing_duty_cycle_percent);
4474     printMsg("Num peers = %d\n", local_link_ptr->num_peers);
4475 }
4476 
update_per_link_data(u8 ** buf,int link_id)4477 void update_per_link_data(u8 **buf, int link_id) {
4478     wifi_link_stat *local_link_ptr = (wifi_link_stat*)(*buf);
4479     if (!local_link_ptr) {
4480        printMsg("link data not found, skip\n");
4481        return;
4482     }
4483 
4484     printPerLinkStats(local_link_ptr, link_id);
4485 
4486     /* For STA, peer would be only one - AP. */
4487     if (local_link_ptr->num_peers == NUM_PEER_AP) {
4488         for (int j = 0; j < local_link_ptr->num_peers; j++) {
4489             *buf += offsetof(wifi_link_stat, peer_info);
4490             if (!*buf) {
4491                 ALOGE("No valid peer info\n");
4492                 continue;
4493             }
4494             update_peer_info_per_link(buf);
4495         }
4496     }
4497 }
4498 
onMultiLinkStatsResults(wifi_request_id id,wifi_iface_ml_stat * iface_ml_stat,int num_radios,wifi_radio_stat * radio_stat)4499 void onMultiLinkStatsResults(wifi_request_id id, wifi_iface_ml_stat *iface_ml_stat,
4500         int num_radios, wifi_radio_stat *radio_stat)
4501 {
4502     u8 *local_rx_ptr = NULL, *local_cca_ptr = NULL, *buf_ptr = NULL;
4503     int channel_size = 0, num_channels = 0;
4504     int cca_avail_size = MAX_CH_BUF_SIZE;
4505 
4506     if (!num_radios || !radio_stat) {
4507         ALOGE("No valid radio stat data\n");
4508         return;
4509     }
4510 
4511     radios = num_radios;
4512     local_rx_ptr = (u8*)radio_stat;
4513     local_cca_ptr = (u8*)cca_stat;
4514 
4515     for (int i = 0; i < num_radios; i++) {
4516         memset(&rx_stat[i], 0, sizeof(wifi_radio_stat));
4517         memcpy(&rx_stat[i], (u8*)local_rx_ptr, offsetof(wifi_radio_stat, channels));
4518         local_rx_ptr += offsetof(wifi_radio_stat, channels);
4519         num_channels = rx_stat[i].num_channels;
4520 
4521         if (num_channels >= MAX_WIFI_USABLE_CHANNELS) {
4522             ALOGE("Invalid num_channels value %d\n", num_channels);
4523             break;
4524         }
4525 
4526         channel_size = sizeof(wifi_channel_stat)*num_channels;
4527         if (cca_avail_size > num_channels) {
4528 	    memcpy(local_cca_ptr, (u8*)local_rx_ptr, channel_size);
4529             cca_avail_size -= num_channels;
4530         } else {
4531 	    ALOGE("No space left for chan_stat!!: cca_avail: %d, req: %d\n",
4532                 cca_avail_size, num_channels);
4533             break;
4534         }
4535 
4536         if (i == (num_radios - 1)) {
4537             break;
4538         }
4539         local_rx_ptr += channel_size;
4540         local_cca_ptr += channel_size;
4541     }
4542     /* radio stat data and channel stats data is printed in printMultiLinkStats */
4543     if (!iface_ml_stat) {
4544         ALOGE("No valid ml stats data\n");
4545         return;
4546     }
4547 
4548     buf_ptr = (u8*)iface_ml_stat;
4549     ml_links = iface_ml_stat->num_links;
4550 
4551     if (ml_links < MAX_MLO_LINK) {
4552         buf_ptr += offsetof(wifi_iface_ml_stat, links);
4553         for (int i = 0; i < ml_links; i++) {
4554             if (!buf_ptr) {
4555                 ALOGE("No valid multilink data\n");
4556                 continue;
4557             }
4558             printMsg("-----------------------------------------------------\n\n");
4559             update_per_link_data(&buf_ptr, i);
4560         }
4561     } else {
4562         ALOGE("Invalid ml links %d\n", ml_links);
4563     }
4564 }
4565 
4566 wifi_iface_stat link_stat;
4567 int num_rate;
4568 bssload_info_t bssload;
4569 wifi_peer_info peer_info[32];
4570 wifi_rate_stat rate_stat[NUM_RATES];
4571 wifi_rate_stat eht_rate_stat[NUM_EHT_RATES];
4572 
onLinkStatsResults(wifi_request_id id,wifi_iface_stat * iface_stat,int num_radios,wifi_radio_stat * radio_stat)4573 void onLinkStatsResults(wifi_request_id id, wifi_iface_stat *iface_stat,
4574         int num_radios, wifi_radio_stat *radio_stat)
4575 {
4576     int num_peer = 0;
4577     u8 *local_rx_stat_ptr = NULL, *local_cca_ptr = NULL;
4578     int channel_size = 0, num_channels = 0;
4579     int cca_avail_size = MAX_CH_BUF_SIZE;
4580 
4581     if (!num_radios || !radio_stat) {
4582         ALOGE("No valid radio stat data\n");
4583         return;
4584     }
4585 
4586     radios = num_radios;
4587     local_rx_stat_ptr = (u8*)radio_stat;
4588     local_cca_ptr = (u8*)cca_stat;
4589     for (int i = 0; i < num_radios; i++) {
4590         memset(&rx_stat[i], 0, sizeof(wifi_radio_stat));
4591         memcpy(&rx_stat[i], (u8*)local_rx_stat_ptr, offsetof(wifi_radio_stat, channels));
4592         local_rx_stat_ptr += offsetof(wifi_radio_stat, channels);
4593         num_channels = rx_stat[i].num_channels;
4594         if (num_channels) {
4595             channel_size = sizeof(wifi_channel_stat)*num_channels;
4596             if (cca_avail_size > num_channels) {
4597                 memcpy(local_cca_ptr, (u8*)local_rx_stat_ptr, channel_size);
4598                 cca_avail_size -= num_channels;
4599             } else {
4600                 ALOGE("No space left for chan_stat!!: cca_avail: %d, req: %d\n",
4601                     cca_avail_size, num_channels);
4602                 break;
4603             }
4604         }
4605         if (i == (num_radios - 1)) {
4606             break;
4607         }
4608         local_rx_stat_ptr += channel_size;
4609         local_cca_ptr += channel_size;
4610     }
4611 
4612     if (!iface_stat) {
4613         ALOGE("No valid iface stats data\n");
4614         return;
4615     }
4616 
4617     num_peer = iface_stat->num_peers;
4618     printMsg("onLinkStatsResults num_peer = %d \n", num_peer);
4619     memset(&link_stat, 0, sizeof(wifi_iface_stat));
4620     memcpy(&link_stat, iface_stat, sizeof(wifi_iface_stat));
4621     memcpy(peer_info, iface_stat->peer_info, num_peer*sizeof(wifi_peer_info));
4622     num_rate = peer_info[0].num_rate;
4623     printMsg("onLinkStatsResults num_rate = %d \n", num_rate);
4624 
4625     memset(&bssload, 0, sizeof(bssload_info_t));
4626     memcpy(&bssload, &iface_stat->peer_info->bssload, sizeof(bssload_info_t));
4627 
4628     if (num_rate == NUM_EHT_RATES) {
4629         memset(eht_rate_stat, 0, num_rate*sizeof(wifi_rate_stat));
4630         memcpy(&eht_rate_stat, iface_stat->peer_info->rate_stats, num_rate*sizeof(wifi_rate_stat));
4631     } else if (num_rate == NUM_RATES) {
4632         memset(rate_stat, 0, num_rate*sizeof(wifi_rate_stat));
4633         memcpy(&rate_stat, iface_stat->peer_info->rate_stats, num_rate*sizeof(wifi_rate_stat));
4634     }
4635 }
4636 
printFeatureListBitMask(void)4637 void printFeatureListBitMask(void)
4638 {
4639     printMsg("WIFI_FEATURE_INFRA              0x000000001 - Basic infrastructure mode\n");
4640     printMsg("WIFI_FEATURE_INFRA_5G           0x000000002 - Support for 5 GHz Band\n");
4641     printMsg("WIFI_FEATURE_HOTSPOT            0x000000004 - Support for GAS/ANQP\n");
4642     printMsg("WIFI_FEATURE_P2P                0x000000008 - Wifi-Direct\n");
4643     printMsg("WIFI_FEATURE_SOFT_AP            0x000000010 - Soft AP\n");
4644     printMsg("WIFI_FEATURE_GSCAN              0x000000020 - Google-Scan APIs\n");
4645     printMsg("WIFI_FEATURE_NAN                0x000000040 - Neighbor Awareness Networking\n");
4646     printMsg("WIFI_FEATURE_D2D_RTT            0x000000080 - Device-to-device RTT\n");
4647     printMsg("WIFI_FEATURE_D2AP_RTT           0x000000100 - Device-to-AP RTT\n");
4648     printMsg("WIFI_FEATURE_BATCH_SCAN         0x000000200 - Batched Scan (legacy)\n");
4649     printMsg("WIFI_FEATURE_PNO                0x000000400 - Preferred network offload\n");
4650     printMsg("WIFI_FEATURE_ADDITIONAL_STA     0x000000800 - Support for two STAs\n");
4651     printMsg("WIFI_FEATURE_TDLS               0x000001000 - Tunnel directed link setup\n");
4652     printMsg("WIFI_FEATURE_TDLS_OFFCHANNEL    0x000002000 - Support for TDLS off channel\n");
4653     printMsg("WIFI_FEATURE_EPR                0x000004000 - Enhanced power reporting\n");
4654     printMsg("WIFI_FEATURE_AP_STA             0x000008000 - Support for AP STA Concurrency\n");
4655     printMsg("WIFI_FEATURE_LINK_LAYER_STATS   0x000010000 - Link layer stats collection\n");
4656     printMsg("WIFI_FEATURE_LOGGER             0x000020000 - WiFi Logger\n");
4657     printMsg("WIFI_FEATURE_HAL_EPNO           0x000040000 - iFi PNO enhanced\n");
4658     printMsg("WIFI_FEATURE_RSSI_MONITOR       0x000080000 - RSSI Monitor\n");
4659     printMsg("WIFI_FEATURE_MKEEP_ALIVE        0x000100000 - WiFi mkeep_alive\n");
4660     printMsg("WIFI_FEATURE_CONFIG_NDO         0x000200000 - ND offload configure\n");
4661     printMsg("WIFI_FEATURE_TX_TRANSMIT_POWER  0x000400000 - apture Tx transmit power levels\n");
4662     printMsg("WIFI_FEATURE_CONTROL_ROAMING    0x000800000 - Enable/Disable firmware roaming\n");
4663     printMsg("WIFI_FEATURE_IE_WHITELIST       0x001000000 - Support Probe IE white listing\n");
4664     printMsg("WIFI_FEATURE_SCAN_RAND          0x002000000 - "
4665         "Support MAC & Probe Sequence Number randomization\n");
4666     printMsg("WIFI_FEATURE_SET_TX_POWER_LIMIT 0x004000000 - Support Tx Power Limit setting\n");
4667     printMsg("WIFI_FEATURE_USE_BODY_HEAD_SAR  0x008000000 - Support Using Body/Head Proximity for SAR\n");
4668     printMsg("WIFI_FEATURE_DYNAMIC_SET_MAC    0x010000000 - Support changing MAC address without"
4669         " iface reset(down and up)\n");
4670     printMsg("WIFI_FEATURE_SET_LATENCY_MODE   0x040000000 - Support Latency mode setting\n");
4671     printMsg("WIFI_FEATURE_P2P_RAND_MAC       0x080000000 - Support P2P MAC randomization\n");
4672     printMsg("WIFI_FEATURE_INFRA_60G          0x100000000 - Support for 60GHz Band\n");
4673 }
4674 
printRadioComboMatrix(wifi_radio_combination_matrix * rc)4675 void printRadioComboMatrix(wifi_radio_combination_matrix *rc)
4676 {
4677     u32 num_radio_combinations = rc->num_radio_combinations;
4678     wifi_radio_combination *radio_combinations = rc->radio_combinations;
4679     u32 num_radio_configurations;
4680     int i,j;
4681 
4682     printMsg("printing band info for combinations:%d\n", num_radio_combinations);
4683 
4684     for (i=0; i < num_radio_combinations; i++) {
4685         num_radio_configurations = radio_combinations->num_radio_configurations;
4686         printMsg("combination:%d num_radio_configurations:%d\n", i, num_radio_configurations);
4687         for (j=0; j < num_radio_configurations; j++) {
4688             printMsg("band:%s (%d) antenna cfg:%s (%d)\n",
4689                 BandToString(radio_combinations->radio_configurations[j].band),
4690                 radio_combinations->radio_configurations[j].band,
4691                 AntennCfgToString(radio_combinations->radio_configurations[j].antenna_cfg),
4692                 radio_combinations->radio_configurations[j].antenna_cfg);
4693         }
4694 
4695         if (j == (num_radio_combinations - 1)) {
4696             break;
4697         }
4698         radio_combinations = (wifi_radio_combination *)((u8*)radio_combinations + sizeof(u32) +
4699             (num_radio_configurations * sizeof(wifi_radio_configuration)));
4700     }
4701     return;
4702 }
4703 
4704 #define CHAN_STR_LEN 10
4705 static char chan_str[CHAN_STR_LEN];
4706 
frequency_to_channel(int center_freq)4707 static char* frequency_to_channel(int center_freq)
4708 {
4709     if (center_freq >= 2412 && center_freq <= 2484) {
4710         if (center_freq == 2484) {
4711             snprintf(chan_str, CHAN_STR_LEN, "2g/ch14");
4712         } else {
4713             snprintf(chan_str, CHAN_STR_LEN, "2g/ch%d", (center_freq - 2407) / 5);
4714         }
4715     } else if (center_freq >= 5180 && center_freq <= 5825) {
4716         snprintf(chan_str, CHAN_STR_LEN, "5g/ch%d", (center_freq - 5000) / 5);
4717     } else if (center_freq >= 5845 && center_freq <= 5885) {
4718         /* UNII-4 channels */
4719         snprintf(chan_str, CHAN_STR_LEN, "5g/ch%d", (center_freq - 5000) / 5);
4720     } else if (center_freq >= 5935 && center_freq <= 7115) {
4721         if (center_freq == 5935) {
4722             snprintf(chan_str, CHAN_STR_LEN, "6g/ch2");
4723         } else {
4724             snprintf(chan_str, CHAN_STR_LEN, "6g/ch%d", (center_freq - 5950) / 5);
4725         }
4726     } else {
4727         snprintf(chan_str, CHAN_STR_LEN, "Err");
4728     }
4729 
4730    return &chan_str[0];
4731 }
4732 
printMultiLinkStats(wifi_channel_stat cca_stat[],wifi_radio_stat rx_stat[],int radios)4733 void printMultiLinkStats(wifi_channel_stat cca_stat[],
4734     wifi_radio_stat rx_stat[], int radios)
4735 {
4736     int new_chan_base = 0;
4737     printMsg("\nPrinting radio statistics of multi link\n");
4738     printMsg("--------------------------------------\n");
4739     for (int i = 0; i < radios; i++) {
4740         printMsg("--------------------------------------\n");
4741         printMsg("radio = %d\n", rx_stat[i].radio);
4742         printMsg("on time = %d\n", rx_stat[i].on_time);
4743         printMsg("tx time = %d\n", rx_stat[i].tx_time);
4744         printMsg("num_tx_levels = %d\n", rx_stat[i].num_tx_levels);
4745         printMsg("rx time = %d\n", rx_stat[i].rx_time);
4746         printMsg("SCAN\n");
4747         printMsg("on_time_scan(duration)= %d\n", rx_stat[i].on_time_scan);
4748         printMsg("on_time_nbd(duration)= %d\n", rx_stat[i].on_time_nbd);
4749         printMsg("on_time_gscan(duration)= %d\n", rx_stat[i].on_time_gscan);
4750         printMsg("on_time_roam_scan(duration)= %d\n", rx_stat[i].on_time_roam_scan);
4751         printMsg("on_time_pno_scan(duration)= %d\n", rx_stat[i].on_time_pno_scan);
4752         printMsg("on_time_hs20 = %d\n", rx_stat[i].on_time_hs20);
4753         printMsg("cca channel statistics: (num_channels: %d)\n", rx_stat[i].num_channels);
4754         printMsg("--------------------------------------\n");
4755             for (int j = new_chan_base; j < (new_chan_base + rx_stat[i].num_channels); j++) {
4756                 printMsg("center_freq=%d (%8s), radio_on_time %10d, cca_busytime %10d\n",
4757                 cca_stat[j].channel.center_freq,
4758                 frequency_to_channel(cca_stat[j].channel.center_freq),
4759                 cca_stat[j].on_time, cca_stat[j].cca_busy_time);
4760             }
4761         new_chan_base += rx_stat[i].num_channels;
4762     }
4763     printMsg("\n");
4764 }
4765 /////////////////////////////////////////////////////////////////////
printLinkStats(wifi_iface_stat * link_stat,wifi_channel_stat cca_stat[],wifi_radio_stat rx_stat[],bssload_info_t * bssload,int radios)4766 void printLinkStats(wifi_iface_stat *link_stat, wifi_channel_stat cca_stat[],
4767     wifi_radio_stat rx_stat[], bssload_info_t *bssload, int radios)
4768 {
4769     int new_chan_base = 0;
4770     printMsg("Printing link layer statistics:\n");
4771     printMsg("--------------------------------------\n");
4772     printMsg("Num peer = %d\n", link_stat->num_peers);
4773     printMsg("beacon_rx = %d\n", link_stat->beacon_rx);
4774     printMsg("RSSI = %d\n", link_stat->rssi_mgmt);
4775     printMsg("Load_info(Station Count) = %d\n", bssload->sta_count);
4776     printMsg("CCA_level(Channel Utilization) = %d\n", bssload->chan_util);
4777     printMsg("AC_BE:\n");
4778     printMsg("txmpdu = %d\n", link_stat->ac[WIFI_AC_BE].tx_mpdu);
4779     printMsg("rxmpdu = %d\n", link_stat->ac[WIFI_AC_BE].rx_mpdu);
4780     printMsg("mpdu_lost = %d\n", link_stat->ac[WIFI_AC_BE].mpdu_lost);
4781     printMsg("retries = %d\n", link_stat->ac[WIFI_AC_BE].retries);
4782     printMsg("AC_BK:\n");
4783     printMsg("txmpdu = %d\n", link_stat->ac[WIFI_AC_BK].tx_mpdu);
4784     printMsg("rxmpdu = %d\n", link_stat->ac[WIFI_AC_BK].rx_mpdu);
4785     printMsg("mpdu_lost = %d\n", link_stat->ac[WIFI_AC_BK].mpdu_lost);
4786     printMsg("AC_VI:\n");
4787     printMsg("txmpdu = %d\n", link_stat->ac[WIFI_AC_VI].tx_mpdu);
4788     printMsg("rxmpdu = %d\n", link_stat->ac[WIFI_AC_VI].rx_mpdu);
4789     printMsg("mpdu_lost = %d\n", link_stat->ac[WIFI_AC_VI].mpdu_lost);
4790     printMsg("AC_VO:\n");
4791     printMsg("txmpdu = %d\n", link_stat->ac[WIFI_AC_VO].tx_mpdu);
4792     printMsg("rxmpdu = %d\n", link_stat->ac[WIFI_AC_VO].rx_mpdu);
4793     printMsg("mpdu_lost = %d\n", link_stat->ac[WIFI_AC_VO].mpdu_lost);
4794     printMsg("time slicing duty_cycle = %d\n", link_stat->info.time_slicing_duty_cycle_percent);
4795     printMsg("\n");
4796     printMsg("Printing radio statistics:\n");
4797     printMsg("--------------------------------------\n");
4798     for (int i = 0; i < radios; i++) {
4799         printMsg("--------------------------------------\n");
4800         printMsg("radio = %d\n", rx_stat[i].radio);
4801         printMsg("on time = %d\n", rx_stat[i].on_time);
4802         printMsg("tx time = %d\n", rx_stat[i].tx_time);
4803         printMsg("num_tx_levels = %d\n", rx_stat[i].num_tx_levels);
4804         printMsg("rx time = %d\n", rx_stat[i].rx_time);
4805         printMsg("SCAN\n");
4806         printMsg("on_time_scan(duration)= %d\n", rx_stat[i].on_time_scan);
4807         printMsg("on_time_nbd(duration)= %d\n", rx_stat[i].on_time_nbd);
4808         printMsg("on_time_gscan(duration)= %d\n", rx_stat[i].on_time_gscan);
4809         printMsg("on_time_roam_scan(duration)= %d\n", rx_stat[i].on_time_roam_scan);
4810         printMsg("on_time_pno_scan(duration)= %d\n", rx_stat[i].on_time_pno_scan);
4811         printMsg("on_time_hs20 = %d\n", rx_stat[i].on_time_hs20);
4812         printMsg("cca channel statistics: (num_channels: %d)\n", rx_stat[i].num_channels);
4813         for (int j = new_chan_base; j < (new_chan_base + rx_stat[i].num_channels); j++) {
4814             printMsg("center_freq=%d (%8s), radio_on_time %10d, cca_busytime %10d\n",
4815                 cca_stat[j].channel.center_freq,
4816                 frequency_to_channel(cca_stat[j].channel.center_freq),
4817                 cca_stat[j].on_time, cca_stat[j].cca_busy_time);
4818         }
4819         new_chan_base += rx_stat[i].num_channels;
4820     }
4821     printMsg("\n");
4822     if (num_rate == NUM_EHT_RATES) {
4823         printMsg("(current BSS info: %s, %dMhz)\n",
4824             rate_stat_preamble[eht_rate_stat[RATE_SPEC_CHECK_INDEX].rate.preamble],
4825             rate_stat_bandwidth[eht_rate_stat[RATE_SPEC_CHECK_INDEX].rate.bw]);
4826     } else if (num_rate == NUM_RATES) {
4827         printMsg("(current BSS info: %s, %dMhz)\n",
4828             rate_stat_preamble[rate_stat[RATE_SPEC_CHECK_INDEX].rate.preamble],
4829             rate_stat_bandwidth[rate_stat[RATE_SPEC_CHECK_INDEX].rate.bw]);
4830     } else {
4831         printMsg("No peer found!");
4832         return;
4833     }
4834     printMsg("Printing rate statistics: num_rate %d", num_rate);
4835     printMsg("--------------------------------------\n");
4836     printMsg("%40s %12s %14s %15s\n", "TX",  "RX", "LOST", "RETRIES");
4837     for (int i=0; i < num_rate; i++) {
4838         if (num_rate == NUM_EHT_RATES) {
4839             printMsg("%-28s  %10d   %10d     %10d      %10d\n",
4840                 eht_rates[i], eht_rate_stat[i].tx_mpdu, eht_rate_stat[i].rx_mpdu,
4841                 eht_rate_stat[i].mpdu_lost, eht_rate_stat[i].retries);
4842         } else if (num_rate == NUM_RATES) {
4843             printMsg("%-28s  %10d   %10d     %10d      %10d\n",
4844                 rates[i], rate_stat[i].tx_mpdu, rate_stat[i].rx_mpdu,
4845                 rate_stat[i].mpdu_lost, rate_stat[i].retries);
4846         }
4847     }
4848 }
4849 
getLinkStats(void)4850 void getLinkStats(void)
4851 {
4852     wifi_stats_result_handler handler;
4853     memset(&handler, 0, sizeof(handler));
4854 
4855     handler.on_link_stats_results = &onLinkStatsResults;
4856     handler.on_multi_link_stats_results = &onMultiLinkStatsResults;
4857 
4858     int result = hal_fn.wifi_get_link_stats(0, wlan0Handle, handler);
4859     if (result < 0) {
4860         printMsg("failed to get link stat - %d\n", result);
4861     } else if (!radios) {
4862         printMsg("Invalid link stat data\n");
4863     } else if (ml_links) {
4864         printMultiLinkStats(cca_stat, rx_stat, radios);
4865     } else {
4866         printLinkStats(&link_stat, cca_stat, rx_stat, &bssload, radios);
4867     }
4868 }
4869 
getChannelList(void)4870 void getChannelList(void)
4871 {
4872     wifi_channel channel[MAX_CH_BUF_SIZE] =  {0, };
4873     int num_channels = 0, i = 0;
4874 
4875     if (ifHandle == NULL) {
4876         printMsg("-iface <> is mandatory\n");
4877         return;
4878     }
4879 
4880     int result = hal_fn.wifi_get_valid_channels(ifHandle, band, MAX_CH_BUF_SIZE,
4881             channel, &num_channels);
4882     if (result < 0) {
4883         printMsg("failed to get valid channels %d\n", result);
4884         return;
4885     }
4886     printMsg("Number of channels - %d\nChannel List:\n",num_channels);
4887     for (i = 0; i < num_channels; i++) {
4888         printMsg("%d MHz\n", channel[i]);
4889     }
4890 }
4891 
getFeatureSet(void)4892 void getFeatureSet(void)
4893 {
4894     feature_set set;
4895     int result = hal_fn.wifi_get_supported_feature_set(wlan0Handle, &set);
4896 
4897     if (result < 0) {
4898         printMsg("Error %d\n", result);
4899         return;
4900     }
4901     printFeatureListBitMask();
4902     printMsg("Supported feature set bit mask - %lx\n", set);
4903     return;
4904 }
4905 
getFeatureSetMatrix(void)4906 void getFeatureSetMatrix(void)
4907 {
4908     feature_set set[MAX_FEATURE_SET];
4909     int size;
4910 
4911     int result = hal_fn.wifi_get_concurrency_matrix(wlan0Handle, MAX_FEATURE_SET, set, &size);
4912 
4913     if (result < 0) {
4914         printMsg("Error %d\n",result);
4915         return;
4916     }
4917     printFeatureListBitMask();
4918     for (int i = 0; i < size; i++)
4919         printMsg("Concurrent feature set - %lx\n", set[i]);
4920     return;
4921 }
4922 
getSupportedRadioMatrix(void)4923 void getSupportedRadioMatrix(void)
4924 {
4925     wifi_radio_combination_matrix *radio_matrix;
4926     u32 size, max_size = 0;
4927     int result;
4928 
4929     max_size = sizeof(wifi_radio_combination_matrix) +
4930         MAX_RADIO_COMBO*(sizeof(wifi_radio_combination) +
4931         MAX_CORE * sizeof(wifi_radio_configuration));
4932 
4933     radio_matrix = (wifi_radio_combination_matrix*)malloc(max_size);
4934     if (!radio_matrix) {
4935         printMsg("%s:Malloc failed\n",__FUNCTION__);
4936         return;
4937     }
4938     memset(radio_matrix, 0 , max_size);
4939 
4940     result = hal_fn.wifi_get_supported_radio_combinations_matrix(halHandle,
4941         max_size, &size, radio_matrix);
4942     if (!radio_matrix || !size || result < 0) {
4943         printMsg("Error %d\n", result);
4944         goto free_mem;
4945     }
4946 
4947     printRadioComboMatrix(radio_matrix);
4948 
4949 free_mem:
4950     if (radio_matrix) {
4951         free(radio_matrix);
4952     }
4953 
4954     return;
4955 }
4956 
getWakeStats()4957 int getWakeStats()
4958 {
4959     WLAN_DRIVER_WAKE_REASON_CNT *wake_reason_cnt;
4960 
4961     wake_reason_cnt = (WLAN_DRIVER_WAKE_REASON_CNT*) malloc(sizeof(WLAN_DRIVER_WAKE_REASON_CNT));
4962     if (!wake_reason_cnt) {
4963         printMsg("%s:Malloc failed\n",__FUNCTION__);
4964         return WIFI_ERROR_OUT_OF_MEMORY;
4965     }
4966     memset(wake_reason_cnt, 0 , sizeof(WLAN_DRIVER_WAKE_REASON_CNT));
4967 
4968     wake_reason_cnt->cmd_event_wake_cnt_sz = EVENT_COUNT;
4969     wake_reason_cnt->cmd_event_wake_cnt = (int*)malloc(EVENT_COUNT * sizeof(int));
4970     if (!wake_reason_cnt->cmd_event_wake_cnt) {
4971         printMsg("%s:Malloc failed\n",__FUNCTION__);
4972         free(wake_reason_cnt);
4973         return WIFI_ERROR_OUT_OF_MEMORY;
4974     }
4975     memset(wake_reason_cnt->cmd_event_wake_cnt, 0 , EVENT_COUNT * sizeof(int));
4976 
4977     int result = hal_fn.wifi_get_wake_reason_stats(wlan0Handle, wake_reason_cnt);
4978     if (result < 0) {
4979         printMsg("Error %d\n",result);
4980         free(wake_reason_cnt->cmd_event_wake_cnt);
4981         free(wake_reason_cnt);
4982         return WIFI_ERROR_NOT_SUPPORTED;
4983     }
4984 
4985     printMsg(" ------- DRIVER WAKE REASON STATS -------\n");
4986     printMsg("TotalCmdWake = %d\n", wake_reason_cnt->total_cmd_event_wake);
4987     printMsg("MaxCmdEvent  = %d\n", wake_reason_cnt->cmd_event_wake_cnt_sz);
4988     printMsg("MaxCmdEventUsed = %d\n", wake_reason_cnt->cmd_event_wake_cnt_used);
4989     printMsg("-----------------------------------------------------------\n");
4990     printMsg("TotalRxDataWake = %d\n", wake_reason_cnt->total_rx_data_wake);
4991     printMsg("RxUniCnt = %d\n", wake_reason_cnt->rx_wake_details.rx_unicast_cnt);
4992     printMsg("RxMultiCnt = %d\n", wake_reason_cnt->rx_wake_details.rx_multicast_cnt);
4993     printMsg("RxBcastCnt = %d\n", wake_reason_cnt->rx_wake_details.rx_broadcast_cnt);
4994     printMsg("-----------------------------------------------------------\n");
4995     printMsg("ICMP count = %d\n", wake_reason_cnt->rx_wake_pkt_classification_info.icmp_pkt);
4996     printMsg("ICMP6 count = %d\n", wake_reason_cnt->rx_wake_pkt_classification_info.icmp6_pkt);
4997     printMsg("ICMP6 ra count = %d\n", wake_reason_cnt->rx_wake_pkt_classification_info.icmp6_ra);
4998     printMsg("ICMP6 na count = %d\n", wake_reason_cnt->rx_wake_pkt_classification_info.icmp6_na);
4999     printMsg("ICMP6 ns count = %d\n", wake_reason_cnt->rx_wake_pkt_classification_info.icmp6_ns);
5000     printMsg("-----------------------------------------------------------\n");
5001     printMsg("Rx IPV4 Mcast  = %d\n", wake_reason_cnt->rx_multicast_wake_pkt_info.ipv4_rx_multicast_addr_cnt);
5002     printMsg("Rx IPV6 Mcast = %d\n", wake_reason_cnt->rx_multicast_wake_pkt_info.ipv6_rx_multicast_addr_cnt);
5003     printMsg("Rx Other Mcast = %d\n", wake_reason_cnt->rx_multicast_wake_pkt_info.other_rx_multicast_addr_cnt);
5004     printMsg("-----------------------------------------------------------\n");
5005     printMsg("Events Received and received count\n");
5006     for (int i = 0; i <= wake_reason_cnt->cmd_event_wake_cnt_used; i++) {
5007         if (wake_reason_cnt->cmd_event_wake_cnt[i] != 0)
5008             printMsg("Event ID %d = %u\n", i, wake_reason_cnt->cmd_event_wake_cnt[i]);
5009     }
5010 
5011     free(wake_reason_cnt->cmd_event_wake_cnt);
5012     free(wake_reason_cnt);
5013     return WIFI_SUCCESS;
5014 }
5015 
setBlacklist(bool clear)5016 static wifi_error setBlacklist(bool clear)
5017 {
5018     if (num_blacklist_bssids == -1 && !clear)
5019         return WIFI_SUCCESS;
5020     wifi_roaming_config roam_config;
5021     cmdId = getNewCmdId();
5022     if (clear) {
5023         roam_config.num_blacklist_bssid = 0;
5024         printMsg("Clear Blacklist BSSIDs\n");
5025     } else {
5026         roam_config.num_blacklist_bssid = num_blacklist_bssids;
5027         printMsg("Setting %d Blacklist BSSIDs\n", num_blacklist_bssids);
5028     }
5029     for (int i = 0; i < num_blacklist_bssids; i++) {
5030         memcpy(&roam_config.blacklist_bssid[i], &blacklist_bssids[i],
5031         sizeof(mac_addr) );
5032     }
5033     return  hal_fn.wifi_configure_roaming(wlan0Handle, &roam_config);
5034 }
5035 
setRoamingConfiguration()5036 static wifi_error setRoamingConfiguration()
5037 {
5038     wifi_error ret;
5039     wifi_roaming_config roam_config;
5040     cmdId = getNewCmdId();
5041 
5042     roam_config.num_blacklist_bssid = num_blacklist_bssids;
5043     roam_config.num_whitelist_ssid = num_whitelist_ssids;
5044     if(num_blacklist_bssids != -1) {
5045         for (int i = 0; i < num_blacklist_bssids; i++) {
5046             memcpy(&roam_config.blacklist_bssid[i], &blacklist_bssids[i], sizeof(mac_addr) );
5047         }
5048     }
5049 
5050     if(num_whitelist_ssids != -1) {
5051         for (int j = 0; j < num_whitelist_ssids; j++) {
5052             printf("%s\n", whitelist_ssids[j]);
5053             strncpy(roam_config.whitelist_ssid[j].ssid_str, whitelist_ssids[j], (MAX_SSID_LENGTH - 1));
5054             roam_config.whitelist_ssid[j].ssid_str[MAX_SSID_LENGTH - 1] = '\0';
5055             roam_config.whitelist_ssid[j].length =
5056                 strlen(roam_config.whitelist_ssid[j].ssid_str);
5057         }
5058     }
5059 
5060     ret = hal_fn.wifi_configure_roaming(wlan0Handle, &roam_config);
5061 
5062     return ret;
5063 }
5064 
getRoamingCapabilities(char * argv[])5065 static wifi_error getRoamingCapabilities(char *argv[])
5066 {
5067     wifi_error ret;
5068     wifi_roaming_capabilities roam_capability;
5069     char *param, *val_p;
5070 
5071     /* skip utility */
5072     argv++;
5073     /* skip command */
5074     argv++;
5075 
5076     while ((param = *argv++) != NULL) {
5077         val_p = *argv++;
5078         if (!val_p || *val_p == '-') {
5079             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
5080             ret = WIFI_ERROR_NOT_SUPPORTED;
5081             goto exit;
5082         }
5083         if (strcmp(param, "-iface") == 0) {
5084             ifHandle = wifi_get_iface_handle_by_iface_name(val_p);
5085         } else {
5086             printMsg("%s:Unsupported Param to get roaming capabilites request\n", __FUNCTION__);
5087             ret = WIFI_ERROR_INVALID_ARGS;
5088             goto exit;
5089         }
5090     }
5091 
5092     if (ifHandle == NULL) {
5093         printMsg("-iface <> is mandatory\n");
5094         ret = WIFI_ERROR_INVALID_ARGS;
5095         goto exit;
5096     }
5097 
5098     ret = hal_fn.wifi_get_roaming_capabilities(ifHandle, &roam_capability);
5099     if (ret == WIFI_SUCCESS) {
5100         printMsg("Roaming Capabilities\n"
5101             "max_blacklist_size = %d\n"
5102             "max_whitelist_size = %d\n", roam_capability.max_blacklist_size,
5103             roam_capability.max_whitelist_size);
5104     } else {
5105         printMsg("Failed to get Roaming capabilities\n");
5106     }
5107 exit:
5108     return ret;
5109 }
5110 
setFWRoamingState(fw_roaming_state_t state)5111 static wifi_error setFWRoamingState(fw_roaming_state_t state)
5112 {
5113     wifi_error ret = WIFI_SUCCESS;
5114     ret = hal_fn.wifi_enable_firmware_roaming(wlan0Handle,
5115             state);
5116     if (ret != WIFI_SUCCESS) {
5117         printMsg("Failed to set Firmware Roaming state %d\n", state);
5118     }
5119 
5120     return ret;
5121 }
5122 
testRssiMonitor()5123 static void testRssiMonitor()
5124 {
5125     int id = -1;
5126     wifi_rssi_event_handler handler;
5127     EventInfo info;
5128     handler.on_rssi_threshold_breached = onRssiThresholdbreached;
5129     if (rssi_monitor) {
5130         rssiMonId = getNewCmdId();
5131         wifi_error ret = hal_fn.wifi_start_rssi_monitoring(rssiMonId, wlan0Handle,
5132                     max_rssi, min_rssi, handler);
5133         if (ret != WIFI_SUCCESS) {
5134             printMsg("Failed to set RSSI monitor %d\n", ret);
5135             return;
5136         }
5137         printMsg("rssi_monitor: %d %d %d %d\n", rssi_monitor, max_rssi, min_rssi,rssiMonId);
5138         while (true) {
5139             memset(&info, 0, sizeof(info));
5140             getEventFromCache(info);
5141             if (info.type == EVENT_TYPE_RSSI_MONITOR) {
5142                 printMsg("done!!\n");
5143                 break;
5144             }
5145         }
5146     } else {
5147         if (rssiMonId == 0)
5148             id = -1;
5149         hal_fn.wifi_stop_rssi_monitoring(id, wlan0Handle);
5150     }
5151     return;
5152 }
5153 
setApfProgram(char * str,wifi_interface_handle ifHandle)5154 static wifi_error setApfProgram(char *str, wifi_interface_handle ifHandle)
5155 {
5156     u32 program_len;
5157     u8* program;
5158     wifi_error ret;
5159 
5160     if (str == NULL) {
5161         printMsg("APF program missing\n");
5162         printApfUsage();
5163         return WIFI_ERROR_UNINITIALIZED;
5164     }
5165 
5166     if (strncmp(str, "0x", 2) == 0 || strncmp(str, "0X", 2) == 0) {
5167         str = str + 2; /* Skip past 0x */
5168     }
5169     program_len = (strlen((const char *)str) / 2);
5170     program = (u8 *)malloc(program_len);
5171     if (!program) {
5172         printMsg("Memory allocation failed\n");
5173         return WIFI_ERROR_OUT_OF_MEMORY;
5174     }
5175 
5176     if ((u32)str2hex(str, (char *)program) != program_len) {
5177         printMsg("Invalid APF program\n");
5178         if (program) {
5179             free(program);
5180         }
5181         return WIFI_ERROR_INVALID_ARGS;
5182     }
5183 
5184     ret = hal_fn.wifi_set_packet_filter(ifHandle, program, program_len);
5185     if (ret != WIFI_SUCCESS) {
5186         if (program) {
5187             free(program);
5188         }
5189         printMsg("Failed to set APF program, ret = %d\n", ret);
5190         return WIFI_ERROR_NOT_SUPPORTED;
5191     }
5192 
5193     if (program) {
5194         free(program);
5195     }
5196 
5197     return ret;
5198 }
5199 
getApfCapabilities(wifi_interface_handle ifHandle)5200 static wifi_error getApfCapabilities(wifi_interface_handle ifHandle)
5201 {
5202     u32 version, max_len;
5203 
5204     wifi_error ret = hal_fn.wifi_get_packet_filter_capabilities(ifHandle,
5205         &version, &max_len);
5206     if (ret != WIFI_SUCCESS) {
5207         printMsg("Failed to get APF capability, ret = %d\n", ret);
5208         return WIFI_ERROR_NOT_SUPPORTED;
5209     }
5210     printMsg("APF capabilities, version = %u, max_len = %u bytes\n",
5211         version, max_len);
5212     return WIFI_SUCCESS;
5213 }
5214 
getApfFilterData(wifi_interface_handle ifHandle)5215 static wifi_error getApfFilterData(wifi_interface_handle ifHandle)
5216 {
5217     u8 *buf, *pc;
5218     u32 version, max_len, i;
5219     wifi_error ret;
5220 
5221     ret = hal_fn.wifi_get_packet_filter_capabilities(ifHandle,
5222             &version, &max_len);
5223     if (ret != WIFI_SUCCESS) {
5224         printMsg("Failed to get APF buffer size, ret = %d\n", ret);
5225         return WIFI_ERROR_NOT_SUPPORTED;
5226     }
5227 
5228     buf = (u8 *)malloc(max_len);
5229     if (!buf) {
5230         printMsg("Memory allocation failed\n");
5231         return WIFI_ERROR_OUT_OF_MEMORY;
5232     }
5233 
5234     ret = hal_fn.wifi_read_packet_filter(ifHandle, 0, buf, max_len);
5235     if (ret != WIFI_SUCCESS) {
5236         if (buf) {
5237             free(buf);
5238         }
5239         printMsg("Failed to get APF buffer dump, ret = %d\n", ret);
5240         return WIFI_ERROR_NOT_SUPPORTED;
5241     }
5242     printMsg("\nAPF buffer size = %u (0x%x) bytes\n\n", max_len, max_len);
5243     printMsg("APF buffer data =\n\n");
5244     for (i = 1, pc = buf; pc && (i <= max_len); pc++, i++) {
5245        printf("%02X", *pc);
5246        if (i && ((i % 64) == 0)) {
5247            printf("\n");
5248        }
5249     }
5250     printf("\n");
5251 
5252     if (buf) {
5253         free(buf);
5254     }
5255     return WIFI_SUCCESS;
5256 }
5257 
testApfOptions(int argc,char * argv[])5258 int testApfOptions(int argc, char *argv[])
5259 {
5260     void printApfUsage();          // declaration for below printUsage()
5261     /* Interface name */
5262     char iface_name[IFNAMSIZ+1];
5263     char *val_p = NULL;
5264     wifi_error ret;
5265     wifi_interface_handle ifHandle = NULL;
5266 
5267     memset(iface_name, 0, sizeof(iface_name));
5268 
5269     argv++; /* skip utility */
5270     argv++; /* skip -apf command */
5271 
5272     val_p = *argv++;
5273     if (val_p != NULL) {
5274         if (!set_interface_params(iface_name, val_p, (IFNAMSIZ - 1))) {
5275             printMsg("set interface name successfull\n");
5276         } else {
5277             printMsg("Invalid  iface name\n");
5278             ret = WIFI_ERROR_INVALID_ARGS;
5279             goto usage;
5280         }
5281     } else {
5282         printMsg("argv is null\n");
5283         ret = WIFI_ERROR_INVALID_ARGS;
5284         goto usage;
5285     }
5286 
5287     ifHandle = wifi_get_iface_handle(halHandle, iface_name);
5288     if (ifHandle == NULL) {
5289         printMsg("Invalid iface handle for the requested interface\n");
5290         ret = WIFI_ERROR_INVALID_ARGS;
5291         goto usage;
5292     } else {
5293         while ((val_p = *argv++) != NULL) {
5294             if (strcmp(val_p, "-set") == 0) {
5295                 val_p = *argv++;
5296                 if (strcmp(val_p, "program") == 0) {
5297                     val_p = *argv++;
5298                     printMsg("program = %s\n\n", val_p);
5299                     printMsg("set program capa: Iface handle = %p for the requested interface: %s\n",
5300                         ifHandle, iface_name);
5301                     if (ifHandle) {
5302                        ret = setApfProgram(val_p, ifHandle);
5303                     }
5304                 } else {
5305                     printMsg("Invalid value after program arg\n");
5306                     ret = WIFI_ERROR_INVALID_ARGS;
5307                     goto usage;
5308                 }
5309             } else if (strcmp(val_p, "-get") == 0) {
5310                 val_p = *argv++;
5311                 if (strcmp(val_p, "capa") == 0) {
5312                     printMsg("get capa: Iface handle = %p for the requested interface: %s\n",
5313                         ifHandle, iface_name);
5314                     if (ifHandle) {
5315                         ret = getApfCapabilities(ifHandle);
5316                     }
5317                 } else if (strcmp(val_p, "data") == 0) {
5318                     printMsg("get data: Iface handle = %p for the requested interface: %s\n",
5319                         ifHandle, iface_name);
5320                     if (ifHandle) {
5321                         ret = getApfFilterData(ifHandle);
5322                     }
5323                 } else {
5324                     printMsg("Invalid value for get cmd\n");
5325                     ret = WIFI_ERROR_INVALID_ARGS;
5326                     goto usage;
5327                 }
5328             } else {
5329                 printMsg("Invalid option for apf cmd\n");
5330                 ret = WIFI_ERROR_INVALID_ARGS;
5331                 goto usage;
5332             }
5333         }
5334     }
5335 
5336 usage:
5337     printApfUsage();
5338     return WIFI_ERROR_INVALID_ARGS;
5339 }
5340 
setDscpMap(s32 start,s32 end,s32 ac)5341 static int setDscpMap(s32 start, s32 end, s32 ac)
5342 {
5343     void printUsage();          // declaration for below printUsage()
5344     int ret;
5345 
5346     if (start == -1 || end == -1 || ac == -1) {
5347         printMsg("DSCP param missing\n");
5348         printUsage();
5349         return WIFI_ERROR_UNINITIALIZED;
5350     }
5351 
5352     ret = hal_fn.wifi_map_dscp_access_category(halHandle, start, end, ac);
5353     if (ret != WIFI_SUCCESS) {
5354         printMsg("Failed to set DSCP: %d\n", ret);
5355         return WIFI_ERROR_UNKNOWN;
5356     }
5357     return WIFI_SUCCESS;
5358 }
5359 
resetDscpMap()5360 static int resetDscpMap()
5361 {
5362     int ret;
5363 
5364     ret = hal_fn.wifi_reset_dscp_mapping(halHandle);
5365     if (ret != WIFI_SUCCESS) {
5366         printMsg("Failed to reset DSCP: %d\n", ret);
5367         return WIFI_ERROR_UNKNOWN;
5368     }
5369     return WIFI_SUCCESS;
5370 }
5371 
setChannelAvoidance(u32 num,wifi_coex_unsafe_channel configs[],u32 mandatory)5372 static int setChannelAvoidance(u32 num, wifi_coex_unsafe_channel configs[], u32 mandatory)
5373 {
5374     int ret;
5375 
5376     ret = hal_fn.wifi_set_coex_unsafe_channels(halHandle, num, configs, mandatory);
5377     if (ret != WIFI_SUCCESS) {
5378         printMsg("Failed to set Channel Avoidance: %d\n", ret);
5379         return WIFI_ERROR_UNKNOWN;
5380     }
5381     return WIFI_SUCCESS;
5382 }
5383 
testSarOptions(int argc,char * argv[])5384 void testSarOptions(int argc, char *argv[])
5385 {
5386     void printUsage();          // declaration for below printUsage()
5387     wifi_power_scenario mWifi_power_scenario;
5388     wifi_error res;
5389     int scenario;
5390 
5391     if (argc < 2) {
5392         goto usage;
5393     }
5394 
5395     if ((argc > 2) && (strcmp(argv[1], "enable") == 0)) {
5396         scenario = atoi(argv[2]);
5397         if ((scenario < WIFI_POWER_SCENARIO_INVALID) || (scenario > SAR_CONFIG_SCENARIO_COUNT)) {
5398             printMsg("Unsupported tx power value:%d: Allowed range -1 to 99\n", scenario);
5399             return;
5400         }
5401         mWifi_power_scenario = (wifi_power_scenario)scenario;
5402         res = hal_fn.wifi_select_tx_power_scenario(wlan0Handle, mWifi_power_scenario);
5403     } else if ((strcmp(argv[1], "disable") == 0)) {
5404         res = hal_fn.wifi_reset_tx_power_scenario(wlan0Handle);
5405     } else {
5406         goto usage;
5407     }
5408 
5409     if (res == WIFI_SUCCESS) {
5410         printMsg("Success to execute sar test command\n");
5411     } else {
5412         printMsg("Failed to execute sar test command, res = %d\n", res);
5413     }
5414     return;
5415 
5416 usage:
5417     printUsage();
5418     return;
5419 }
5420 
testThermalMitigationOptions(int argc,char * argv[])5421 void testThermalMitigationOptions(int argc, char *argv[])
5422 {
5423   void printUsage();  //declaration for below printUsage()
5424   wifi_thermal_mode mode;
5425   wifi_error result;
5426 
5427   if (argc < 2) {
5428       goto usage;
5429   }
5430 
5431   if (strcmp(argv[1], "none") == 0) {
5432       mode = WIFI_MITIGATION_NONE;
5433   } else if (strcmp(argv[1], "light") == 0) {
5434       mode = WIFI_MITIGATION_LIGHT;
5435   } else if (strcmp(argv[1], "moderate") == 0) {
5436       mode = WIFI_MITIGATION_MODERATE;
5437   } else if (strcmp(argv[1], "severe") == 0) {
5438       mode = WIFI_MITIGATION_SEVERE;
5439   } else if (strcmp(argv[1], "critical") == 0) {
5440       mode = WIFI_MITIGATION_CRITICAL;
5441   } else if (strcmp(argv[1], "emergency") == 0) {
5442       mode = WIFI_MITIGATION_EMERGENCY;
5443   } else {
5444       printMsg("unknown thermal mode %s\n", argv[1]);
5445       goto usage;
5446   }
5447 
5448   result = hal_fn.wifi_set_thermal_mitigation_mode(halHandle, mode, 0);
5449   if (result == WIFI_ERROR_NONE) {
5450       printMsg("Success set thermal mode\n");
5451   } else {
5452       printMsg("Failed set thermal mode, result = %d\n", result);
5453   }
5454   return;
5455 
5456 usage:
5457   printUsage();
5458 }
5459 
testLatencyModeOptions(int argc,char * argv[])5460 void testLatencyModeOptions(int argc, char *argv[])
5461 {
5462     void printUsage();          // declaration for below printUsage()
5463     wifi_latency_mode mWifi_latency_mode;
5464     wifi_error res;
5465 
5466     if (argc < 2) {
5467         goto usage;
5468     }
5469 
5470     if (strcmp(argv[1], "normal") == 0) {
5471         mWifi_latency_mode = WIFI_LATENCY_MODE_NORMAL;
5472     } else if (strcmp(argv[1], "low") == 0) {
5473         mWifi_latency_mode = WIFI_LATENCY_MODE_LOW;
5474     } else if (strcmp(argv[1], "ultra-low") == 0) {
5475         mWifi_latency_mode = (wifi_latency_mode)2 ; //TODO: To be removed
5476     } else {
5477         goto usage;
5478     }
5479 
5480     res = hal_fn.wifi_set_latency_mode(wlan0Handle, mWifi_latency_mode);
5481     if (res == WIFI_SUCCESS) {
5482         printMsg("Success to execute set wifi latency mode test command\n");
5483     } else {
5484         printMsg("Failed to execute set wifi latency mode test command, res = %d\n", res);
5485     }
5486     return;
5487 
5488 usage:
5489     printUsage();
5490     return;
5491 }
5492 
testDscpOptions(int argc,char * argv[])5493 void testDscpOptions(int argc, char *argv[])
5494 {
5495     void printUsage();          // declaration for below printUsage()
5496     int j = 1;
5497     s32 start = -1;
5498     s32 end = -1;
5499     s32 ac = -1;
5500 
5501     if (argc < 3) {
5502         goto usage;
5503     }
5504 
5505     if ((strcmp(argv[j], "-reset") == 0) && (argc == 3)) {
5506         resetDscpMap();
5507     } else if ((strcmp(argv[j], "-set") == 0) && (argc == 9)) {
5508         if ((strcmp(argv[++j], "-s") == 0) && isdigit(argv[j+1][0]))
5509             start = atoi(argv[++j]);
5510         if ((strcmp(argv[++j], "-e") == 0) && isdigit(argv[j+1][0]))
5511             end = atoi(argv[++j]);
5512         if ((strcmp(argv[++j], "-ac") == 0) && isdigit(argv[j+1][0]))
5513             ac = atoi(argv[++j]);
5514         setDscpMap(start, end, ac);
5515     } else {
5516         goto usage;
5517     }
5518     return;
5519 
5520 usage:
5521     printUsage();
5522     return;
5523 }
5524 
printTxPowerUsage()5525 static void printTxPowerUsage() {
5526     printf("Usage: halutil [OPTION]\n");
5527     printf(" -tx_pwr_cap -enable\n");
5528     printf(" -tx_pwr_cap -disable\n");
5529     return;
5530 }
5531 
printApfUsage()5532 static void printApfUsage() {
5533     printf("Usage: halutil [OPTION]\n");
5534     printf(" -apf [-ifname] <interface name> [-get] [capa]\n");
5535     printf(" -apf [-ifname] <interface name> [-get] [data]\n");
5536     printf(" -apf [-ifname] <interface name> [-set] [program] <bytecodes>\n");
5537     return;
5538 }
5539 
printTwtUsage()5540 static void printTwtUsage() {
5541     printf("Usage: halutil [OPTION]\n");
5542     printf("halutil -twt -setup -iface <> -config_id <> -neg_type <0 for individual TWT, 1 for broadcast TWT> "
5543             "-trigger_type <0 for non-triggered TWT, 1 for triggered TWT> "
5544             "-wake_dur_us <> -wake_int_us <> -wake_int_min_us <> "
5545             "-wake_int_max_us <> -wake_dur_min_us <> -wake_dur_max_us <> "
5546             "-avg_pkt_size <> -avg_pkt_num <> -wake_time_off_us <>\n");
5547     printf("halutil -twt -info_frame -iface <> -config_id <>"
5548             " -all_twt <0 for individual setp request, 1 for all TWT> -resume_time_us <>\n");
5549     printf("halutil -twt -teardown -iface <> -config_id <> -all_twt <> "
5550             " -neg_type <0 for individual TWT, 1 for broadcast TWT>\n");
5551     printf("halutil -twt -get_stats -iface <> -config_id <>\n");
5552     printf("halutil -twt -clear_stats -iface <> -config_id <>\n");
5553     printf("halutil -get_capa_twt -iface <>\n");
5554     printf("halutil -twt -event_chk\n");
5555     return;
5556 }
5557 
printChreNanRttUsage()5558 static void printChreNanRttUsage() {
5559     printf("Usage: halutil [OPTION]\n");
5560     printf("halutil -chre_nan_rtt -enable\n");
5561     printf("halutil -chre_nan_rtt -disable\n");
5562     printf("halutil -chre -register\n");
5563     return;
5564 }
5565 
5566 void
bandstr_to_macband(char * band_str,wlan_mac_band * band)5567 bandstr_to_macband(char *band_str, wlan_mac_band *band)
5568 {
5569     if (!strcasecmp(band_str, "a")) {
5570         *band = WLAN_MAC_5_0_BAND;
5571     } else if (!strcasecmp(band_str, "b")) {
5572         *band = WLAN_MAC_2_4_BAND;
5573     } else if (!strcasecmp(band_str, "6g")) {
5574         *band = WLAN_MAC_6_0_BAND;
5575     } else if (!strcasecmp(band_str, "60")) {
5576         *band = WLAN_MAC_60_0_BAND;
5577     }
5578 }
5579 void
bandstr_to_band(char * band_str,u32 * band)5580 bandstr_to_band(char *band_str, u32 *band)
5581 {
5582    if (!strcasecmp(band_str, "a")) {
5583        *band = WIFI_BAND_A;
5584    } else if (!strcasecmp(band_str, "b")) {
5585        *band = WIFI_BAND_BG;
5586    } else if (!strcasecmp(band_str, "all")) {
5587        *band = WIFI_BAND_ABG;
5588    } else {
5589        *band = WIFI_BAND_UNSPECIFIED;
5590    }
5591 }
5592 
parse_unsafe(char * val_p,wifi_coex_unsafe_channel ca_configs[],int * idx)5593 void parse_unsafe(char *val_p, wifi_coex_unsafe_channel ca_configs[], int *idx)
5594 {
5595    char *space_end;
5596    char *comma_end;
5597    char *space = strtok_r(val_p, ":", &space_end);
5598    wlan_mac_band band;
5599    while (space != NULL) {
5600        char *token = strtok_r(space, ",", &comma_end);
5601        if (!token) {
5602            printf("Need 3 values\n");
5603            return;
5604        }
5605        bandstr_to_macband(token, &band);
5606        if (band != WLAN_MAC_2_4_BAND && band != WLAN_MAC_5_0_BAND) {
5607            printMsg("Unsupported band\n");
5608            return;
5609        }
5610        ca_configs[*idx].band = band;
5611        token = strtok_r(NULL, ",", &comma_end);
5612        if (!token) {
5613            printf("Need 3 values\n");
5614            return;
5615        }
5616        ca_configs[*idx].channel = atoi(token);
5617        token = strtok_r(NULL, ",", &comma_end);
5618        if (!token) {
5619            printf("Need 3 values\n");
5620            return;
5621        }
5622        ca_configs[*idx].power_cap_dbm = atoi(token);
5623 
5624        token = strtok_r(NULL, ",", &comma_end);
5625        if (token) {
5626            printf("Need only 3 values\n");
5627            return;
5628        }
5629        (*idx)++;
5630 
5631        space = strtok_r(NULL, ":", &space_end);
5632    }
5633 }
5634 
5635 
testChannelAvoidanceOptions(int argc,char * argv[])5636 void testChannelAvoidanceOptions(int argc, char *argv[])
5637 {
5638     char *param;
5639     char *val_p;
5640     wifi_coex_unsafe_channel ca_configs[MAX_CH_AVOID];
5641     u32 mandatory;
5642     int idx = 0;
5643     memset(ca_configs, 0, MAX_CH_AVOID * sizeof(wifi_coex_unsafe_channel));
5644 
5645     argv++;
5646 
5647     while ((param = *argv++) != NULL) {
5648         val_p = *argv++;
5649         if (!val_p || *val_p == '-') {
5650             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
5651             return;
5652         }
5653 
5654         if (!strncmp(param, "-unsafe", 7)) {
5655             parse_unsafe(val_p, ca_configs, &idx);
5656         } else if (!strncmp(param, "-m", 2)) {
5657             mandatory = atoi(val_p);
5658         }
5659     }
5660 
5661     for (int i=0; i<idx; i++) {
5662         printMsg("CONFIG  %d %d %d\n",
5663             ca_configs[i].band, ca_configs[i].channel, ca_configs[i].power_cap_dbm);
5664     }
5665 
5666     setChannelAvoidance(idx, ca_configs, mandatory);
5667     return;
5668 }
5669 
5670 void
bandstr_to_wlan_mac_band(char * band_str,u32 * band)5671 bandstr_to_wlan_mac_band(char *band_str, u32 *band)
5672 {
5673    if (!strcasecmp(band_str, "2g")) {
5674        *band = WLAN_MAC_2_4_BAND;
5675    } else if (!strcasecmp(band_str, "5g")) {
5676        *band = WLAN_MAC_5_0_BAND;
5677    } else if (!strcasecmp(band_str, "6g")) {
5678        *band = WLAN_MAC_6_0_BAND;
5679    }
5680 }
5681 
5682 void
ifacestr_to_wifi_interface_mode(char * iface_str,wifi_interface_mode * mode)5683 ifacestr_to_wifi_interface_mode(char *iface_str, wifi_interface_mode *mode)
5684 {
5685    if (!strcasecmp(iface_str, "sta")) {
5686        *mode = WIFI_INTERFACE_STA;
5687    } else if (!strcasecmp(iface_str, "softap")) {
5688        *mode = WIFI_INTERFACE_SOFTAP;
5689    } else if (!strcasecmp(iface_str, "ibss")) {
5690        *mode = WIFI_INTERFACE_IBSS;
5691    } else if (!strcasecmp(iface_str, "p2p_cli")) {
5692        *mode = WIFI_INTERFACE_P2P_CLIENT;
5693    } else if (!strcasecmp(iface_str, "p2p_go")) {
5694        *mode = WIFI_INTERFACE_P2P_GO;
5695    } else if (!strcasecmp(iface_str, "nan")) {
5696        *mode = WIFI_INTERFACE_NAN;
5697    } else if (!strcasecmp(iface_str, "mesh")) {
5698        *mode = WIFI_INTERFACE_MESH;
5699    } else if (!strcasecmp(iface_str, "tdls")) {
5700        *mode = WIFI_INTERFACE_TDLS;
5701    } else {
5702        printMsg("Incorrect iface type."
5703            " ex: sta/softap/ibss/p2p_cli/p2p_go/nan/mesh/tdls\n");
5704        *mode = WIFI_INTERFACE_UNKNOWN;
5705    }
5706 }
5707 
usable_channel_parse_band(char * val_p)5708 u32 usable_channel_parse_band(char *val_p)
5709 {
5710     char *delim_end;
5711     char *delim = strtok_r(val_p, ",", &delim_end);
5712     u32 band;
5713     u32 band_mask = 0;
5714     while (delim != NULL) {
5715         band = 0;
5716         bandstr_to_wlan_mac_band(delim, &band);
5717         if (band) {
5718             band_mask |= band;
5719         }
5720         delim = strtok_r(NULL, ",", &delim_end);
5721     }
5722     return band_mask;
5723 }
5724 
usable_channel_parse_iface(char * val_p)5725 u32 usable_channel_parse_iface(char *val_p)
5726 {
5727     char *delim_end;
5728     char *delim = strtok_r(val_p, ",", &delim_end);
5729     wifi_interface_mode iface_mode = WIFI_INTERFACE_UNKNOWN;
5730     u32 iface_mode_mask = 0;
5731 
5732     while (delim != NULL) {
5733         ifacestr_to_wifi_interface_mode(delim, &iface_mode);
5734         if (iface_mode != WIFI_INTERFACE_UNKNOWN) {
5735             iface_mode_mask |= (1 << iface_mode);
5736             delim = strtok_r(NULL, ",", &delim_end);
5737         }
5738     }
5739     return iface_mode_mask;
5740 }
5741 
testUsableChannelOptions(int argc,char * argv[])5742 static wifi_error testUsableChannelOptions(int argc, char *argv[])
5743 {
5744     char *param;
5745     char *val_p;
5746     u32 band_mask = 0;
5747     u32 iface_mode_mask = 0;
5748     u32 filter_mask = 0;
5749     u32 max_size = 0;
5750     u32 size = 0;
5751     wifi_error ret;
5752     wifi_usable_channel* channels = NULL;
5753 
5754     argv++;
5755 
5756     while ((param = *argv++) != NULL) {
5757         val_p = *argv++;
5758         if (!val_p || *val_p == '-') {
5759             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
5760             return WIFI_ERROR_INVALID_ARGS;
5761         }
5762 
5763         if (!strncmp(param, "-b", 2)) {
5764             band_mask = usable_channel_parse_band(val_p);
5765         } else if (!strncmp(param, "-i", 2)) {
5766             iface_mode_mask = usable_channel_parse_iface(val_p);
5767         } else if (!strncmp(param, "-f", 2)) {
5768             filter_mask = atoi(val_p);
5769         } else if (!strncmp(param, "-m", 2)) {
5770             max_size = atoi(val_p);
5771         }
5772     }
5773 
5774     if ((max_size == 0) || (max_size > MAX_WIFI_USABLE_CHANNELS)) {
5775         printMsg("Max size should be non-zero and less than MAX_WIFI_USABLE_CHANNELS\n");
5776         return WIFI_ERROR_INVALID_ARGS;
5777     }
5778 
5779     if (band_mask == 0) {
5780         printMsg("Band mask should be bigger than 0\n");
5781         return WIFI_ERROR_INVALID_ARGS;
5782     }
5783     printMsg("Usable channel param BAND:%d IFACE:%d FILTER:%d MAX_SIZE:%d\n", band_mask, iface_mode_mask, filter_mask, max_size);
5784 
5785     channels = (wifi_usable_channel *)malloc(sizeof(wifi_usable_channel) * max_size);
5786     if (!channels) {
5787         printMsg("Failed to alloc channels\n");
5788         return WIFI_ERROR_OUT_OF_MEMORY;
5789     }
5790 
5791     memset(channels, 0, sizeof(wifi_usable_channel) * max_size);
5792 
5793     printMsg("Call wifi_get_usable_channels\n");
5794     ret = hal_fn.wifi_get_usable_channels(halHandle, band_mask, iface_mode_mask, filter_mask, max_size, &size, channels);
5795     if (ret == WIFI_SUCCESS) {
5796         printMsg("Usable channel success: size:%d max_size:%d\n", size, max_size);
5797 
5798         for (unsigned int i=0; i < size; i++) {
5799             printMsg("[%d] freq=%d, width=%d(%s), iface=%d ",
5800                     i+1, channels[i].freq, channels[i].width,
5801                     RBchanWidthToString(channels[i].width), channels[i].iface_mode_mask);
5802             if (channels[i].iface_mode_mask & (1 << WIFI_INTERFACE_STA)) {
5803                 printMsg("STA ");
5804             }
5805             if (channels[i].iface_mode_mask & (1 << WIFI_INTERFACE_SOFTAP)) {
5806                 printMsg("SOFTAP ");
5807             }
5808             if (channels[i].iface_mode_mask & (1 << WIFI_INTERFACE_IBSS)) {
5809                 printMsg("IBSS ");
5810             }
5811             if (channels[i].iface_mode_mask & (1 << WIFI_INTERFACE_P2P_CLIENT)) {
5812                 printMsg("P2P_CLI ");
5813             }
5814             if (channels[i].iface_mode_mask & (1 << WIFI_INTERFACE_P2P_GO)) {
5815                 printMsg("P2P_GO ");
5816             }
5817             if (channels[i].iface_mode_mask & (1 << WIFI_INTERFACE_NAN)) {
5818                 printMsg("NAN ");
5819             }
5820             if (channels[i].iface_mode_mask & (1 << WIFI_INTERFACE_MESH)) {
5821                 printMsg("MESH ");
5822             }
5823             if (channels[i].iface_mode_mask & (1 << WIFI_INTERFACE_TDLS)) {
5824                 printMsg("TDLS ");
5825             }
5826             printMsg("\n");
5827         }
5828     } else {
5829         printMsg("Failed to get usable channels\n");
5830     }
5831 
5832     free(channels);
5833 
5834     return ret;
5835 }
5836 
testTxPowerLimitOptions(int argc,char * argv[])5837 void testTxPowerLimitOptions(int argc, char *argv[])
5838 {
5839     void printUsage();          // declaration for below printUsage()
5840     wifi_error res;
5841 
5842     if (argc < 2) {
5843         goto usage;
5844     }
5845 
5846     if ((strcmp(argv[1], "-enable") == 0)) {
5847         res = hal_fn.wifi_enable_tx_power_limits(wlan0Handle, true);
5848     } else if ((strcmp(argv[1], "-disable") == 0)) {
5849         res = hal_fn.wifi_enable_tx_power_limits(wlan0Handle, false);
5850     } else {
5851         goto usage;
5852     }
5853 
5854     if (res == WIFI_SUCCESS) {
5855         printMsg("Success to execute tx power limit command\n");
5856     } else {
5857         printMsg("Failed to execute tx power limit command, res = %d\n", res);
5858     }
5859     return;
5860 
5861 usage:
5862     printUsage();
5863     return;
5864 }
5865 
printUsage()5866 void printUsage() {
5867     printf("Usage:  halutil [OPTION]\n");
5868     printf(" -v               print version\n");
5869     printf(" -s               start AP scan test\n");
5870     printf(" -swc             start Significant Wifi change test\n");
5871     printf(" -h               start Hotlist APs scan test\n");
5872     printf(" -ss              stop scan test\n");
5873     printf(" -max_ap          Max AP for scan \n");
5874     printf(" -base_period     Base period for scan \n");
5875     printf(" -threshold       Threshold scan test\n");
5876     printf(" -avg_RSSI        samples for averaging RSSI\n");
5877     printf(" -ap_loss         samples to confirm AP loss\n");
5878     printf(" -ap_breach       APs breaching threshold\n");
5879     printf(" -ch_threshold    Change in threshold\n");
5880     printf(" -wt_event        Waiting event for test\n");
5881     printf(" -low_th          Low threshold for hotlist APs\n");
5882     printf(" -hight_th        High threshold for hotlist APs\n");
5883     printf(" -hotlist_bssids  BSSIDs for hotlist test\n");
5884     printf(" -stats       print link layer statistics\n");
5885     printf(" -get_ch_list <a/bg/abg/a_nodfs/abg_nodfs/dfs/"
5886             "6g/a6g_nodfs/all_nodfs/all>  Get channel list\n");
5887     printf(" -get_feature_set  Get Feature set\n");
5888     printf(" -get_feature_matrix  Get concurrent feature matrix\n");
5889     printf(" -get_wake_stats  print wake reason statistics\n");
5890     printf(" -rtt [-get_ch_list <a/bg/abg/a_nodfs/abg_nodfs/dfs/"
5891             "6g/a6g_nodfs/all_nodfs/all>] [-i <burst_period of 100ms unit> [0 - 31] ]"
5892             "    [-n <exponents of 2 = (num_bursts)> [0 - 15]]\n"
5893             "    [-f <num_frames_per_burst>] [-r <num_retries_per_ftm>]\n"
5894             "    [-m <num_retries_per_ftmr>] [-b <burst_duration [2-11 or 15]>]"
5895             "    [-max_ap <count of allowed max AP>] [-l <file to read>] [-o <file to be stored>]\n");
5896     printf(" -cancel_rtt      cancel current RTT process\n");
5897     printf(" -enable_resp     enables the responder\n");
5898     printf(" -cancel_resp     cancel the responder\n");
5899     printf(" -get_responder_info    return the responder info\n");
5900     printf(" -rtt -sta/-nan <peer mac addr> <channel> [ <bandwidth> [0 - 2]] <is_6g>"
5901         "  bandwidth - 0 for 20, 1 for 40 , 2 for 80 . is_6g = 1 if channel is 6G\n");
5902     printf(" -get_capa_rtt Get the capability of RTT such as 11mc");
5903     printf(" -scan_mac_oui XY:AB:CD\n");
5904     printf(" -nodfs <0|1>     Turn OFF/ON non-DFS locales\n");
5905     printf(" -country <alpha2 country code> Set country\n");
5906     printf(" -ePNO Configure ePNO SSIDs\n");
5907     printf(" -blacklist_bssids blacklist bssids\n");
5908     printf(" -whitelist_ssids set whitelist ssids\n"
5909            " -whitelist_ssids ssid1 ssid2 ...\n");
5910     printf(" -get_roaming_capabilities -iface <iface name> get roaming capabilities\n");
5911     printf(" -set_fw_roaming_state set FW roaming state\n");
5912     printf(" -logger [-start] [-d <debug_level> -f <flags> -i <max_interval_sec>\n"
5913            "                   -s <min_data_size> -n <ring_name>]\n"
5914            "                  [pktmonitor]\n"
5915            "         [-get]   [fw] [-iface <iface name>]"
5916            "         [-get]   [driver] [-iface <iface name>]\n"
5917            "         [-get]   [feature] [memdump -o <filename>]\n"
5918            "                  [ringstatus] [ringdata -n <ring_name>]\n"
5919            "                  [txfate -n <no of pkts> -f <filename>] -iface <iface name>\n"
5920            "                  [rxfate -n <no of pkts> -f <filename>] -iface <iface name>\n"
5921            "         [-set]   [loghandler] [alerthandler]\n");
5922     printf(" -rssi_monitor enable/disable\n");
5923     printf(" -max_rssi max rssi threshold for RSSI monitor\n");
5924     printf(" -min_rssi min rssi threshold for RSSI monitor\n");
5925     printf(" -mkeep_alive [-start] <index (1 to 3)> <period_msec> <src_mac> <dst_mac> <ether_type>"
5926                                    "[IP packet contents by Hexa format string]\n");
5927     printf("              [-stop]  <index (1 to 3)>\n");
5928     printf("    e.g., -mkeep_alive -start 1 20000 000f66f45b7e 0014a54b164f 0800 4500001e0000400040"
5929            "11c52a0a8830700a88302513c413c4000a00000a0d\n");
5930     printf(" -nd_offload <0|1>   enable/disable ND offload feature\n"
5931            "                     enable also triggers IPv6 address update\n");
5932     printf(" -latency_mode set latency mode WIFI_LATENCY_MODE_NORMAL/WIFI_LATENCY_MODE_LOW on particular interface\n"
5933            " -latency_mode <interface_name> <low/normal/ultra-low mode>\n");
5934     printf(" -sar enable <wifi_power_scenario -1 to 99>\n");
5935     printf(" -sar disable\n");
5936     printf(" -thermal <mode (none/light/moderate/severe/critical/emergency)>\n");
5937     printf(" -nan [-enable] [-master_pref <master pref (2 to 254)>]\n"
5938             "                [-clus_id <cluster ID (50:6F:9A:01:XX:XX)]>\n"
5939             "                [-cluster_low <0 to 0xffff> -cluster_high <0 to 0xffff>\n"
5940             "                [-nan_addr <nan interface mac address(XX:XX:XX:XX:XX:XX)]>\n"
5941             "                [-dual_band <0/1>]\n"
5942             "                [-24g_chan <2.4GHz channel in MHz >]\n"
5943             "                [-5g_chan <5GHz channel in MHz >]\n"
5944             "                [-hc_limit <hop count limit>]\n"
5945             "                [-warmup_time <warm up time>]  [-disc_ind_cfg <0 to 7>]\n"
5946             "                [-random_factor <random factor value>]\n"
5947             "                [-rssi_close_2dot4g_val  <value>] [-rssi_middle_2dot4g_val <value>]\n"
5948             "                [-rssi_proximity_2dot4g_val <value>] [-support_2dot4g_val <0/1>]\n"
5949             "                [-beacon_2dot4g_val <0/1>] [-sdf_2dot4g_val <0/1>]\n"
5950             "                [-beacon_5g_val <0/1>] [-sdf_5g_val <0/1>] [-rssi_close_5g_val <RSSI value>]\n"
5951             "                [-rssi_middle_5g_val <RSSI value>] [-rssi_close_proximity_5g_val  <RSSI value>]\n"
5952             "                [-rssi_window_size_val <value>] [-config_cluster_attribute_val <0/1>]\n"
5953             "                [-dwell_time <value in ms>] [-scan_period <value>] [-sid_flag <0/1>] [-sid_count <1 to 127>]\n"
5954             "                [-sub_sid_flag <0/1>] [-sub_sid_count <1 to 127>]\n"
5955             "                [-dwell_time_5g <value in ms>] [-scan_period_5g <value>]\n"
5956             "                [-awake_dw_2g <value> -awake_dw_5g <value>]\n"
5957             "                [-instant_mode <0-disable, 1-enable>]\n"
5958             "                [-instant_chan <2.4/5GHz channel in MHz >]\n");
5959     printf(" -nan [-disable]\n");
5960     printf(" -nan [-config] [-sid_flag <0/1>]\n"
5961             "                [-sid_count <1 to 127>]\n"
5962             "                [-sub_sid_flag <0/1>] [-sub_sid_count <1 to 127>]\n"
5963             "                [-rssi_proximity <rssi_proximity value>]\n"
5964             "                [-numchans <No of channels> -entry_control <Availability interval duration>]\n"
5965             "                [-channel <Channel value in MHz> -avail_interval_bitmap <u32 value>]\n"
5966             "                [-master_pref <master_pref>]\n"
5967             "                [-rssi_close_prox_5g <rssi_close_prox_5g value>]\n"
5968             "                [-rssi_window_size_val <rssi_window_size_val>]\n"
5969             "                [-dwell_time <dwell_time value in ms>\n"
5970             "                [-scan_period <scan_period  value>]\n"
5971             "                [-dwell_time_5g <value in ms>] [-scan_period_5g <value>]\n"
5972             "                [-random_factor <random_factor value>]\n"
5973             "                [-hc_limit <hc_limit>]  [-disc_ind_cfg <0 to 7>]\n"
5974             "                [-awake_dw_2g <value> -awake_dw_5g <value>]\n"
5975             "                [-instant_mode <0-disable, 1-enable>]\n"
5976             "                [-instant_chan <2.4/5GHz channel in MHz >]\n");
5977     printf(" -nan [-publish] [-svc <svc_name>] [-info <svc info>\n"
5978             "    [-pub_type <0/1/2>] [-pub_count <val>] [-rssi_thresh_flag <0/1>]\n"
5979             "    [-tx_type <0/1>] [-ttl <val>] [-svc_awake_dw <val>] [-match_ind <0/1/2>]\n"
5980             "    [-match_rx <0/ascii str>] [-match_tx <0/ascii str>]"
5981             "    [-passphrase <Passphrase value, len must not be less than 8 or greater than 63>]\n"
5982             "    [-recv_flag <0 to 15>] [-csid <cipher suite type 0/1/2/4/8>]"
5983             "    [-key_type <1 or 2>] [-pmk <PMK value>]\n"
5984             "    [-scid <scid value>] [-dp_type <0-Unicast, 1-multicast>]\n"
5985             "    [-secure_dp <0-No security, 1-Security>] [-ranging <0-disable, 1-enable>)]\n"
5986             "    [-ranging_intvl [intrvl in ms betw two ranging measurements] -ranging_ind \n"
5987             "    [BIT0 - Continuous Ranging event notification, "
5988             "    BIT1 - Ingress distance is <=, BIT2 - Egress distance is >=.]\n"
5989             "    [-ingress [Ingress distance in centimeters] \n"
5990             "    [ -egress [Egress distance in centimeters] \n"
5991             "    [-auto_dp_accept [0 - User response required to accept dp,"
5992             "    1 - User response not required to accept dp] \n"
5993             "    [-suspendable <0/1>] [-nik <local nik of 16 chars>]\n"
5994             "    [-bs_methods <supported bootstrapping methods>] \n"
5995             "    [-pairing_setup <supported 0/1>] [-pairing_cache <supported 0/1]"
5996             "    [-pairing_verification <supported 0/1>] \n");
5997     printf(" -nan [-subscribe] [-svc <svc_name>] [-info <svc info>]\n"
5998             "    [-sub_type <0/1>] [-sub_count <val>] [-pub_ssi <0/1>]\n"
5999             "    [-ttl <val>] [-svc_awake_dw <val>] [-match_ind <0/1/2>]\n"
6000             "    [-match_rx <0/ascii str>] [-match_tx <0/ascii str>]\n"
6001             "    [-mac_list <addr>] [-srf_use <0/1>] [-rssi_thresh_flag <0/1>]]\n"
6002             "    [-srf_include <0/1>] [-srf_type <0/1>] [-recv_flag <0 to 7>]\n"
6003             "    [-csid <cipher suite type 0/1/2/4/8>]  [-key_type <1 or 2>]\n"
6004             "    [-scid <scid value>] [-dp_type <0-Unicast,1-multicast>]\n"
6005             "    [-secure_dp <0-No security, 1-Security>] [-ranging <0-disable, 1-enable>)]\n"
6006             "    [-ranging_intvl [intrvl in ms betw two ranging measurements] -ranging_ind \n"
6007             "    [BIT0 - Continuous Ranging event notification, "
6008             "    BIT1 - Ingress distance is <=, BIT2 - Egress distance is >=.]\n"
6009             "    [-ingress [Ingress distance in centimeters] \n"
6010             "    [ -egress [Egress distance in centimeters] \n"
6011             "    [-suspendable <0/1>] [-nik <local nik of 16 chars>]\n"
6012             "    [-bs_methods <supported bootstrapping methods>] \n"
6013             "    [-pairing_setup <supported 0/1>] [-pairing_cache <supported 0/1]"
6014             "    [-pairing_verification <supported 0/1>] \n");
6015     printf(" -nan [-cancel_pub <publish id>]\n");
6016     printf(" -nan [-cancel_sub <subscribe id>\n");
6017     printf(" -nan [-transmit] [-src_id <instance id>] [-dest_id <instance id>]\n"
6018             "    [-peer_addr <mac addr>] [-info <svc info>] \n"
6019             "    [-recv_flag <1-Disable followUp response, 0-Enable followup response from FW>]\n");
6020     printf(" -nan [-get_capabilities]\n");
6021     printf("\n ****** Nan Data Path Commands ***** \n");
6022     printf(" -nan [-create] [-iface <iface name>]\n");
6023     printf(" -nan [-delete] [-iface <iface name>]\n");
6024     printf(" -nan [-init] [-pub_id <pub id>] [-disc_mac <discovery mac addr>]\n"
6025             "    [-chan_req_type <NAN DP channel config options>]\n"
6026             "    [-chan <channel in mhz>] [-iface <iface>] [-sec <security>] [-key_type <1 or 2>\n"
6027             "    [-qos <qos>] [-info <seq of values in the frame body>]"
6028             "    [-passphrase <Passphrase value, len must not be less than 8 or greater than 63>]\n"
6029             "    [-csid <cipher suite type 0/1/2/4/8>] [-key_type <1 or 2>]"
6030             "    [-pmk <PMK value>] [-svc <svc_name>]\n"
6031             "    [-lcl_svc_id <local service id>] \n");
6032     printf(" -nan [-resp] [-ndp_id <NDP id>] [-iface <NDP iface name>]\n"
6033             "    [-resp_code <accept = 0, reject = 1>] [-qos <qos>]  [-key_type <1 or 2>] \n"
6034             "    [-info <seq of values in the frame body>] "
6035             "    [-passphrase <Passphrase value, len must not be less than 8 or greater than 63>]\n"
6036             "    [-csid <cipher suite type 0/1/2/4/8>]"
6037             "    [-key_type <1 or 2>] [-pmk <PMK value>] [-svc <svc_name>]\n"
6038             "    [-lcl_svc_id <local service id>] \n");
6039     printf(" -nan [-end] [-inst_count <count>] [-inst_id <NDP id>\n");
6040     printf(" -nan [-up] [-iface <iface name>] [-ip <ip>]\n");
6041     printf(" -nan [-addr]\n");
6042     printf(" -nan [-event_chk]\n");
6043     printf(" -nan [-ver]\n");
6044     printf(" -nan [-exit]\n");
6045     printf(" -nan [-suspend] -svc_id [service_id]\n");
6046     printf(" -nan [-resume] -svc_id [service_id]\n");
6047     printf(" -nan [-pairing_req] [-pub_id <instance id>]\n"
6048            "      [-type <0-setup, 1-verification>] [-peer_addr <mac addr>]\n"
6049            "      [-password <password>] [-csid <cipher suite - 64/128>] [-akm <0-SAE, 1-PASN] \n"
6050            "      [-nik <local nik>] [-pairing_cache <1-Enable , 0-Disable pairing cache>]\n"
6051            "      [-pmk <32 byte PMK value>]\n");
6052     printf(" -nan [-pairing_resp] [-pairing_id <pairing instance id>]\n"
6053            "      [-rsp_code <0-ACCEPT,1-REJECT>] [-type <0-setup, 1-verification>]\n"
6054            "      [-password <password>] [-csid <cipher suite - 64/128>] [-akm <0-SAE, 1-PASN] \n"
6055            "      [-nik <local nik>] [-pairing_cache <1-Enable , 0-Disable pairing cache>]\n"
6056            "      [-pmk <32 byte PMK value>]\n");
6057     printf(" -nan [-pairing_end] -pid <pairing_instance_id>\n");
6058     printf(" -nan [-bs_req] -dest_id <peer inst id> -lcl_id <local inst id> -peer_addr <mac addr>\n"
6059            "      [-bs_methods <supported bootstrapping methods>] [-comeback <is it comeback BS req>]\n"
6060            "      [-cookie <cookie info>] [-info <svc info>] [-sdea_info <sdea svc info>]\n");
6061     printf(" -nan [-bs_resp] -dest_id <peer inst id> -lcl_id <local inst id> -peer_addr <macaddr>\n"
6062            "      [-rsp_code <0-ACCEPT, 1-REJECT, 2- COMEBACK>] [-comeback_delay]\n"
6063            "      [-cookie <cookie info>] [-info <svc info>] [-sdea_info <sdea svc info>]\n");
6064     printf(" -dscp [-set] [-s <start>] [-e <end>] [-ac <access_category>]\n");
6065     printf(" -dscp [-reset] \n");
6066     printf(" -ch_avoid [-unsafe <band type, a,b>,<channel number>,"
6067             "   <power capacity, maximum output for the channel in dBm>]\n"
6068             "   -unsafe can be used multiple times b for BAND_24GHZ\n"
6069             "   a for BAND_5GHZ [-m <mandatory flag as decimal>]\n"
6070             "   1 << 0 for FLAG_UNSPECIFIED \n"
6071             "   1 << 1 for FLAG_WIFI_DIRECT\n"
6072             "   1 << 2 for FLAG_SOFTAP\n"
6073             "   1 << 4 for FLAG_WIFI_AWARE\n");
6074     printf(" -usable_ch [-b <band_mask>], [-i <iface_mask>], [-f <filter_mask>], "
6075             "   [-m <max_size of channel>] [-b 2g,5g,6g]\n"
6076             "   [-i sta,nan,softap,p2p_go,p2p_cli]\n");
6077     printf("-ifadd -name <virtual iface name to be created>"
6078            " -type <0 for STA, 1 for AP, 2 for P2P, 3 for NAN>\n");
6079     printf("-ifdel -name <virtual iface name to be deleted>\n");
6080     printf(" -voip_mode <interface_name> <0|1> voip mode off/on on particular interface\n");
6081     printf(" -dtim_multiplier <dtim count>  Set suspend bcn_li_dtim.\n");
6082     printf(" -on_ssr  cmd to trigger sub system restart.\n");
6083     printf(" -getSupportedRadioMatrix  cmd to get the supported radio combo matrix.\n");
6084     printf(" -get_cached_scan_results cmd to get the cached scan results.\n");
6085     printf(" -set_channel_mask <value> [1 for indoor channel, 2 for DFS channel]\n");
6086     printTwtUsage();
6087     printTxPowerUsage();
6088     printChreNanRttUsage();
6089 }
6090 
6091 /* Generic function to copy Iface_name/Ip/App specific Info to the buffer */
set_interface_params(char * p_info,char * val_p,int len)6092 static int set_interface_params(char *p_info, char *val_p, int len) {
6093     void *p;
6094     p = strncpy(p_info, val_p, len);
6095     if (p_info[len - 1] == '\n') {
6096         p_info[len - 1] = '\0';
6097     }
6098     if (!p) {
6099         printMsg("Error\n");
6100         return WIFI_ERROR_UNKNOWN;
6101     }
6102     printMsg("Info/Iface/Ip = \"%s\"\n", (char*)p);
6103     return WIFI_SUCCESS;
6104 }
6105 
wifi_get_iface_handle_by_iface_name(char * val_p)6106 static wifi_interface_handle wifi_get_iface_handle_by_iface_name(char *val_p) {
6107     /* Interface name */
6108     char iface_name[IFNAMSIZ+1];
6109     wifi_interface_handle ifHandle = NULL;
6110 
6111     memset(iface_name, 0, sizeof(iface_name));
6112 
6113     if (!set_interface_params(iface_name, val_p, (IFNAMSIZ - 1))) {
6114         printMsg("set interface name successfull %s\n", iface_name);
6115     } else {
6116         printMsg("Invalid iface name\n");
6117         return ifHandle;
6118     }
6119     ifHandle = wifi_get_iface_handle(halHandle, iface_name);
6120     if (ifHandle == NULL) {
6121         printMsg("Invalid iface handle for the requested interface\n");
6122     }
6123     return ifHandle;
6124 }
6125 
OnNanNotifyResponse(transaction_id id,NanResponseMsg * rsp_data)6126 void OnNanNotifyResponse(transaction_id id, NanResponseMsg* rsp_data) {
6127     if (rsp_data) {
6128     switch (rsp_data->response_type) {
6129     case NAN_RESPONSE_ENABLED:
6130         printMsg("Nan Enable Response Received, status = %d\n", rsp_data->status);
6131         break;
6132     case NAN_RESPONSE_DISABLED:
6133         printMsg("Nan Disable Response Received, status = %d\n", rsp_data->status);
6134         break;
6135     case NAN_RESPONSE_CONFIG:
6136         printMsg("Nan Config Response Received, status = %d\n", rsp_data->status);
6137         break;
6138     case NAN_RESPONSE_PUBLISH:
6139         printMsg("Nan Publish Response Received, Publish ID "
6140             "= %d, status = %d\n",
6141             rsp_data->body.publish_response.publish_id, rsp_data->status);
6142         break;
6143     case NAN_RESPONSE_SUBSCRIBE:
6144         printMsg("Nan Subscribe Response Received, Subscribe ID "
6145             "= %d, status = %d\n",
6146             rsp_data->body.subscribe_response.subscribe_id, rsp_data->status);
6147         break;
6148     case NAN_RESPONSE_PUBLISH_CANCEL:
6149         printMsg("Nan Cancel Publish Response Received, status = %d\n", rsp_data->status);
6150         break;
6151     case NAN_RESPONSE_SUBSCRIBE_CANCEL:
6152         printMsg("Nan Cancel Subscribe Response Received, status = %d\n", rsp_data->status);
6153         break;
6154     case NAN_RESPONSE_TRANSMIT_FOLLOWUP:
6155         printMsg("Transmit followup response received, status = %d\n", rsp_data->status);
6156         break;
6157     case NAN_DP_INTERFACE_CREATE:
6158         printMsg("ndp iface create response received, status = %d\n", rsp_data->status);
6159         break;
6160     case NAN_DP_INTERFACE_DELETE:
6161         printMsg("ndp iface delete response received, status = %d\n", rsp_data->status);
6162         break;
6163     case NAN_DP_INITIATOR_RESPONSE:
6164         printMsg("ndp response received, ndp_instance_id = %d, status = %d\n",
6165             rsp_data->body.data_request_response.ndp_instance_id, rsp_data->status);
6166         break;
6167     case NAN_DP_RESPONDER_RESPONSE:
6168         printMsg("Nan Data Path Response Received, status = %d\n", rsp_data->status);
6169         break;
6170     case NAN_DP_END:
6171         printMsg("Nan Data Path End Response Received, status = %d\n", rsp_data->status);
6172         break;
6173     case NAN_SUSPEND_REQUEST_RESPONSE:
6174         printMsg("Nan Suspend Response Received, status = %d\n", rsp_data->status);
6175         break;
6176     case NAN_RESUME_REQUEST_RESPONSE:
6177         printMsg("Nan Resume Response Received, status = %d\n", rsp_data->status);
6178         break;
6179     case NAN_PAIRING_INITIATOR_RESPONSE:
6180         printMsg("Pairing init response received, pairing_instance_id = %d, status = %d\n",
6181                 rsp_data->body.pairing_request_response.paring_instance_id, rsp_data->status);
6182         break;
6183     case NAN_PAIRING_RESPONDER_RESPONSE:
6184         printMsg("Pairing Response Received, status = %d\n", rsp_data->status);
6185         break;
6186     case NAN_PAIRING_END:
6187         printMsg("Pairing End Response Received, status = %d\n", rsp_data->status);
6188         break;
6189     case NAN_BOOTSTRAPPING_INITIATOR_RESPONSE:
6190         printMsg("Bootstrapping init response received, Bootstrapping_instance_id = %d,"
6191                 "status = %d\n",
6192                 rsp_data->body.bootstrapping_request_response.bootstrapping_instance_id,
6193                 rsp_data->status);
6194         break;
6195     case NAN_BOOTSTRAPPING_RESPONDER_RESPONSE:
6196         printMsg("Bootstrapping Response Received, status = %d\n", rsp_data->status);
6197         break;
6198     case NAN_GET_CAPABILITIES:
6199         printMsg("Nan Get Capabilities Response Received, status = %d\n", rsp_data->status);
6200         printMsg("max_concurrent_nan_clusters = %d\n",
6201             rsp_data->body.nan_capabilities.max_concurrent_nan_clusters);
6202         printMsg("max_publishes = %d\n",
6203             rsp_data->body.nan_capabilities.max_publishes);
6204         printMsg("max_subscribes = %d\n",
6205             rsp_data->body.nan_capabilities.max_subscribes);
6206         printMsg("max_service_name_len = %d\n",
6207             rsp_data->body.nan_capabilities.max_service_name_len);
6208         printMsg("max_match_filter_len = %d\n",
6209             rsp_data->body.nan_capabilities.max_match_filter_len);
6210         printMsg("max_total_match_filter_len = %d\n",
6211             rsp_data->body.nan_capabilities.max_total_match_filter_len);
6212         printMsg("max_service_specific_info_len = %d\n",
6213             rsp_data->body.nan_capabilities.max_service_specific_info_len);
6214         printMsg("max_ndi_interfaces = %d\n",
6215             rsp_data->body.nan_capabilities.max_ndi_interfaces);
6216         printMsg("max_ndp_sessions = %d\n",
6217             rsp_data->body.nan_capabilities.max_ndp_sessions);
6218         printMsg("max_app_info_len = %d\n",
6219             rsp_data->body.nan_capabilities.max_app_info_len);
6220         printMsg("max_queued_transmit_followup_msgs = %d\n",
6221             rsp_data->body.nan_capabilities.max_queued_transmit_followup_msgs);
6222         printMsg("max_Subscribe_Interface_Addresses = %d\n",
6223             rsp_data->body.nan_capabilities.max_subscribe_address);
6224         printMsg("supported_CipherSuites = %d\n",
6225             rsp_data->body.nan_capabilities.cipher_suites_supported);
6226         printMsg("max_Extended_ServiceSpecific_Info_Len = %d\n",
6227             rsp_data->body.nan_capabilities.max_sdea_service_specific_info_len);
6228         printMsg("ndpe_attr_supported = %d\n",
6229             rsp_data->body.nan_capabilities.ndpe_attr_supported);
6230         printMsg("suspension_supported = %d\n",
6231             rsp_data->body.nan_capabilities.is_suspension_supported);
6232         printMsg("pairing_supported = %d\n",
6233             rsp_data->body.nan_capabilities.is_pairing_supported);
6234         break;
6235     default:
6236         printMsg("Unknown Response Received, %d\n",
6237             rsp_data->response_type);
6238         }
6239     }
6240     return;
6241 }
OnNanEventPublishTerminated(NanPublishTerminatedInd * event)6242 void OnNanEventPublishTerminated(NanPublishTerminatedInd* event) {
6243     char msg_buf[MAX_NAN_MSG_BUF_SIZE] = {'\0'};
6244     printMsg("\n NanPublishTerminated\n");
6245     snprintf(msg_buf, MAX_NAN_MSG_BUF_SIZE,
6246         "NanPublishTerminated: id %u, reason %u\n",
6247         event->publish_id, event->reason);
6248     printMsg("Publish Terminated: nan_reason = %s\n", event->nan_reason);
6249     putEventInCache(EVENT_TYPE_NAN_PUBLISH_TERMINATED, msg_buf);
6250 }
OnNanEventMatch(NanMatchInd * event)6251 void OnNanEventMatch (NanMatchInd* event) {
6252     printMsg("\n Subscriber id = %d\n", event->publish_subscribe_id);
6253     printMsg("Publisher Id = %d\n", event->requestor_instance_id);
6254     printMsg("Subscribe Match found: Publisher Device Addr( " MACSTR " )\n",
6255         MAC2STR(event->addr));
6256     if (event->service_specific_info_len) {
6257         printMsg("svc info len = %d and svc info = %s\n",
6258             event->service_specific_info_len,
6259             event->service_specific_info);
6260     }
6261     if(event->sdf_match_filter_len) {
6262         printMsg("sdf match filter len = %d and sdf_match_filter = %s\n",
6263             event->sdf_match_filter_len,
6264             event->sdf_match_filter);
6265     }
6266     printMsg("Match occurred flag = %d\n", event->match_occured_flag);
6267     printMsg("Out of resource flag = %d\n", event->out_of_resource_flag);
6268     printMsg("rssi value = %d\n", event->rssi_value);
6269     printMsg("Peer cipher suite type = %d\n", event->peer_cipher_type);
6270     if (event->scid_len) {
6271         printMsg("scid len = %d and scid = %s\n",
6272             event->scid_len, event->scid);
6273     }
6274     /* Peer sdea params */
6275     printMsg("Peer config for data path needed %d\n", event->peer_sdea_params.config_nan_data_path);
6276     printMsg("Data Path type %d\n", event->peer_sdea_params.ndp_type);
6277     printMsg("Security configuration %d\n", event->peer_sdea_params.security_cfg);
6278     printMsg("Ranging report state %d\n", event->peer_sdea_params.range_report);
6279 
6280     printMsg("Distance to the device: %d mm\n", event->range_info.range_measurement_mm);
6281     printMsg("Ranging event type: %d\n", event->range_info.ranging_event_type);
6282 
6283     if (event->sdea_service_specific_info_len) {
6284         printMsg("sdea svc info len = %d and sdea svc info = %s\n",
6285             event->sdea_service_specific_info_len,
6286             event->sdea_service_specific_info);
6287     }
6288     printMsg("Enable Pairing cache: %d\n", event->peer_pairing_config.enable_pairing_cache);
6289     printMsg("Enable Pairing setup: %d\n", event->peer_pairing_config.enable_pairing_setup);
6290     printMsg("Enable Pairing verification: %d\n",
6291         event->peer_pairing_config.enable_pairing_verification);
6292     printMsg("Peer Bootstrapping methods: %d\n",
6293         event->peer_pairing_config.supported_bootstrapping_methods);
6294     prhex_msg("NIRA nonce", event->nira.nonce, NAN_IDENTITY_NONCE_LEN);
6295     prhex_msg("NIRA tag", event->nira.tag, NAN_IDENTITY_TAG_LEN);
6296     /* Event enabled is not available in android-m */
6297     putEventInCache(EVENT_TYPE_SUBSCRIBE_MATCHED,
6298         "SubscribeMatched");
6299 }
OnNanEventMatchExpired(NanMatchExpiredInd * event)6300 void OnNanEventMatchExpired (NanMatchExpiredInd* event) {
6301     printMsg("NanMatchExpired between publish_subscribe_id = %u "
6302             "and peer_instance_id = %u\n",
6303             event->publish_subscribe_id, event->requestor_instance_id);
6304 }
OnNanEventSubscribeTerminated(NanSubscribeTerminatedInd * event)6305 void OnNanEventSubscribeTerminated (NanSubscribeTerminatedInd* event) {
6306     char msg_buf[MAX_NAN_MSG_BUF_SIZE] = {'\0'};
6307     printMsg("\n NanSubscribeTerminated\n");
6308     snprintf(msg_buf, MAX_NAN_MSG_BUF_SIZE,
6309         "NanSubscribeTerminated: id %u, reason %u\n",
6310         event->subscribe_id, event->reason);
6311     printMsg("Subscribe Terminated: nan_reason = %s\n", event->nan_reason);
6312     putEventInCache(EVENT_TYPE_NAN_SUBSCRIBE_TERMINATED, msg_buf);
6313 }
OnNanEventFollowup(NanFollowupInd * event)6314 void OnNanEventFollowup (NanFollowupInd* event) {
6315     printMsg("\n Instance id= %u\n",
6316         event->publish_subscribe_id);
6317     printMsg("Peer instance id = %u\n",
6318         event->requestor_instance_id);
6319     printMsg("Transmit Followup Received in %s\n",
6320         (event->dw_or_faw)? "FAW":"DW");
6321     printMsg("peer addr (" MACSTR ")\n", MAC2STR(event->addr));
6322     if (event->service_specific_info_len) {
6323         printMsg("followup svc_info len = %d and info = %s\n",
6324             event->service_specific_info_len,event->service_specific_info);
6325     }
6326     if (event->sdea_service_specific_info_len) {
6327         printMsg("sdea svc info len = %d and sdea svc info = %s\n",
6328             event->sdea_service_specific_info_len,
6329             event->sdea_service_specific_info);
6330     }
6331 
6332     putEventInCache(EVENT_TYPE_NAN_FOLLOWUP_RECIEVE,
6333         "NanFollowupReceived");
6334 }
OnNanTransmitFollowupInd(NanTransmitFollowupInd * event)6335 void OnNanTransmitFollowupInd (NanTransmitFollowupInd* event) {
6336     printMsg("\n Transaction id = %u\n",
6337         event->id);
6338     printMsg("Transmit Followup Status = %u\n",
6339         event->reason);
6340     printMsg("Nan Transmit Followup Ind: nan_reason = %s\n", event->nan_reason);
6341     putEventInCache(EVENT_TYPE_NAN_TRANSMIT_FOLLOWUP_INDICATION,
6342         "NanTransmitFollowupInd");
6343 }
6344 
OnNanPublishRepliedInd(NanPublishRepliedInd * event)6345 void OnNanPublishRepliedInd (NanPublishRepliedInd* event) {
6346     printMsg("\n Requestor Instance Id/Subscriber Id = %d\n", event->requestor_instance_id);
6347     printMsg("Subscriber found: Device( " MACSTR " )\n",
6348         MAC2STR(event->addr));
6349     printMsg("rssi value = %d\n", event->rssi_value);
6350 }
6351 
OnNanEventDiscEngEvent(NanDiscEngEventInd * event)6352 void OnNanEventDiscEngEvent (NanDiscEngEventInd* event) {
6353     if (event->event_type == NAN_EVENT_ID_DISC_MAC_ADDR) {
6354         printMsg("\n DE Event Received, Nan Disc Mac Addr Creation Event\n");
6355         printMsg("NMI Mac address (" MACSTR ")\n",
6356             MAC2STR(event->data.mac_addr.addr));
6357     } else if (event->event_type == NAN_EVENT_ID_STARTED_CLUSTER) {
6358         printMsg("DE Event Received, Nan Cluster Started \n");
6359     } else if (event->event_type == NAN_EVENT_ID_JOINED_CLUSTER) {
6360         printMsg("DE Event Received, Nan Cluster Joined \n");
6361         printMsg("Joined cluster ID (" MACSTR ")\n",
6362             MAC2STR(event->data.cluster.addr));
6363     } else {
6364         printMsg("Unknown DE Event Received, %d\n", event->event_type);
6365         return;
6366     }
6367 }
OnNanEventDisabled(NanDisabledInd * event)6368 void OnNanEventDisabled (NanDisabledInd* event) {
6369     printMsg("\n Nan disabledInd received, reason = %u\n", event->reason);
6370     printMsg("Nan Disabled Event: nan_reason = %s\n", event->nan_reason);
6371 }
OnNanEventTca(NanTCAInd * event)6372 void OnNanEventTca (NanTCAInd* event) {}
OnNanEventBeaconSdfPayload(NanBeaconSdfPayloadInd * event)6373 void OnNanEventBeaconSdfPayload (NanBeaconSdfPayloadInd* event) {}
OnNanEventDataIndication(NanDataPathRequestInd * event)6374 void OnNanEventDataIndication (NanDataPathRequestInd* event) {
6375     printMsg("\n service id = %d\n", event->service_instance_id);
6376     printMsg("Discovery MAC addr of the peer/initiator(" MACSTR ")\n",
6377         MAC2STR(event->peer_disc_mac_addr));
6378     printMsg("ndp id = %d\n", event->ndp_instance_id);
6379     printMsg("qos = %d\n", event->ndp_cfg.qos_cfg);
6380     printMsg("security = %d\n", event->ndp_cfg.security_cfg);
6381     if (event->app_info.ndp_app_info_len) {
6382         printMsg("service info = %s and its length = %d\n",
6383             event->app_info.ndp_app_info,
6384             event->app_info.ndp_app_info_len);
6385     }
6386     putEventInCache(EVENT_TYPE_NAN_DATA_REQUEST_INDICATION,
6387         "NanDataEventIndication");
6388 }
OnNanEventDataConfirmation(NanDataPathConfirmInd * event)6389 void OnNanEventDataConfirmation (NanDataPathConfirmInd* event) {
6390     printMsg("\n ndp id = %d\n", event->ndp_instance_id);
6391     printMsg("NDI mac address of the peer = (" MACSTR ")\n",
6392         MAC2STR(event->peer_ndi_mac_addr));
6393     if (event->app_info.ndp_app_info_len) {
6394         printMsg("service info = %s and length = %d\n",
6395             event->app_info.ndp_app_info,
6396             event->app_info.ndp_app_info_len);
6397     }
6398     printMsg("Response code = %d\n", event->rsp_code);
6399     switch (event->rsp_code) {
6400     case NAN_DP_REQUEST_ACCEPT:
6401         printMsg("Response code [%d]:NAN_DP_REQUEST_ACCEPT\n", event->rsp_code);
6402         break;
6403     case NAN_DP_REQUEST_REJECT:
6404         printMsg("Response code [%d]:NAN_DP_REQUEST_REJECT\n", event->rsp_code);
6405         printMsg("Reason code for rejection= %d\n", event->reason_code);
6406         break;
6407     default:
6408         printMsg("Unknown response code = %d\n", event->rsp_code);
6409         break;
6410     }
6411     putEventInCache(EVENT_TYPE_NAN_DATA_CONFIRMATION,
6412         "NanDataConfirmation");
6413 }
OnNanEventDataPathEnd(NanDataPathEndInd * event)6414 void OnNanEventDataPathEnd (NanDataPathEndInd* event) {
6415     printMsg("\n ndp id count = %d\n", event->num_ndp_instances);
6416     printMsg("ndp id = %d\n",
6417         event->ndp_instance_id[event->num_ndp_instances -1]);
6418     putEventInCache(EVENT_TYPE_NAN_DATA_END_INDICAION,
6419         "NanDataEndIndication");
6420 }
6421 
OnNanRangeRequestInd(NanRangeRequestInd * event)6422 void OnNanRangeRequestInd (NanRangeRequestInd *event) {
6423     printMsg("\n Received NanRangeRequestInd\n");
6424 }
OnNanRangeReportInd(NanRangeReportInd * event)6425 void OnNanRangeReportInd (NanRangeReportInd *event) {
6426     printMsg("\n Received NanRangeReportInd\n");
6427 }
OnNanDataPathScheduleUpdateInd(NanDataPathScheduleUpdateInd * event)6428 void OnNanDataPathScheduleUpdateInd (NanDataPathScheduleUpdateInd *event) {
6429     printMsg("\n Received NanDataPathScheduleUpdateInd\n");
6430 }
OnNanSuspensionStatus(NanSuspensionModeChangeInd * event)6431 void OnNanSuspensionStatus (NanSuspensionModeChangeInd *event) {
6432     printMsg("\n Received NanSuspensionModeChangeInd\n");
6433 }
OnNanEventPairingIndication(NanPairingRequestInd * event)6434 void OnNanEventPairingIndication(NanPairingRequestInd* event) {
6435     printMsg("\n Local service id = %d\n", event->publish_subscribe_id);
6436     printMsg(" Discovery MAC addr of the peer/initiator(" MACSTR ")\n",
6437         MAC2STR(event->peer_disc_mac_addr));
6438     printMsg(" pairing id = %d\n", event->pairing_instance_id);
6439     printMsg(" request type = %d\n", event->nan_pairing_request_type);
6440     printMsg(" pairing cache enabled = %d\n", event->enable_pairing_cache);
6441     prhex_msg(" NIRA nonce", (u8 *)event->nira.nonce, NAN_IDENTITY_NONCE_LEN);
6442     prhex_msg(" NIRA tag", (u8 *)event->nira.tag, NAN_IDENTITY_TAG_LEN);
6443     putEventInCache(EVENT_TYPE_NAN_PAIRING_REQUEST_INDICATION,
6444         "NanPairingEventIndication");
6445 }
6446 
OnNanEventPairingConfirmation(NanPairingConfirmInd * event)6447 void OnNanEventPairingConfirmation(NanPairingConfirmInd* event) {
6448     printMsg("\n pairing id = %d\n", event->pairing_instance_id);
6449     printMsg(" rsp_code = %d\n", event->rsp_code);
6450     printMsg(" reason = %s\n", event->reason_code);
6451     printMsg(" request type = %d\n", event->nan_pairing_request_type);
6452     printMsg(" pairing cache enabled = %d\n", event->enable_pairing_cache);
6453     prhex_msg(" Peer NIK", event->npk_security_association.peer_nan_identity_key,
6454         NAN_IDENTITY_KEY_LEN);
6455     prhex_msg(" Local NIK", event->npk_security_association.local_nan_identity_key,
6456         NAN_IDENTITY_KEY_LEN);
6457     printMsg(" akm = %d\n", event->npk_security_association.akm);
6458     printMsg(" csid = %d\n", event->npk_security_association.cipher_type);
6459     prhex_msg(" NPK", (u8 *)event->npk_security_association.npk.pmk,
6460         event->npk_security_association.npk.pmk_len);
6461 
6462     putEventInCache(EVENT_TYPE_NAN_PAIRING_CONFIRMATION, "NanPairingEventConfirmation");
6463 }
OnNanEventBootstrappingIndication(NanBootstrappingRequestInd * event)6464 void OnNanEventBootstrappingIndication(NanBootstrappingRequestInd* event) {
6465     printMsg("\n Requestor service id = %d\n", event->requestor_instance_id);
6466     printMsg(" Local service id = %d\n", event->publish_subscribe_id);
6467     printMsg(" Discovery MAC addr of the peer/initiator(" MACSTR ")\n",
6468         MAC2STR(event->peer_disc_mac_addr));
6469     printMsg(" Peer bootstrapping methods = %d\n", event->request_bootstrapping_method);
6470     printMsg(" Bootstrapping instance id = %d\n", event->bootstrapping_instance_id);
6471     putEventInCache(EVENT_TYPE_NAN_BOOTSTRAP_REQUEST_INDICATION,
6472         "NanBootstrappingEventIndication");
6473 }
6474 
OnNanEventBootstrappingConfirmation(NanBootstrappingConfirmInd * event)6475 void OnNanEventBootstrappingConfirmation(NanBootstrappingConfirmInd* event) {
6476     printMsg("\n Bootstrapping instance id = %d\n", event->bootstrapping_instance_id);
6477     printMsg(" rsp_code = %d\n", event->rsp_code);
6478     printMsg(" reason = %d\n", event->reason_code);
6479     printMsg(" come_back_delay = %d\n", event->come_back_delay);
6480     if (event->cookie_length) {
6481         prhex_msg("Cookie: ", event->cookie, event->cookie_length);
6482     }
6483     putEventInCache(EVENT_TYPE_NAN_BOOTSTRAP_CONFIRMATION,
6484         "NanBootstrappingEventCOnfirmation");
6485 }
6486 
nan_init_handlers(void)6487 wifi_error nan_init_handlers(void) {
6488     wifi_error ret = WIFI_SUCCESS;
6489     NanCallbackHandler handlers;
6490     memset(&handlers, 0, sizeof(handlers));
6491     handlers.NotifyResponse = OnNanNotifyResponse;
6492     handlers.EventPublishTerminated = OnNanEventPublishTerminated;
6493     handlers.EventMatch = OnNanEventMatch;
6494     handlers.EventMatchExpired = OnNanEventMatchExpired;
6495     handlers.EventSubscribeTerminated = OnNanEventSubscribeTerminated;
6496     handlers.EventFollowup = OnNanEventFollowup;
6497     handlers.EventDiscEngEvent = OnNanEventDiscEngEvent;
6498     handlers.EventDisabled = OnNanEventDisabled;
6499     handlers.EventTca = OnNanEventTca;
6500     handlers.EventBeaconSdfPayload = OnNanEventBeaconSdfPayload;
6501     handlers.EventDataRequest = OnNanEventDataIndication;
6502     handlers.EventDataConfirm = OnNanEventDataConfirmation;
6503     handlers.EventDataEnd = OnNanEventDataPathEnd;
6504     handlers.EventTransmitFollowup = OnNanTransmitFollowupInd;
6505     handlers.EventPublishReplied = OnNanPublishRepliedInd;
6506     handlers.EventRangeRequest = OnNanRangeRequestInd;
6507     handlers.EventRangeReport = OnNanRangeReportInd;
6508     handlers.EventScheduleUpdate = OnNanDataPathScheduleUpdateInd;
6509     handlers.EventSuspensionModeChange = OnNanSuspensionStatus;
6510     handlers.EventPairingRequest = OnNanEventPairingIndication;
6511     handlers.EventPairingConfirm = OnNanEventPairingConfirmation;
6512     handlers.EventBootstrappingRequest = OnNanEventBootstrappingIndication;
6513     handlers.EventBootstrappingConfirm = OnNanEventBootstrappingConfirmation;
6514     ret = nan_register_handler(wlan0Handle, handlers);
6515     printMsg("%s: ret = %d\n", __FUNCTION__, ret);
6516     return ret;
6517 }
6518 
OnTwtNotify(TwtDeviceNotify * event)6519 static void OnTwtNotify(TwtDeviceNotify* event) {
6520     if (event) {
6521         printMsg("OnTwtNotify, notification = %d\n", event->notification);
6522     }
6523     return;
6524 }
6525 
OnTwtSetupResponse(TwtSetupResponse * event)6526 static void OnTwtSetupResponse(TwtSetupResponse* event) {
6527     printMsg("\n OnTwtSetupResponse\n");
6528     if (event) {
6529         printMsg("config id = %d\n", event->config_id);
6530         printMsg("status = %d\n", event->status);
6531         printMsg("reason_code = %d\n", event->reason_code);
6532         printMsg("negotiation_type = %d\n", event->negotiation_type);
6533         printMsg("trigger_type = %d\n", event->trigger_type);
6534         printMsg("wake_dur_us = %d\n", event->wake_dur_us);
6535         printMsg("wake_int_us = %d\n", event->wake_int_us);
6536         printMsg("wake_time_off_us = %d\n", event->wake_time_off_us);
6537     }
6538     return;
6539 }
6540 
OnTwtTearDownCompletion(TwtTeardownCompletion * event)6541 static void OnTwtTearDownCompletion(TwtTeardownCompletion* event) {
6542     printMsg("\n OnTwtTearDownCompletion\n");
6543     if (event) {
6544         printMsg("config id = %d\n", event->config_id);
6545         printMsg("status = %d\n", event->status);
6546         printMsg("all twt = %d\n", event->all_twt);
6547         printMsg("reason = %d\n", event->reason);
6548     }
6549     return;
6550 }
6551 
OnTwtInfoFrameReceived(TwtInfoFrameReceived * event)6552 static void OnTwtInfoFrameReceived(TwtInfoFrameReceived* event) {
6553     printMsg("\n OnTwtInfoFrameReceived\n");
6554     if (event) {
6555         printMsg("config id = %d\n", event->config_id);
6556         printMsg("status = %d\n", event->status);
6557         printMsg("all twt = %d\n", event->all_twt);
6558         printMsg("reason = %d\n", event->reason);
6559         printMsg("twt_resumed = %d\n", event->twt_resumed);
6560     }
6561     return;
6562 }
6563 
twt_init_handlers(void)6564 wifi_error twt_init_handlers(void) {
6565     wifi_error ret = WIFI_SUCCESS;
6566     TwtCallbackHandler handlers;
6567     memset(&handlers, 0, sizeof(handlers));
6568     handlers.EventTwtDeviceNotify = OnTwtNotify;
6569     handlers.EventTwtSetupResponse = OnTwtSetupResponse;
6570     handlers.EventTwtTeardownCompletion = OnTwtTearDownCompletion;
6571     handlers.EventTwtInfoFrameReceived = OnTwtInfoFrameReceived;
6572     ret = twt_register_handler(wlan0Handle , handlers);
6573     printMsg("%s: ret = %d\n", __FUNCTION__, ret);
6574     return ret;
6575 }
6576 
6577 /*
6578  * Debug function to see the events reaching to HAL
6579  * CTRL-C to exit the blocking command.
6580  */
twtEventCheck(void)6581 void twtEventCheck(void) {
6582     wifi_error ret = WIFI_SUCCESS;
6583 
6584     ret = twt_init_handlers();
6585     if (ret != WIFI_SUCCESS) {
6586         printMsg("Failed to initialize twt handlers %d\n", ret);
6587         return;
6588     }
6589 
6590     twtCmdId = getNewCmdId();
6591     ret = twt_event_check_request(twtCmdId, wlan0Handle);
6592     if (ret != WIFI_SUCCESS) {
6593         printMsg("Failed to check the twt events: %d\n", ret);
6594         return;
6595     }
6596 
6597     printMsg("CTRL-C to exit the thread.\n");
6598     while (1)
6599     {
6600         EventInfo info;
6601         memset(&info, 0, sizeof(info));
6602         getEventFromCache(info);
6603         printMsg("\n Retrieved event %d : %s\n\n", info.type, info.buf);
6604     }
6605 }
6606 /*
6607  * Debug function to see the events reaching to HAL
6608  * CTRL-C to exit the blocking command.
6609  */
nanEventCheck(void)6610 void nanEventCheck(void) {
6611     wifi_error ret = WIFI_SUCCESS;
6612     ret = nan_init_handlers();
6613     if (ret != WIFI_SUCCESS) {
6614         printMsg("Failed to initialize handlers %d\n", ret);
6615         return;
6616     }
6617     nanCmdId = getNewCmdId();
6618     nan_event_check_request(nanCmdId, wlan0Handle);
6619     printMsg("CTRL-C to exit the thread.\n");
6620     while (1)
6621     {
6622         EventInfo info;
6623         memset(&info, 0, sizeof(info));
6624         getEventFromCache(info);
6625         printMsg("\n Retrieved event %d : %s\n\n", info.type, info.buf);
6626     }
6627 }
6628 
nanVersion(void)6629 void nanVersion(void) {
6630     NanVersion version = 0;
6631     wifi_error err = WIFI_SUCCESS;
6632     err = nan_get_version(0, &version);
6633     if (err == WIFI_SUCCESS) {
6634         printMsg("NAN VERSION is %d\n", version);
6635     } else {
6636         printMsg("Nan Version Command Failed, err = %d\n", err);
6637     }
6638 }
6639 
set_cluster_id(char * clus_id,NanEnableRequest * msg)6640 void set_cluster_id(char *clus_id, NanEnableRequest *msg) {
6641     u8 addr[NAN_MAC_ADDR_LEN]; /* cluster id */
6642     if (!clus_id || (!ether_atoe(clus_id, addr))) {
6643         printMsg("bad cluster id !!\n");
6644     } else {
6645         msg->cluster_high = ((addr[4] << 8) | addr[5]);
6646         msg->cluster_low = msg->cluster_high;
6647         printMsg("cluster low: %x, cluster high: %x\n", msg->cluster_low, msg->cluster_high);
6648     }
6649     return;
6650 }
6651 
6652 int
get_oui_bytes(u8 * oui_str,u8 * oui)6653 get_oui_bytes(u8 *oui_str, u8 *oui)
6654 {
6655     int idx;
6656     u8 val;
6657     u8 *src, *dest;
6658     char hexstr[3];
6659     char* endptr = NULL;
6660 
6661     src = oui_str;
6662     dest = oui;
6663 
6664     for (idx = 0; idx < 3; idx++) {
6665         hexstr[0] = src[0];
6666         hexstr[1] = src[1];
6667         hexstr[2] = '\0';
6668         val = (u8) strtoul(hexstr, &endptr, 16);
6669         *dest++ = val;
6670         src += 2;
6671         if (((idx < (3 - 1)) && (*src++ != ':')) || (*endptr != '\0'))
6672             return WIFI_ERROR_UNKNOWN;
6673     }
6674     return WIFI_SUCCESS;
6675 }
6676 
nanSetOui(char * nan_oui,char * nan_type,NanEnableRequest * msg)6677 void nanSetOui(char *nan_oui, char* nan_type, NanEnableRequest *msg) {
6678     u8 type;
6679     u32 value;
6680     char* endptr;
6681 
6682     if(!nan_type) {
6683         printMsg("nan oui type is missing. Setting NAN OUI to default \n");
6684         return;
6685     }
6686 
6687     if (get_oui_bytes((u8 *)nan_oui, (u8 *)&value)) {
6688         printMsg("%s: Wrong OUI value. Setting Default OUI and type\n",__FUNCTION__);
6689         msg->oui_val = 0;
6690         return;
6691     }
6692 
6693     type = strtoul(nan_type, &endptr, 0);
6694     if (*endptr != '\0') {
6695         printMsg("%s:Wrong nan OUI type. Setting default OUI and type\n", __FUNCTION__);
6696         msg->oui_val = 0;
6697         return;
6698     }
6699     value = (value & 0xffffff) + (type << 24);
6700     msg->config_oui = 1;
6701     msg->oui_val = value;
6702 }
6703 
enableNan(char * argv[])6704 void enableNan(char *argv[]) {
6705     NanEnableRequest msg ;
6706     wifi_error ret = WIFI_SUCCESS;
6707     char *endptr, *param, *val_p;
6708     int sid_flag = 0xff, sid_count = 0xff;
6709     int sub_sid_flag = 0xff, sub_sid_count = 0xff;
6710     u8 val;
6711     u16 clust_range = 0;
6712 
6713     /* Set Default enable params */
6714     memset(&msg, 0, sizeof(msg));
6715     msg.hop_count_limit_val = 5;
6716     msg.config_2dot4g_support = FEATURE_SUPPORTED;
6717     msg.support_2dot4g_val = FEATURE_SUPPORTED;
6718     msg.config_2dot4g_beacons = FEATURE_SUPPORTED;
6719     msg.beacon_2dot4g_val = FEATURE_SUPPORTED;
6720     msg.config_2dot4g_sdf = FEATURE_SUPPORTED;
6721     msg.sdf_2dot4g_val = FEATURE_SUPPORTED;
6722     msg.config_disc_mac_addr_randomization = true;
6723     msg.disc_mac_addr_rand_interval_sec = 0;
6724     msg.config_ndpe_attr = false;
6725     msg.cluster_low = 0;
6726     msg.cluster_high = NAN_MAX_CLUST_VALUE_RANGE;
6727 
6728     enab_for_chre = 0;
6729 
6730     /* Parse args for nan params */
6731     /* skip utility */
6732     argv++;
6733     /* skip command */
6734     argv++;
6735     /* skip command */
6736     argv++;
6737 
6738     while ((param = *argv++) != NULL) {
6739         val_p = *argv++;
6740         if (!val_p || *val_p == '-') {
6741             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
6742             ret = WIFI_ERROR_NOT_SUPPORTED;
6743             goto exit;
6744         }
6745         if (strcmp(param, "-clus_id") == 0) {
6746             set_cluster_id(val_p, &msg);
6747         } else if (strcmp(param, "-cluster_low") == 0) {
6748             clust_range = atoi(val_p);
6749             if (clust_range < 0 || clust_range > NAN_MAX_CLUST_VALUE_RANGE) {
6750                 msg.cluster_low = 0;
6751             }
6752             msg.cluster_low = clust_range;
6753         } else if (strcmp(param, "-cluster_high") == 0) {
6754              clust_range = atoi(val_p);
6755              if (clust_range < 0 || clust_range > NAN_MAX_CLUST_VALUE_RANGE) {
6756                 msg.cluster_high = NAN_MAX_CLUST_VALUE_RANGE;
6757              }
6758              msg.cluster_high = clust_range;
6759         } else if (strcmp(param, "-master_pref") == 0) {
6760             msg.master_pref = strtoul(val_p, &endptr, 0);
6761             if (*endptr != '\0' || (msg.master_pref < 2 || msg.master_pref > 254)) {
6762                 printMsg("%s:Invalid Master Preference.Setting it to Random\n", __FUNCTION__);
6763                 msg.master_pref = 0;
6764             }
6765         } else if (strcmp(param, "-dual_band") == 0) {
6766             msg.support_5g_val = strtoul(val_p, &endptr, 0);
6767             if (*endptr != '\0' ||  msg.support_5g_val > 1) {
6768                 printMsg("%s:Invalid Dual Band Value.\n", __FUNCTION__);
6769                 msg.config_support_5g = false;
6770                 ret = WIFI_ERROR_INVALID_ARGS;
6771                 goto exit;
6772             } else {
6773                 msg.config_support_5g = true;
6774             }
6775         } else if (strcmp(param, "-hc_limit") == 0) {
6776             msg.hop_count_limit_val = strtoul(val_p, &endptr, 0);
6777             if (*endptr != '\0') {
6778                 printMsg("%s:Invalid Hop Count Limit. Setting to Default\n", __FUNCTION__);
6779                 msg.config_hop_count_limit = false;
6780                 ret = WIFI_ERROR_INVALID_ARGS;
6781                 goto exit;
6782             } else {
6783                 msg.config_hop_count_limit = true;
6784             }
6785         } else if (strcmp(param, "-oui") == 0) {
6786             nanSetOui(val_p, *argv++, &msg);
6787         } else if (strcmp(param, "-sid_flag") == 0) {
6788             sid_flag = atoi(val_p);
6789             if (sid_flag) {
6790                 msg.config_sid_beacon = true;
6791             } else {
6792                 printMsg("%s:Invalid Service Id Flag. Setting to Default\n", __FUNCTION__);
6793                 msg.config_sid_beacon = false;
6794                 ret = WIFI_ERROR_INVALID_ARGS;
6795                 goto exit;
6796             }
6797         } else if (strcmp(param, "-sid_count") == 0) {
6798             sid_count = atoi(val_p);
6799             if (sid_count < 0 || sid_count > NAN_MAX_SIDS_IN_BEACONS) {
6800                 printMsg("%s:Invalid  Service ID Count Limit. Setting to Default\n", __FUNCTION__);
6801                 sid_count = 0;
6802             } else  {
6803                 msg.sid_beacon_val = ((sid_count << 1) | sid_flag);
6804             }
6805         } else if (strcmp(param, "-sub_sid_flag") == 0) {
6806             sub_sid_flag = atoi(val_p);
6807             if (sub_sid_flag) {
6808                 msg.config_subscribe_sid_beacon = true;
6809             } else {
6810                 printMsg("%s:Invalid Subscribe Service Id Flag. Setting to Default\n", __FUNCTION__);
6811                 msg.config_subscribe_sid_beacon = false;
6812                 ret = WIFI_ERROR_INVALID_ARGS;
6813                 goto exit;
6814             }
6815         } else if (strcmp(param, "-sub_sid_count") == 0) {
6816             sub_sid_count = atoi(val_p);
6817             if (sub_sid_count < 0 || sub_sid_count > NAN_MAX_SIDS_IN_BEACONS) {
6818                 printMsg("%s:Invalid Subscribe Service ID Count Limit. Setting to Default\n",
6819                     __FUNCTION__);
6820                 sub_sid_count = 0;
6821             } else  {
6822                 msg.subscribe_sid_beacon_val = ((sub_sid_count << 1) | sub_sid_flag);
6823             }
6824         } else if (strcmp(param, "-rssi_close_2dot4g_val") == 0) {
6825             msg.rssi_close_2dot4g_val = atoi(val_p);
6826             if (msg.rssi_close_2dot4g_val) {
6827                 msg.config_2dot4g_rssi_close = true;
6828             }
6829         } else if (strcmp(param, "-rssi_middle_2dot4g_val") == 0) {
6830             msg.rssi_middle_2dot4g_val = atoi(val_p);
6831             if (msg.rssi_middle_2dot4g_val) {
6832                 msg.config_2dot4g_rssi_middle = true;
6833             }
6834         } else if (strcmp(param, "-rssi_proximity_2dot4g_val") == 0) {
6835             msg.rssi_proximity_2dot4g_val = atoi(val_p);
6836             if (msg.rssi_proximity_2dot4g_val) {
6837                 msg.config_2dot4g_rssi_proximity = true;
6838             }
6839         } else if (strcmp(param, "-support_2dot4g_val") == 0) {
6840             val = atoi(val_p);
6841             /*
6842              * Defines 2.4G channel access support
6843              * 0 - No Support
6844              * 1 - Supported
6845              */
6846             switch(val) {
6847                 case FEATURE_NOT_SUPPORTED:
6848                     msg.support_2dot4g_val = FEATURE_NOT_SUPPORTED;
6849                     break;
6850                 default:
6851                     msg.support_2dot4g_val = FEATURE_SUPPORTED;
6852                     break;
6853             }
6854          } else if (strcmp(param, "-beacon_2dot4g_val") == 0) {
6855             val = atoi(val_p);
6856            /*
6857             * Defines 2.4G channels will be used for sync/discovery beacons
6858             * 0 - 2.4G channels not used for beacons
6859             * 1 - 2.4G channels used for beacons
6860             */
6861             switch(val) {
6862                 case FEATURE_NOT_SUPPORTED:
6863                     msg.beacon_2dot4g_val = FEATURE_NOT_SUPPORTED;
6864                     break;
6865                 default:
6866                     msg.beacon_2dot4g_val = FEATURE_SUPPORTED;
6867                     break;
6868             }
6869         } else if (strcmp(param, "-sdf_2dot4g_val") == 0) {
6870             val = atoi(val_p);
6871             /*
6872              * Defines 2.4G channels will be used for Service Discovery frames
6873              * 0 - 2.4G channels not used for Service Discovery frames
6874              * 1 - 2.4G channels used for Service Discovery frames
6875              */
6876             switch(val) {
6877                 case FEATURE_NOT_SUPPORTED:
6878                     msg.sdf_2dot4g_val = FEATURE_NOT_SUPPORTED;
6879                     break;
6880                 default:
6881                     msg.sdf_2dot4g_val = FEATURE_SUPPORTED;
6882                     break;
6883             }
6884         } else if (strcmp(param, "-beacon_5g_val") == 0) {
6885             val = atoi(val_p);
6886             /*
6887              * Defines 5G channels will be used for sync/discovery beacons
6888              * 0 - 5G channels not used for beacons
6889              * 1 - 5G channels used for beacons
6890              */
6891             switch(val) {
6892                 case FEATURE_SUPPORTED:
6893                     msg.beacon_5g_val = FEATURE_SUPPORTED;
6894                     break;
6895                 default:
6896                     msg.beacon_5g_val = FEATURE_NOT_SUPPORTED;
6897                     break;
6898             }
6899             msg.config_5g_beacons = true;
6900         } else if (strcmp(param, "-sdf_5g_val") == 0) {
6901             val = atoi(val_p);
6902             /*
6903              * Defines 5G channels will be used for Service Discovery frames
6904              * 0 - 5G channels not used for Service Discovery frames
6905              * 1 - 5G channels used for Service Discovery frames
6906              */
6907             switch(val) {
6908                 case FEATURE_SUPPORTED:
6909                     msg.sdf_5g_val = FEATURE_SUPPORTED;
6910                     break;
6911                 default:
6912                     msg.sdf_5g_val = FEATURE_NOT_SUPPORTED;
6913                     break;
6914             }
6915             msg.config_5g_sdf = true;
6916         } else if (strcmp(param, "-rssi_close_5g_val") == 0) {
6917             msg.rssi_close_5g_val = atoi(val_p);
6918             if (msg.rssi_close_5g_val) {
6919                 msg.config_5g_rssi_close = true;
6920             }
6921         } else if (strcmp(param, "-rssi_middle_5g_val") == 0) {
6922             msg.rssi_middle_5g_val = atoi(val_p);
6923             if (msg.rssi_middle_5g_val) {
6924                 msg.config_5g_rssi_middle = true;
6925             }
6926         } else if (strcmp(param, "-rssi_close_proximity_5g_val") == 0) {
6927             msg.rssi_close_proximity_5g_val = atoi(val_p);
6928             if (msg.rssi_close_proximity_5g_val) {
6929                 msg.config_5g_rssi_close_proximity = true;
6930             }
6931         } else if (strcmp(param, "-rssi_window_size_val") == 0) {
6932             msg.rssi_window_size_val = atoi(val_p);
6933             if (msg.rssi_window_size_val) {
6934                 msg.config_rssi_window_size = true;
6935             } else {
6936                 printMsg("%s:Invalid rssi_window_size_val\n", __FUNCTION__);
6937                 msg.config_rssi_window_size = false;
6938                 ret = WIFI_ERROR_INVALID_ARGS;
6939                 goto exit;
6940             }
6941         } else if (strcmp(param, "-config_cluster_attribute_val") == 0) {
6942             val = atoi(val_p);
6943             /*
6944              * If set to 1, the Discovery Engine will enclose the Cluster
6945              * Attribute only sent in Beacons in a Vendor Specific Attribute
6946              * and transmit in a Service Descriptor Frame.
6947              */
6948 
6949             switch(val) {
6950                 case FEATURE_SUPPORTED:
6951                     msg.config_cluster_attribute_val = FEATURE_SUPPORTED;
6952                     break;
6953                 default:
6954                     msg.config_cluster_attribute_val = FEATURE_NOT_SUPPORTED;
6955                     break;
6956             }
6957         } else if (strcmp(param, "-dwell_time") == 0) {
6958             msg.scan_params_val.dwell_time[0] = atoi(val_p);
6959             if (msg.scan_params_val.dwell_time[0]) {
6960                 msg.config_scan_params = true;
6961             } else {
6962                 msg.config_scan_params = false;
6963                 printMsg("%s:Invalid config_scan_params\n", __FUNCTION__);
6964                 ret = WIFI_ERROR_INVALID_ARGS;
6965                 goto exit;
6966             }
6967         }  else if (strcmp(param, "-scan_period") == 0) {
6968                 msg.scan_params_val.scan_period[0] = atoi(val_p);
6969             if (msg.scan_params_val.scan_period[0]) {
6970                 msg.config_scan_params = true;
6971             } else {
6972                 msg.config_scan_params = false;
6973                 printMsg("%s:Invalid config_scan_params\n", __FUNCTION__);
6974                 ret = WIFI_ERROR_INVALID_ARGS;
6975                 goto exit;
6976             }
6977         } else if (strcmp(param, "-dwell_time_5g") == 0) {
6978             msg.scan_params_val.dwell_time[1] = atoi(val_p);
6979             if (msg.scan_params_val.dwell_time[1]) {
6980                 msg.config_scan_params = true;
6981             } else {
6982                 msg.config_scan_params = false;
6983                 printMsg("%s:Invalid config_scan_params for 5g\n", __FUNCTION__);
6984                 ret = WIFI_ERROR_INVALID_ARGS;
6985                 goto exit;
6986             }
6987         }  else if (strcmp(param, "-scan_period_5g") == 0) {
6988                 msg.scan_params_val.scan_period[1] = atoi(val_p);
6989             if (msg.scan_params_val.scan_period[1]) {
6990                 msg.config_scan_params = true;
6991             } else {
6992                 msg.config_scan_params = false;
6993                 printMsg("%s:Invalid config_scan_params for 5g\n", __FUNCTION__);
6994                 ret = WIFI_ERROR_INVALID_ARGS;
6995                 goto exit;
6996             }
6997         } else if (strcmp(param, "-random_factor") == 0) {
6998             msg.random_factor_force_val = atoi(val_p);
6999             if (msg.random_factor_force_val) {
7000                 msg.config_random_factor_force = true;
7001             } else {
7002                 printMsg("%s:Invalid random factor\n", __FUNCTION__);
7003                 msg.config_random_factor_force = false;
7004                 ret = WIFI_ERROR_INVALID_ARGS;
7005                 goto exit;
7006             }
7007         } else if (strcmp(param, "-24g_chan") == 0) {
7008             msg.channel_24g_val = atoi(val_p);
7009             if (msg.channel_24g_val) {
7010                 msg.config_24g_channel = true;
7011             } else {
7012                 printMsg("%s:Invalid 2.4GHz channel value\n", __FUNCTION__);
7013                 msg.config_24g_channel = false;
7014                 ret = WIFI_ERROR_INVALID_ARGS;
7015                 goto exit;
7016             }
7017         } else if (strcmp(param, "-5g_chan") == 0) {
7018             msg.channel_5g_val = atoi(val_p);
7019             if (msg.channel_5g_val) {
7020                 msg.config_5g_channel = true;
7021             } else {
7022                 printMsg("%s:Invalid 5GHz channel value\n", __FUNCTION__);
7023                 msg.config_5g_channel = false;
7024                 ret = WIFI_ERROR_INVALID_ARGS;
7025                 goto exit;
7026             }
7027         } else if (strcmp(param, "-nan_addr") == 0) {
7028             if (!ether_atoe(val_p, msg.intf_addr_val)) {
7029                 printMsg("bad nan interface mac addr, setting to random mac by fw!\n");
7030                 msg.config_intf_addr = false;
7031                 ret = WIFI_ERROR_INVALID_ARGS;
7032                 goto exit;
7033             }
7034             msg.config_intf_addr = true;
7035         } else if (strcmp(param, "-awake_dw_2g") == 0) {
7036             msg.config_dw.dw_2dot4g_interval_val = atoi(val_p);
7037             if (msg.config_dw.dw_2dot4g_interval_val) {
7038                 msg.config_dw.config_2dot4g_dw_band = true;
7039             }
7040         } else if (strcmp(param, "-awake_dw_5g") == 0) {
7041             msg.config_dw.dw_5g_interval_val = atoi(val_p);
7042             if (msg.config_dw.dw_5g_interval_val) {
7043                 msg.config_dw.config_5g_dw_band = true;
7044             }
7045         } else if (strncmp(param, "-disc_ind_cfg", strlen("-disc_ind_cfg")) == 0) {
7046             msg.discovery_indication_cfg = strtoul(val_p, &endptr, 0);
7047             printMsg("%s:disc_ind_cfg value = %d.\n",
7048                 __FUNCTION__, msg.discovery_indication_cfg);
7049         } else if (strncmp(param, "-rand_mac", strlen("-rand_mac")) == 0) {
7050             msg.config_disc_mac_addr_randomization = true;
7051             msg.disc_mac_addr_rand_interval_sec = atoi(val_p);
7052         } else if (strcmp(param, "-use_ndpe") == 0) {
7053             msg.use_ndpe_attr = atoi(val_p);
7054             msg.config_ndpe_attr = true;
7055             if ((msg.use_ndpe_attr != 1) && (msg.use_ndpe_attr != 0)) {
7056                 msg.config_ndpe_attr = false;
7057                 printMsg("%s:Invalid use_ndpe_attr value\n", __FUNCTION__);
7058                 ret = WIFI_ERROR_INVALID_ARGS;
7059                 goto exit;
7060             }
7061         } else if (strcmp(param, "-disc_bcn_interval") == 0) {
7062                 msg.discovery_beacon_interval = atoi(val_p);
7063                 msg.config_discovery_beacon_int = true;
7064         } else if (strcmp(param, "-enable_ranging") == 0) {
7065             msg.enable_ranging = atoi(val_p);
7066             if (msg.enable_ranging) {
7067                 msg.config_enable_ranging = true;
7068             }
7069         } else if (strcmp(param, "-nss") == 0) {
7070             msg.nss = atoi(val_p);
7071             if (msg.nss) {
7072                 msg.config_nss = true;
7073             }
7074         } else if (strcmp(param, "-enable_dw_term") == 0) {
7075             msg.enable_dw_termination = atoi(val_p);
7076             if (msg.enable_dw_termination) {
7077                 msg.config_dw_early_termination = true;
7078             }
7079         } else if (strcmp(param, "-instant_mode") == 0) {
7080             msg.enable_instant_mode = atoi(val_p);
7081             msg.config_enable_instant_mode = true;
7082         } else if (strcmp(param, "-instant_chan") == 0) {
7083             msg.instant_mode_channel = atoi(val_p);
7084             if (msg.instant_mode_channel) {
7085                 msg.config_instant_mode_channel = true;
7086             } else {
7087                 printMsg("%s:Invalid Instant channel \n", __FUNCTION__);
7088                 msg.config_instant_mode_channel = false;
7089                 ret = WIFI_ERROR_INVALID_ARGS;
7090                 goto exit;
7091             }
7092         } else if (strcmp(param, "-chre") == 0) {
7093             enab_for_chre = atoi(val_p);
7094         } else {
7095             printMsg("%s:Unsupported Parameter for Nan Enable\n", __FUNCTION__);
7096             ret = WIFI_ERROR_INVALID_ARGS;
7097             goto exit;
7098         }
7099     }
7100 
7101     nanCmdId = getNewCmdId();
7102 
7103     if (enab_for_chre) {
7104 #ifdef CHRE_NAN
7105         ret = nan_chre_enable_request(nanCmdId, wlan0Handle, NULL);
7106         if (ret != WIFI_SUCCESS) {
7107             printMsg("Failed to enable NAN for CHRE %d\n", ret);
7108             goto exit;
7109         }
7110 #endif /* CHRE_NAN */
7111     } else {
7112         ret = nan_init_handlers();
7113         if (ret != WIFI_SUCCESS) {
7114             printMsg("Failed to initialize handlers %d\n", ret);
7115             goto exit;
7116         }
7117         ret = nan_enable_request(nanCmdId, wlan0Handle, &msg);
7118         if (ret != WIFI_SUCCESS) {
7119             printMsg("Failed to enable NAN %d\n", ret);
7120             goto exit;
7121         }
7122     }
7123 exit:
7124     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
7125     return;
7126 }
7127 
disableNan(char * argv[])7128 void disableNan(char *argv[]) {
7129     wifi_error ret = WIFI_SUCCESS;
7130     char *param, *val_p;
7131 
7132     /* Parse args for nan params */
7133     /* skip utility */
7134     argv++;
7135     /* skip command */
7136     argv++;
7137     /* skip command */
7138     argv++;
7139 
7140     disab_for_chre = 0;
7141 
7142     while ((param = *argv++) != NULL) {
7143         val_p = *argv++;
7144         if (!val_p || *val_p == '-') {
7145             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
7146             ret = WIFI_ERROR_NOT_SUPPORTED;
7147             goto exit;
7148         }
7149         if (strcmp(param, "-chre") == 0) {
7150             disab_for_chre = atoi(val_p);
7151         }
7152     }
7153 
7154     nanCmdId = getNewCmdId();
7155 
7156     if (disab_for_chre) {
7157 #ifdef CHRE_NAN
7158         ret = nan_chre_disable_request(nanCmdId, wlan0Handle);
7159 #endif /* CHRE_NAN */
7160     } else {
7161         ret = nan_init_handlers();
7162         if (ret != WIFI_SUCCESS) {
7163             printMsg("Failed to initialize handlers %d\n", ret);
7164             return;
7165         }
7166         ret = nan_disable_request(nanCmdId, wlan0Handle);
7167     }
7168 
7169 exit:
7170     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
7171     return;
7172 }
7173 
configNan(char * argv[])7174 void configNan(char *argv[]) {
7175     NanConfigRequest msg;
7176     wifi_error ret = WIFI_SUCCESS;
7177     char *endptr, *param, *val_p;
7178     int sid_flag = 0xff, sid_count = 0xff;
7179     int sub_sid_flag = 0xff, sub_sid_count = 0xff;
7180     u8 val, numchans = 0;
7181 
7182     memset(&msg, 0, sizeof(msg));
7183     msg.fam_val.famchan[numchans].entry_control = NAN_DURATION_16MS;
7184     msg.config_ndpe_attr = false;
7185 
7186     /* Parse args for nan params */
7187     /* skip utility */
7188     argv++;
7189     /* skip command */
7190     argv++;
7191     /* skip command */
7192     argv++;
7193 
7194     while ((param = *argv++) != NULL) {
7195         val_p = *argv++;
7196         if (!val_p) {
7197             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
7198             ret = WIFI_ERROR_NOT_SUPPORTED;
7199             goto exit;
7200         }
7201 
7202         if (strcmp(param, "-sid_flag") == 0) {
7203             sid_flag = atoi(val_p);
7204             if (sid_flag) {
7205                 msg.config_sid_beacon = true;
7206             } else {
7207                 printMsg("%s:Invalid Service Id Flag. Setting to Default\n", __FUNCTION__);
7208                 msg.config_sid_beacon = false;
7209                 ret = WIFI_ERROR_INVALID_ARGS;
7210                 goto exit;
7211             }
7212         } else if (strcmp(param, "-sid_count") == 0) {
7213             sid_count = atoi(val_p);
7214             if (sid_count < 0 || sid_count > NAN_MAX_SIDS_IN_BEACONS) {
7215                 printMsg("%s:Invalid  Service ID Count Limit. Setting to Default\n", __FUNCTION__);
7216                 sid_count = 0;
7217             } else  {
7218                 msg.sid_beacon = ((sid_count << 1) | sid_flag);
7219             }
7220         } else if (strcmp(param, "-sub_sid_flag") == 0) {
7221             sub_sid_flag = atoi(val_p);
7222             if (sub_sid_flag) {
7223                 msg.config_subscribe_sid_beacon = true;
7224             } else {
7225                 printMsg("%s:Invalid Subscribe Service Id Flag. Setting to Default\n",
7226                     __FUNCTION__);
7227                 msg.config_subscribe_sid_beacon = false;
7228                 ret = WIFI_ERROR_INVALID_ARGS;
7229                 goto exit;
7230             }
7231         } else if (strcmp(param, "-sub_sid_count") == 0) {
7232             sub_sid_count = atoi(val_p);
7233             if (sub_sid_count < 0 || sub_sid_count > NAN_MAX_SIDS_IN_BEACONS) {
7234                 printMsg("%s:Invalid Subscribe Service ID Count Limit. Setting to Default\n",
7235                     __FUNCTION__);
7236                 sub_sid_count = 0;
7237             } else  {
7238                 msg.subscribe_sid_beacon_val = ((sub_sid_count << 1) | sub_sid_flag);
7239             }
7240         } else if (strcmp(param, "-rssi_proximity") == 0) {
7241             msg.rssi_proximity = atoi(val_p);
7242             if (msg.rssi_proximity) {
7243                 msg.config_rssi_proximity = true;
7244             } else {
7245                 printMsg("%s:Invalid rssi proximity\n", __FUNCTION__);
7246                 msg.config_rssi_proximity = false;
7247                 ret = WIFI_ERROR_INVALID_ARGS;
7248                 goto exit;
7249             }
7250         } else if (strcmp(param, "-master_pref") == 0) {
7251             msg.master_pref = atoi(val_p);
7252             if (msg.master_pref) {
7253                 msg.config_master_pref = true;
7254             } else {
7255                 printMsg("%s:Invalid master_pref\n", __FUNCTION__);
7256                 msg.config_master_pref = false;
7257                 ret = WIFI_ERROR_INVALID_ARGS;
7258                 goto exit;
7259             }
7260         } else if (strcmp(param, "-rssi_close_prox_5g") == 0) {
7261             msg.rssi_close_proximity_5g_val = atoi(val_p);
7262             if (msg.rssi_close_proximity_5g_val) {
7263                 msg.config_5g_rssi_close_proximity = true;
7264             } else {
7265                 printMsg("%s:Invalid 5g rssi close proximity \n", __FUNCTION__);
7266                 msg.config_5g_rssi_close_proximity = false;
7267                 ret = WIFI_ERROR_INVALID_ARGS;
7268                 goto exit;
7269             }
7270         } else if (strcmp(param, "-rssi_window_size_val") == 0) {
7271             msg.rssi_window_size_val = atoi(val_p);
7272             if (msg.rssi_window_size_val) {
7273                 msg.config_rssi_window_size = true;
7274             } else {
7275                 printMsg("%s:Invalid rssi window size val \n", __FUNCTION__);
7276                 msg.config_rssi_window_size = false;
7277                 ret = WIFI_ERROR_INVALID_ARGS;
7278                 goto exit;
7279             }
7280         } else if (strcmp(param, "-config_cluster_attribute_val") == 0) {
7281             val = atoi(val_p);
7282             /*
7283              * If set to 1, the Discovery Engine will enclose the Cluster
7284              * Attribute only sent in Beacons in a Vendor Specific Attribute
7285              * and transmit in a Service Descriptor Frame.
7286              */
7287 
7288             switch(val) {
7289                 case FEATURE_SUPPORTED:
7290                     msg.config_cluster_attribute_val = FEATURE_SUPPORTED;
7291                     break;
7292                 default:
7293                     msg.config_cluster_attribute_val = FEATURE_NOT_SUPPORTED;
7294                     break;
7295             }
7296         } else if (strcmp(param, "-dwell_time") == 0) {
7297             msg.scan_params_val.dwell_time[0] = atoi(val_p);
7298             if (msg.scan_params_val.dwell_time[0]) {
7299                 msg.config_scan_params = true;
7300             } else {
7301                 msg.config_scan_params = false;
7302                 printMsg("%s:Invalid config_scan_params\n", __FUNCTION__);
7303                 ret = WIFI_ERROR_INVALID_ARGS;
7304                 goto exit;
7305             }
7306         }  else if (strcmp(param, "-scan_period") == 0) {
7307             msg.scan_params_val.scan_period[0] = atoi(val_p);
7308             if (msg.scan_params_val.scan_period[0]) {
7309                 msg.config_scan_params = true;
7310             } else {
7311                 msg.config_scan_params = false;
7312                 printMsg("%s:Invalid config_scan_params\n", __FUNCTION__);
7313                 ret = WIFI_ERROR_INVALID_ARGS;
7314                 goto exit;
7315             }
7316         } else if (strcmp(param, "-dwell_time_5g") == 0) {
7317             msg.scan_params_val.dwell_time[1] = atoi(val_p);
7318             if (msg.scan_params_val.dwell_time[1]) {
7319                 msg.config_scan_params = true;
7320             } else {
7321                 msg.config_scan_params = false;
7322                 printMsg("%s:Invalid config_scan_params for 5g\n", __FUNCTION__);
7323                 ret = WIFI_ERROR_INVALID_ARGS;
7324                 goto exit;
7325             }
7326         }  else if (strcmp(param, "-scan_period_5g") == 0) {
7327                 msg.scan_params_val.scan_period[1] = atoi(val_p);
7328             if (msg.scan_params_val.scan_period[1]) {
7329                 msg.config_scan_params = true;
7330             } else {
7331                 msg.config_scan_params = false;
7332                 printMsg("%s:Invalid config_scan_params for 5g\n", __FUNCTION__);
7333                 ret = WIFI_ERROR_INVALID_ARGS;
7334                 goto exit;
7335             }
7336         } else if (strcmp(param, "-random_factor") == 0) {
7337             msg.random_factor_force_val = atoi(val_p);
7338             if (msg.random_factor_force_val) {
7339                 msg.config_random_factor_force = true;
7340             } else {
7341                 printMsg("%s:Invalid random factor\n", __FUNCTION__);
7342                 msg.config_random_factor_force = false;
7343                 ret = WIFI_ERROR_INVALID_ARGS;
7344                 goto exit;
7345             }
7346         } else if (strcmp(param, "-hc_limit") == 0) {
7347             msg.hop_count_force_val = atoi(val_p);
7348             if (msg.hop_count_force_val) {
7349                 msg.config_hop_count_force = true;
7350             } else {
7351                 printMsg("%s:Invalid hop_count_force_val. Setting to Default\n", __FUNCTION__);
7352                 msg.config_hop_count_force = false;
7353                 ret = WIFI_ERROR_INVALID_ARGS;
7354                 goto exit;
7355             }
7356         } else if (strcmp(param, "-numchans") == 0) {
7357             numchans = atoi(val_p);
7358             if (numchans && (numchans < NAN_MAX_FAM_CHANNELS)) {
7359                 msg.config_fam = true;
7360                 msg.fam_val.numchans = numchans;
7361             } else {
7362                 printMsg("%s:Invalid num chan\n", __FUNCTION__);
7363                 msg.config_fam = false;
7364                 ret = WIFI_ERROR_INVALID_ARGS;
7365                 goto exit;
7366             }
7367         } else if (strcmp(param, "-entry_control") == 0) {
7368             val = atoi(val_p);
7369             msg.config_fam = true;
7370             switch(val) {
7371             case NAN_DURATION_16MS:
7372                 msg.fam_val.famchan[numchans].entry_control = NAN_DURATION_16MS;
7373                 break;
7374             case NAN_DURATION_32MS:
7375                 msg.fam_val.famchan[numchans].entry_control = NAN_DURATION_32MS;
7376                 break;
7377             case NAN_DURATION_64MS:
7378                 msg.fam_val.famchan[numchans].entry_control = NAN_DURATION_64MS;
7379                 break;
7380             default:
7381                 printMsg("%s: Invalid entry_control\n", __FUNCTION__);
7382                 ret = WIFI_ERROR_INVALID_ARGS;
7383                 msg.config_fam = false;
7384                 break;
7385             }
7386         } else if (strcmp(param, "-class_val") == 0) {
7387             msg.fam_val.famchan[numchans].class_val = atoi(val_p);
7388             if (msg.fam_val.famchan[numchans].class_val) {
7389                 msg.config_fam = true;
7390             } else {
7391                 printMsg("%s:Invalid fam val\n", __FUNCTION__);
7392                 msg.config_fam = false;
7393                 ret = WIFI_ERROR_INVALID_ARGS;
7394                 goto exit;
7395             }
7396         } else if (strcmp(param, "-channel") == 0) {
7397             msg.fam_val.famchan[numchans].channel = atoi(val_p);
7398             if (msg.fam_val.famchan[numchans].channel) {
7399                 msg.config_fam = true;
7400             } else {
7401                 printMsg("%s:Invalid fam val\n", __FUNCTION__);
7402                 msg.config_fam = false;
7403                 ret = WIFI_ERROR_INVALID_ARGS;
7404                 goto exit;
7405             }
7406         } else if (strcmp(param, "-mapid") == 0) {
7407             msg.fam_val.famchan[numchans].mapid = atoi(val_p);
7408             if (msg.fam_val.famchan[numchans].mapid) {
7409                 msg.config_fam = true;
7410             } else {
7411                 printMsg("%s:Invalid fam val\n", __FUNCTION__);
7412                 msg.config_fam = false;
7413                 ret = WIFI_ERROR_INVALID_ARGS;
7414                 goto exit;
7415             }
7416         } else if (strcmp(param, "-avail_interval_bitmap") == 0) {
7417             msg.fam_val.famchan[numchans].avail_interval_bitmap = atoi(val_p);
7418             printMsg("avail_interval_bitmap = %d\n",
7419                 msg.fam_val.famchan[numchans].avail_interval_bitmap);
7420             if (msg.fam_val.famchan[numchans].avail_interval_bitmap) {
7421                 msg.config_fam = true;
7422             } else {
7423                 printMsg("%s:Invalid fam val\n", __FUNCTION__);
7424                 msg.config_fam = false;
7425                 ret = WIFI_ERROR_INVALID_ARGS;
7426                 goto exit;
7427             }
7428         } else if (strcmp(param, "-awake_dw_2g") == 0) {
7429             msg.config_dw.dw_2dot4g_interval_val = atoi(val_p);
7430             if (msg.config_dw.dw_2dot4g_interval_val) {
7431                 msg.config_dw.config_2dot4g_dw_band = true;
7432             }
7433         } else if (strcmp(param, "-awake_dw_5g") == 0) {
7434             msg.config_dw.dw_5g_interval_val = atoi(val_p);
7435             if (msg.config_dw.dw_5g_interval_val) {
7436                 msg.config_dw.config_5g_dw_band = true;
7437             }
7438         } else if (strncmp(param, "-disc_ind_cfg", strlen("-disc_ind_cfg")) == 0) {
7439                 msg.discovery_indication_cfg = strtoul(val_p, &endptr, 0);
7440                 printMsg("%s:disc_ind_cfg value = %d.\n",
7441                     __FUNCTION__, msg.discovery_indication_cfg);
7442         } else if (strcmp(param, "-use_ndpe") == 0) {
7443             msg.use_ndpe_attr = atoi(val_p);
7444             msg.config_ndpe_attr = true;
7445             if ((msg.use_ndpe_attr != 1) && (msg.use_ndpe_attr != 0)) {
7446                 msg.config_ndpe_attr = false;
7447                 printMsg("%s:Invalid use_ndpe_attr value\n", __FUNCTION__);
7448                 ret = WIFI_ERROR_INVALID_ARGS;
7449                 goto exit;
7450             }
7451         } else if (strncmp(param, "-rand_mac", strlen("-rand_mac")) == 0) {
7452             msg.config_disc_mac_addr_randomization = true;
7453             msg.disc_mac_addr_rand_interval_sec = atoi(val_p);
7454         } else if (strcmp(param, "-disc_bcn_interval") == 0) {
7455                 msg.discovery_beacon_interval = atoi(val_p);
7456                 msg.config_discovery_beacon_int = true;
7457         } else if (strcmp(param, "-enable_ranging") == 0) {
7458             msg.enable_ranging = atoi(val_p);
7459             if (msg.enable_ranging) {
7460                 msg.config_enable_ranging = true;
7461             }
7462         } else if (strcmp(param, "-nss") == 0) {
7463             msg.nss = atoi(val_p);
7464             if (msg.nss) {
7465                 msg.config_nss = true;
7466             }
7467         } else if (strcmp(param, "-enable_dw_term") == 0) {
7468             msg.enable_dw_termination = atoi(val_p);
7469             if (msg.enable_dw_termination) {
7470                 msg.config_dw_early_termination = true;
7471             }
7472         } else if (strcmp(param, "-instant_mode") == 0) {
7473             msg.enable_instant_mode = atoi(val_p);
7474             msg.config_enable_instant_mode = true;
7475         } else if (strcmp(param, "-instant_chan") == 0) {
7476             msg.instant_mode_channel = atoi(val_p);
7477             if (msg.instant_mode_channel) {
7478                 msg.config_instant_mode_channel = true;
7479             } else {
7480                 printMsg("%s:Invalid Instant channel \n", __FUNCTION__);
7481                 msg.config_instant_mode_channel = false;
7482                 ret = WIFI_ERROR_INVALID_ARGS;
7483                 goto exit;
7484             }
7485         } else {
7486             printMsg("%s:Unsupported Parameter for Nan Config\n", __FUNCTION__);
7487             ret = WIFI_ERROR_INVALID_ARGS;
7488             goto exit;
7489         }
7490     }
7491 
7492     nanCmdId = getNewCmdId();
7493     ret = nan_init_handlers();
7494     if (ret != WIFI_SUCCESS) {
7495         printMsg("Failed to initialize handlers %d\n", ret);
7496         goto exit;
7497     }
7498     ret = nan_config_request(nanCmdId, wlan0Handle, &msg);
7499 exit:
7500     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
7501     return;
7502 }
7503 
publishNan(int argc,char * argv[])7504 void publishNan(int argc, char *argv[]) {
7505     NanPublishRequest msg;
7506     wifi_error ret = WIFI_SUCCESS;
7507     char *param = NULL, *val_p = NULL, *endptr = NULL;
7508     u32 val = 0;
7509     u8 *match_rxtmp = NULL, *match_txtmp = NULL;
7510 
7511     memset(&msg, 0, sizeof(msg));
7512     msg.publish_id = 0;
7513     msg.publish_type = NAN_PUBLISH_TYPE_UNSOLICITED_SOLICITED;
7514     msg.publish_match_indicator = NAN_MATCH_ALG_MATCH_CONTINUOUS;
7515     msg.tx_type = NAN_TX_TYPE_UNICAST;
7516     msg.sdea_params.ndp_type = NAN_DATA_PATH_UNICAST_MSG;
7517     msg.service_responder_policy = NAN_SERVICE_ACCEPT_POLICY_NONE;
7518     msg.period = 1;
7519 
7520     /* skip utility */
7521     argv++;
7522     /* skip command */
7523     argv++;
7524     /* skip command */
7525     argv++;
7526 
7527     while ((param = *argv++) != NULL) {
7528         val_p = *argv++;
7529         if (!val_p || *val_p == '-') {
7530             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
7531             ret = WIFI_ERROR_NOT_SUPPORTED;
7532             goto exit;
7533         }
7534         if (strcmp(param, "-svc") == 0) {
7535             if (strlen((const char *)val_p) > NAN_MAX_SERVICE_NAME_LEN) {
7536                 printMsg("Invalid  service name\n");
7537                 ret = WIFI_ERROR_INVALID_ARGS;
7538                 goto exit;
7539             } else {
7540                 msg.service_name_len =
7541                 strlen((const char *)val_p);
7542                 if (!set_interface_params((char*)msg.service_name,
7543                     val_p, msg.service_name_len)) {
7544                     printMsg("Set service name successfull\n");
7545                 }
7546             }
7547         } else if (strcmp(param, "-info") == 0) {
7548             if (strlen((const char*)val_p) > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
7549                 printMsg("Invalid  service specific info\n");
7550                 ret = WIFI_ERROR_INVALID_ARGS;
7551                 goto exit;
7552             } else {
7553                 msg.service_specific_info_len =
7554                 strlen((const char*)val_p);
7555                 if (!set_interface_params((char*)msg.service_specific_info,
7556                     val_p, msg.service_specific_info_len)) {
7557                     printMsg("Set service specific info successfull\n");
7558                 }
7559             }
7560         } else if (strcmp(param, "-pub_count") == 0) {
7561             msg.publish_count = strtoul(val_p, &endptr, 0);
7562         } else if (strcmp(param, "-pub_id") == 0) {
7563             msg.publish_id = strtoul(val_p, &endptr, 0);
7564         } else if (strcmp(param, "-pub_type") == 0) {
7565             val = atoi(val_p);
7566             switch(val) {
7567                 case NAN_PUBLISH_TYPE_UNSOLICITED:
7568                     msg.publish_type = NAN_PUBLISH_TYPE_UNSOLICITED;
7569                     break;
7570                 case NAN_PUBLISH_TYPE_SOLICITED:
7571                     msg.publish_type = NAN_PUBLISH_TYPE_SOLICITED;
7572                     break;
7573                 default:
7574                     msg.publish_type = NAN_PUBLISH_TYPE_UNSOLICITED_SOLICITED;
7575                     break;
7576             }
7577         } else if (strcmp(param, "-tx_type") == 0) {
7578             val = atoi(val_p);
7579             switch(val) {
7580                 case NAN_TX_TYPE_BROADCAST:
7581                     msg.tx_type = NAN_TX_TYPE_BROADCAST;
7582                     break;
7583                 default:
7584                     msg.tx_type = NAN_TX_TYPE_UNICAST;
7585                     break;
7586             }
7587         } else if (strcmp(param, "-ttl") == 0) {
7588             msg.ttl = strtoul(val_p, &endptr, 0);
7589         } else if (strcmp(param, "-svc_awake_dw") == 0) {
7590             msg.period = strtoul(val_p, &endptr, 0);
7591         } else if (strcmp(param, "-match_tx") == 0) {
7592             u8 m_len = strlen(val_p);
7593             if (!match_txtmp) {
7594                 match_txtmp = msg.tx_match_filter;
7595             }
7596             if (strcmp(val_p, "0") == 0) {
7597                 printMsg("wild card\n");
7598                 if (m_len < (NAN_MAX_MATCH_FILTER_LEN - msg.tx_match_filter_len)) {
7599                     *match_txtmp++ = 0;
7600                     msg.tx_match_filter_len++;
7601                 }
7602             } else {
7603                 if (m_len < (NAN_MAX_MATCH_FILTER_LEN - msg.tx_match_filter_len)) {
7604                     *match_txtmp++ = strlen(val_p);
7605                     msg.tx_match_filter_len++;
7606                     strncpy((char *)match_txtmp, val_p, strlen(val_p));
7607                     match_txtmp += m_len;
7608                     msg.tx_match_filter_len += m_len;
7609                 } else {
7610                     printMsg("Invalid match filter len\n");
7611                     ret = WIFI_ERROR_INVALID_ARGS;
7612                     goto exit;
7613                 }
7614             }
7615         } else if (strcmp(param, "-match_rx") == 0) {
7616             u8 m_len = strlen(val_p);
7617             if (!match_rxtmp) {
7618                 match_rxtmp = msg.rx_match_filter;
7619             }
7620             if (strcmp(val_p, "0") == 0) {
7621                 printMsg("wild card\n");
7622                 if (m_len < (NAN_MAX_MATCH_FILTER_LEN - msg.rx_match_filter_len)) {
7623                     *match_rxtmp++ = 0;
7624                     msg.rx_match_filter_len++;
7625                 }
7626             } else {
7627                 if (m_len < (NAN_MAX_MATCH_FILTER_LEN - msg.rx_match_filter_len)) {
7628                     *match_rxtmp++ = strlen(val_p);
7629                     msg.rx_match_filter_len++;
7630                     strncpy((char *)match_rxtmp, val_p, strlen(val_p));
7631                     match_rxtmp += m_len;
7632                     msg.rx_match_filter_len += m_len;
7633                 } else {
7634                     printMsg("Invalid match filter len\n");
7635                     ret = WIFI_ERROR_INVALID_ARGS;
7636                     goto exit;
7637                 }
7638             }
7639         } else if (strncmp(param, "-recv_flag", strlen("-recv_flag")) == 0) {
7640             msg.recv_indication_cfg = strtoul(val_p, &endptr, 0);
7641         } else if (strcmp(param, "-match_ind") == 0) {
7642             val = atoi(val_p);
7643             switch(val) {
7644                 case NAN_MATCH_ALG_MATCH_ONCE:
7645                     msg.publish_match_indicator = NAN_MATCH_ALG_MATCH_ONCE;
7646                     break;
7647                 case NAN_MATCH_ALG_MATCH_NEVER:
7648                     msg.publish_match_indicator = NAN_MATCH_ALG_MATCH_NEVER;
7649                     break;
7650                 default:
7651                     msg.publish_match_indicator = NAN_MATCH_ALG_MATCH_CONTINUOUS;
7652                     break;
7653             }
7654         } else if (strcmp(param, "-csid") == 0) {
7655             val = atoi(val_p);
7656             switch(val) {
7657                 case NAN_CIPHER_SUITE_SHARED_KEY_NONE:
7658                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_NONE;
7659                     break;
7660                 case NAN_CIPHER_SUITE_SHARED_KEY_128_MASK:
7661                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_128_MASK;
7662                     break;
7663                 case NAN_CIPHER_SUITE_SHARED_KEY_256_MASK:
7664                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_256_MASK;
7665                     break;
7666                 case NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_128_MASK:
7667                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_128_MASK;
7668                     break;
7669                 case NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_256_MASK:
7670                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_256_MASK;
7671                     break;
7672                 case NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_128_MASK:
7673                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_128_MASK;
7674                     break;
7675                 case NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_256_MASK:
7676                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_256_MASK;
7677                     break;
7678                 default:
7679                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_NONE;
7680                     break;
7681             }
7682         } else if (strcmp(param, "-key_type") == 0) {
7683             val = atoi(val_p);
7684             switch(val) {
7685                 case NAN_SECURITY_KEY_INPUT_PMK:
7686                     msg.key_info.key_type = NAN_SECURITY_KEY_INPUT_PMK;
7687                     break;
7688                 case NAN_SECURITY_KEY_INPUT_PASSPHRASE:
7689                     msg.key_info.key_type = NAN_SECURITY_KEY_INPUT_PASSPHRASE;
7690                     break;
7691                 default:
7692                     printMsg("Invalid security key type\n");
7693                     ret = WIFI_ERROR_INVALID_ARGS;
7694                     goto exit;
7695             }
7696         } else if (strcmp(param, "-pmk") == 0) {
7697             if (strlen((const char*)val_p) > NAN_PMK_INFO_LEN) {
7698                 printMsg("Invalid PMK\n");
7699                 ret = WIFI_ERROR_INVALID_ARGS;
7700                 goto exit;
7701             } else {
7702                 msg.key_info.body.pmk_info.pmk_len=
7703                 strlen((const char*)val_p);
7704                 if (!set_interface_params((char*)msg.key_info.body.pmk_info.pmk,
7705                     val_p, msg.key_info.body.pmk_info.pmk_len)) {
7706                     printMsg("Set PMK successfull\n");
7707                 }
7708             }
7709         } else if (strcmp(param, "-passphrase") == 0) {
7710             if (strlen((const char*)val_p) < NAN_SECURITY_MIN_PASSPHRASE_LEN ||
7711                 strlen((const char*)val_p) > NAN_SECURITY_MAX_PASSPHRASE_LEN) {
7712                 printMsg("passphrase must be between %d and %d characters long\n",
7713                 NAN_SECURITY_MIN_PASSPHRASE_LEN,
7714                 NAN_SECURITY_MAX_PASSPHRASE_LEN);
7715                 ret = WIFI_ERROR_INVALID_ARGS;
7716                 goto exit;
7717             } else {
7718                 msg.key_info.body.passphrase_info.passphrase_len =
7719                 (strlen((const char*)val_p));
7720                 if (!set_interface_params((char*)msg.key_info.body.passphrase_info.passphrase,
7721                     val_p, msg.key_info.body.passphrase_info.passphrase_len)) {
7722                     printMsg("Set passphrase successfull, len = %d\n",
7723                         msg.key_info.body.passphrase_info.passphrase_len);
7724                 } else {
7725                     printMsg("Invalid passphrase\n");
7726                     ret = WIFI_ERROR_INVALID_ARGS;
7727                     goto exit;
7728                 }
7729             }
7730         } else if (strcmp(param, "-scid") == 0) {
7731             if (strlen((const char*)val_p) > NAN_MAX_SCID_BUF_LEN) {
7732                printMsg("Invalid SCID\n");
7733                ret = WIFI_ERROR_INVALID_ARGS;
7734                goto exit;
7735             } else {
7736                msg.scid_len=
7737                strlen((const char*)val_p);
7738                if (!set_interface_params((char*)msg.scid,
7739                   val_p, msg.scid_len)) {
7740                   printMsg("Set SCID successfull\n");
7741                }
7742             }
7743         } else if (strcmp(param, "-dp_type") == 0) {
7744             val = atoi(val_p);
7745             msg.sdea_params.config_nan_data_path = true;
7746             switch(val) {
7747                 case NAN_DATA_PATH_MULTICAST_MSG:
7748                     msg.sdea_params.ndp_type = NAN_DATA_PATH_MULTICAST_MSG;
7749                     break;
7750                 case NAN_DATA_PATH_UNICAST_MSG:
7751                     msg.sdea_params.ndp_type = NAN_DATA_PATH_UNICAST_MSG;
7752                     break;
7753                 default:
7754                     printMsg("Invalid datapath type\n");
7755                     msg.sdea_params.config_nan_data_path = false;
7756                     ret = WIFI_ERROR_INVALID_ARGS;
7757                     break;
7758             }
7759         } else if (strcmp(param, "-secure_dp") == 0) {
7760             val = atoi(val_p);
7761             switch(val) {
7762                 case NAN_DP_CONFIG_SECURITY:
7763                     msg.sdea_params.security_cfg = NAN_DP_CONFIG_SECURITY;
7764                     break;
7765                 default:
7766                     msg.sdea_params.security_cfg = NAN_DP_CONFIG_NO_SECURITY;
7767                     break;
7768             }
7769         } else if (strcmp(param, "-ranging") == 0) {
7770             val = atoi(val_p);
7771             switch(val) {
7772                 case NAN_RANGING_ENABLE:
7773                     msg.sdea_params.ranging_state = NAN_RANGING_ENABLE;
7774                     break;
7775                 default:
7776                     msg.sdea_params.ranging_state = NAN_RANGING_DISABLE;
7777                     break;
7778                 }
7779         } else if (strcmp(param, "-ranging_intvl") == 0) {
7780             msg.ranging_cfg.ranging_interval_msec = atoi(val_p);
7781         } else if (strcmp(param, "-ranging_ind") == 0) {
7782             msg.ranging_cfg.config_ranging_indications = atoi(val_p);
7783         } else if (strcmp(param, "-ingress") == 0) {
7784             msg.ranging_cfg.distance_ingress_mm = atoi(val_p);
7785         } else if (strcmp(param, "-egress") == 0) {
7786             msg.ranging_cfg.distance_egress_mm= atoi(val_p);
7787         } else if (strcmp(param, "-rssi_thresh_flag") == 0) {
7788             msg.rssi_threshold_flag = atoi(val_p);
7789         } else if (strcmp(param, "-sdea_info") == 0) {
7790             if (strlen((const char*)val_p) > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
7791                 printMsg("Invalid SDEA service specific info\n");
7792                 ret = WIFI_ERROR_INVALID_ARGS;
7793                 goto exit;
7794             } else {
7795                 msg.sdea_service_specific_info_len =
7796                    strlen((const char*)val_p);
7797                 if (!set_interface_params((char*)msg.sdea_service_specific_info,
7798                     val_p, msg.sdea_service_specific_info_len)) {
7799                         printMsg("Set SDEA service specific info successfull\n");
7800                 }
7801             }
7802         } else if (strcmp(param, "-auto_dp_accept") == 0) {
7803             val = atoi(val_p);
7804             switch(val) {
7805                 case NAN_SERVICE_ACCEPT_POLICY_ALL:
7806                 msg.service_responder_policy = NAN_SERVICE_ACCEPT_POLICY_ALL;
7807                 break;
7808                 default:
7809                 msg.service_responder_policy = NAN_SERVICE_ACCEPT_POLICY_NONE;
7810                 break;
7811             }
7812         } else if (strcmp(param, "-suspendable") == 0) {
7813             val = atoi(val_p);
7814             if (val) {
7815                 msg.enable_suspendability = true;
7816             }
7817         } else if (strcmp(param, "-nik") == 0) {
7818             int len = str2hex(val_p, (char*)msg.nan_identity_key);
7819 
7820             if (len != NAN_IDENTITY_KEY_LEN) {
7821                 printMsg("Invalid local NIK info, len %d expected 16 bytes \n", len);
7822                 ret = WIFI_ERROR_INVALID_ARGS;
7823                 goto exit;
7824             } else {
7825                 prhex_msg("NIK", msg.nan_identity_key, NAN_IDENTITY_KEY_LEN);
7826             }
7827         } else if (strcmp(param, "-bs_methods") == 0) {
7828             msg.nan_pairing_config.supported_bootstrapping_methods = atoi(val_p);
7829         } else if (strcmp(param, "-pairing_setup") == 0) {
7830             msg.nan_pairing_config.enable_pairing_setup = atoi(val_p);
7831         } else if (strcmp(param, "-pairing_cache") == 0) {
7832             msg.nan_pairing_config.enable_pairing_cache = atoi(val_p);
7833         } else if (strcmp(param, "-pairing_verification") == 0) {
7834             msg.nan_pairing_config.enable_pairing_verification = atoi(val_p);
7835         } else {
7836             printMsg("%s:Unsupported Parameter for Nan Publish\n", __FUNCTION__);
7837             goto exit;
7838         }
7839     }
7840     if (!msg.service_name_len) {
7841         printMsg("service name is mandatory !!\n");
7842         goto exit;
7843     }
7844 
7845     nanCmdId = getNewCmdId();
7846     ret = nan_init_handlers();
7847     if (ret != WIFI_SUCCESS) {
7848         printMsg("Failed to initialize handlers %d\n", ret);
7849         goto exit;
7850     }
7851     ret = nan_publish_request(nanCmdId, wlan0Handle, &msg);
7852 exit:
7853     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
7854     return;
7855 }
7856 
subscribeNan(int argc,char * argv[])7857 void subscribeNan(int argc, char *argv[]) {
7858     NanSubscribeRequest msg;
7859     wifi_error ret = WIFI_SUCCESS;
7860     char *param = NULL, *val_p = NULL, *endptr = NULL;
7861     u8 num_mac_addr = 0;
7862     u32 val = 0;
7863     u8 *match_rxtmp = NULL, *match_txtmp = NULL;
7864 
7865     memset(&msg, 0, sizeof(msg));
7866 
7867     /* set mandatory default values */
7868     msg.subscribe_id = 0;
7869     msg.subscribe_type = NAN_SUBSCRIBE_TYPE_PASSIVE;
7870     msg.useServiceResponseFilter = NAN_DO_NOT_USE_SRF;
7871     /*
7872      * Set NAN_MATCH_ALG_MATCH_ONCE as default param to avoid
7873      * flooding of discovery result events
7874      */
7875     msg.subscribe_match_indicator = NAN_MATCH_ALG_MATCH_ONCE;
7876     msg.sdea_params.ndp_type = NAN_DATA_PATH_UNICAST_MSG;
7877     msg.rx_match_filter_len = 0;
7878     msg.tx_match_filter_len = 0;
7879     msg.period = 1;
7880 
7881     /* skip utility */
7882     argv++;
7883     /* skip command */
7884     argv++;
7885     /* skip command */
7886     argv++;
7887 
7888     while ((param = *argv++) != NULL) {
7889         val_p = *argv++;
7890         if (!val_p || *val_p == '-') {
7891             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
7892             ret = WIFI_ERROR_NOT_SUPPORTED;
7893             goto exit;
7894         }
7895         if (strcmp(param, "-svc") == 0) {
7896             if (strlen((const char *)val_p) > NAN_MAX_SERVICE_NAME_LEN) {
7897                 printMsg("Invalid service name\n");
7898                 ret = WIFI_ERROR_INVALID_ARGS;
7899                 goto exit;
7900             } else {
7901                 msg.service_name_len =
7902                 strlen((const char *)val_p);
7903                 if (!set_interface_params((char*)msg.service_name,
7904                     val_p, msg.service_name_len)) {
7905                         printMsg("Set service name successfull\n");
7906                 }
7907             }
7908         } else if (strcmp(param, "-info") == 0) {
7909             if (strlen((const char*)val_p) > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
7910                 printMsg("Invalid  service specific info\n");
7911                 ret = WIFI_ERROR_INVALID_ARGS;
7912                 goto exit;
7913             } else {
7914                 msg.service_specific_info_len =
7915                 strlen((const char*)val_p);
7916                 if (!set_interface_params((char*)msg.service_specific_info,
7917                     val_p, msg.service_specific_info_len)) {
7918                     printMsg("Set service specific info successfull\n");
7919                 }
7920             }
7921         } else if (strcmp(param, "-sub_count") == 0) {
7922             msg.subscribe_count = strtoul(val_p, &endptr, 0);
7923         } else if (strcmp(param, "-pub_ssi") == 0) {
7924             val = atoi(val_p);
7925             /*
7926              * Flag which specifies if the Service Specific Info is needed in
7927              * the Publish message before creating the MatchIndication
7928              */
7929             /* 0= Not needed, 1= Required */
7930             switch(val) {
7931                 case NAN_SSI_REQUIRED_IN_MATCH_IND:
7932                     msg.ssiRequiredForMatchIndication = NAN_SSI_REQUIRED_IN_MATCH_IND;
7933                     break;
7934                 default:
7935                     msg.ssiRequiredForMatchIndication = NAN_SSI_NOT_REQUIRED_IN_MATCH_IND;
7936                     break;
7937             }
7938         } else if (strcmp(param, "-sub_id") == 0) {
7939             msg.subscribe_id = strtoul(val_p, &endptr, 0);
7940         } else if (strcmp(param, "-sub_type") == 0) {
7941             val = atoi(val_p);
7942             switch(val) {
7943                 case NAN_SUBSCRIBE_TYPE_ACTIVE:
7944                     msg.subscribe_type = NAN_SUBSCRIBE_TYPE_ACTIVE;
7945                     break;
7946                 default:
7947                     msg.subscribe_type = NAN_SUBSCRIBE_TYPE_PASSIVE;
7948                     break;
7949             }
7950         } else if (strcmp(param, "-ttl") == 0) {
7951             msg.ttl = strtoul(val_p, &endptr, 0);
7952         } else if (strcmp(param, "-svc_awake_dw") == 0) {
7953             msg.period = strtoul(val_p, &endptr, 0);
7954         } else if (strncmp(param, "-srf_use", strlen("-srf_use")) == 0) {
7955             val = atoi(val_p);
7956             /* 0=Do not send the Service Response Filter,1= send */
7957             switch(val) {
7958                 case NAN_USE_SRF:
7959                     msg.useServiceResponseFilter = NAN_USE_SRF;
7960                     break;
7961                 default:
7962                     msg.useServiceResponseFilter = NAN_DO_NOT_USE_SRF;
7963                     break;
7964             }
7965         } else if (strncmp(param, "-srf_include", strlen("-srf_include")) == 0) {
7966             val = strtoul(val_p, &endptr, 0);
7967             /* 0=Do not respond if in the Address Set, 1= Respond */
7968             switch(val) {
7969                 case NAN_SRF_INCLUDE_RESPOND:
7970                     msg.serviceResponseInclude = NAN_SRF_INCLUDE_RESPOND;
7971                     break;
7972                 default:
7973                     msg.serviceResponseInclude = NAN_SRF_INCLUDE_DO_NOT_RESPOND;
7974                     break;
7975             }
7976         } else if (strncmp(param, "-srf_type", strlen("-srf_type")) == 0) {
7977             val = atoi(val_p);
7978             /* 0 - Bloom Filter, 1 - MAC Addr */
7979             switch(val) {
7980                 case NAN_SRF_ATTR_PARTIAL_MAC_ADDR:
7981                     msg.serviceResponseFilter = NAN_SRF_ATTR_PARTIAL_MAC_ADDR;
7982                     break;
7983                 default:
7984                     msg.serviceResponseFilter = NAN_SRF_ATTR_BLOOM_FILTER;
7985                     break;
7986             }
7987         } else if (strcmp(param, "-mac_list") == 0) {
7988             if (num_mac_addr < NAN_MAX_SUBSCRIBE_MAX_ADDRESS) {
7989                 if (!ether_atoe(val_p, msg.intf_addr[num_mac_addr])) {
7990                     printMsg("bad mac addr !!\n");
7991                     ret = WIFI_ERROR_INVALID_ARGS;
7992                     goto exit;
7993                 }
7994                 msg.num_intf_addr_present = ++num_mac_addr;
7995             } else {
7996                 printMsg("max limit reached, %d!!!\n", num_mac_addr);
7997                 ret = WIFI_ERROR_INVALID_ARGS;
7998                 goto exit;
7999             }
8000             if (msg.num_intf_addr_present) {
8001                 msg.useServiceResponseFilter = NAN_USE_SRF;
8002                 msg.serviceResponseFilter = NAN_SRF_ATTR_PARTIAL_MAC_ADDR;
8003             }
8004         } else if (strcmp(param, "-match_ind") == 0) {
8005             val = atoi(val_p);
8006             switch(val) {
8007                 case NAN_MATCH_ALG_MATCH_ONCE:
8008                     msg.subscribe_match_indicator = NAN_MATCH_ALG_MATCH_ONCE;
8009                     break;
8010                 case NAN_MATCH_ALG_MATCH_NEVER:
8011                     msg.subscribe_match_indicator = NAN_MATCH_ALG_MATCH_NEVER;
8012                     break;
8013                 default:
8014                     msg.subscribe_match_indicator = NAN_MATCH_ALG_MATCH_CONTINUOUS;
8015                     break;
8016             }
8017         } else if (strcmp(param, "-match_tx") == 0) {
8018             u8 m_len = strlen(val_p);
8019             if (!match_txtmp) {
8020                 match_txtmp = msg.tx_match_filter;
8021             }
8022             if (strcmp(val_p, "0") == 0) {
8023                 printMsg("wild card\n");
8024                 if (m_len < (NAN_MAX_MATCH_FILTER_LEN - msg.tx_match_filter_len)) {
8025                     *match_txtmp++ = 0;
8026                     msg.tx_match_filter_len++;
8027                 }
8028             } else {
8029                 if (m_len < (NAN_MAX_MATCH_FILTER_LEN - msg.tx_match_filter_len)) {
8030                     *match_txtmp++ = strlen(val_p);
8031                     msg.tx_match_filter_len++;
8032                     strncpy((char *)match_txtmp, val_p, strlen(val_p));
8033                     match_txtmp += m_len;
8034                     msg.tx_match_filter_len += m_len;
8035                 } else {
8036                     printMsg("Invalid match filter len\n");
8037                     ret = WIFI_ERROR_INVALID_ARGS;
8038                     goto exit;
8039                 }
8040             }
8041         } else if (strcmp(param, "-match_rx") == 0) {
8042             u8 m_len = strlen(val_p);
8043             if (!match_rxtmp) {
8044                 match_rxtmp = msg.rx_match_filter;
8045             }
8046             if (strcmp(val_p, "0") == 0) {
8047                 printMsg("wild card\n");
8048                 if (m_len < (NAN_MAX_MATCH_FILTER_LEN - msg.rx_match_filter_len)) {
8049                     *match_rxtmp++ = 0;
8050                     msg.rx_match_filter_len++;
8051                 }
8052             } else {
8053                 if (m_len < (NAN_MAX_MATCH_FILTER_LEN - msg.rx_match_filter_len)) {
8054                     *match_rxtmp++ = strlen(val_p);
8055                     msg.rx_match_filter_len++;
8056                     strncpy((char *)match_rxtmp, val_p, strlen(val_p));
8057                     match_rxtmp += m_len;
8058                     msg.rx_match_filter_len += m_len;
8059                 } else {
8060                     printMsg("Invalid match filter len\n");
8061                     ret = WIFI_ERROR_INVALID_ARGS;
8062                     goto exit;
8063                 }
8064             }
8065         } else if (strncmp(param, "-recv_flag", strlen("-recv_flag")) == 0) {
8066             msg.recv_indication_cfg = strtoul(val_p, &endptr, 0);
8067         } else if (strcmp(param, "-csid") == 0) {
8068             val = atoi(val_p);
8069             switch(val) {
8070                 case NAN_CIPHER_SUITE_SHARED_KEY_NONE:
8071                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_NONE;
8072                     break;
8073                 case NAN_CIPHER_SUITE_SHARED_KEY_128_MASK:
8074                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_128_MASK;
8075                     break;
8076                 case NAN_CIPHER_SUITE_SHARED_KEY_256_MASK:
8077                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_256_MASK;
8078                     break;
8079                 case NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_128_MASK:
8080                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_128_MASK;
8081                     break;
8082                 case NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_256_MASK:
8083                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_256_MASK;
8084                     break;
8085                 case NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_128_MASK:
8086                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_128_MASK;
8087                     break;
8088                 case NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_256_MASK:
8089                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_256_MASK;
8090                     break;
8091                 default:
8092                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_NONE;
8093                     break;
8094             }
8095         } else if (strcmp(param, "-key_type") == 0) {
8096             val = atoi(val_p);
8097             switch(val) {
8098                 case NAN_SECURITY_KEY_INPUT_PMK:
8099                     msg.key_info.key_type = NAN_SECURITY_KEY_INPUT_PMK;
8100                     break;
8101                 case NAN_SECURITY_KEY_INPUT_PASSPHRASE:
8102                     msg.key_info.key_type = NAN_SECURITY_KEY_INPUT_PASSPHRASE;
8103                     break;
8104                 default:
8105                     printMsg("Invalid security key type\n");
8106                     ret = WIFI_ERROR_INVALID_ARGS;
8107                     goto exit;
8108             }
8109         } else if (strcmp(param, "-pmk") == 0) {
8110             if (strlen((const char*)val_p) > NAN_PMK_INFO_LEN) {
8111                 printMsg("Invalid PMK\n");
8112                 ret = WIFI_ERROR_INVALID_ARGS;
8113                 goto exit;
8114             } else {
8115                 msg.key_info.body.pmk_info.pmk_len=
8116                 strlen((const char*)val_p);
8117                 if (!set_interface_params((char*)msg.key_info.body.pmk_info.pmk,
8118                     val_p, msg.key_info.body.pmk_info.pmk_len)) {
8119                     printMsg("Set PMK successfull\n");
8120                 }
8121             }
8122         } else if (strcmp(param, "-passphrase") == 0) {
8123             if (strlen((const char*)val_p) < NAN_SECURITY_MIN_PASSPHRASE_LEN ||
8124                 strlen((const char*)val_p) > NAN_SECURITY_MAX_PASSPHRASE_LEN) {
8125                     printMsg("passphrase must be between %d and %d characters long\n",
8126                     NAN_SECURITY_MIN_PASSPHRASE_LEN,
8127                     NAN_SECURITY_MAX_PASSPHRASE_LEN);
8128                     ret = WIFI_ERROR_INVALID_ARGS;
8129                     goto exit;
8130             } else {
8131                 msg.key_info.body.passphrase_info.passphrase_len =
8132                 (strlen((const char*)val_p));
8133                 if (!set_interface_params((char*)msg.key_info.body.passphrase_info.passphrase,
8134                     val_p, msg.key_info.body.passphrase_info.passphrase_len)) {
8135                     printMsg("Set passphrase successfull, len = %d\n",
8136                         msg.key_info.body.passphrase_info.passphrase_len);
8137                 } else {
8138                     printMsg("Invalid passphrase\n");
8139                     ret = WIFI_ERROR_INVALID_ARGS;
8140                     goto exit;
8141                }
8142             }
8143         } else if (strcmp(param, "-scid") == 0) {
8144             if (strlen((const char*)val_p) > NAN_MAX_SCID_BUF_LEN) {
8145                 printMsg("Invalid SCID\n");
8146                 ret = WIFI_ERROR_INVALID_ARGS;
8147                 goto exit;
8148             } else {
8149                 msg.scid_len=
8150                 strlen((const char*)val_p);
8151                 if (!set_interface_params((char*)msg.scid,
8152                     val_p, msg.scid_len)) {
8153                     printMsg("Set SCID successfull\n");
8154                 }
8155             }
8156         } else if (strcmp(param, "-dp_type") == 0) {
8157             val = atoi(val_p);
8158             msg.sdea_params.config_nan_data_path = true;
8159             switch(val) {
8160                 case NAN_DATA_PATH_MULTICAST_MSG:
8161                     msg.sdea_params.ndp_type = NAN_DATA_PATH_MULTICAST_MSG;
8162                     break;
8163                 case NAN_DATA_PATH_UNICAST_MSG:
8164                     msg.sdea_params.ndp_type = NAN_DATA_PATH_UNICAST_MSG;
8165                     break;
8166                 default:
8167                     printMsg("Invalid datapath type\n");
8168                     msg.sdea_params.config_nan_data_path = false;
8169                     ret = WIFI_ERROR_INVALID_ARGS;
8170                     break;
8171             }
8172         } else if (strcmp(param, "-secure_dp") == 0) {
8173             val = atoi(val_p);
8174             switch(val) {
8175                 case NAN_DP_CONFIG_SECURITY:
8176                     msg.sdea_params.security_cfg = NAN_DP_CONFIG_SECURITY;
8177                     break;
8178                 default:
8179                     msg.sdea_params.security_cfg = NAN_DP_CONFIG_NO_SECURITY;
8180                     break;
8181             }
8182         } else if (strcmp(param, "-ranging") == 0) {
8183             val = atoi(val_p);
8184             switch(val) {
8185                 case NAN_RANGING_ENABLE:
8186                     msg.sdea_params.ranging_state = NAN_RANGING_ENABLE;
8187                     break;
8188                 default:
8189                     msg.sdea_params.ranging_state = NAN_RANGING_DISABLE;
8190                     break;
8191                 }
8192         } else if (strcmp(param, "-ranging_intvl") == 0) {
8193             msg.ranging_cfg.ranging_interval_msec = atoi(val_p);
8194         } else if (strcmp(param, "-ranging_ind") == 0) {
8195             msg.ranging_cfg.config_ranging_indications = atoi(val_p);
8196         } else if (strcmp(param, "-ingress") == 0) {
8197             msg.ranging_cfg.distance_ingress_mm = atoi(val_p);
8198         } else if (strcmp(param, "-egress") == 0) {
8199             msg.ranging_cfg.distance_egress_mm= atoi(val_p);
8200         } else if (strcmp(param, "-rssi_thresh_flag") == 0) {
8201             msg.rssi_threshold_flag = atoi(val_p);
8202         } else if (strcmp(param, "-sdea_info") == 0) {
8203             if (strlen((const char*)val_p) > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
8204                 printMsg("Invalid SDEA service specific info\n");
8205                 ret = WIFI_ERROR_INVALID_ARGS;
8206                 goto exit;
8207             } else {
8208                 msg.sdea_service_specific_info_len = strlen((const char*)val_p);
8209                 if (!set_interface_params((char*)msg.sdea_service_specific_info,
8210                     val_p, msg.sdea_service_specific_info_len)) {
8211                     printMsg("Set SDEA service specific info successfull\n");
8212                 }
8213             }
8214         } else if (strcmp(param, "-suspendable") == 0) {
8215             val = atoi(val_p);
8216             if (val) {
8217                 msg.enable_suspendability = true;
8218             }
8219         } else if (strcmp(param, "-nik") == 0) {
8220             int len = str2hex(val_p, (char*)msg.nan_identity_key);
8221 
8222             if (len != NAN_IDENTITY_KEY_LEN) {
8223                 printMsg("Invalid local NIK info, len %d expected 16 bytes \n", len);
8224                 ret = WIFI_ERROR_INVALID_ARGS;
8225                 goto exit;
8226             } else {
8227                 prhex_msg("NIK", msg.nan_identity_key, NAN_IDENTITY_KEY_LEN);
8228             }
8229         } else if (strcmp(param, "-bs_methods") == 0) {
8230             msg.nan_pairing_config.supported_bootstrapping_methods = atoi(val_p);
8231         } else if (strcmp(param, "-pairing_setup") == 0) {
8232             msg.nan_pairing_config.enable_pairing_setup = atoi(val_p);
8233         } else if (strcmp(param, "-pairing_cache") == 0) {
8234             msg.nan_pairing_config.enable_pairing_cache = atoi(val_p);
8235         } else if (strcmp(param, "-pairing_verification") == 0) {
8236             msg.nan_pairing_config.enable_pairing_verification = atoi(val_p);
8237         } else {
8238             printMsg("%s:Unsupported Parameter for Nan Subscribe\n", __FUNCTION__);
8239             goto exit;
8240         }
8241     }
8242     if (!msg.service_name_len) {
8243         printMsg("service name is mandatory !!\n");
8244         goto exit;
8245     }
8246 
8247     nanCmdId = getNewCmdId();
8248     ret = nan_init_handlers();
8249     if (ret != WIFI_SUCCESS) {
8250         printMsg("Failed to initialize handlers %d\n", ret);
8251         goto exit;
8252     }
8253     ret = nan_subscribe_request(nanCmdId, wlan0Handle, &msg);
8254 exit:
8255     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
8256     return;
8257 }
8258 
cancelPublishNan(char * argv[])8259 void cancelPublishNan(char *argv[]) {
8260     NanPublishCancelRequest msg ;
8261     wifi_error ret = WIFI_SUCCESS;
8262     u16 pub_id;
8263     pub_id = atoi(argv[3]);
8264     if (pub_id) {
8265         msg.publish_id = pub_id;
8266     } else {
8267         printMsg("\nInvalid argument \n");
8268         ret = WIFI_ERROR_INVALID_ARGS;
8269         goto exit;
8270     }
8271     nanCmdId = getNewCmdId();
8272     ret = nan_init_handlers();
8273     if (ret != WIFI_SUCCESS) {
8274         printMsg("Failed to initialize handlers %d\n", ret);
8275         goto exit;
8276     }
8277     ret = nan_publish_cancel_request(nanCmdId, wlan0Handle, &msg);
8278 exit:
8279     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
8280     return;
8281 }
8282 
8283 
cancelSubscribeNan(char * argv[])8284 void cancelSubscribeNan(char *argv[]) {
8285     NanSubscribeCancelRequest msg ;
8286     wifi_error ret = WIFI_SUCCESS;
8287     u16 sub_id;
8288     sub_id = atoi(argv[3]);
8289     if (sub_id) {
8290         msg.subscribe_id = sub_id;
8291     } else {
8292         printMsg("\nInvalid argument \n");
8293         ret = WIFI_ERROR_INVALID_ARGS;
8294         goto exit;
8295     }
8296     nanCmdId = getNewCmdId();
8297     ret = nan_init_handlers();
8298     if (ret != WIFI_SUCCESS) {
8299         printMsg("Failed to initialize handlers %d\n", ret);
8300         goto exit;
8301     }
8302     ret = nan_subscribe_cancel_request(nanCmdId, wlan0Handle, &msg);
8303 #ifdef NAN_BLOCK_FOR_EVENT
8304     memset(&info, 0, sizeof(info));
8305     getEventFromCache(info);
8306     printMsg("retrieved event %d : %s\n", info.type, info.buf);
8307 #endif
8308 exit:
8309     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
8310     return;
8311 }
8312 
nanSuspendRequest(char * argv[])8313 void nanSuspendRequest(char *argv[]) {
8314     NanSuspendRequest msg;
8315     wifi_error ret = WIFI_SUCCESS;
8316     char *param = NULL, *val_p = NULL, *endptr = NULL;
8317     u16 svc_id = 0;
8318     /* skip utility */
8319     argv++;
8320     /* skip command */
8321     argv++;
8322     /* skip command */
8323     argv++;
8324 
8325     if ((param = *argv++) != NULL) {
8326         val_p = *argv++;
8327         if (!val_p || *val_p == '-') {
8328             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
8329             ret = WIFI_ERROR_NOT_SUPPORTED;
8330             goto exit;
8331         }
8332         if (strcmp(param, "-svc_id") == 0) {
8333             svc_id = strtoul(val_p, &endptr, 0);
8334             msg.publish_subscribe_id = svc_id;
8335         } else {
8336             printMsg("%s:Unsupported Parameter for Nan Suspend Request\n", __FUNCTION__);
8337             goto exit;
8338         }
8339     } else {
8340         printMsg("%s: Additional -svc_id required for Nan Suspend Request\n", __FUNCTION__);
8341         goto exit;
8342     }
8343 
8344     printMsg("nan Suspend svc_id %d \n", svc_id);
8345     nanCmdId = getNewCmdId();
8346     ret = nan_init_handlers();
8347     if (ret != WIFI_SUCCESS) {
8348         printMsg("Failed to initialize handlers %d\n", ret);
8349         goto exit;
8350     }
8351     ret = hal_fn.wifi_nan_suspend_request(nanCmdId, wlan0Handle, &msg);
8352 exit:
8353     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
8354     return;
8355 }
8356 
nanResumeRequest(char * argv[])8357 void nanResumeRequest(char *argv[]) {
8358     NanResumeRequest msg ;
8359     wifi_error ret = WIFI_SUCCESS;
8360     char *param = NULL, *val_p = NULL, *endptr = NULL;
8361     u16 svc_id = 0;
8362     /* skip utility */
8363     argv++;
8364     /* skip command */
8365     argv++;
8366     /* skip command */
8367     argv++;
8368 
8369     if ((param = *argv++) != NULL) {
8370         val_p = *argv++;
8371         if (!val_p || *val_p == '-') {
8372             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
8373             ret = WIFI_ERROR_NOT_SUPPORTED;
8374             goto exit;
8375         }
8376         if (strcmp(param, "-svc_id") == 0) {
8377             svc_id = strtoul(val_p, &endptr, 0);
8378             msg.publish_subscribe_id = svc_id;
8379         } else {
8380             printMsg("%s:Unsupported Parameter for Nan Resume Request\n", __FUNCTION__);
8381             goto exit;
8382         }
8383     } else {
8384         printMsg("%s: Additional -svc_id required for Nan Resume Request\n", __FUNCTION__);
8385         goto exit;
8386     }
8387 
8388     printMsg("nan Resume: svc_id %d \n", svc_id);
8389     nanCmdId = getNewCmdId();
8390     ret = nan_init_handlers();
8391     if (ret != WIFI_SUCCESS) {
8392         printMsg("Failed to initialize handlers %d\n", ret);
8393         goto exit;
8394     }
8395     ret = hal_fn.wifi_nan_resume_request(nanCmdId, wlan0Handle, &msg);
8396 exit:
8397     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
8398     return;
8399 }
8400 
transmitNan(int argc,char * argv[])8401 void transmitNan(int argc, char *argv[]) {
8402     NanTransmitFollowupRequest msg;
8403     wifi_error ret = WIFI_SUCCESS;
8404     char *param = NULL, *val_p = NULL, *endptr = NULL;
8405     u16 src_id = 0;
8406     u32 dest_id = 0;
8407     u8 *mac_addr = NULL;
8408 
8409     memset(&msg, 0, sizeof(msg));
8410 
8411     /* skip utility */
8412     argv++;
8413     /* skip command */
8414     argv++;
8415     /* skip command */
8416     argv++;
8417 
8418     while ((param = *argv++) != NULL) {
8419         val_p = *argv++;
8420         if (!val_p || *val_p == '-') {
8421             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
8422             ret = WIFI_ERROR_NOT_SUPPORTED;
8423             goto exit;
8424         }
8425         if (strcmp(param, "-src_id") == 0) {
8426             msg.publish_subscribe_id = atoi(val_p);
8427             src_id = msg.publish_subscribe_id;
8428         } else if (strcmp(param, "-dest_id") == 0) {
8429             msg.requestor_instance_id = atoi(val_p);
8430             dest_id = msg.requestor_instance_id;
8431         } else if (strcmp(param, "-peer_addr") == 0) {
8432             if (!ether_atoe(val_p, msg.addr)) {
8433                 printMsg("bad peer mac addr !!\n");
8434                 ret = WIFI_ERROR_INVALID_ARGS;
8435                 goto exit;
8436             }
8437             mac_addr = msg.addr;
8438         } else if (strcmp(param, "-info") == 0) {
8439             if (strlen((const char*)val_p) > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
8440                 printMsg("Invalid  service specific info\n");
8441                 ret = WIFI_ERROR_INVALID_ARGS;
8442                 goto exit;
8443             } else {
8444                 msg.service_specific_info_len =
8445                 strlen((const char*)val_p);
8446                 if (!set_interface_params((char*)msg.service_specific_info,
8447                     val_p, msg.service_specific_info_len)) {
8448                     printMsg("Set service specific info successfull\n");
8449                 }
8450             }
8451         } else if (strncmp(param, "-recv_flag", strlen("-recv_flag")) == 0) {
8452             msg.recv_indication_cfg = strtoul(val_p, &endptr, 0);
8453         } else if (strcmp(param, "-sdea_info") == 0) {
8454             if (strlen((const char*)val_p) > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
8455                 printMsg("Invalid SDEA service specific info\n");
8456                 ret = WIFI_ERROR_INVALID_ARGS;
8457                 goto exit;
8458             } else {
8459                 msg.sdea_service_specific_info_len =
8460                 strlen((const char*)val_p);
8461                 if (!set_interface_params((char*)msg.sdea_service_specific_info,
8462                     val_p, msg.sdea_service_specific_info_len)) {
8463                     printMsg("Set SDEA service specific info successfull\n");
8464                 }
8465             }
8466         } else {
8467             printMsg("%s:Unsupported Parameter for nan transmit followup\n", __FUNCTION__);
8468             goto exit;
8469         }
8470     }
8471 
8472     if (!src_id) {
8473         printMsg("Source Instance Id is mandatory !!\n");
8474         goto exit;
8475     }
8476     if (!dest_id) {
8477         printMsg("Destination Instance Id is mandatory !!\n");
8478         goto exit;
8479     }
8480     if (!mac_addr) {
8481         printMsg("Peer MAC Address is mandatory !!\n");
8482         goto exit;
8483     }
8484     nanCmdId = getNewCmdId();
8485     ret = nan_init_handlers();
8486     if (ret != WIFI_SUCCESS) {
8487         printMsg("Failed to initialize handlers %d\n", ret);
8488         goto exit;
8489     }
8490     ret = nan_transmit_followup_request(nanCmdId, wlan0Handle, &msg);
8491 exit:
8492     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
8493     return;
8494 }
8495 
nanPairingRequest(int argc,char * argv[])8496 void nanPairingRequest(int argc, char *argv[])
8497 {
8498     NanPairingRequest msg;
8499     wifi_error ret = WIFI_SUCCESS;
8500     char *param = NULL, *val_p = NULL;
8501     u32 pub_id = 0;
8502     u8 *mac_addr = NULL;
8503     u32 val = 0;
8504     u32 len = 0;
8505 
8506     memset(&msg, 0, sizeof(msg));
8507 
8508     /* skip utility */
8509     argv++;
8510     /* skip command */
8511     argv++;
8512     /* skip command */
8513     argv++;
8514 
8515     msg.is_opportunistic = 1;
8516     while ((param = *argv++) != NULL) {
8517         val_p = *argv++;
8518         if (!val_p || *val_p == '-') {
8519             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
8520             ret = WIFI_ERROR_NOT_SUPPORTED;
8521             goto exit;
8522         }
8523         if (strcmp(param, "-pub_id") == 0) {
8524             msg.requestor_instance_id = atoi(val_p);
8525             pub_id = msg.requestor_instance_id;
8526         } else if (strcmp(param, "-peer_addr") == 0) {
8527             if (!ether_atoe(val_p, msg.peer_disc_mac_addr)) {
8528                 printMsg("bad peer mac addr !!\n");
8529                 ret = WIFI_ERROR_INVALID_ARGS;
8530                 goto exit;
8531             }
8532             mac_addr = msg.peer_disc_mac_addr;
8533         } else if (strcmp(param, "-type") == 0) {
8534             msg.nan_pairing_request_type = (NanPairingRequestType)atoi(val_p);
8535             if ((msg.nan_pairing_request_type < NAN_PAIRING_SETUP) ||
8536                     (msg.nan_pairing_request_type > NAN_PAIRING_VERIFICATION)) {
8537                 printMsg("Invalid type \n");
8538                 ret = WIFI_ERROR_INVALID_ARGS;
8539                 goto exit;
8540             }
8541         } else if (strcmp(param, "-password") == 0) {
8542             if (strlen((const char*)val_p) < NAN_SECURITY_MIN_PASSPHRASE_LEN ||
8543                     strlen((const char*)val_p) > NAN_SECURITY_MAX_PASSPHRASE_LEN) {
8544                 printMsg("passphrase must be between %d and %d characters long\n",
8545                         NAN_SECURITY_MIN_PASSPHRASE_LEN, NAN_SECURITY_MAX_PASSPHRASE_LEN);
8546                 ret = WIFI_ERROR_INVALID_ARGS;
8547                 goto exit;
8548             } else {
8549                 msg.key_info.body.passphrase_info.passphrase_len = (strlen((const char*)val_p));
8550                 if (!set_interface_params((char*)msg.key_info.body.passphrase_info.passphrase,
8551                         val_p, msg.key_info.body.passphrase_info.passphrase_len)) {
8552                     printMsg("Set passphrase successfull, len = %d\n",
8553                             msg.key_info.body.passphrase_info.passphrase_len);
8554                     msg.key_info.key_type = NAN_SECURITY_KEY_INPUT_PASSPHRASE;
8555                     msg.is_opportunistic = 0;
8556                 } else {
8557                     printMsg("Invalid passphrase\n");
8558                     ret = WIFI_ERROR_INVALID_ARGS;
8559                     goto exit;
8560                 }
8561             }
8562         } else if (strcmp(param, "-pmk") == 0) {
8563             len = str2hex(val_p, (char*)msg.key_info.body.pmk_info.pmk);
8564 
8565             if (len != NAN_PMK_INFO_LEN) {
8566                 printMsg("Invalid NPK info, len %d expected 32 bytes \n", len);
8567                 ret = WIFI_ERROR_INVALID_ARGS;
8568                 goto exit;
8569             } else {
8570                 prhex_msg("NPK successfull", msg.key_info.body.pmk_info.pmk, len);
8571                 msg.key_info.body.pmk_info.pmk_len = NAN_PMK_INFO_LEN;
8572                 msg.key_info.key_type = NAN_SECURITY_KEY_INPUT_PMK;
8573                 msg.is_opportunistic = 0;
8574             }
8575         } else if (strcmp(param, "-csid") == 0) {
8576             val = atoi(val_p);
8577             switch (val) {
8578                 case NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_128_MASK:
8579                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_128_MASK;
8580                     break;
8581                 case NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_256_MASK:
8582                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_256_MASK;
8583                     break;
8584                 default:
8585                     printMsg("%s:Unsupported csid, only PASN csids are supported\n", __FUNCTION__);
8586                     ret = WIFI_ERROR_INVALID_ARGS;
8587                     goto exit;
8588             }
8589         } else if (strcmp(param, "-akm") == 0) {
8590             msg.akm = (NanAkm)atoi(val_p);
8591             if ((msg.akm < SAE) || (msg.akm > PASN)) {
8592                 printMsg("Invalid akm \n");
8593                 ret = WIFI_ERROR_INVALID_ARGS;
8594                 goto exit;
8595             }
8596         } else if (strcmp(param, "-nik") == 0) {
8597             len = str2hex(val_p, (char*)msg.nan_identity_key);
8598 
8599             if (len != NAN_IDENTITY_KEY_LEN) {
8600                 printMsg("Invalid local NIK info, len %d expected 16 bytes \n", len);
8601                 ret = WIFI_ERROR_INVALID_ARGS;
8602                 goto exit;
8603             } else {
8604                 prhex_msg("NIK", msg.nan_identity_key, NAN_IDENTITY_KEY_LEN);
8605             }
8606         } else if (strcmp(param, "-pairing_cache") == 0) {
8607             msg.enable_pairing_cache = atoi(val_p);
8608         } else {
8609             printMsg("%s:Unsupported Parameter for nan pairing request \n", __FUNCTION__);
8610             goto exit;
8611         }
8612     }
8613 
8614     if (!pub_id) {
8615         printMsg("Destination Instance Id is mandatory !!\n");
8616         goto exit;
8617     }
8618     if (!mac_addr) {
8619         printMsg("Peer MAC Address is mandatory !!\n");
8620         goto exit;
8621     }
8622     nanCmdId = getNewCmdId();
8623     ret = nan_init_handlers();
8624     if (ret != WIFI_SUCCESS) {
8625         printMsg("Failed to initialize handlers %d\n", ret);
8626         goto exit;
8627     }
8628     ret = nan_pairing_request(nanCmdId, wlan0Handle, &msg);
8629 exit:
8630     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
8631     return;
8632 }
8633 
nanPairingResponse(int argc,char * argv[])8634 void nanPairingResponse(int argc, char *argv[])
8635 {
8636     NanPairingIndicationResponse msg;
8637     wifi_error ret = WIFI_SUCCESS;
8638     char *param = NULL, *val_p = NULL;
8639     u32 val = 0;
8640     u32 len = 0;
8641 
8642     memset(&msg, 0, sizeof(msg));
8643 
8644     /* skip utility */
8645     argv++;
8646     /* skip command */
8647     argv++;
8648     /* skip command */
8649     argv++;
8650 
8651     msg.is_opportunistic = 1;
8652     while ((param = *argv++) != NULL) {
8653         val_p = *argv++;
8654         if (!val_p || *val_p == '-') {
8655             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
8656             ret = WIFI_ERROR_NOT_SUPPORTED;
8657             goto exit;
8658         }
8659         if (strcmp(param, "-pairing_id") == 0) {
8660             msg.pairing_instance_id = atoi(val_p);
8661         } else if (strcmp(param, "-rsp_code") == 0) {
8662             msg.rsp_code = (NanPairingResponseCode)atoi(val_p);
8663         } else if (strcmp(param, "-type") == 0) {
8664             msg.nan_pairing_request_type = (NanPairingRequestType)atoi(val_p);
8665             if ((msg.nan_pairing_request_type < NAN_PAIRING_SETUP) ||
8666                     (msg.nan_pairing_request_type > NAN_PAIRING_VERIFICATION)) {
8667                 printMsg("Invalid type \n");
8668                 ret = WIFI_ERROR_INVALID_ARGS;
8669                 goto exit;
8670             }
8671         } else if (strcmp(param, "-password") == 0) {
8672             if (strlen((const char*)val_p) < NAN_SECURITY_MIN_PASSPHRASE_LEN ||
8673                     strlen((const char*)val_p) > NAN_SECURITY_MAX_PASSPHRASE_LEN) {
8674                 printMsg("passphrase must be between %d and %d characters long\n",
8675                         NAN_SECURITY_MIN_PASSPHRASE_LEN, NAN_SECURITY_MAX_PASSPHRASE_LEN);
8676                 ret = WIFI_ERROR_INVALID_ARGS;
8677                 goto exit;
8678             } else {
8679                 msg.key_info.body.passphrase_info.passphrase_len = (strlen((const char*)val_p));
8680                 if (!set_interface_params((char*)msg.key_info.body.passphrase_info.passphrase,
8681                         val_p, msg.key_info.body.passphrase_info.passphrase_len)) {
8682                     printMsg("Set passphrase successfull, len = %d\n",
8683                             msg.key_info.body.passphrase_info.passphrase_len);
8684                     msg.key_info.key_type = NAN_SECURITY_KEY_INPUT_PASSPHRASE;
8685                     msg.is_opportunistic = 0;
8686                 } else {
8687                     printMsg("Invalid passphrase\n");
8688                     ret = WIFI_ERROR_INVALID_ARGS;
8689                     goto exit;
8690                 }
8691             }
8692         } else if (strcmp(param, "-pmk") == 0) {
8693             len = str2hex(val_p, (char*)msg.key_info.body.pmk_info.pmk);
8694 
8695             if (len != NAN_PMK_INFO_LEN) {
8696                 printMsg("Invalid NPK info, len %d expected 32 bytes \n", len);
8697                 ret = WIFI_ERROR_INVALID_ARGS;
8698                 goto exit;
8699             } else {
8700                 prhex_msg("NPK successfull", msg.key_info.body.pmk_info.pmk, len);
8701                 msg.key_info.body.pmk_info.pmk_len = NAN_PMK_INFO_LEN;
8702                 msg.key_info.key_type = NAN_SECURITY_KEY_INPUT_PMK;
8703                 msg.is_opportunistic = 0;
8704             }
8705         } else if (strcmp(param, "-csid") == 0) {
8706             val = atoi(val_p);
8707             switch (val) {
8708                 case NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_128_MASK:
8709                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_128_MASK;
8710                     break;
8711                 case NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_256_MASK:
8712                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_256_MASK;
8713                     break;
8714                 default:
8715                     printMsg("%s:Unsupported csid, only PASN csids are supported\n", __FUNCTION__);
8716                     ret = WIFI_ERROR_INVALID_ARGS;
8717                     goto exit;
8718             }
8719         } else if (strcmp(param, "-akm") == 0) {
8720             msg.akm = (NanAkm)atoi(val_p);
8721             if ((msg.akm < SAE) || (msg.akm > PASN)) {
8722                 printMsg("Invalid akm \n");
8723                 ret = WIFI_ERROR_INVALID_ARGS;
8724                 goto exit;
8725             }
8726         } else if (strcmp(param, "-nik") == 0) {
8727             int len = str2hex(val_p, (char*)msg.nan_identity_key);
8728 
8729             if (len != NAN_IDENTITY_KEY_LEN) {
8730                 printMsg("Invalid local NIK info, len %d expected 16 bytes \n", len);
8731                 ret = WIFI_ERROR_INVALID_ARGS;
8732                 goto exit;
8733             } else {
8734                 prhex_msg("NIK", msg.nan_identity_key, NAN_IDENTITY_KEY_LEN);
8735             }
8736         } else if (strcmp(param, "-pairing_cache") == 0) {
8737             msg.enable_pairing_cache = atoi(val_p);
8738         } else {
8739             printMsg("%s:Unsupported Parameter for nan pairing response \n", __FUNCTION__);
8740             goto exit;
8741         }
8742     }
8743 
8744     nanCmdId = getNewCmdId();
8745     ret = nan_init_handlers();
8746     if (ret != WIFI_SUCCESS) {
8747         printMsg("Failed to initialize handlers %d\n", ret);
8748         goto exit;
8749     }
8750     ret = nan_pairing_indication_response(nanCmdId, wlan0Handle, &msg);
8751 exit:
8752     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
8753     return;
8754 }
8755 
nanPairingEnd(int argc,char * argv[])8756 void nanPairingEnd(int argc, char *argv[])
8757 {
8758     NanPairingEndRequest msg;
8759     wifi_error ret = WIFI_SUCCESS;
8760     char *param = NULL, *val_p = NULL;
8761 
8762     /* skip utility */
8763     argv++;
8764     /* skip command */
8765     argv++;
8766     /* skip command */
8767     argv++;
8768 
8769 
8770     while ((param = *argv++) != NULL) {
8771         val_p = *argv++;
8772         if (!val_p || *val_p == '-') {
8773             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
8774             ret = WIFI_ERROR_NOT_SUPPORTED;
8775             goto exit;
8776         }
8777         if (strcmp(param, "-pid") == 0) {
8778             msg.pairing_instance_id = atoi(val_p);
8779         } else {
8780             printMsg("%s:Unsupported Parameter for Pairing End Request\n", __FUNCTION__);
8781             goto exit;
8782         }
8783     }
8784 
8785     nanCmdId = getNewCmdId();
8786     ret = nan_init_handlers();
8787     if (ret != WIFI_SUCCESS) {
8788         printMsg("Failed to initialize handlers %d\n", ret);
8789         goto exit;
8790     }
8791     ret = nan_pairing_end(nanCmdId, wlan0Handle, &msg);
8792 exit:
8793     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
8794     return;
8795 }
8796 
nanBootstrappingReq(int argc,char * argv[])8797 void nanBootstrappingReq(int argc, char *argv[])
8798 {
8799     NanBootstrappingRequest msg;
8800     wifi_error ret = WIFI_SUCCESS;
8801     char *param = NULL, *val_p = NULL;
8802     u32 dest_id = 0, lcl_id = 0;
8803 
8804     memset(&msg, 0, sizeof(msg));
8805 
8806     /* skip utility */
8807     argv++;
8808     /* skip command */
8809     argv++;
8810     /* skip command */
8811     argv++;
8812 
8813     while ((param = *argv++) != NULL) {
8814         val_p = *argv++;
8815         if (!val_p || *val_p == '-') {
8816             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
8817             ret = WIFI_ERROR_NOT_SUPPORTED;
8818             goto exit;
8819         }
8820         if (strcmp(param, "-dest_id") == 0) {
8821             msg.requestor_instance_id = atoi(val_p);
8822             dest_id = msg.requestor_instance_id;
8823         } else if (strcmp(param, "-lcl_id") == 0) {
8824             msg.publish_subscribe_id = atoi(val_p);
8825             lcl_id = msg.publish_subscribe_id;
8826         } else if (strcmp(param, "-peer_addr") == 0) {
8827             if (!ether_atoe(val_p, msg.peer_disc_mac_addr)) {
8828                 printMsg("bad peer mac addr !!\n");
8829                 ret = WIFI_ERROR_INVALID_ARGS;
8830                 goto exit;
8831             }
8832         } else if (strcmp(param, "-bs_methods") == 0) {
8833             msg.request_bootstrapping_method = atoi(val_p);
8834         } else if (strcmp(param, "-sdea_info") == 0) {
8835             if (strlen((const char*)val_p) > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
8836                 printMsg("Invalid SDEA service specific info\n");
8837                 ret = WIFI_ERROR_INVALID_ARGS;
8838                 goto exit;
8839             } else {
8840                 msg.sdea_service_specific_info_len = strlen((const char*)val_p);
8841                 if (!set_interface_params((char*)msg.sdea_service_specific_info,
8842                     val_p, msg.sdea_service_specific_info_len)) {
8843                         printMsg("Set SDEA service specific info successfull\n");
8844                 }
8845             }
8846         } else if (strcmp(param, "-info") == 0) {
8847             if (strlen((const char*)val_p) > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
8848                 printMsg("Invalid  service specific info\n");
8849                 ret = WIFI_ERROR_INVALID_ARGS;
8850                 goto exit;
8851             } else {
8852                 msg.service_specific_info_len = strlen((const char*)val_p);
8853                 if (!set_interface_params((char*)msg.service_specific_info,
8854                     val_p, msg.service_specific_info_len)) {
8855                     printMsg("Set service specific info successfull\n");
8856                 }
8857             }
8858         } else if (strcmp(param, "-cookie") == 0) {
8859             if (strlen((const char*)val_p) > NAN_MAX_COOKIE_LEN) {
8860                 printMsg("Invalid cookie info\n");
8861                 ret = WIFI_ERROR_INVALID_ARGS;
8862                 goto exit;
8863             } else {
8864                 msg.cookie_length = strlen((const char*)val_p);
8865                 if (!set_interface_params((char*)msg.cookie, val_p, msg.cookie_length)) {
8866                     printMsg("Set cookie info successfull\n");
8867                 }
8868             }
8869         } else {
8870             printMsg("%s:Unsupported Parameter for nan bootstrapping request \n", __FUNCTION__);
8871             goto exit;
8872         }
8873     }
8874 
8875     if (!dest_id) {
8876         printMsg("Destination Instance Id is mandatory !!\n");
8877         goto exit;
8878     }
8879     if (!lcl_id) {
8880         printMsg("Local Instance Id is mandatory !!\n");
8881         goto exit;
8882     }
8883     nanCmdId = getNewCmdId();
8884     ret = nan_init_handlers();
8885     if (ret != WIFI_SUCCESS) {
8886         printMsg("Failed to initialize handlers %d\n", ret);
8887         goto exit;
8888     }
8889     ret = nan_bootstrapping_request(nanCmdId, wlan0Handle, &msg);
8890 exit:
8891     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
8892     return;
8893 }
8894 
nanBootstrappingResp(int argc,char * argv[])8895 void nanBootstrappingResp(int argc, char *argv[])
8896 {
8897     NanBootstrappingIndicationResponse msg;
8898     wifi_error ret = WIFI_SUCCESS;
8899     char *param = NULL, *val_p = NULL;
8900     u32 dest_id = 0, lcl_id = 0;
8901 
8902     memset(&msg, 0, sizeof(msg));
8903 
8904     /* skip utility */
8905     argv++;
8906     /* skip command */
8907     argv++;
8908     /* skip command */
8909     argv++;
8910 
8911     while ((param = *argv++) != NULL) {
8912         val_p = *argv++;
8913         if (!val_p || *val_p == '-') {
8914             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
8915             ret = WIFI_ERROR_NOT_SUPPORTED;
8916             goto exit;
8917         }
8918         if (strcmp(param, "-dest_id") == 0) {
8919             msg.service_instance_id = atoi(val_p);
8920             dest_id = msg.service_instance_id;
8921         } else if (strcmp(param, "-lcl_id") == 0) {
8922             msg.publish_subscribe_id = atoi(val_p);
8923             lcl_id = msg.publish_subscribe_id;
8924         } else if (strcmp(param, "-peer_addr") == 0) {
8925             if (!ether_atoe(val_p, msg.peer_disc_mac_addr)) {
8926                 printMsg("bad peer mac addr !!\n");
8927                 ret = WIFI_ERROR_INVALID_ARGS;
8928                 goto exit;
8929             }
8930         } else if (strcmp(param, "-rsp_code") == 0) {
8931             msg.rsp_code = (NanBootstrappingResponseCode)atoi(val_p);
8932         } else if (strcmp(param, "-comeback_delay") == 0) {
8933             msg.come_back_delay = atoi(val_p);
8934         } else if (strcmp(param, "-sdea_info") == 0) {
8935             if (strlen((const char*)val_p) > NAN_MAX_SDEA_SERVICE_SPECIFIC_INFO_LEN) {
8936                 printMsg("Invalid SDEA service specific info\n");
8937                 ret = WIFI_ERROR_INVALID_ARGS;
8938                 goto exit;
8939             } else {
8940                 msg.sdea_service_specific_info_len = strlen((const char*)val_p);
8941                 if (!set_interface_params((char*)msg.sdea_service_specific_info,
8942                     val_p, msg.sdea_service_specific_info_len)) {
8943                         printMsg("Set SDEA service specific info successfull\n");
8944                 }
8945             }
8946         } else if (strcmp(param, "-info") == 0) {
8947             if (strlen((const char*)val_p) > NAN_MAX_SERVICE_SPECIFIC_INFO_LEN) {
8948                 printMsg("Invalid  service specific info\n");
8949                 ret = WIFI_ERROR_INVALID_ARGS;
8950                 goto exit;
8951             } else {
8952                 msg.service_specific_info_len = strlen((const char*)val_p);
8953                 if (!set_interface_params((char*)msg.service_specific_info,
8954                     val_p, msg.service_specific_info_len)) {
8955                     printMsg("Set service specific info successfull\n");
8956                 }
8957             }
8958         } else if (strcmp(param, "-cookie") == 0) {
8959             if (strlen((const char*)val_p) > NAN_MAX_COOKIE_LEN) {
8960                 printMsg("Invalid cookie info\n");
8961                 ret = WIFI_ERROR_INVALID_ARGS;
8962                 goto exit;
8963             } else {
8964                 msg.cookie_length = strlen((const char*)val_p);
8965                 if (!set_interface_params((char*)msg.cookie, val_p, msg.cookie_length)) {
8966                     printMsg("Set cookie info successfull\n");
8967                 }
8968             }
8969         } else {
8970             printMsg("%s:Unsupported Parameter for nan bootstrapping response  %s \n", __FUNCTION__, param);
8971             goto exit;
8972         }
8973     }
8974 
8975     if (!dest_id) {
8976         printMsg("Destination Instance Id is mandatory !!\n");
8977         goto exit;
8978     }
8979     if (!lcl_id) {
8980         printMsg("Local Instance Id is mandatory !!\n");
8981         goto exit;
8982     }
8983     nanCmdId = getNewCmdId();
8984     ret = nan_init_handlers();
8985     if (ret != WIFI_SUCCESS) {
8986         printMsg("Failed to initialize handlers %d\n", ret);
8987         goto exit;
8988     }
8989     ret = nan_bootstrapping_indication_response(nanCmdId, wlan0Handle, &msg);
8990 exit:
8991     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
8992     return;
8993 }
8994 
getNanCapabilities(void)8995 void getNanCapabilities(void) {
8996     nanCmdId = getNewCmdId();
8997     wifi_error ret = nan_init_handlers();
8998     if (ret != WIFI_SUCCESS) {
8999         printMsg("Failed to initialize handlers %d\n", ret);
9000         return;
9001     }
9002     nan_get_capabilities(nanCmdId, wlan0Handle);
9003 }
9004 
nanDataPathIfaceCreate(char * argv[])9005 void nanDataPathIfaceCreate(char *argv[]) {
9006     wifi_error ret = WIFI_SUCCESS;
9007     char *param = NULL, *val_p = NULL;
9008     /* Interface name */
9009     char ndp_iface[IFNAMSIZ+1];
9010 
9011     memset(ndp_iface, 0, sizeof(ndp_iface));
9012 
9013     /* skip utility */
9014     argv++;
9015     /* skip command */
9016     argv++;
9017     /* skip command */
9018     argv++;
9019 
9020     while ((param = *argv++) != NULL) {
9021         val_p = *argv++;
9022         if (!val_p || *val_p == '-') {
9023             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
9024             ret = WIFI_ERROR_NOT_SUPPORTED;
9025             goto exit;
9026         }
9027         if (strcmp(param, "-iface") == 0) {
9028             if (!set_interface_params(ndp_iface, val_p, (IFNAMSIZ - 1))) {
9029                 printMsg("set interface name successfull\n");
9030             } else {
9031                 printMsg("Invalid  Iface name\n");
9032                 ret = WIFI_ERROR_INVALID_ARGS;
9033                 goto exit;
9034             }
9035         } else {
9036             printMsg("Unsupported Parameter for ndp iface create\n");
9037             goto exit;
9038         }
9039     }
9040 
9041     nanCmdId = getNewCmdId();
9042     ret = nan_init_handlers();
9043     if (ret != WIFI_SUCCESS) {
9044         printMsg("Failed to initialize handlers %d\n", ret);
9045         goto exit;
9046     }
9047     ret = nan_data_interface_create(nanCmdId, wlan0Handle, ndp_iface);
9048 exit:
9049     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
9050     return;
9051 }
9052 
nanDataPathIfaceDelete(char * argv[])9053 void nanDataPathIfaceDelete(char *argv[]) {
9054     wifi_error ret = WIFI_SUCCESS;
9055     char *param = NULL, *val_p = NULL;
9056     /* Interface name */
9057     char ndp_iface[IFNAMSIZ+1];
9058 
9059     memset(ndp_iface, 0, sizeof(ndp_iface));
9060 
9061     /* skip utility */
9062     argv++;
9063     /* skip command */
9064     argv++;
9065     /* skip command */
9066     argv++;
9067 
9068     while ((param = *argv++) != NULL) {
9069         val_p = *argv++;
9070         if (!val_p || *val_p == '-') {
9071             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
9072             ret = WIFI_ERROR_NOT_SUPPORTED;
9073             goto exit;
9074         }
9075         if (strcmp(param, "-iface") == 0) {
9076             if (!set_interface_params(ndp_iface, val_p, (IFNAMSIZ - 1))) {
9077                 printMsg("clear interface name successfull\n");
9078             } else {
9079                 printMsg("Invalid  Iface name\n");
9080                 ret = WIFI_ERROR_INVALID_ARGS;
9081                 goto exit;
9082             }
9083         } else {
9084             printMsg("Unsupported Parameter for ndp iface delete\n");
9085             goto exit;
9086         }
9087     }
9088 
9089     nanCmdId = getNewCmdId();
9090     ret = nan_init_handlers();
9091     if (ret != WIFI_SUCCESS) {
9092         printMsg("Failed to initialize handlers %d\n", ret);
9093         goto exit;
9094     }
9095     ret = nan_data_interface_delete(nanCmdId, wlan0Handle, ndp_iface);
9096 exit:
9097     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
9098     return;
9099 }
9100 
nanDataInitRequest(int argc,char * argv[])9101 void nanDataInitRequest(int argc, char *argv[]) {
9102     NanDataPathInitiatorRequest msg;
9103     wifi_error ret = WIFI_SUCCESS;
9104     char *param = NULL, *val_p = NULL;
9105     u32 val = 0;
9106 
9107     memset(&msg, 0, sizeof(msg));
9108     msg.ndp_cfg.security_cfg = NAN_DP_CONFIG_NO_SECURITY;
9109     msg.ndp_cfg.qos_cfg = NAN_DP_CONFIG_NO_QOS;
9110 
9111     /* skip utility */
9112     argv++;
9113     /* skip command */
9114     argv++;
9115     /* skip command */
9116     argv++;
9117 
9118     while ((param = *argv++) != NULL) {
9119         val_p = *argv++;
9120         if (!val_p || *val_p == '-') {
9121             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
9122             ret = WIFI_ERROR_NOT_SUPPORTED;
9123             goto exit;
9124         }
9125         if (strcmp(param, "-pub_id") == 0) {
9126             msg.requestor_instance_id = atoi(val_p);
9127         } else if (strcmp(param, "-chan_req_type") == 0) {
9128             val = atoi(val_p);
9129             switch(val) {
9130                 case NAN_DP_CHANNEL_NOT_REQUESTED:
9131                     msg.channel_request_type = NAN_DP_CHANNEL_NOT_REQUESTED ;
9132                     break;
9133                 case NAN_DP_REQUEST_CHANNEL_SETUP:
9134                     msg.channel_request_type = NAN_DP_REQUEST_CHANNEL_SETUP;
9135                     break;
9136                 case NAN_DP_FORCE_CHANNEL_SETUP:
9137                     msg.channel_request_type = NAN_DP_FORCE_CHANNEL_SETUP;
9138                     break;
9139                 default:
9140                     msg.channel_request_type = NAN_DP_CHANNEL_NOT_REQUESTED;
9141                     break;
9142             }
9143         } else if (strcmp(param, "-chan") == 0) {
9144             msg.channel = atoi(val_p);
9145         } else if (strcmp(param, "-disc_mac") == 0) {
9146             if (!ether_atoe(val_p, msg.peer_disc_mac_addr)) {
9147                 printMsg("bad Discovery Mac address !!\n");
9148                 ret = WIFI_ERROR_INVALID_ARGS;
9149                 goto exit;
9150             }
9151         } else if (strcmp(param, "-iface") == 0) {
9152             if (!set_interface_params(msg.ndp_iface, val_p, (IFNAMSIZ - 1))) {
9153                 printMsg("Set Iface name successfull\n");
9154             } else {
9155                 printMsg("Invalid  Iface name\n");
9156                 ret = WIFI_ERROR_INVALID_ARGS;
9157                 goto exit;
9158             }
9159         } else if (strcmp(param, "-sec") == 0) {
9160             val = atoi(val_p);
9161             switch(val) {
9162                 case NAN_DP_CONFIG_SECURITY:
9163                     msg.ndp_cfg.security_cfg = NAN_DP_CONFIG_SECURITY;
9164                     break;
9165                 default:
9166                     msg.ndp_cfg.security_cfg = NAN_DP_CONFIG_NO_SECURITY;
9167                     break;
9168             }
9169         } else if (strcmp(param, "-qos") == 0) {
9170             val = atoi(val_p);
9171             switch(val) {
9172                 case NAN_DP_CONFIG_QOS:
9173                     msg.ndp_cfg.qos_cfg = NAN_DP_CONFIG_QOS;
9174                     break;
9175                 default:
9176                     msg.ndp_cfg.qos_cfg = NAN_DP_CONFIG_NO_QOS;
9177                     break;
9178             }
9179         } else if (strcmp(param, "-info") == 0) {
9180             if (strlen((const char*)val_p) > NAN_DP_MAX_APP_INFO_LEN) {
9181                 printMsg("Invalid app info\n");
9182                 ret = WIFI_ERROR_INVALID_ARGS;
9183                 goto exit;
9184             } else {
9185                 msg.app_info.ndp_app_info_len =
9186                 strlen((const char*)val_p);
9187                 if (!set_interface_params((char*)msg.app_info.ndp_app_info,
9188                     val_p, msg.app_info.ndp_app_info_len)) {
9189                     printMsg("Set app info successfull\n");
9190                 }
9191             }
9192         } else if (strcmp(param, "-csid") == 0) {
9193             val = atoi(val_p);
9194             switch(val) {
9195                 case NAN_CIPHER_SUITE_SHARED_KEY_NONE:
9196                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_NONE;
9197                     break;
9198                 case NAN_CIPHER_SUITE_SHARED_KEY_128_MASK:
9199                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_128_MASK;
9200                     break;
9201                 case NAN_CIPHER_SUITE_SHARED_KEY_256_MASK:
9202                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_256_MASK;
9203                     break;
9204                 case NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_128_MASK:
9205                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_128_MASK;
9206                     break;
9207                 case NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_256_MASK:
9208                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_256_MASK;
9209                     break;
9210                 case NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_128_MASK:
9211                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_128_MASK;
9212                     break;
9213                 case NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_256_MASK:
9214                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_256_MASK;
9215                     break;
9216                 default:
9217                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_NONE;
9218                     break;
9219             }
9220         } else if (strcmp(param, "-key_type") == 0) {
9221             val = atoi(val_p);
9222             switch(val) {
9223                 case NAN_SECURITY_KEY_INPUT_PMK:
9224                     msg.key_info.key_type = NAN_SECURITY_KEY_INPUT_PMK;
9225                     break;
9226                 case NAN_SECURITY_KEY_INPUT_PASSPHRASE:
9227                     msg.key_info.key_type = NAN_SECURITY_KEY_INPUT_PASSPHRASE;
9228                     break;
9229                 default:
9230                     printMsg("Invalid security key type\n");
9231                     ret = WIFI_ERROR_INVALID_ARGS;
9232                     goto exit;
9233             }
9234         } else if (strcmp(param, "-pmk") == 0) {
9235             if (strlen((const char*)val_p) > NAN_PMK_INFO_LEN) {
9236                 printMsg("Invalid PMK\n");
9237                 ret = WIFI_ERROR_INVALID_ARGS;
9238                 goto exit;
9239             } else {
9240                 msg.key_info.body.pmk_info.pmk_len=
9241                 strlen((const char*)val_p);
9242                 if (!set_interface_params((char*)msg.key_info.body.pmk_info.pmk,
9243                 val_p, msg.key_info.body.pmk_info.pmk_len)) {
9244                 printMsg("Set PMK successfull\n");
9245                 }
9246             }
9247         } else if (strcmp(param, "-passphrase") == 0) {
9248             if (strlen((const char*)val_p) < NAN_SECURITY_MIN_PASSPHRASE_LEN ||
9249             strlen((const char*)val_p) > NAN_SECURITY_MAX_PASSPHRASE_LEN) {
9250                 printMsg("passphrase must be between %d and %d characters long\n",
9251                 NAN_SECURITY_MIN_PASSPHRASE_LEN,
9252                 NAN_SECURITY_MAX_PASSPHRASE_LEN);
9253                 ret = WIFI_ERROR_INVALID_ARGS;
9254                 goto exit;
9255             } else {
9256                 msg.key_info.body.passphrase_info.passphrase_len =
9257                 (strlen((const char*)val_p));
9258                 if (!set_interface_params((char*)msg.key_info.body.passphrase_info.passphrase,
9259                     val_p, msg.key_info.body.passphrase_info.passphrase_len)) {
9260                     printMsg("Set passphrase successfull, len = %d\n",
9261                         msg.key_info.body.passphrase_info.passphrase_len);
9262                 } else {
9263                     printMsg("Invalid passphrase\n");
9264                     ret = WIFI_ERROR_INVALID_ARGS;
9265                     goto exit;
9266                 }
9267             }
9268         } else if (strcmp(param, "-scid") == 0) {
9269             if (strlen((const char*)val_p) > NAN_MAX_SCID_BUF_LEN) {
9270                 printMsg("Invalid SCID\n");
9271                 ret = WIFI_ERROR_INVALID_ARGS;
9272                 goto exit;
9273             } else {
9274                 msg.scid_len=
9275                 strlen((const char*)val_p);
9276                 if (!set_interface_params((char*)msg.scid,
9277                     val_p, msg.scid_len)) {
9278                     printMsg("Set SCID successfull\n");
9279                 }
9280             }
9281         } else if (strcmp(param, "-svc") == 0) {
9282             if (strlen((const char *)val_p) > NAN_MAX_SERVICE_NAME_LEN) {
9283                 printMsg("Invalid service name\n");
9284                 ret = WIFI_ERROR_INVALID_ARGS;
9285                 goto exit;
9286             } else {
9287                 msg.service_name_len =
9288                 strlen((const char *)val_p);
9289                 if (!set_interface_params((char*)msg.service_name,
9290                     val_p, msg.service_name_len)) {
9291                     printMsg("Set service name successfull\n");
9292                 }
9293             }
9294         } else if (strcmp(param, "-lcl_svc_id") == 0) {
9295             msg.publish_subscribe_id = atoi(val_p);
9296         } else {
9297             printMsg("%s:Unsupported Parameter for Nan Data Path Request\n", __FUNCTION__);
9298             goto exit;
9299         }
9300     }
9301 
9302     nanCmdId = getNewCmdId();
9303     ret = nan_init_handlers();
9304     if (ret != WIFI_SUCCESS) {
9305         printMsg("Failed to initialize handlers %d\n", ret);
9306         goto exit;
9307     }
9308     ret = nan_data_request_initiator(nanCmdId, wlan0Handle, &msg);
9309 exit:
9310     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
9311     return;
9312 }
9313 
nanDataIndResponse(int argc,char * argv[])9314 void nanDataIndResponse(int argc, char *argv[]) {
9315     NanDataPathIndicationResponse msg;
9316     wifi_error ret = WIFI_SUCCESS;
9317     char *param = NULL, *val_p = NULL;
9318     u32 val = 0;
9319 
9320     memset(&msg, 0, sizeof(msg));
9321     msg.ndp_cfg.security_cfg = NAN_DP_CONFIG_NO_SECURITY;
9322     msg.ndp_cfg.qos_cfg = NAN_DP_CONFIG_NO_QOS;
9323 
9324     /* skip utility */
9325     argv++;
9326     /* skip command */
9327     argv++;
9328     /* skip command */
9329     argv++;
9330 
9331     while ((param = *argv++) != NULL) {
9332         val_p = *argv++;
9333         if (!val_p || *val_p == '-') {
9334             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
9335             ret = WIFI_ERROR_NOT_SUPPORTED;
9336             goto exit;
9337         }
9338         if (strcmp(param, "-ndp_id") == 0) {
9339             msg.ndp_instance_id = atoi(val_p);
9340         } else if (strcmp(param, "-iface") == 0) {
9341             if (!set_interface_params(msg.ndp_iface, val_p, (IFNAMSIZ - 1))) {
9342                 printMsg("Set Iface name successfull\n");
9343             } else {
9344                 printMsg("Invalid  Iface name\n");
9345                 ret = WIFI_ERROR_INVALID_ARGS;
9346                 goto exit;
9347             }
9348         } else if (strcmp(param, "-sec") == 0) {
9349             val = atoi(val_p);
9350             switch(val) {
9351                 case NAN_DP_CONFIG_SECURITY:
9352                     msg.ndp_cfg.security_cfg = NAN_DP_CONFIG_SECURITY;
9353                     break;
9354                 default:
9355                     msg.ndp_cfg.security_cfg = NAN_DP_CONFIG_NO_SECURITY;
9356                     break;
9357             }
9358         } else if (strcmp(param, "-qos") == 0) {
9359             val = atoi(val_p);
9360             switch(val) {
9361                 case NAN_DP_CONFIG_QOS:
9362                     msg.ndp_cfg.qos_cfg = NAN_DP_CONFIG_QOS;
9363                     break;
9364                 default:
9365                     msg.ndp_cfg.qos_cfg = NAN_DP_CONFIG_NO_QOS;
9366                     break;
9367             }
9368         } else if (strcmp(param, "-info") == 0) {
9369             if ((u16)strlen((const char*)val_p) > NAN_DP_MAX_APP_INFO_LEN) {
9370                 printMsg("Invalid app info\n");
9371                 ret = WIFI_ERROR_INVALID_ARGS;
9372                 goto exit;
9373             } else {
9374                 msg.app_info.ndp_app_info_len =
9375                     (u16)strlen((const char*)val_p);
9376                 if (!set_interface_params((char*)msg.app_info.ndp_app_info,
9377                     val_p, msg.app_info.ndp_app_info_len)) {
9378                     printMsg("Set app info successfull\n");
9379                 }
9380             }
9381         } else if (strcmp(param, "-resp_code") == 0) {
9382             val = atoi(val_p);
9383             switch(val) {
9384                 case NAN_DP_REQUEST_REJECT:
9385                     msg.rsp_code = NAN_DP_REQUEST_REJECT;
9386                     break;
9387                 case NAN_DP_REQUEST_ACCEPT:
9388                     msg.rsp_code = NAN_DP_REQUEST_ACCEPT;
9389                     break;
9390                 default:
9391                     printMsg("Invalid response code\n");
9392                     ret = WIFI_ERROR_INVALID_ARGS;
9393                     goto exit;
9394             }
9395         } else if (strcmp(param, "-csid") == 0) {
9396             val = atoi(val_p);
9397             switch(val) {
9398                 case NAN_CIPHER_SUITE_SHARED_KEY_NONE:
9399                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_NONE;
9400                     break;
9401                 case NAN_CIPHER_SUITE_SHARED_KEY_128_MASK:
9402                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_128_MASK;
9403                     break;
9404                 case NAN_CIPHER_SUITE_SHARED_KEY_256_MASK:
9405                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_256_MASK;
9406                     break;
9407                 case NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_128_MASK:
9408                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_128_MASK;
9409                     break;
9410                 case NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_256_MASK:
9411                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_2WDH_256_MASK;
9412                     break;
9413                 case NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_128_MASK:
9414                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_128_MASK;
9415                     break;
9416                 case NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_256_MASK:
9417                     msg.cipher_type = NAN_CIPHER_SUITE_PUBLIC_KEY_PASN_256_MASK;
9418                     break;
9419                 default:
9420                     msg.cipher_type = NAN_CIPHER_SUITE_SHARED_KEY_NONE;
9421                     break;
9422             }
9423         } else if (strcmp(param, "-key_type") == 0) {
9424             val = atoi(val_p);
9425             switch(val) {
9426                 case NAN_SECURITY_KEY_INPUT_PMK:
9427                     msg.key_info.key_type = NAN_SECURITY_KEY_INPUT_PMK;
9428                     break;
9429                 case NAN_SECURITY_KEY_INPUT_PASSPHRASE:
9430                     msg.key_info.key_type = NAN_SECURITY_KEY_INPUT_PASSPHRASE;
9431                     break;
9432                 default:
9433                     printMsg("Invalid security key type\n");
9434                     ret = WIFI_ERROR_INVALID_ARGS;
9435                     goto exit;
9436             }
9437         } else if (strcmp(param, "-pmk") == 0) {
9438             if (strlen((const char*)val_p) > NAN_PMK_INFO_LEN) {
9439                 printMsg("Invalid PMK\n");
9440                 ret = WIFI_ERROR_INVALID_ARGS;
9441                 goto exit;
9442             } else {
9443                 msg.key_info.body.pmk_info.pmk_len =
9444                     strlen((const char*)val_p);
9445                 if (!set_interface_params((char*)msg.key_info.body.pmk_info.pmk,
9446                     val_p, msg.key_info.body.pmk_info.pmk_len)) {
9447                     printMsg("Set PMK successfull\n");
9448                 }
9449             }
9450         } else if (strcmp(param, "-passphrase") == 0) {
9451             if (strlen((const char*)val_p) < NAN_SECURITY_MIN_PASSPHRASE_LEN ||
9452                 strlen((const char*)val_p) > NAN_SECURITY_MAX_PASSPHRASE_LEN) {
9453                 printMsg("passphrase must be between %d and %d characters long\n",
9454                     NAN_SECURITY_MIN_PASSPHRASE_LEN,
9455                     NAN_SECURITY_MAX_PASSPHRASE_LEN);
9456                 ret = WIFI_ERROR_INVALID_ARGS;
9457                 goto exit;
9458             } else {
9459                 msg.key_info.body.passphrase_info.passphrase_len =
9460                     (strlen((const char*)val_p));
9461                 if (!set_interface_params((char*)msg.key_info.body.passphrase_info.passphrase,
9462                     val_p, msg.key_info.body.passphrase_info.passphrase_len)) {
9463                     printMsg("Set passphrase successfull, len = %d\n",
9464                         msg.key_info.body.passphrase_info.passphrase_len);
9465                 } else {
9466                     printMsg("Invalid passphrase\n");
9467                     ret = WIFI_ERROR_INVALID_ARGS;
9468                     goto exit;
9469                 }
9470             }
9471         } else if (strcmp(param, "-scid") == 0) {
9472             if (strlen((const char*)val_p) > NAN_MAX_SCID_BUF_LEN) {
9473                 printMsg("Invalid SCID\n");
9474                 ret = WIFI_ERROR_INVALID_ARGS;
9475                 goto exit;
9476             } else {
9477                 msg.scid_len= strlen((const char*)val_p);
9478                 if (!set_interface_params((char*)msg.scid, val_p, msg.scid_len)) {
9479                     printMsg("Set SCID successfull\n");
9480                 }
9481             }
9482         } else if (strcmp(param, "-svc") == 0) {
9483             if (strlen((const char *)val_p) > NAN_MAX_SERVICE_NAME_LEN) {
9484                 printMsg("Invalid service name\n");
9485                 ret = WIFI_ERROR_INVALID_ARGS;
9486                 goto exit;
9487             } else {
9488                 msg.service_name_len =
9489                 strlen((const char *)val_p);
9490                 if (!set_interface_params((char*)msg.service_name,
9491                     val_p, msg.service_name_len)) {
9492                     printMsg("Set service name successfull\n");
9493                 }
9494             }
9495         } else if (strcmp(param, "-lcl_svc_id") == 0) {
9496             msg.publish_subscribe_id = atoi(val_p);
9497         } else {
9498             printMsg("%s:Unsupported Parameter for Nan Data Path Request\n", __FUNCTION__);
9499             goto exit;
9500         }
9501     }
9502     nanCmdId = getNewCmdId();
9503     ret = nan_init_handlers();
9504     if (ret != WIFI_SUCCESS) {
9505         printMsg("Failed to initialize handlers %d\n", ret);
9506         goto exit;
9507     }
9508     ret = nan_data_indication_response(nanCmdId, wlan0Handle, &msg);
9509 exit:
9510     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
9511     return;
9512 }
9513 
nanDataPathEnd(int argc,char * argv[])9514 void nanDataPathEnd(int argc, char *argv[]) {
9515     NanDataPathEndRequest *msg;
9516     wifi_error ret = WIFI_SUCCESS;
9517     char *param = NULL, *val_p = NULL, *endptr = NULL;
9518     u8 count = 0, i = 0;
9519     NanDataPathId ndp_id = 0;
9520 
9521     /* skip utility */
9522     argv++;
9523     /* skip command */
9524     argv++;
9525     /* skip command */
9526     argv++;
9527 
9528     msg = (NanDataPathEndRequest *)malloc(NAN_MAX_NDP_COUNT_SIZE + sizeof(u8));
9529     if (!msg) {
9530         printMsg("Failed to alloc for end request\n");
9531         ret = WIFI_ERROR_OUT_OF_MEMORY;
9532         goto exit;
9533     }
9534     memset(msg, 0, NAN_MAX_NDP_COUNT_SIZE + sizeof(u8));
9535 
9536     while ((param = *argv++) != NULL) {
9537         val_p = *argv++;
9538         if (!val_p || *val_p == '-') {
9539             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
9540             ret = WIFI_ERROR_NOT_SUPPORTED;
9541             goto exit;
9542         }
9543         if (strcmp(param, "-inst_count") == 0) {
9544             count = atoi(val_p);
9545             if (!count || count > 1) {
9546                 printMsg("%s:Invalid inst_count value.\n", __FUNCTION__);
9547                 ret = WIFI_ERROR_INVALID_ARGS;
9548                 goto exit;
9549             }
9550             msg->num_ndp_instances = count;
9551         } else if (strcmp(param, "-inst_id") == 0) {
9552             if (!msg->num_ndp_instances || (i > msg->num_ndp_instances)) {
9553                 printMsg("num of ndp instances need to be minimum 1\n");
9554                 goto exit;
9555             }
9556             ndp_id = strtoul(val_p, &endptr, 0);
9557             msg->ndp_instance_id[i++] = ndp_id;
9558         } else {
9559             printMsg("%s:Unsupported Parameter for Nan Data Path End Request\n", __FUNCTION__);
9560             goto exit;
9561         }
9562     }
9563 
9564     nanCmdId = getNewCmdId();
9565     ret = nan_init_handlers();
9566     if (ret != WIFI_SUCCESS) {
9567         printMsg("Failed to initialize handlers %d\n", ret);
9568         goto exit;
9569     }
9570     ret = nan_data_end(nanCmdId, wlan0Handle, msg);
9571 exit:
9572     if (msg) {
9573         free(msg);
9574     }
9575     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
9576     return;
9577 }
9578 
VirtualIfaceAdd(char * argv[])9579 void VirtualIfaceAdd(char *argv[]) {
9580     wifi_error ret = WIFI_SUCCESS;
9581     char *param = NULL, *val_p = NULL;
9582     /* Interface name */
9583     char iface_name[IFNAMSIZ+1];
9584     wifi_interface_type iface_type = WIFI_INTERFACE_TYPE_STA;
9585     bool set_iface = false;
9586 
9587     memset(iface_name, 0, sizeof(iface_name));
9588 
9589     /* skip utility */
9590     argv++;
9591     /* skip command */
9592     argv++;
9593 
9594     while ((param = *argv++) != NULL) {
9595         val_p = *argv++;
9596         if (!val_p || *val_p == '-') {
9597             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
9598             ret = WIFI_ERROR_NOT_SUPPORTED;
9599             goto exit;
9600         }
9601         if (strcmp(param, "-name") == 0) {
9602             if (!set_interface_params(iface_name, val_p, (IFNAMSIZ - 1))) {
9603                 printMsg("set interface name successfull\n");
9604             } else {
9605                 printMsg("Invalid Iface name\n");
9606                 ret = WIFI_ERROR_INVALID_ARGS;
9607                 goto exit;
9608             }
9609         } else if (strcmp(param, "-type") == 0) {
9610             iface_type = (wifi_interface_type)atoi(val_p);
9611             set_iface = true;
9612         } else {
9613             printMsg("Unsupported Parameter for virtual iface delete\n");
9614             goto exit;
9615         }
9616     }
9617 
9618     if (!set_iface) {
9619         printMsg("Error, Mandatory iface type is not set\n");
9620         goto exit;
9621     }
9622 
9623     ret = hal_fn.wifi_virtual_interface_create(halHandle, iface_name, iface_type);
9624     if (ret == WIFI_ERROR_NONE) {
9625         printMsg("Successful to add virtual iface\n");
9626     } else {
9627         printMsg("Failed to add virtual iface, result = %d\n", ret);
9628     }
9629 
9630 exit:
9631     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
9632     return;
9633 }
9634 
VirtualIfaceDelete(char * argv[])9635 void VirtualIfaceDelete(char *argv[]) {
9636     wifi_error ret = WIFI_SUCCESS;
9637     char *param = NULL, *val_p = NULL;
9638     /* Interface name */
9639     char iface_name[IFNAMSIZ+1];
9640     memset(iface_name, 0, sizeof(iface_name));
9641 
9642     /* skip utility */
9643     argv++;
9644     /* skip command */
9645     argv++;
9646 
9647     while ((param = *argv++) != NULL) {
9648         val_p = *argv++;
9649         if (!val_p || *val_p == '-') {
9650             printMsg("%s: Need value following %s\n", __FUNCTION__, param);
9651             ret = WIFI_ERROR_NOT_SUPPORTED;
9652             goto exit;
9653         }
9654         if (strcmp(param, "-name") == 0) {
9655             if (!set_interface_params(iface_name, val_p, (IFNAMSIZ - 1))) {
9656                 printMsg("set interface name successfull\n");
9657             } else {
9658                 printMsg("Invalid  face name\n");
9659                 ret = WIFI_ERROR_INVALID_ARGS;
9660                 goto exit;
9661             }
9662         } else {
9663             printMsg("Unsupported Parameter for virtual iface delete\n");
9664             goto exit;
9665         }
9666     }
9667 
9668     ret = hal_fn.wifi_virtual_interface_delete(halHandle, iface_name);
9669     if (ret == WIFI_ERROR_NONE) {
9670         printMsg("Successful to delete virtual iface\n");
9671     } else {
9672         printMsg("Failed to delete virtual iface, result = %d\n", ret);
9673     }
9674 exit:
9675     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
9676     return;
9677 }
9678 
9679 static void
MultiStaSetPrimaryConnection(char * argv[])9680 MultiStaSetPrimaryConnection(char *argv[]) {
9681     wifi_error ret = WIFI_SUCCESS;
9682     char *param = NULL;
9683     /* Interface name */
9684     char iface_name[IFNAMSIZ+1];
9685     wifi_interface_handle ifHandle = NULL;
9686 
9687     memset(iface_name, 0, sizeof(iface_name));
9688 
9689     /* skip utility */
9690     argv++;
9691     /* skip command */
9692     argv++;
9693 
9694     while ((param = *argv++) != NULL) {
9695         if (!set_interface_params(iface_name, param, (IFNAMSIZ - 1))) {
9696             printMsg("set interface name successfull\n");
9697         } else {
9698             printMsg("Invalid  iface name\n");
9699             ret = WIFI_ERROR_INVALID_ARGS;
9700             goto exit;
9701         }
9702     }
9703 
9704     ifHandle = wifi_get_iface_handle(halHandle, iface_name);
9705     if (ifHandle == NULL) {
9706         printMsg("Invalid  iface handle for the requested interface\n");
9707         ret = WIFI_ERROR_INVALID_ARGS;
9708         goto exit;
9709     } else {
9710         ret = hal_fn.wifi_multi_sta_set_primary_connection(halHandle, ifHandle);
9711         if (ret == WIFI_ERROR_NONE) {
9712             printMsg("Successfully set as primary connection\n");
9713         }
9714     }
9715 exit:
9716     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
9717     return;
9718 }
9719 
9720 static void
MultiStaSetUsecase(char * argv[])9721 MultiStaSetUsecase(char *argv[]) {
9722     wifi_error ret = WIFI_SUCCESS;
9723     uint use_case = 0;
9724     wifi_multi_sta_use_case mMultiStaUsecase;
9725 
9726     /* skip utility */
9727     argv++;
9728     /* skip command */
9729     argv++;
9730 
9731     use_case = (uint)atoi(*argv);
9732     if ((use_case == WIFI_DUAL_STA_TRANSIENT_PREFER_PRIMARY) ||
9733         (use_case == WIFI_DUAL_STA_NON_TRANSIENT_UNBIASED)) {
9734         mMultiStaUsecase = (wifi_multi_sta_use_case)use_case;
9735     } else {
9736         printMsg("Invalid  multi_sta usecase\n");
9737         ret = WIFI_ERROR_INVALID_ARGS;
9738         goto exit;
9739     }
9740 
9741     ret = hal_fn.wifi_multi_sta_set_use_case(halHandle, mMultiStaUsecase);
9742     if (ret == WIFI_ERROR_NONE) {
9743         printMsg("Successful to set multista usecase\n");
9744     } else {
9745         printMsg("Failed to set multista usecase, result = %d\n", ret);
9746     }
9747 exit:
9748     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
9749     return;
9750 }
9751 
9752 static void
SetLatencyMode(char * argv[])9753 SetLatencyMode(char *argv[]) {
9754     wifi_error ret = WIFI_SUCCESS;
9755     char *param = NULL;
9756     /* Interface name */
9757     char iface_name[IFNAMSIZ+1];
9758     wifi_interface_handle ifHandle = NULL;
9759 
9760     memset(iface_name, 0, sizeof(iface_name));
9761 
9762     /* skip utility */
9763     argv++;
9764     /* skip command */
9765     argv++;
9766 
9767     param = *argv++;
9768     if (param != NULL) {
9769         if (!set_interface_params(iface_name, param, (IFNAMSIZ - 1))) {
9770            printMsg("set interface name successfull %s\n", iface_name);
9771         } else {
9772             printMsg("Invalid  iface name\n");
9773             ret = WIFI_ERROR_INVALID_ARGS;
9774             goto exit;
9775         }
9776     } else {
9777         printMsg("argv is null\n");
9778         ret = WIFI_ERROR_INVALID_ARGS;
9779         goto exit;
9780     }
9781 
9782     ifHandle = wifi_get_iface_handle(halHandle, iface_name);
9783     if (ifHandle == NULL) {
9784         printMsg("Invalid  iface handle for the requested interface\n");
9785         ret = WIFI_ERROR_INVALID_ARGS;
9786         goto exit;
9787     } else {
9788         /* Read the requested latency mode */
9789         wifi_latency_mode latency_mode = (wifi_latency_mode)(atoi)(*argv);
9790         ret = hal_fn.wifi_set_latency_mode(ifHandle, latency_mode);
9791         if (ret == WIFI_ERROR_NONE) {
9792             printMsg("Successfully set latency mode\n");
9793         }
9794     }
9795 exit:
9796     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
9797     return;
9798 
9799 }
9800 
9801 static void
SetVoipMode(char * argv[])9802 SetVoipMode(char *argv[]) {
9803     wifi_error ret = WIFI_SUCCESS;
9804     char *param = NULL;
9805     /* Interface name */
9806     char iface_name[IFNAMSIZ+1];
9807     wifi_interface_handle ifHandle = NULL;
9808 
9809     memset(iface_name, 0, sizeof(iface_name));
9810 
9811     /* skip utility */
9812     argv++;
9813     /* skip command */
9814     argv++;
9815 
9816     param = *argv++;
9817     if (param != NULL) {
9818         if (!set_interface_params(iface_name, param, (IFNAMSIZ - 1))) {
9819             printMsg("set interface name successfull\n");
9820         } else {
9821             printMsg("Invalid  iface name\n");
9822             ret = WIFI_ERROR_INVALID_ARGS;
9823             goto exit;
9824         }
9825     } else {
9826         printMsg("argv is null\n");
9827         ret = WIFI_ERROR_INVALID_ARGS;
9828         goto exit;
9829     }
9830 
9831     ifHandle = wifi_get_iface_handle(halHandle, iface_name);
9832     if (ifHandle == NULL) {
9833         printMsg("Invalid  iface handle for the requested interface\n");
9834         ret = WIFI_ERROR_INVALID_ARGS;
9835         goto exit;
9836     } else {
9837         /* Read the requested voip mode */
9838         wifi_voip_mode mode = (wifi_voip_mode)(atoi)(*argv);
9839         ret = hal_fn.wifi_set_voip_mode(ifHandle, mode);
9840         if (ret == WIFI_ERROR_NONE) {
9841             printMsg("Successfully set voip mode\n");
9842         }
9843     }
9844 exit:
9845     printMsg("%s:ret = %d\n", __FUNCTION__, ret);
9846     return;
9847 }
9848 
main(int argc,char * argv[])9849 int main(int argc, char *argv[]) {
9850     pthread_mutex_init(&printMutex, NULL);
9851 
9852     set_hautil_mode(true);
9853     if (init() != 0) {
9854         printMsg("could not initiate HAL");
9855         return WIFI_ERROR_UNKNOWN;
9856     } else {
9857         ALOGD("successfully initialized HAL; wlan0 = %p\n", wlan0Handle);
9858     }
9859 
9860     sem_init(&event_thread_mutex,0,0);
9861 
9862     pthread_cond_init(&eventCacheCondition, NULL);
9863     pthread_mutex_init(&eventCacheMutex, NULL);
9864 
9865     pthread_t tidEvent;
9866     pthread_create(&tidEvent, NULL, &eventThreadFunc, NULL);
9867     sem_wait(&event_thread_mutex);
9868 
9869     if (argc < 2) {
9870         printUsage();
9871         goto cleanup;
9872     } else if (argv[1][0] != '-') {
9873         printUsage();
9874         goto cleanup;
9875     } else if ((strcmp(argv[1], "-nan") == 0) && (argc < 3)) {
9876         printUsage();
9877         goto cleanup;
9878     }
9879     memset(mac_oui, 0, 3);
9880     if (strcmp(argv[1], "-nan") == 0) {
9881         if ((strcmp(argv[2], "-enable") == 0)) {
9882             enableNan(argv);
9883         } else if ((strcmp(argv[2], "-disable") == 0)) {
9884             disableNan(argv);
9885         } else if ((strcmp(argv[2], "-config") == 0)) {
9886             configNan(argv);
9887         } else if ((strcmp(argv[2], "-publish") == 0)) {
9888             if (argc < 4) {
9889                 printMsg(" -nan [-publish] [-svc <svc_name>] [-info <svc info>\n"
9890                     "    [-pub_type <0/1/2>] [-pub_count <val>] [-rssi_thresh_flag <0/1>]\n"
9891                     "    [-tx_type <0/1>] [-ttl <val>] [-svc_awake_dw <val>]\n"
9892                     "    [-match_rx <0/ascii str>] [-match_tx <0/ascii str>]] [-match_ind <1/2>]\n"
9893                     "    [-csid <cipher suite type 0/1/2/4/8>] [-key_type <1 or 2>]"
9894                     "    [-pmk <PMK value>] [-passphrase <Passphrase value, len must "
9895                     "    not be less than 8 or greater than 63>] [-scid <scid value>]"
9896                     "    [-dp_type <0-Unicast, 1-multicast>]\n"
9897                     "    [-secure_dp <0-No security, 1-Security>]"
9898                     "    -ranging <0-disable, 1-enable>)\n"
9899                     "    [-ranging_intvl [intrvl in ms betw"
9900                     "    two ranging measurements] -ranging_ind [ BIT0 -"
9901                     "    Continuous Ranging event notification,"
9902                     "    BIT1 - Ingress distance is <=, BIT2 - Egress distance is >=.]\n"
9903                     "    [-ingress [Ingress distance in centimeters] \n"
9904                     "    [ -egress [Egress distance in centimeters] \n"
9905                     "    [-auto_dp_accept [0 - User response required to accept dp,"
9906                     "    1 - User response not required to accept dp] \n"
9907                     "    [-recv_flag <0 to 15>] [-suspendable <0/1>] \n"
9908                     "    [-bs_methods <supported bootstrapping methods]>\n"
9909                     "    [-pairing_setup <supported 0/1>] [-pairing_cache <supported 0/1]"
9910                     "    [-pairing_verification <supported 0/1>] [-nik <local nik of 16 char>]\n");
9911                 printMsg("\n *Set/Enable corresponding bits to disable any"
9912                     "    indications that follow a publish"
9913                     "\n *BIT0 - Disable publish termination indication."
9914                     "\n *BIT1 - Disable match expired indication."
9915                     "\n *BIT2 - Disable followUp indication received (OTA)");
9916                 goto cleanup;
9917             }
9918             publishNan(argc, argv);
9919         } else if ((strcmp(argv[2], "-subscribe") == 0)) {
9920             if (argc < 3) {
9921                 printMsg(" -nan [-subscribe] [-svc <svc_name>] [-info <svc info>\n"
9922                     "    [-sub_type <0/1>] [-sub_count <val>] [-pub_ssi <0/1>]\n"
9923                     "    [-ttl <val>] [-svc_awake_dw <val>] [-match_ind <1/2>]\n"
9924                     "    [-match_rx <0/ascii str>] [-match_tx <0/ascii str>]\n"
9925                     "    [-mac_list <addr>] [-srf_include <0/1>] [-rssi_thresh_flag <0/1>]]\n"
9926                     "    [-csid <cipher suite type 0/1/2/4/8>] [-key_type <1 or 2>]"
9927                     "    [-pmk <PMK value>] [-passphrase <Passphrase value,"
9928                     "    len must not be less than 8 or greater than 63>]\n"
9929                     "    [-scid <scid value>] [-dp_type <0-Unicast, 1-multicast>]\n"
9930                     "    [-secure_dp <0-No security, 1-Security>] -ranging <0-disable, 1-enable>)\n"
9931                     "    [-ranging_intvl [intrvl in ms betw two ranging measurements] -ranging_ind \n"
9932                     "    [BIT0 - Continuous Ranging event notification,"
9933                     "    BIT1 - Ingress distance is <=, BIT2 - Egress distance is >=.]\n"
9934                     "    [-ingress [Ingress distance in centimeters] \n"
9935                     "    [ -egress [Egress distance in centimeters] \n"
9936                     "    [-recv_flag <0 to 7>] [-suspendable <0/1>] \n"
9937                     "    [-bs_methods <supported bootstrapping methods]>\n"
9938                     "    [-pairing_setup <supported 0/1>] [-pairing_cache <supported 0/1]"
9939                     "    [-pairing_verification <supported 0/1>]  [-nik <local nik of 16 char>]\n");
9940                 printMsg("\n *Set/Enable corresponding bits to disable any indications that"
9941                     "    follow a publish"
9942                     "\n *BIT0 - Disable publish termination indication."
9943                     "\n *BIT1 - Disable match expired indication."
9944                     "\n *BIT2 - Disable followUp indication received (OTA)");
9945                 goto cleanup;
9946             }
9947             subscribeNan(argc, argv);
9948         } else if ((strcmp(argv[2], "-cancel_pub") == 0)) {
9949             if(argc < 3) {
9950                 printMsg(" -nan [-cancel_pub] [<publish id>]\n");
9951                 goto cleanup;
9952             }
9953             cancelPublishNan(argv);
9954         } else if ((strcmp(argv[2], "-cancel_sub") == 0)) {
9955             if(argc < 3) {
9956                 printMsg(" -nan [-cancel_sub] [<sublish id>]\n");
9957                 goto cleanup;
9958             }
9959             cancelSubscribeNan(argv);
9960         } else if ((strcmp(argv[2], "-transmit") == 0)) {
9961             if(argc < 5) {
9962                 printMsg(" -nan [-transmit] [-src_id <instance id>] [-dest_id <instance id>]\n"
9963                     "    [-peer_addr <mac addr>] [-info <svc info>]\n");
9964                 printMsg("\n Mandatory fields are not present\n");
9965                 goto cleanup;
9966             }
9967             transmitNan(argc,argv);
9968         } else if ((strcmp(argv[2], "-get_capabilities") == 0)) {
9969             getNanCapabilities();
9970         } else if ((strcmp(argv[2], "-create") == 0)) {
9971             if(argc < 3) {
9972                 printMsg("\n Mandatory fields are not present\n");
9973                 printMsg(" -nan [-create] [-iface_name <iface name>]\n");
9974                 goto cleanup;
9975             }
9976             nanDataPathIfaceCreate(argv);
9977         } else if ((strcmp(argv[2], "-delete") == 0)) {
9978             if(argc < 3) {
9979                 printMsg("\n Mandatory fields are not present\n");
9980                 printMsg(" -nan [-delete] [-iface_name <iface name>]\n");
9981                 goto cleanup;
9982             }
9983             nanDataPathIfaceDelete(argv);
9984         } else if ((strcmp(argv[2], "-init") == 0)) {
9985             if(argc < 7) {
9986                 printMsg("\n Mandatory fields are not present\n");
9987                 printMsg(" -nan [-init] [-pub_id <pub id>] [-disc_mac <discovery mac addr>]\n"
9988                     "    [-chan <channel in mhz>] [-iface <iface>] [-sec <security>]\n"
9989                     "    [-qos <qos>] [-info <seq of values in the frame body>]\n"
9990                     "    [-csid <cipher suite type 0/1/2/4/8>]\n"
9991                     "    [-scid <scid value>] [-svc <svc_name>] [-lcl_svc_id <service id>] \n");
9992                 goto cleanup;
9993             }
9994             nanDataInitRequest(argc, argv);
9995         } else if ((strcmp(argv[2], "-resp") == 0)) {
9996             if(argc < 3) {
9997                 printMsg("\n Mandatory fields are not present\n");
9998                 printMsg(" -nan [-resp] [-ndp_id <NDP id>] [-iface <NDP iface name>]\n"
9999                     "    [-resp_code <accept = 0, accept = 1>] [-qos <qos>]\n"
10000                     "    [-info <seq of values in the frame body>]\n"
10001                     "    [-csid <cipher suite type 0/1/2/4/8>]\n"
10002                     "    [-scid <scid value>] [-svc <svc_name>] [-lcl_svc_id <service id>] \n");
10003                 goto cleanup;
10004             }
10005             nanDataIndResponse(argc, argv);
10006         } else if ((strcmp(argv[2], "-suspend") == 0)) {
10007             if(argc < 3) {
10008                 printMsg(" -nan [-suspend] -svc_id [service_id]\n");
10009                 goto cleanup;
10010             }
10011             nanSuspendRequest(argv);
10012         } else if ((strcmp(argv[2], "-resume") == 0)) {
10013             if(argc < 3) {
10014                 printMsg(" -nan [-resume] -svc_id [service_id]\n");
10015                 goto cleanup;
10016             }
10017             nanResumeRequest(argv);
10018         } else if ((strcmp(argv[2], "-end") == 0)) {
10019             if(argc < 3) {
10020                 printMsg("\n Mandatory fields are not present\n");
10021                 printMsg(" -nan [-end] [-inst_count <count>] [-inst_id <NDP id>\n");
10022                 goto cleanup;
10023             }
10024             nanDataPathEnd(argc, argv);
10025         } else if ((strcmp(argv[2], "-pairing_req") == 0)) {
10026             if (argc < 5) {
10027                 printf(" -nan [-pairing_req] -pub_id <instance id>\n"
10028                     "  -type <0-setup, 1-verification> -peer_addr <mac addr>\n"
10029                     "  -password <password> -csid <cipher suite> [-akm <0-SAE, 1-PASN] \n"
10030                     "  [-nik <local nik>] [-pairing_cache <1-Enable , 0-Disable pairing cache>]\n"
10031                     "  [-pmk <32 byte PMK value>]\n");
10032                 printMsg("\n Mandatory fields are not present\n");
10033                 goto cleanup;
10034             }
10035             nanPairingRequest(argc, argv);
10036         } else if ((strcmp(argv[2], "-pairing_resp") == 0)) {
10037             if (argc < 5) {
10038                 printf(" -nan [-pairing_resp] [-pairing_id <pairing instance id>]\n"
10039                     "     [-rsp_code <0-ACCEPT,1-REJECT>] [-type <0-setup, 1-verification>]\n"
10040                     "     [-password <password>] [-csid <cipher suite>] [-akm <0-SAE, 1-PASN] \n"
10041                     "     [-nik <local nik>] [-pairing_cache <1-Enable, 0-Disable pairing cache>]\n"
10042                     "     [-pmk <32 byte PMK value>]\n");
10043                 printMsg("\n Mandatory fields are not present\n");
10044                 goto cleanup;
10045             }
10046             nanPairingResponse(argc, argv);
10047         } else if ((strcmp(argv[2], "-pairing_end") == 0)) {
10048             if (argc < 3) {
10049                 printMsg("\n Mandatory fields are not present\n");
10050                 printf(" -nan [-pairing_end] -pairing_id <pairing_instance_id>\n");
10051                 goto cleanup;
10052             }
10053             nanPairingEnd(argc, argv);
10054         } else if ((strcmp(argv[2], "-bs_req") == 0)) {
10055             if (argc < 5) {
10056                 printf(" -nan [-bs_req] -dest_id <peer inst id> -lcl_id <local inst id>\n"
10057                    "     -peer_addr <mac addr> -bs_methods <supported bootstrapping methiods>\n"
10058                    "     [-comeback <is it comeback BS req>] [-sdea_info <sdea svc info>]\n"
10059                    "     [-cookie <cookie info>] [-info <svc info>]\n");
10060                 printMsg("\n Mandatory fields are not present\n");
10061                 goto cleanup;
10062             }
10063             nanBootstrappingReq(argc, argv);
10064         } else if ((strcmp(argv[2], "-bs_resp") == 0)) {
10065             if (argc < 5) {
10066                 printf(" -nan [-bs_resp] dest_id <peer inst id> -lcl_id <local inst id> \n"
10067                    "     -peer_addr <mac addr> -rsp_code <0-ACCEPT, 1-REJECT, 2- COMEBACK>\n"
10068                    "     [-comeback_delay] [-cookie <cookie info>] [-info <svc info>] \n"
10069                    "     [-sdea_info <sdea svcinfo>]\n");
10070                 printMsg("\n Mandatory fields are not present\n");
10071                 goto cleanup;
10072             }
10073             nanBootstrappingResp(argc, argv);
10074         } else if ((strcmp(argv[2], "-event_chk") == 0)) {
10075             nanEventCheck();
10076         } else if ((strcmp(argv[2], "-ver") == 0)) {
10077             nanVersion();
10078         } else if ((strcmp(argv[2], "-exit") == 0)) {
10079             return WIFI_SUCCESS;
10080         } else {
10081             printMsg("\n Unknown command\n");
10082             printUsage();
10083             return WIFI_SUCCESS;
10084         }
10085     } else if (strcmp(argv[1], "-s") == 0) {
10086         readTestOptions(argc, argv);
10087         setPnoMacOui();
10088         testScan();
10089     } else if(strcmp(argv[1], "-swc") == 0){
10090         readTestOptions(argc, argv);
10091         setPnoMacOui();
10092         trackSignificantChange();
10093     } else if (strcmp(argv[1], "-ss") == 0) {
10094         // Stop scan so clear the OUI too
10095         setPnoMacOui();
10096         testStopScan();
10097     } else if ((strcmp(argv[1], "-h") == 0)  ||
10098             (strcmp(argv[1], "-hotlist_bssids") == 0)) {
10099         readTestOptions(argc, argv);
10100         setPnoMacOui();
10101         testHotlistAPs();
10102     } else if (strcmp(argv[1], "-stats") == 0) {
10103         getLinkStats();
10104     } else if (strcmp(argv[1], "-rtt") == 0) {
10105         readRTTOptions(argc, ++argv);
10106         testRTT();
10107     } else if (strcmp(argv[1], "-cancel_rtt") == 0) {
10108         cancelRTT();
10109     } else if (strcmp(argv[1], "-get_capa_rtt") == 0) {
10110         getRTTCapability();
10111     } else if ((strcmp(argv[1], "-get_ch_list") == 0)) {
10112         readTestOptions(argc, argv);
10113         getChannelList();
10114     } else if ((strcmp(argv[1], "-get_responder_info") == 0)) {
10115         getRttResponderInfo();
10116     } else if ((strcmp(argv[1], "-enable_resp") == 0)) {
10117         RttEnableResponder();
10118     } else if ((strcmp(argv[1], "-cancel_resp") == 0)) {
10119        cancelRttResponder();
10120     } else if ((strcmp(argv[1], "-get_feature_set") == 0)) {
10121         getFeatureSet();
10122     } else if ((strcmp(argv[1], "-get_feature_matrix") == 0)) {
10123         getFeatureSetMatrix();
10124     } else if ((strcmp(argv[1], "-get_wake_stats") == 0)) {
10125         getWakeStats();
10126     } else if ((strcmp(argv[1], "-scan_mac_oui") == 0)) {
10127         readTestOptions(argc, argv);
10128         setPnoMacOui();
10129         testScan();
10130     } else if (strcmp(argv[1], "-nodfs") == 0) {
10131         u32 nodfs = 0;
10132         if (argc > 2)
10133             nodfs = (u32)atoi(argv[2]);
10134         hal_fn.wifi_set_nodfs_flag(wlan0Handle, nodfs);
10135     } else if ((strcmp(argv[1], "-ePNO") == 0) || (strcmp(argv[1], "-ePNOCfg") == 0)) {
10136         memset(&epno_cfg, 0, sizeof(epno_cfg));
10137         epno_cfg.min5GHz_rssi =  -45;
10138         epno_cfg.min24GHz_rssi =  -50;
10139         epno_cfg.initial_score_max  =  110;
10140         epno_cfg.num_networks = -1;
10141         readTestOptions(argc, argv);
10142         epno_cfg.num_networks++;
10143         setBlacklist(false);
10144         testPNO(false, (strcmp(argv[1], "-ePNO") == 0));
10145         if (strcmp(argv[1], "-ePNOCfg") == 0) {
10146             printMsg("Cannot close, will cleanup cfg, ctrl+c to exit\n");
10147             while (1);
10148         }
10149     } else if (strcmp(argv[1], "-ePNOClear") == 0) {
10150         testPNO(true, false);
10151         setBlacklist(true);
10152     } else if (strcmp(argv[1], "-country") == 0) {
10153         char *country_code = nullptr;
10154         if (argc > 2) {
10155             country_code = argv[2];
10156         } else {
10157             printMsg("Country code not provided\n");
10158             goto cleanup;
10159         }
10160         hal_fn.wifi_set_country_code(wlan0Handle, country_code);
10161     } else if ((strcmp(argv[1], "-logger") == 0)) {
10162         readLoggerOptions(argc, ++argv);
10163         runLogger();
10164     } else if (strcmp(argv[1], "-help") == 0) {
10165         printUsage();
10166     } else if ((strcmp(argv[1], "-blacklist_bssids") == 0) ||
10167         (strcmp(argv[1], "-whitelist_ssids") == 0)) {
10168         readTestOptions(argc, argv);
10169         if (set_roaming_configuration) {
10170             setRoamingConfiguration();
10171             set_roaming_configuration = false;
10172         } else {
10173             setBlacklist(((num_blacklist_bssids == -1) ? true: false));
10174         }
10175     } else if ((strcmp(argv[1], "-get_roaming_capabilities") == 0)) {
10176         getRoamingCapabilities(argv);
10177     } else if ((strcmp(argv[1], "-set_fw_roaming_state") == 0)) {
10178         fw_roaming_state_t roamState = (fw_roaming_state_t)(atoi)(argv[2]);
10179         setFWRoamingState(roamState);
10180     } else if (strcmp(argv[1], "-rssi_monitor") == 0) {
10181         readTestOptions(argc, argv);
10182         testRssiMonitor();
10183     } else if (strcmp(argv[1], "-mkeep_alive") == 0) {
10184         readKeepAliveOptions(argc, ++argv);
10185     } else if ((strcmp(argv[1], "-nd_offload") == 0) && (argc > 2)) {
10186         u8 enable = (u8)(atoi)(argv[2]);
10187         hal_fn.wifi_configure_nd_offload(wlan0Handle, enable);
10188     } else if ((strcmp(argv[1], "-apf") == 0)) {
10189         testApfOptions(argc, ++argv);
10190     } else if ((strcmp(argv[1], "-sar") == 0)) {
10191         testSarOptions(argc-1, ++argv);
10192     } else if ((strcmp(argv[1], "-latency") == 0)) {
10193         testLatencyModeOptions(argc-1, ++argv);
10194     } else if ((strcmp(argv[1], "-thermal") == 0)) {
10195         testThermalMitigationOptions(argc-1, ++argv);
10196     } else if ((strcmp(argv[1], "-dscp") == 0)) {
10197         testDscpOptions(argc, ++argv);
10198     } else if ((strcmp(argv[1], "-ch_avoid") == 0)) {
10199         testChannelAvoidanceOptions(argc, ++argv);
10200     } else if ((strcmp(argv[1], "-usable_ch") == 0)) {
10201         testUsableChannelOptions(argc, ++argv);
10202     } else if ((strcmp(argv[1], "-ifadd") == 0)) {
10203         if (argc < 3) {
10204             printMsg("\n Mandatory fields are not present\n");
10205             printMsg(" [-ifadd] [-name <virtual iface name should be wlanX, swlanX, awareX, p2pX>"
10206                 " -type 0/1/2/3]\n");
10207             printMsg(" 0 for STA, 1 for AP, 2 for P2P, 3 for NAN\n");
10208             goto cleanup;
10209         }
10210         VirtualIfaceAdd(argv);
10211     } else if ((strcmp(argv[1], "-ifdel") == 0)) {
10212         if(argc < 3) {
10213             printMsg("\n Mandatory fields are not present\n");
10214             printMsg("[-ifdel] [-name <virtual iface name>]\n");
10215             goto cleanup;
10216         }
10217         VirtualIfaceDelete(argv);
10218     } else if ((strcmp(argv[1], "-latency_mode") == 0) && (argc > 2)) {
10219         SetLatencyMode(argv);
10220     } else if ((strcmp(argv[1], "-multista_pri_connection") == 0)) {
10221         if(argc < 3) {
10222             printMsg("\n Mandatory fields are not present\n");
10223             printMsg("[-multista_pri_connection] [iface name>]\n");
10224             goto cleanup;
10225         }
10226         MultiStaSetPrimaryConnection(argv);
10227     } else if ((strcmp(argv[1], "-multista_usecase") == 0)) {
10228         if(argc < 3) {
10229             printMsg("\n Mandatory fields are not present\n");
10230             printMsg("[-multista_usecase] [multista usecase 0/1]\n");
10231             goto cleanup;
10232         }
10233         MultiStaSetUsecase(argv);
10234     } else if ((strcmp(argv[1], "-voip_mode") == 0) && (argc > 2)) {
10235         SetVoipMode(argv);
10236     } else if (strcmp(argv[1], "-twt") == 0) {
10237         if ((strcmp(argv[2], "-setup") == 0)) {
10238             setupTwtRequest(argv);
10239         } else if ((strcmp(argv[2], "-teardown") == 0)) {
10240             TeardownTwt(argv);
10241         } else if ((strcmp(argv[2], "-info_frame") == 0)) {
10242             InfoFrameTwt(argv);
10243         } else if ((strcmp(argv[2], "-get_stats") == 0)) {
10244             GetTwtStats(argv);
10245         } else if ((strcmp(argv[2], "-clear_stats") == 0)) {
10246             ClearTwtStats(argv);
10247         } else if ((strcmp(argv[2], "-event_chk") == 0)) {
10248             twtEventCheck();
10249         } else {
10250             printMsg("\n Unknown command\n");
10251             printTwtUsage();
10252             return WIFI_SUCCESS;
10253         }
10254     } else if (strcmp(argv[1], "-get_capa_twt") == 0) {
10255         getTWTCapability(argv);
10256     } else if ((strcmp(argv[1], "-dtim_multiplier") == 0) && (argc > 2)) {
10257         int dtim_multiplier = (atoi)(argv[2]);
10258         hal_fn.wifi_set_dtim_config(wlan0Handle, dtim_multiplier);
10259     } else if (strcmp(argv[1], "-on_ssr") == 0) {
10260         hal_fn.wifi_trigger_subsystem_restart(halHandle);
10261     } else if ((strcmp(argv[1], "-getSupportedRadioMatrix") == 0)) {
10262         getSupportedRadioMatrix();
10263     } else if ((strcmp(argv[1], "-tx_pwr_cap") == 0)) {
10264         testTxPowerLimitOptions(argc, ++argv);
10265     } else if (strcmp(argv[1], "-chre_nan_rtt") == 0) {
10266         if ((strcmp(argv[2], "-enable") == 0)) {
10267             //enable CHRE NAN RTT
10268             enableChreNanRtt();
10269         } else if ((strcmp(argv[2], "-disable") == 0)) {
10270             //disable CHRE NAN RTT
10271             disableChreNanRtt();
10272         } else {
10273             printMsg("\n Unknown command\n");
10274             printChreNanRttUsage();
10275         }
10276     } else if (strcmp(argv[1], "-chre") == 0) {
10277         if ((strcmp(argv[2], "-register") == 0)) {
10278             //register CHRE callback
10279             registerChreCallback();
10280         } else {
10281             printMsg("\n Unknown command\n");
10282             printChreNanRttUsage();
10283         }
10284     } else if (strcmp(argv[1], "-get_cached_scan_results") == 0) {
10285         getWifiCachedScanResults();
10286     } else if (strcmp(argv[1], "-set_channel_mask") == 0) {
10287         u32 channel_mask = 0;
10288         if (argc > 2) {
10289             channel_mask = (u32)atoi(argv[2]);
10290         }
10291         hal_fn.wifi_enable_sta_channel_for_peer_network(halHandle, channel_mask);
10292     } else {
10293         printUsage();
10294     }
10295 
10296 cleanup:
10297     cleanup();
10298     return WIFI_SUCCESS;
10299 }
10300