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