e055bebe18387dd108aa4c5faa3901eadba2be8d
[mech_eap.git] / src / drivers / driver_nl80211.c
1 /*
2  * Driver interaction with Linux nl80211/cfg80211
3  * Copyright (c) 2002-2014, Jouni Malinen <j@w1.fi>
4  * Copyright (c) 2003-2004, Instant802 Networks, Inc.
5  * Copyright (c) 2005-2006, Devicescape Software, Inc.
6  * Copyright (c) 2007, Johannes Berg <johannes@sipsolutions.net>
7  * Copyright (c) 2009-2010, Atheros Communications
8  *
9  * This software may be distributed under the terms of the BSD license.
10  * See README for more details.
11  */
12
13 #include "includes.h"
14 #include <sys/ioctl.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <fcntl.h>
18 #include <net/if.h>
19 #include <netlink/genl/genl.h>
20 #include <netlink/genl/family.h>
21 #include <netlink/genl/ctrl.h>
22 #ifdef CONFIG_LIBNL3_ROUTE
23 #include <netlink/route/neighbour.h>
24 #endif /* CONFIG_LIBNL3_ROUTE */
25 #include <linux/rtnetlink.h>
26 #include <netpacket/packet.h>
27 #include <linux/filter.h>
28 #include <linux/errqueue.h>
29 #include "nl80211_copy.h"
30
31 #include "common.h"
32 #include "eloop.h"
33 #include "utils/list.h"
34 #include "common/qca-vendor.h"
35 #include "common/qca-vendor-attr.h"
36 #include "common/ieee802_11_defs.h"
37 #include "common/ieee802_11_common.h"
38 #include "l2_packet/l2_packet.h"
39 #include "netlink.h"
40 #include "linux_ioctl.h"
41 #include "radiotap.h"
42 #include "radiotap_iter.h"
43 #include "rfkill.h"
44 #include "driver.h"
45
46 #ifndef SO_WIFI_STATUS
47 # if defined(__sparc__)
48 #  define SO_WIFI_STATUS        0x0025
49 # elif defined(__parisc__)
50 #  define SO_WIFI_STATUS        0x4022
51 # else
52 #  define SO_WIFI_STATUS        41
53 # endif
54
55 # define SCM_WIFI_STATUS        SO_WIFI_STATUS
56 #endif
57
58 #ifndef SO_EE_ORIGIN_TXSTATUS
59 #define SO_EE_ORIGIN_TXSTATUS   4
60 #endif
61
62 #ifndef PACKET_TX_TIMESTAMP
63 #define PACKET_TX_TIMESTAMP     16
64 #endif
65
66 #ifdef ANDROID
67 #include "android_drv.h"
68 #endif /* ANDROID */
69 #ifdef CONFIG_LIBNL20
70 /* libnl 2.0 compatibility code */
71 #define nl_handle nl_sock
72 #define nl80211_handle_alloc nl_socket_alloc_cb
73 #define nl80211_handle_destroy nl_socket_free
74 #else
75 /*
76  * libnl 1.1 has a bug, it tries to allocate socket numbers densely
77  * but when you free a socket again it will mess up its bitmap and
78  * and use the wrong number the next time it needs a socket ID.
79  * Therefore, we wrap the handle alloc/destroy and add our own pid
80  * accounting.
81  */
82 static uint32_t port_bitmap[32] = { 0 };
83
84 static struct nl_handle *nl80211_handle_alloc(void *cb)
85 {
86         struct nl_handle *handle;
87         uint32_t pid = getpid() & 0x3FFFFF;
88         int i;
89
90         handle = nl_handle_alloc_cb(cb);
91
92         for (i = 0; i < 1024; i++) {
93                 if (port_bitmap[i / 32] & (1 << (i % 32)))
94                         continue;
95                 port_bitmap[i / 32] |= 1 << (i % 32);
96                 pid += i << 22;
97                 break;
98         }
99
100         nl_socket_set_local_port(handle, pid);
101
102         return handle;
103 }
104
105 static void nl80211_handle_destroy(struct nl_handle *handle)
106 {
107         uint32_t port = nl_socket_get_local_port(handle);
108
109         port >>= 22;
110         port_bitmap[port / 32] &= ~(1 << (port % 32));
111
112         nl_handle_destroy(handle);
113 }
114 #endif /* CONFIG_LIBNL20 */
115
116
117 #ifdef ANDROID
118 /* system/core/libnl_2 does not include nl_socket_set_nonblocking() */
119 static int android_nl_socket_set_nonblocking(struct nl_handle *handle)
120 {
121         return fcntl(nl_socket_get_fd(handle), F_SETFL, O_NONBLOCK);
122 }
123 #undef nl_socket_set_nonblocking
124 #define nl_socket_set_nonblocking(h) android_nl_socket_set_nonblocking(h)
125 #endif /* ANDROID */
126
127
128 static struct nl_handle * nl_create_handle(struct nl_cb *cb, const char *dbg)
129 {
130         struct nl_handle *handle;
131
132         handle = nl80211_handle_alloc(cb);
133         if (handle == NULL) {
134                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
135                            "callbacks (%s)", dbg);
136                 return NULL;
137         }
138
139         if (genl_connect(handle)) {
140                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
141                            "netlink (%s)", dbg);
142                 nl80211_handle_destroy(handle);
143                 return NULL;
144         }
145
146         return handle;
147 }
148
149
150 static void nl_destroy_handles(struct nl_handle **handle)
151 {
152         if (*handle == NULL)
153                 return;
154         nl80211_handle_destroy(*handle);
155         *handle = NULL;
156 }
157
158
159 #if __WORDSIZE == 64
160 #define ELOOP_SOCKET_INVALID    (intptr_t) 0x8888888888888889ULL
161 #else
162 #define ELOOP_SOCKET_INVALID    (intptr_t) 0x88888889ULL
163 #endif
164
165 static void nl80211_register_eloop_read(struct nl_handle **handle,
166                                         eloop_sock_handler handler,
167                                         void *eloop_data)
168 {
169         nl_socket_set_nonblocking(*handle);
170         eloop_register_read_sock(nl_socket_get_fd(*handle), handler,
171                                  eloop_data, *handle);
172         *handle = (void *) (((intptr_t) *handle) ^ ELOOP_SOCKET_INVALID);
173 }
174
175
176 static void nl80211_destroy_eloop_handle(struct nl_handle **handle)
177 {
178         *handle = (void *) (((intptr_t) *handle) ^ ELOOP_SOCKET_INVALID);
179         eloop_unregister_read_sock(nl_socket_get_fd(*handle));
180         nl_destroy_handles(handle);
181 }
182
183
184 #ifndef IFF_LOWER_UP
185 #define IFF_LOWER_UP   0x10000         /* driver signals L1 up         */
186 #endif
187 #ifndef IFF_DORMANT
188 #define IFF_DORMANT    0x20000         /* driver signals dormant       */
189 #endif
190
191 #ifndef IF_OPER_DORMANT
192 #define IF_OPER_DORMANT 5
193 #endif
194 #ifndef IF_OPER_UP
195 #define IF_OPER_UP 6
196 #endif
197
198 struct nl80211_global {
199         struct dl_list interfaces;
200         int if_add_ifindex;
201         u64 if_add_wdevid;
202         int if_add_wdevid_set;
203         struct netlink_data *netlink;
204         struct nl_cb *nl_cb;
205         struct nl_handle *nl;
206         int nl80211_id;
207         int ioctl_sock; /* socket for ioctl() use */
208
209         struct nl_handle *nl_event;
210 };
211
212 struct nl80211_wiphy_data {
213         struct dl_list list;
214         struct dl_list bsss;
215         struct dl_list drvs;
216
217         struct nl_handle *nl_beacons;
218         struct nl_cb *nl_cb;
219
220         int wiphy_idx;
221 };
222
223 static void nl80211_global_deinit(void *priv);
224
225 struct i802_bss {
226         struct wpa_driver_nl80211_data *drv;
227         struct i802_bss *next;
228         int ifindex;
229         u64 wdev_id;
230         char ifname[IFNAMSIZ + 1];
231         char brname[IFNAMSIZ];
232         unsigned int beacon_set:1;
233         unsigned int added_if_into_bridge:1;
234         unsigned int added_bridge:1;
235         unsigned int in_deinit:1;
236         unsigned int wdev_id_set:1;
237         unsigned int added_if:1;
238         unsigned int static_ap:1;
239
240         u8 addr[ETH_ALEN];
241
242         int freq;
243         int bandwidth;
244         int if_dynamic;
245
246         void *ctx;
247         struct nl_handle *nl_preq, *nl_mgmt;
248         struct nl_cb *nl_cb;
249
250         struct nl80211_wiphy_data *wiphy_data;
251         struct dl_list wiphy_list;
252 };
253
254 struct wpa_driver_nl80211_data {
255         struct nl80211_global *global;
256         struct dl_list list;
257         struct dl_list wiphy_list;
258         char phyname[32];
259         u8 perm_addr[ETH_ALEN];
260         void *ctx;
261         int ifindex;
262         int if_removed;
263         int if_disabled;
264         int ignore_if_down_event;
265         struct rfkill_data *rfkill;
266         struct wpa_driver_capa capa;
267         u8 *extended_capa, *extended_capa_mask;
268         unsigned int extended_capa_len;
269         int has_capability;
270
271         int operstate;
272
273         int scan_complete_events;
274         enum scan_states {
275                 NO_SCAN, SCAN_REQUESTED, SCAN_STARTED, SCAN_COMPLETED,
276                 SCAN_ABORTED, SCHED_SCAN_STARTED, SCHED_SCAN_STOPPED,
277                 SCHED_SCAN_RESULTS
278         } scan_state;
279
280         struct nl_cb *nl_cb;
281
282         u8 auth_bssid[ETH_ALEN];
283         u8 auth_attempt_bssid[ETH_ALEN];
284         u8 bssid[ETH_ALEN];
285         u8 prev_bssid[ETH_ALEN];
286         int associated;
287         u8 ssid[32];
288         size_t ssid_len;
289         enum nl80211_iftype nlmode;
290         enum nl80211_iftype ap_scan_as_station;
291         unsigned int assoc_freq;
292
293         int monitor_sock;
294         int monitor_ifidx;
295         int monitor_refcount;
296
297         unsigned int disabled_11b_rates:1;
298         unsigned int pending_remain_on_chan:1;
299         unsigned int in_interface_list:1;
300         unsigned int device_ap_sme:1;
301         unsigned int poll_command_supported:1;
302         unsigned int data_tx_status:1;
303         unsigned int scan_for_auth:1;
304         unsigned int retry_auth:1;
305         unsigned int use_monitor:1;
306         unsigned int ignore_next_local_disconnect:1;
307         unsigned int ignore_next_local_deauth:1;
308         unsigned int allow_p2p_device:1;
309         unsigned int hostapd:1;
310         unsigned int start_mode_ap:1;
311         unsigned int start_iface_up:1;
312         unsigned int test_use_roc_tx:1;
313         unsigned int ignore_deauth_event:1;
314         unsigned int roaming_vendor_cmd_avail:1;
315         unsigned int dfs_vendor_cmd_avail:1;
316         unsigned int have_low_prio_scan:1;
317         unsigned int force_connect_cmd:1;
318         unsigned int addr_changed:1;
319
320         u64 remain_on_chan_cookie;
321         u64 send_action_cookie;
322
323         unsigned int last_mgmt_freq;
324
325         struct wpa_driver_scan_filter *filter_ssids;
326         size_t num_filter_ssids;
327
328         struct i802_bss *first_bss;
329
330         int eapol_tx_sock;
331
332         int eapol_sock; /* socket for EAPOL frames */
333
334         struct nl_handle *rtnl_sk; /* nl_sock for NETLINK_ROUTE */
335
336         int default_if_indices[16];
337         int *if_indices;
338         int num_if_indices;
339
340         /* From failed authentication command */
341         int auth_freq;
342         u8 auth_bssid_[ETH_ALEN];
343         u8 auth_ssid[32];
344         size_t auth_ssid_len;
345         int auth_alg;
346         u8 *auth_ie;
347         size_t auth_ie_len;
348         u8 auth_wep_key[4][16];
349         size_t auth_wep_key_len[4];
350         int auth_wep_tx_keyidx;
351         int auth_local_state_change;
352         int auth_p2p;
353 };
354
355
356 static void wpa_driver_nl80211_deinit(struct i802_bss *bss);
357 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx,
358                                             void *timeout_ctx);
359 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
360                                        enum nl80211_iftype nlmode);
361 static int wpa_driver_nl80211_set_mode_ibss(struct i802_bss *bss,
362                                             struct hostapd_freq_params *freq);
363
364 static int
365 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv,
366                                    const u8 *set_addr, int first);
367 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
368                                    const u8 *addr, int cmd, u16 reason_code,
369                                    int local_state_change);
370 static void nl80211_remove_monitor_interface(
371         struct wpa_driver_nl80211_data *drv);
372 static int nl80211_send_frame_cmd(struct i802_bss *bss,
373                                   unsigned int freq, unsigned int wait,
374                                   const u8 *buf, size_t buf_len, u64 *cookie,
375                                   int no_cck, int no_ack, int offchanok);
376 static int nl80211_register_frame(struct i802_bss *bss,
377                                   struct nl_handle *hl_handle,
378                                   u16 type, const u8 *match, size_t match_len);
379 static int wpa_driver_nl80211_probe_req_report(struct i802_bss *bss,
380                                                int report);
381 #ifdef ANDROID
382 static int android_pno_start(struct i802_bss *bss,
383                              struct wpa_driver_scan_params *params);
384 static int android_pno_stop(struct i802_bss *bss);
385 extern int wpa_driver_nl80211_driver_cmd(void *priv, char *cmd, char *buf,
386                                          size_t buf_len);
387 #endif /* ANDROID */
388 #ifdef ANDROID_P2P
389 #ifdef ANDROID_P2P_STUB
390 int wpa_driver_set_p2p_noa(void *priv, u8 count, int start, int duration) {
391         return 0;
392 }
393 int wpa_driver_get_p2p_noa(void *priv, u8 *buf, size_t len) {
394         return 0;
395 }
396 int wpa_driver_set_p2p_ps(void *priv, int legacy_ps, int opp_ps, int ctwindow) {
397         return -1;
398 }
399 int wpa_driver_set_ap_wps_p2p_ie(void *priv, const struct wpabuf *beacon,
400                                  const struct wpabuf *proberesp,
401                                  const struct wpabuf *assocresp) {
402         return 0;
403 }
404 #else /* ANDROID_P2P_STUB */
405 int wpa_driver_set_p2p_noa(void *priv, u8 count, int start, int duration);
406 int wpa_driver_get_p2p_noa(void *priv, u8 *buf, size_t len);
407 int wpa_driver_set_p2p_ps(void *priv, int legacy_ps, int opp_ps, int ctwindow);
408 int wpa_driver_set_ap_wps_p2p_ie(void *priv, const struct wpabuf *beacon,
409                                  const struct wpabuf *proberesp,
410                                  const struct wpabuf *assocresp);
411 #endif /* ANDROID_P2P_STUB */
412 #endif /* ANDROID_P2P */
413
414 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
415 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
416 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
417 static int wpa_driver_nl80211_if_remove(struct i802_bss *bss,
418                                         enum wpa_driver_if_type type,
419                                         const char *ifname);
420
421 static int nl80211_set_channel(struct i802_bss *bss,
422                                struct hostapd_freq_params *freq, int set_chan);
423 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
424                                      int ifindex, int disabled);
425
426 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv);
427 static int wpa_driver_nl80211_authenticate_retry(
428         struct wpa_driver_nl80211_data *drv);
429
430 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq);
431 static int i802_set_iface_flags(struct i802_bss *bss, int up);
432
433
434 static const char * nl80211_command_to_string(enum nl80211_commands cmd)
435 {
436 #define C2S(x) case x: return #x;
437         switch (cmd) {
438         C2S(NL80211_CMD_UNSPEC)
439         C2S(NL80211_CMD_GET_WIPHY)
440         C2S(NL80211_CMD_SET_WIPHY)
441         C2S(NL80211_CMD_NEW_WIPHY)
442         C2S(NL80211_CMD_DEL_WIPHY)
443         C2S(NL80211_CMD_GET_INTERFACE)
444         C2S(NL80211_CMD_SET_INTERFACE)
445         C2S(NL80211_CMD_NEW_INTERFACE)
446         C2S(NL80211_CMD_DEL_INTERFACE)
447         C2S(NL80211_CMD_GET_KEY)
448         C2S(NL80211_CMD_SET_KEY)
449         C2S(NL80211_CMD_NEW_KEY)
450         C2S(NL80211_CMD_DEL_KEY)
451         C2S(NL80211_CMD_GET_BEACON)
452         C2S(NL80211_CMD_SET_BEACON)
453         C2S(NL80211_CMD_START_AP)
454         C2S(NL80211_CMD_STOP_AP)
455         C2S(NL80211_CMD_GET_STATION)
456         C2S(NL80211_CMD_SET_STATION)
457         C2S(NL80211_CMD_NEW_STATION)
458         C2S(NL80211_CMD_DEL_STATION)
459         C2S(NL80211_CMD_GET_MPATH)
460         C2S(NL80211_CMD_SET_MPATH)
461         C2S(NL80211_CMD_NEW_MPATH)
462         C2S(NL80211_CMD_DEL_MPATH)
463         C2S(NL80211_CMD_SET_BSS)
464         C2S(NL80211_CMD_SET_REG)
465         C2S(NL80211_CMD_REQ_SET_REG)
466         C2S(NL80211_CMD_GET_MESH_CONFIG)
467         C2S(NL80211_CMD_SET_MESH_CONFIG)
468         C2S(NL80211_CMD_SET_MGMT_EXTRA_IE)
469         C2S(NL80211_CMD_GET_REG)
470         C2S(NL80211_CMD_GET_SCAN)
471         C2S(NL80211_CMD_TRIGGER_SCAN)
472         C2S(NL80211_CMD_NEW_SCAN_RESULTS)
473         C2S(NL80211_CMD_SCAN_ABORTED)
474         C2S(NL80211_CMD_REG_CHANGE)
475         C2S(NL80211_CMD_AUTHENTICATE)
476         C2S(NL80211_CMD_ASSOCIATE)
477         C2S(NL80211_CMD_DEAUTHENTICATE)
478         C2S(NL80211_CMD_DISASSOCIATE)
479         C2S(NL80211_CMD_MICHAEL_MIC_FAILURE)
480         C2S(NL80211_CMD_REG_BEACON_HINT)
481         C2S(NL80211_CMD_JOIN_IBSS)
482         C2S(NL80211_CMD_LEAVE_IBSS)
483         C2S(NL80211_CMD_TESTMODE)
484         C2S(NL80211_CMD_CONNECT)
485         C2S(NL80211_CMD_ROAM)
486         C2S(NL80211_CMD_DISCONNECT)
487         C2S(NL80211_CMD_SET_WIPHY_NETNS)
488         C2S(NL80211_CMD_GET_SURVEY)
489         C2S(NL80211_CMD_NEW_SURVEY_RESULTS)
490         C2S(NL80211_CMD_SET_PMKSA)
491         C2S(NL80211_CMD_DEL_PMKSA)
492         C2S(NL80211_CMD_FLUSH_PMKSA)
493         C2S(NL80211_CMD_REMAIN_ON_CHANNEL)
494         C2S(NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL)
495         C2S(NL80211_CMD_SET_TX_BITRATE_MASK)
496         C2S(NL80211_CMD_REGISTER_FRAME)
497         C2S(NL80211_CMD_FRAME)
498         C2S(NL80211_CMD_FRAME_TX_STATUS)
499         C2S(NL80211_CMD_SET_POWER_SAVE)
500         C2S(NL80211_CMD_GET_POWER_SAVE)
501         C2S(NL80211_CMD_SET_CQM)
502         C2S(NL80211_CMD_NOTIFY_CQM)
503         C2S(NL80211_CMD_SET_CHANNEL)
504         C2S(NL80211_CMD_SET_WDS_PEER)
505         C2S(NL80211_CMD_FRAME_WAIT_CANCEL)
506         C2S(NL80211_CMD_JOIN_MESH)
507         C2S(NL80211_CMD_LEAVE_MESH)
508         C2S(NL80211_CMD_UNPROT_DEAUTHENTICATE)
509         C2S(NL80211_CMD_UNPROT_DISASSOCIATE)
510         C2S(NL80211_CMD_NEW_PEER_CANDIDATE)
511         C2S(NL80211_CMD_GET_WOWLAN)
512         C2S(NL80211_CMD_SET_WOWLAN)
513         C2S(NL80211_CMD_START_SCHED_SCAN)
514         C2S(NL80211_CMD_STOP_SCHED_SCAN)
515         C2S(NL80211_CMD_SCHED_SCAN_RESULTS)
516         C2S(NL80211_CMD_SCHED_SCAN_STOPPED)
517         C2S(NL80211_CMD_SET_REKEY_OFFLOAD)
518         C2S(NL80211_CMD_PMKSA_CANDIDATE)
519         C2S(NL80211_CMD_TDLS_OPER)
520         C2S(NL80211_CMD_TDLS_MGMT)
521         C2S(NL80211_CMD_UNEXPECTED_FRAME)
522         C2S(NL80211_CMD_PROBE_CLIENT)
523         C2S(NL80211_CMD_REGISTER_BEACONS)
524         C2S(NL80211_CMD_UNEXPECTED_4ADDR_FRAME)
525         C2S(NL80211_CMD_SET_NOACK_MAP)
526         C2S(NL80211_CMD_CH_SWITCH_NOTIFY)
527         C2S(NL80211_CMD_START_P2P_DEVICE)
528         C2S(NL80211_CMD_STOP_P2P_DEVICE)
529         C2S(NL80211_CMD_CONN_FAILED)
530         C2S(NL80211_CMD_SET_MCAST_RATE)
531         C2S(NL80211_CMD_SET_MAC_ACL)
532         C2S(NL80211_CMD_RADAR_DETECT)
533         C2S(NL80211_CMD_GET_PROTOCOL_FEATURES)
534         C2S(NL80211_CMD_UPDATE_FT_IES)
535         C2S(NL80211_CMD_FT_EVENT)
536         C2S(NL80211_CMD_CRIT_PROTOCOL_START)
537         C2S(NL80211_CMD_CRIT_PROTOCOL_STOP)
538         C2S(NL80211_CMD_GET_COALESCE)
539         C2S(NL80211_CMD_SET_COALESCE)
540         C2S(NL80211_CMD_CHANNEL_SWITCH)
541         C2S(NL80211_CMD_VENDOR)
542         C2S(NL80211_CMD_SET_QOS_MAP)
543         default:
544                 return "NL80211_CMD_UNKNOWN";
545         }
546 #undef C2S
547 }
548
549
550 /* Converts nl80211_chan_width to a common format */
551 static enum chan_width convert2width(int width)
552 {
553         switch (width) {
554         case NL80211_CHAN_WIDTH_20_NOHT:
555                 return CHAN_WIDTH_20_NOHT;
556         case NL80211_CHAN_WIDTH_20:
557                 return CHAN_WIDTH_20;
558         case NL80211_CHAN_WIDTH_40:
559                 return CHAN_WIDTH_40;
560         case NL80211_CHAN_WIDTH_80:
561                 return CHAN_WIDTH_80;
562         case NL80211_CHAN_WIDTH_80P80:
563                 return CHAN_WIDTH_80P80;
564         case NL80211_CHAN_WIDTH_160:
565                 return CHAN_WIDTH_160;
566         }
567         return CHAN_WIDTH_UNKNOWN;
568 }
569
570
571 static int is_ap_interface(enum nl80211_iftype nlmode)
572 {
573         return nlmode == NL80211_IFTYPE_AP ||
574                 nlmode == NL80211_IFTYPE_P2P_GO;
575 }
576
577
578 static int is_sta_interface(enum nl80211_iftype nlmode)
579 {
580         return nlmode == NL80211_IFTYPE_STATION ||
581                 nlmode == NL80211_IFTYPE_P2P_CLIENT;
582 }
583
584
585 static int is_p2p_net_interface(enum nl80211_iftype nlmode)
586 {
587         return nlmode == NL80211_IFTYPE_P2P_CLIENT ||
588                 nlmode == NL80211_IFTYPE_P2P_GO;
589 }
590
591
592 static struct i802_bss * get_bss_ifindex(struct wpa_driver_nl80211_data *drv,
593                                          int ifindex)
594 {
595         struct i802_bss *bss;
596
597         for (bss = drv->first_bss; bss; bss = bss->next) {
598                 if (bss->ifindex == ifindex)
599                         return bss;
600         }
601
602         return NULL;
603 }
604
605
606 static void nl80211_mark_disconnected(struct wpa_driver_nl80211_data *drv)
607 {
608         if (drv->associated)
609                 os_memcpy(drv->prev_bssid, drv->bssid, ETH_ALEN);
610         drv->associated = 0;
611         os_memset(drv->bssid, 0, ETH_ALEN);
612 }
613
614
615 struct nl80211_bss_info_arg {
616         struct wpa_driver_nl80211_data *drv;
617         struct wpa_scan_results *res;
618         unsigned int assoc_freq;
619         unsigned int ibss_freq;
620         u8 assoc_bssid[ETH_ALEN];
621 };
622
623 static int bss_info_handler(struct nl_msg *msg, void *arg);
624
625
626 /* nl80211 code */
627 static int ack_handler(struct nl_msg *msg, void *arg)
628 {
629         int *err = arg;
630         *err = 0;
631         return NL_STOP;
632 }
633
634 static int finish_handler(struct nl_msg *msg, void *arg)
635 {
636         int *ret = arg;
637         *ret = 0;
638         return NL_SKIP;
639 }
640
641 static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err,
642                          void *arg)
643 {
644         int *ret = arg;
645         *ret = err->error;
646         return NL_SKIP;
647 }
648
649
650 static int no_seq_check(struct nl_msg *msg, void *arg)
651 {
652         return NL_OK;
653 }
654
655
656 static int send_and_recv(struct nl80211_global *global,
657                          struct nl_handle *nl_handle, struct nl_msg *msg,
658                          int (*valid_handler)(struct nl_msg *, void *),
659                          void *valid_data)
660 {
661         struct nl_cb *cb;
662         int err = -ENOMEM;
663
664         cb = nl_cb_clone(global->nl_cb);
665         if (!cb)
666                 goto out;
667
668         err = nl_send_auto_complete(nl_handle, msg);
669         if (err < 0)
670                 goto out;
671
672         err = 1;
673
674         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
675         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
676         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
677
678         if (valid_handler)
679                 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM,
680                           valid_handler, valid_data);
681
682         while (err > 0) {
683                 int res = nl_recvmsgs(nl_handle, cb);
684                 if (res < 0) {
685                         wpa_printf(MSG_INFO,
686                                    "nl80211: %s->nl_recvmsgs failed: %d",
687                                    __func__, res);
688                 }
689         }
690  out:
691         nl_cb_put(cb);
692         nlmsg_free(msg);
693         return err;
694 }
695
696
697 static int send_and_recv_msgs_global(struct nl80211_global *global,
698                                      struct nl_msg *msg,
699                                      int (*valid_handler)(struct nl_msg *, void *),
700                                      void *valid_data)
701 {
702         return send_and_recv(global, global->nl, msg, valid_handler,
703                              valid_data);
704 }
705
706
707 static int send_and_recv_msgs(struct wpa_driver_nl80211_data *drv,
708                               struct nl_msg *msg,
709                               int (*valid_handler)(struct nl_msg *, void *),
710                               void *valid_data)
711 {
712         return send_and_recv(drv->global, drv->global->nl, msg,
713                              valid_handler, valid_data);
714 }
715
716
717 struct family_data {
718         const char *group;
719         int id;
720 };
721
722
723 static int nl80211_set_iface_id(struct nl_msg *msg, struct i802_bss *bss)
724 {
725         if (bss->wdev_id_set)
726                 NLA_PUT_U64(msg, NL80211_ATTR_WDEV, bss->wdev_id);
727         else
728                 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
729         return 0;
730
731 nla_put_failure:
732         return -1;
733 }
734
735
736 static int family_handler(struct nl_msg *msg, void *arg)
737 {
738         struct family_data *res = arg;
739         struct nlattr *tb[CTRL_ATTR_MAX + 1];
740         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
741         struct nlattr *mcgrp;
742         int i;
743
744         nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
745                   genlmsg_attrlen(gnlh, 0), NULL);
746         if (!tb[CTRL_ATTR_MCAST_GROUPS])
747                 return NL_SKIP;
748
749         nla_for_each_nested(mcgrp, tb[CTRL_ATTR_MCAST_GROUPS], i) {
750                 struct nlattr *tb2[CTRL_ATTR_MCAST_GRP_MAX + 1];
751                 nla_parse(tb2, CTRL_ATTR_MCAST_GRP_MAX, nla_data(mcgrp),
752                           nla_len(mcgrp), NULL);
753                 if (!tb2[CTRL_ATTR_MCAST_GRP_NAME] ||
754                     !tb2[CTRL_ATTR_MCAST_GRP_ID] ||
755                     os_strncmp(nla_data(tb2[CTRL_ATTR_MCAST_GRP_NAME]),
756                                res->group,
757                                nla_len(tb2[CTRL_ATTR_MCAST_GRP_NAME])) != 0)
758                         continue;
759                 res->id = nla_get_u32(tb2[CTRL_ATTR_MCAST_GRP_ID]);
760                 break;
761         };
762
763         return NL_SKIP;
764 }
765
766
767 static int nl_get_multicast_id(struct nl80211_global *global,
768                                const char *family, const char *group)
769 {
770         struct nl_msg *msg;
771         int ret = -1;
772         struct family_data res = { group, -ENOENT };
773
774         msg = nlmsg_alloc();
775         if (!msg)
776                 return -ENOMEM;
777         genlmsg_put(msg, 0, 0, genl_ctrl_resolve(global->nl, "nlctrl"),
778                     0, 0, CTRL_CMD_GETFAMILY, 0);
779         NLA_PUT_STRING(msg, CTRL_ATTR_FAMILY_NAME, family);
780
781         ret = send_and_recv_msgs_global(global, msg, family_handler, &res);
782         msg = NULL;
783         if (ret == 0)
784                 ret = res.id;
785
786 nla_put_failure:
787         nlmsg_free(msg);
788         return ret;
789 }
790
791
792 static void * nl80211_cmd(struct wpa_driver_nl80211_data *drv,
793                           struct nl_msg *msg, int flags, uint8_t cmd)
794 {
795         return genlmsg_put(msg, 0, 0, drv->global->nl80211_id,
796                            0, flags, cmd, 0);
797 }
798
799
800 struct wiphy_idx_data {
801         int wiphy_idx;
802         enum nl80211_iftype nlmode;
803         u8 *macaddr;
804 };
805
806
807 static int netdev_info_handler(struct nl_msg *msg, void *arg)
808 {
809         struct nlattr *tb[NL80211_ATTR_MAX + 1];
810         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
811         struct wiphy_idx_data *info = arg;
812
813         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
814                   genlmsg_attrlen(gnlh, 0), NULL);
815
816         if (tb[NL80211_ATTR_WIPHY])
817                 info->wiphy_idx = nla_get_u32(tb[NL80211_ATTR_WIPHY]);
818
819         if (tb[NL80211_ATTR_IFTYPE])
820                 info->nlmode = nla_get_u32(tb[NL80211_ATTR_IFTYPE]);
821
822         if (tb[NL80211_ATTR_MAC] && info->macaddr)
823                 os_memcpy(info->macaddr, nla_data(tb[NL80211_ATTR_MAC]),
824                           ETH_ALEN);
825
826         return NL_SKIP;
827 }
828
829
830 static int nl80211_get_wiphy_index(struct i802_bss *bss)
831 {
832         struct nl_msg *msg;
833         struct wiphy_idx_data data = {
834                 .wiphy_idx = -1,
835                 .macaddr = NULL,
836         };
837
838         msg = nlmsg_alloc();
839         if (!msg)
840                 return NL80211_IFTYPE_UNSPECIFIED;
841
842         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_GET_INTERFACE);
843
844         if (nl80211_set_iface_id(msg, bss) < 0)
845                 goto nla_put_failure;
846
847         if (send_and_recv_msgs(bss->drv, msg, netdev_info_handler, &data) == 0)
848                 return data.wiphy_idx;
849         msg = NULL;
850 nla_put_failure:
851         nlmsg_free(msg);
852         return -1;
853 }
854
855
856 static enum nl80211_iftype nl80211_get_ifmode(struct i802_bss *bss)
857 {
858         struct nl_msg *msg;
859         struct wiphy_idx_data data = {
860                 .nlmode = NL80211_IFTYPE_UNSPECIFIED,
861                 .macaddr = NULL,
862         };
863
864         msg = nlmsg_alloc();
865         if (!msg)
866                 return -1;
867
868         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_GET_INTERFACE);
869
870         if (nl80211_set_iface_id(msg, bss) < 0)
871                 goto nla_put_failure;
872
873         if (send_and_recv_msgs(bss->drv, msg, netdev_info_handler, &data) == 0)
874                 return data.nlmode;
875         msg = NULL;
876 nla_put_failure:
877         nlmsg_free(msg);
878         return NL80211_IFTYPE_UNSPECIFIED;
879 }
880
881
882 static int nl80211_get_macaddr(struct i802_bss *bss)
883 {
884         struct nl_msg *msg;
885         struct wiphy_idx_data data = {
886                 .macaddr = bss->addr,
887         };
888
889         msg = nlmsg_alloc();
890         if (!msg)
891                 return NL80211_IFTYPE_UNSPECIFIED;
892
893         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_GET_INTERFACE);
894         if (nl80211_set_iface_id(msg, bss) < 0)
895                 goto nla_put_failure;
896
897         return send_and_recv_msgs(bss->drv, msg, netdev_info_handler, &data);
898
899 nla_put_failure:
900         nlmsg_free(msg);
901         return NL80211_IFTYPE_UNSPECIFIED;
902 }
903
904
905 static int nl80211_register_beacons(struct wpa_driver_nl80211_data *drv,
906                                     struct nl80211_wiphy_data *w)
907 {
908         struct nl_msg *msg;
909         int ret = -1;
910
911         msg = nlmsg_alloc();
912         if (!msg)
913                 return -1;
914
915         nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_BEACONS);
916
917         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, w->wiphy_idx);
918
919         ret = send_and_recv(drv->global, w->nl_beacons, msg, NULL, NULL);
920         msg = NULL;
921         if (ret) {
922                 wpa_printf(MSG_DEBUG, "nl80211: Register beacons command "
923                            "failed: ret=%d (%s)",
924                            ret, strerror(-ret));
925                 goto nla_put_failure;
926         }
927         ret = 0;
928 nla_put_failure:
929         nlmsg_free(msg);
930         return ret;
931 }
932
933
934 static void nl80211_recv_beacons(int sock, void *eloop_ctx, void *handle)
935 {
936         struct nl80211_wiphy_data *w = eloop_ctx;
937         int res;
938
939         wpa_printf(MSG_EXCESSIVE, "nl80211: Beacon event message available");
940
941         res = nl_recvmsgs(handle, w->nl_cb);
942         if (res < 0) {
943                 wpa_printf(MSG_INFO, "nl80211: %s->nl_recvmsgs failed: %d",
944                            __func__, res);
945         }
946 }
947
948
949 static int process_beacon_event(struct nl_msg *msg, void *arg)
950 {
951         struct nl80211_wiphy_data *w = arg;
952         struct wpa_driver_nl80211_data *drv;
953         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
954         struct nlattr *tb[NL80211_ATTR_MAX + 1];
955         union wpa_event_data event;
956
957         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
958                   genlmsg_attrlen(gnlh, 0), NULL);
959
960         if (gnlh->cmd != NL80211_CMD_FRAME) {
961                 wpa_printf(MSG_DEBUG, "nl80211: Unexpected beacon event? (%d)",
962                            gnlh->cmd);
963                 return NL_SKIP;
964         }
965
966         if (!tb[NL80211_ATTR_FRAME])
967                 return NL_SKIP;
968
969         dl_list_for_each(drv, &w->drvs, struct wpa_driver_nl80211_data,
970                          wiphy_list) {
971                 os_memset(&event, 0, sizeof(event));
972                 event.rx_mgmt.frame = nla_data(tb[NL80211_ATTR_FRAME]);
973                 event.rx_mgmt.frame_len = nla_len(tb[NL80211_ATTR_FRAME]);
974                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
975         }
976
977         return NL_SKIP;
978 }
979
980
981 static struct nl80211_wiphy_data *
982 nl80211_get_wiphy_data_ap(struct i802_bss *bss)
983 {
984         static DEFINE_DL_LIST(nl80211_wiphys);
985         struct nl80211_wiphy_data *w;
986         int wiphy_idx, found = 0;
987         struct i802_bss *tmp_bss;
988
989         if (bss->wiphy_data != NULL)
990                 return bss->wiphy_data;
991
992         wiphy_idx = nl80211_get_wiphy_index(bss);
993
994         dl_list_for_each(w, &nl80211_wiphys, struct nl80211_wiphy_data, list) {
995                 if (w->wiphy_idx == wiphy_idx)
996                         goto add;
997         }
998
999         /* alloc new one */
1000         w = os_zalloc(sizeof(*w));
1001         if (w == NULL)
1002                 return NULL;
1003         w->wiphy_idx = wiphy_idx;
1004         dl_list_init(&w->bsss);
1005         dl_list_init(&w->drvs);
1006
1007         w->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
1008         if (!w->nl_cb) {
1009                 os_free(w);
1010                 return NULL;
1011         }
1012         nl_cb_set(w->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, no_seq_check, NULL);
1013         nl_cb_set(w->nl_cb, NL_CB_VALID, NL_CB_CUSTOM, process_beacon_event,
1014                   w);
1015
1016         w->nl_beacons = nl_create_handle(bss->drv->global->nl_cb,
1017                                          "wiphy beacons");
1018         if (w->nl_beacons == NULL) {
1019                 os_free(w);
1020                 return NULL;
1021         }
1022
1023         if (nl80211_register_beacons(bss->drv, w)) {
1024                 nl_destroy_handles(&w->nl_beacons);
1025                 os_free(w);
1026                 return NULL;
1027         }
1028
1029         nl80211_register_eloop_read(&w->nl_beacons, nl80211_recv_beacons, w);
1030
1031         dl_list_add(&nl80211_wiphys, &w->list);
1032
1033 add:
1034         /* drv entry for this bss already there? */
1035         dl_list_for_each(tmp_bss, &w->bsss, struct i802_bss, wiphy_list) {
1036                 if (tmp_bss->drv == bss->drv) {
1037                         found = 1;
1038                         break;
1039                 }
1040         }
1041         /* if not add it */
1042         if (!found)
1043                 dl_list_add(&w->drvs, &bss->drv->wiphy_list);
1044
1045         dl_list_add(&w->bsss, &bss->wiphy_list);
1046         bss->wiphy_data = w;
1047         return w;
1048 }
1049
1050
1051 static void nl80211_put_wiphy_data_ap(struct i802_bss *bss)
1052 {
1053         struct nl80211_wiphy_data *w = bss->wiphy_data;
1054         struct i802_bss *tmp_bss;
1055         int found = 0;
1056
1057         if (w == NULL)
1058                 return;
1059         bss->wiphy_data = NULL;
1060         dl_list_del(&bss->wiphy_list);
1061
1062         /* still any for this drv present? */
1063         dl_list_for_each(tmp_bss, &w->bsss, struct i802_bss, wiphy_list) {
1064                 if (tmp_bss->drv == bss->drv) {
1065                         found = 1;
1066                         break;
1067                 }
1068         }
1069         /* if not remove it */
1070         if (!found)
1071                 dl_list_del(&bss->drv->wiphy_list);
1072
1073         if (!dl_list_empty(&w->bsss))
1074                 return;
1075
1076         nl80211_destroy_eloop_handle(&w->nl_beacons);
1077
1078         nl_cb_put(w->nl_cb);
1079         dl_list_del(&w->list);
1080         os_free(w);
1081 }
1082
1083
1084 static int wpa_driver_nl80211_get_bssid(void *priv, u8 *bssid)
1085 {
1086         struct i802_bss *bss = priv;
1087         struct wpa_driver_nl80211_data *drv = bss->drv;
1088         if (!drv->associated)
1089                 return -1;
1090         os_memcpy(bssid, drv->bssid, ETH_ALEN);
1091         return 0;
1092 }
1093
1094
1095 static int wpa_driver_nl80211_get_ssid(void *priv, u8 *ssid)
1096 {
1097         struct i802_bss *bss = priv;
1098         struct wpa_driver_nl80211_data *drv = bss->drv;
1099         if (!drv->associated)
1100                 return -1;
1101         os_memcpy(ssid, drv->ssid, drv->ssid_len);
1102         return drv->ssid_len;
1103 }
1104
1105
1106 static void wpa_driver_nl80211_event_newlink(
1107         struct wpa_driver_nl80211_data *drv, char *ifname)
1108 {
1109         union wpa_event_data event;
1110
1111         if (os_strcmp(drv->first_bss->ifname, ifname) == 0) {
1112                 if (if_nametoindex(drv->first_bss->ifname) == 0) {
1113                         wpa_printf(MSG_DEBUG, "nl80211: Interface %s does not exist - ignore RTM_NEWLINK",
1114                                    drv->first_bss->ifname);
1115                         return;
1116                 }
1117                 if (!drv->if_removed)
1118                         return;
1119                 wpa_printf(MSG_DEBUG, "nl80211: Mark if_removed=0 for %s based on RTM_NEWLINK event",
1120                            drv->first_bss->ifname);
1121                 drv->if_removed = 0;
1122         }
1123
1124         os_memset(&event, 0, sizeof(event));
1125         os_strlcpy(event.interface_status.ifname, ifname,
1126                    sizeof(event.interface_status.ifname));
1127         event.interface_status.ievent = EVENT_INTERFACE_ADDED;
1128         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_STATUS, &event);
1129 }
1130
1131
1132 static void wpa_driver_nl80211_event_dellink(
1133         struct wpa_driver_nl80211_data *drv, char *ifname)
1134 {
1135         union wpa_event_data event;
1136
1137         if (os_strcmp(drv->first_bss->ifname, ifname) == 0) {
1138                 if (drv->if_removed) {
1139                         wpa_printf(MSG_DEBUG, "nl80211: if_removed already set - ignore RTM_DELLINK event for %s",
1140                                    ifname);
1141                         return;
1142                 }
1143                 wpa_printf(MSG_DEBUG, "RTM_DELLINK: Interface '%s' removed - mark if_removed=1",
1144                            ifname);
1145                 drv->if_removed = 1;
1146         } else {
1147                 wpa_printf(MSG_DEBUG, "RTM_DELLINK: Interface '%s' removed",
1148                            ifname);
1149         }
1150
1151         os_memset(&event, 0, sizeof(event));
1152         os_strlcpy(event.interface_status.ifname, ifname,
1153                    sizeof(event.interface_status.ifname));
1154         event.interface_status.ievent = EVENT_INTERFACE_REMOVED;
1155         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_STATUS, &event);
1156 }
1157
1158
1159 static int wpa_driver_nl80211_own_ifname(struct wpa_driver_nl80211_data *drv,
1160                                          u8 *buf, size_t len)
1161 {
1162         int attrlen, rta_len;
1163         struct rtattr *attr;
1164
1165         attrlen = len;
1166         attr = (struct rtattr *) buf;
1167
1168         rta_len = RTA_ALIGN(sizeof(struct rtattr));
1169         while (RTA_OK(attr, attrlen)) {
1170                 if (attr->rta_type == IFLA_IFNAME) {
1171                         if (os_strcmp(((char *) attr) + rta_len,
1172                                       drv->first_bss->ifname) == 0)
1173                                 return 1;
1174                         else
1175                                 break;
1176                 }
1177                 attr = RTA_NEXT(attr, attrlen);
1178         }
1179
1180         return 0;
1181 }
1182
1183
1184 static int wpa_driver_nl80211_own_ifindex(struct wpa_driver_nl80211_data *drv,
1185                                           int ifindex, u8 *buf, size_t len)
1186 {
1187         if (drv->ifindex == ifindex)
1188                 return 1;
1189
1190         if (drv->if_removed && wpa_driver_nl80211_own_ifname(drv, buf, len)) {
1191                 wpa_printf(MSG_DEBUG, "nl80211: Update ifindex for a removed "
1192                            "interface");
1193                 wpa_driver_nl80211_finish_drv_init(drv, NULL, 0);
1194                 return 1;
1195         }
1196
1197         return 0;
1198 }
1199
1200
1201 static struct wpa_driver_nl80211_data *
1202 nl80211_find_drv(struct nl80211_global *global, int idx, u8 *buf, size_t len)
1203 {
1204         struct wpa_driver_nl80211_data *drv;
1205         dl_list_for_each(drv, &global->interfaces,
1206                          struct wpa_driver_nl80211_data, list) {
1207                 if (wpa_driver_nl80211_own_ifindex(drv, idx, buf, len) ||
1208                     have_ifidx(drv, idx))
1209                         return drv;
1210         }
1211         return NULL;
1212 }
1213
1214
1215 static void wpa_driver_nl80211_event_rtm_newlink(void *ctx,
1216                                                  struct ifinfomsg *ifi,
1217                                                  u8 *buf, size_t len)
1218 {
1219         struct nl80211_global *global = ctx;
1220         struct wpa_driver_nl80211_data *drv;
1221         int attrlen;
1222         struct rtattr *attr;
1223         u32 brid = 0;
1224         char namebuf[IFNAMSIZ];
1225         char ifname[IFNAMSIZ + 1];
1226         char extra[100], *pos, *end;
1227
1228         drv = nl80211_find_drv(global, ifi->ifi_index, buf, len);
1229         if (!drv) {
1230                 wpa_printf(MSG_DEBUG, "nl80211: Ignore RTM_NEWLINK event for foreign ifindex %d",
1231                            ifi->ifi_index);
1232                 return;
1233         }
1234
1235         extra[0] = '\0';
1236         pos = extra;
1237         end = pos + sizeof(extra);
1238         ifname[0] = '\0';
1239
1240         attrlen = len;
1241         attr = (struct rtattr *) buf;
1242         while (RTA_OK(attr, attrlen)) {
1243                 switch (attr->rta_type) {
1244                 case IFLA_IFNAME:
1245                         if (RTA_PAYLOAD(attr) >= IFNAMSIZ)
1246                                 break;
1247                         os_memcpy(ifname, RTA_DATA(attr), RTA_PAYLOAD(attr));
1248                         ifname[RTA_PAYLOAD(attr)] = '\0';
1249                         break;
1250                 case IFLA_MASTER:
1251                         brid = nla_get_u32((struct nlattr *) attr);
1252                         pos += os_snprintf(pos, end - pos, " master=%u", brid);
1253                         break;
1254                 case IFLA_WIRELESS:
1255                         pos += os_snprintf(pos, end - pos, " wext");
1256                         break;
1257                 case IFLA_OPERSTATE:
1258                         pos += os_snprintf(pos, end - pos, " operstate=%u",
1259                                            nla_get_u32((struct nlattr *) attr));
1260                         break;
1261                 case IFLA_LINKMODE:
1262                         pos += os_snprintf(pos, end - pos, " linkmode=%u",
1263                                            nla_get_u32((struct nlattr *) attr));
1264                         break;
1265                 }
1266                 attr = RTA_NEXT(attr, attrlen);
1267         }
1268         extra[sizeof(extra) - 1] = '\0';
1269
1270         wpa_printf(MSG_DEBUG, "RTM_NEWLINK: ifi_index=%d ifname=%s%s ifi_family=%d ifi_flags=0x%x (%s%s%s%s)",
1271                    ifi->ifi_index, ifname, extra, ifi->ifi_family,
1272                    ifi->ifi_flags,
1273                    (ifi->ifi_flags & IFF_UP) ? "[UP]" : "",
1274                    (ifi->ifi_flags & IFF_RUNNING) ? "[RUNNING]" : "",
1275                    (ifi->ifi_flags & IFF_LOWER_UP) ? "[LOWER_UP]" : "",
1276                    (ifi->ifi_flags & IFF_DORMANT) ? "[DORMANT]" : "");
1277
1278         if (!drv->if_disabled && !(ifi->ifi_flags & IFF_UP)) {
1279                 if (if_indextoname(ifi->ifi_index, namebuf) &&
1280                     linux_iface_up(drv->global->ioctl_sock,
1281                                    drv->first_bss->ifname) > 0) {
1282                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface down "
1283                                    "event since interface %s is up", namebuf);
1284                         return;
1285                 }
1286                 wpa_printf(MSG_DEBUG, "nl80211: Interface down");
1287                 if (drv->ignore_if_down_event) {
1288                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface down "
1289                                    "event generated by mode change");
1290                         drv->ignore_if_down_event = 0;
1291                 } else {
1292                         drv->if_disabled = 1;
1293                         wpa_supplicant_event(drv->ctx,
1294                                              EVENT_INTERFACE_DISABLED, NULL);
1295
1296                         /*
1297                          * Try to get drv again, since it may be removed as
1298                          * part of the EVENT_INTERFACE_DISABLED handling for
1299                          * dynamic interfaces
1300                          */
1301                         drv = nl80211_find_drv(global, ifi->ifi_index,
1302                                                buf, len);
1303                         if (!drv)
1304                                 return;
1305                 }
1306         }
1307
1308         if (drv->if_disabled && (ifi->ifi_flags & IFF_UP)) {
1309                 if (if_indextoname(ifi->ifi_index, namebuf) &&
1310                     linux_iface_up(drv->global->ioctl_sock,
1311                                    drv->first_bss->ifname) == 0) {
1312                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
1313                                    "event since interface %s is down",
1314                                    namebuf);
1315                 } else if (if_nametoindex(drv->first_bss->ifname) == 0) {
1316                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
1317                                    "event since interface %s does not exist",
1318                                    drv->first_bss->ifname);
1319                 } else if (drv->if_removed) {
1320                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
1321                                    "event since interface %s is marked "
1322                                    "removed", drv->first_bss->ifname);
1323                 } else {
1324                         struct i802_bss *bss;
1325                         u8 addr[ETH_ALEN];
1326
1327                         /* Re-read MAC address as it may have changed */
1328                         bss = get_bss_ifindex(drv, ifi->ifi_index);
1329                         if (bss &&
1330                             linux_get_ifhwaddr(drv->global->ioctl_sock,
1331                                                bss->ifname, addr) < 0) {
1332                                 wpa_printf(MSG_DEBUG,
1333                                            "nl80211: %s: failed to re-read MAC address",
1334                                            bss->ifname);
1335                         } else if (bss &&
1336                                    os_memcmp(addr, bss->addr, ETH_ALEN) != 0) {
1337                                 wpa_printf(MSG_DEBUG,
1338                                            "nl80211: Own MAC address on ifindex %d (%s) changed from "
1339                                            MACSTR " to " MACSTR,
1340                                            ifi->ifi_index, bss->ifname,
1341                                            MAC2STR(bss->addr),
1342                                            MAC2STR(addr));
1343                                 os_memcpy(bss->addr, addr, ETH_ALEN);
1344                         }
1345
1346                         wpa_printf(MSG_DEBUG, "nl80211: Interface up");
1347                         drv->if_disabled = 0;
1348                         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_ENABLED,
1349                                              NULL);
1350                 }
1351         }
1352
1353         /*
1354          * Some drivers send the association event before the operup event--in
1355          * this case, lifting operstate in wpa_driver_nl80211_set_operstate()
1356          * fails. This will hit us when wpa_supplicant does not need to do
1357          * IEEE 802.1X authentication
1358          */
1359         if (drv->operstate == 1 &&
1360             (ifi->ifi_flags & (IFF_LOWER_UP | IFF_DORMANT)) == IFF_LOWER_UP &&
1361             !(ifi->ifi_flags & IFF_RUNNING)) {
1362                 wpa_printf(MSG_DEBUG, "nl80211: Set IF_OPER_UP again based on ifi_flags and expected operstate");
1363                 netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
1364                                        -1, IF_OPER_UP);
1365         }
1366
1367         if (ifname[0])
1368                 wpa_driver_nl80211_event_newlink(drv, ifname);
1369
1370         if (ifi->ifi_family == AF_BRIDGE && brid) {
1371                 /* device has been added to bridge */
1372                 if_indextoname(brid, namebuf);
1373                 wpa_printf(MSG_DEBUG, "nl80211: Add ifindex %u for bridge %s",
1374                            brid, namebuf);
1375                 add_ifidx(drv, brid);
1376         }
1377 }
1378
1379
1380 static void wpa_driver_nl80211_event_rtm_dellink(void *ctx,
1381                                                  struct ifinfomsg *ifi,
1382                                                  u8 *buf, size_t len)
1383 {
1384         struct nl80211_global *global = ctx;
1385         struct wpa_driver_nl80211_data *drv;
1386         int attrlen;
1387         struct rtattr *attr;
1388         u32 brid = 0;
1389         char ifname[IFNAMSIZ + 1];
1390         char extra[100], *pos, *end;
1391
1392         drv = nl80211_find_drv(global, ifi->ifi_index, buf, len);
1393         if (!drv) {
1394                 wpa_printf(MSG_DEBUG, "nl80211: Ignore RTM_DELLINK event for foreign ifindex %d",
1395                            ifi->ifi_index);
1396                 return;
1397         }
1398
1399         extra[0] = '\0';
1400         pos = extra;
1401         end = pos + sizeof(extra);
1402         ifname[0] = '\0';
1403
1404         attrlen = len;
1405         attr = (struct rtattr *) buf;
1406         while (RTA_OK(attr, attrlen)) {
1407                 switch (attr->rta_type) {
1408                 case IFLA_IFNAME:
1409                         if (RTA_PAYLOAD(attr) >= IFNAMSIZ)
1410                                 break;
1411                         os_memcpy(ifname, RTA_DATA(attr), RTA_PAYLOAD(attr));
1412                         ifname[RTA_PAYLOAD(attr)] = '\0';
1413                         break;
1414                 case IFLA_MASTER:
1415                         brid = nla_get_u32((struct nlattr *) attr);
1416                         pos += os_snprintf(pos, end - pos, " master=%u", brid);
1417                         break;
1418                 case IFLA_OPERSTATE:
1419                         pos += os_snprintf(pos, end - pos, " operstate=%u",
1420                                            nla_get_u32((struct nlattr *) attr));
1421                         break;
1422                 case IFLA_LINKMODE:
1423                         pos += os_snprintf(pos, end - pos, " linkmode=%u",
1424                                            nla_get_u32((struct nlattr *) attr));
1425                         break;
1426                 }
1427                 attr = RTA_NEXT(attr, attrlen);
1428         }
1429         extra[sizeof(extra) - 1] = '\0';
1430
1431         wpa_printf(MSG_DEBUG, "RTM_DELLINK: ifi_index=%d ifname=%s%s ifi_family=%d ifi_flags=0x%x (%s%s%s%s)",
1432                    ifi->ifi_index, ifname, extra, ifi->ifi_family,
1433                    ifi->ifi_flags,
1434                    (ifi->ifi_flags & IFF_UP) ? "[UP]" : "",
1435                    (ifi->ifi_flags & IFF_RUNNING) ? "[RUNNING]" : "",
1436                    (ifi->ifi_flags & IFF_LOWER_UP) ? "[LOWER_UP]" : "",
1437                    (ifi->ifi_flags & IFF_DORMANT) ? "[DORMANT]" : "");
1438
1439         if (ifname[0] && (ifi->ifi_family != AF_BRIDGE || !brid))
1440                 wpa_driver_nl80211_event_dellink(drv, ifname);
1441
1442         if (ifi->ifi_family == AF_BRIDGE && brid) {
1443                 /* device has been removed from bridge */
1444                 char namebuf[IFNAMSIZ];
1445                 if_indextoname(brid, namebuf);
1446                 wpa_printf(MSG_DEBUG, "nl80211: Remove ifindex %u for bridge "
1447                            "%s", brid, namebuf);
1448                 del_ifidx(drv, brid);
1449         }
1450 }
1451
1452
1453 static void mlme_event_auth(struct wpa_driver_nl80211_data *drv,
1454                             const u8 *frame, size_t len)
1455 {
1456         const struct ieee80211_mgmt *mgmt;
1457         union wpa_event_data event;
1458
1459         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME) &&
1460             drv->force_connect_cmd) {
1461                 /*
1462                  * Avoid reporting two association events that would confuse
1463                  * the core code.
1464                  */
1465                 wpa_printf(MSG_DEBUG,
1466                            "nl80211: Ignore auth event when using driver SME");
1467                 return;
1468         }
1469
1470         wpa_printf(MSG_DEBUG, "nl80211: Authenticate event");
1471         mgmt = (const struct ieee80211_mgmt *) frame;
1472         if (len < 24 + sizeof(mgmt->u.auth)) {
1473                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1474                            "frame");
1475                 return;
1476         }
1477
1478         os_memcpy(drv->auth_bssid, mgmt->sa, ETH_ALEN);
1479         os_memset(drv->auth_attempt_bssid, 0, ETH_ALEN);
1480         os_memset(&event, 0, sizeof(event));
1481         os_memcpy(event.auth.peer, mgmt->sa, ETH_ALEN);
1482         event.auth.auth_type = le_to_host16(mgmt->u.auth.auth_alg);
1483         event.auth.auth_transaction =
1484                 le_to_host16(mgmt->u.auth.auth_transaction);
1485         event.auth.status_code = le_to_host16(mgmt->u.auth.status_code);
1486         if (len > 24 + sizeof(mgmt->u.auth)) {
1487                 event.auth.ies = mgmt->u.auth.variable;
1488                 event.auth.ies_len = len - 24 - sizeof(mgmt->u.auth);
1489         }
1490
1491         wpa_supplicant_event(drv->ctx, EVENT_AUTH, &event);
1492 }
1493
1494
1495 static unsigned int nl80211_get_assoc_freq(struct wpa_driver_nl80211_data *drv)
1496 {
1497         struct nl_msg *msg;
1498         int ret;
1499         struct nl80211_bss_info_arg arg;
1500
1501         os_memset(&arg, 0, sizeof(arg));
1502         msg = nlmsg_alloc();
1503         if (!msg)
1504                 goto nla_put_failure;
1505
1506         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
1507         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1508
1509         arg.drv = drv;
1510         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
1511         msg = NULL;
1512         if (ret == 0) {
1513                 unsigned int freq = drv->nlmode == NL80211_IFTYPE_ADHOC ?
1514                         arg.ibss_freq : arg.assoc_freq;
1515                 wpa_printf(MSG_DEBUG, "nl80211: Operating frequency for the "
1516                            "associated BSS from scan results: %u MHz", freq);
1517                 if (freq)
1518                         drv->assoc_freq = freq;
1519                 return drv->assoc_freq;
1520         }
1521         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
1522                    "(%s)", ret, strerror(-ret));
1523 nla_put_failure:
1524         nlmsg_free(msg);
1525         return drv->assoc_freq;
1526 }
1527
1528
1529 static void mlme_event_assoc(struct wpa_driver_nl80211_data *drv,
1530                             const u8 *frame, size_t len)
1531 {
1532         const struct ieee80211_mgmt *mgmt;
1533         union wpa_event_data event;
1534         u16 status;
1535
1536         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME) &&
1537             drv->force_connect_cmd) {
1538                 /*
1539                  * Avoid reporting two association events that would confuse
1540                  * the core code.
1541                  */
1542                 wpa_printf(MSG_DEBUG,
1543                            "nl80211: Ignore assoc event when using driver SME");
1544                 return;
1545         }
1546
1547         wpa_printf(MSG_DEBUG, "nl80211: Associate event");
1548         mgmt = (const struct ieee80211_mgmt *) frame;
1549         if (len < 24 + sizeof(mgmt->u.assoc_resp)) {
1550                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1551                            "frame");
1552                 return;
1553         }
1554
1555         status = le_to_host16(mgmt->u.assoc_resp.status_code);
1556         if (status != WLAN_STATUS_SUCCESS) {
1557                 os_memset(&event, 0, sizeof(event));
1558                 event.assoc_reject.bssid = mgmt->bssid;
1559                 if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
1560                         event.assoc_reject.resp_ies =
1561                                 (u8 *) mgmt->u.assoc_resp.variable;
1562                         event.assoc_reject.resp_ies_len =
1563                                 len - 24 - sizeof(mgmt->u.assoc_resp);
1564                 }
1565                 event.assoc_reject.status_code = status;
1566
1567                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
1568                 return;
1569         }
1570
1571         drv->associated = 1;
1572         os_memcpy(drv->bssid, mgmt->sa, ETH_ALEN);
1573         os_memcpy(drv->prev_bssid, mgmt->sa, ETH_ALEN);
1574
1575         os_memset(&event, 0, sizeof(event));
1576         if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
1577                 event.assoc_info.resp_ies = (u8 *) mgmt->u.assoc_resp.variable;
1578                 event.assoc_info.resp_ies_len =
1579                         len - 24 - sizeof(mgmt->u.assoc_resp);
1580         }
1581
1582         event.assoc_info.freq = drv->assoc_freq;
1583
1584         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
1585 }
1586
1587
1588 static void mlme_event_connect(struct wpa_driver_nl80211_data *drv,
1589                                enum nl80211_commands cmd, struct nlattr *status,
1590                                struct nlattr *addr, struct nlattr *req_ie,
1591                                struct nlattr *resp_ie)
1592 {
1593         union wpa_event_data event;
1594
1595         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1596                 /*
1597                  * Avoid reporting two association events that would confuse
1598                  * the core code.
1599                  */
1600                 wpa_printf(MSG_DEBUG, "nl80211: Ignore connect event (cmd=%d) "
1601                            "when using userspace SME", cmd);
1602                 return;
1603         }
1604
1605         if (cmd == NL80211_CMD_CONNECT)
1606                 wpa_printf(MSG_DEBUG, "nl80211: Connect event");
1607         else if (cmd == NL80211_CMD_ROAM)
1608                 wpa_printf(MSG_DEBUG, "nl80211: Roam event");
1609
1610         os_memset(&event, 0, sizeof(event));
1611         if (cmd == NL80211_CMD_CONNECT &&
1612             nla_get_u16(status) != WLAN_STATUS_SUCCESS) {
1613                 if (addr)
1614                         event.assoc_reject.bssid = nla_data(addr);
1615                 if (resp_ie) {
1616                         event.assoc_reject.resp_ies = nla_data(resp_ie);
1617                         event.assoc_reject.resp_ies_len = nla_len(resp_ie);
1618                 }
1619                 event.assoc_reject.status_code = nla_get_u16(status);
1620                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
1621                 return;
1622         }
1623
1624         drv->associated = 1;
1625         if (addr) {
1626                 os_memcpy(drv->bssid, nla_data(addr), ETH_ALEN);
1627                 os_memcpy(drv->prev_bssid, drv->bssid, ETH_ALEN);
1628         }
1629
1630         if (req_ie) {
1631                 event.assoc_info.req_ies = nla_data(req_ie);
1632                 event.assoc_info.req_ies_len = nla_len(req_ie);
1633         }
1634         if (resp_ie) {
1635                 event.assoc_info.resp_ies = nla_data(resp_ie);
1636                 event.assoc_info.resp_ies_len = nla_len(resp_ie);
1637         }
1638
1639         event.assoc_info.freq = nl80211_get_assoc_freq(drv);
1640
1641         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
1642 }
1643
1644
1645 static void mlme_event_disconnect(struct wpa_driver_nl80211_data *drv,
1646                                   struct nlattr *reason, struct nlattr *addr,
1647                                   struct nlattr *by_ap)
1648 {
1649         union wpa_event_data data;
1650         unsigned int locally_generated = by_ap == NULL;
1651
1652         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1653                 /*
1654                  * Avoid reporting two disassociation events that could
1655                  * confuse the core code.
1656                  */
1657                 wpa_printf(MSG_DEBUG, "nl80211: Ignore disconnect "
1658                            "event when using userspace SME");
1659                 return;
1660         }
1661
1662         if (drv->ignore_next_local_disconnect) {
1663                 drv->ignore_next_local_disconnect = 0;
1664                 if (locally_generated) {
1665                         wpa_printf(MSG_DEBUG, "nl80211: Ignore disconnect "
1666                                    "event triggered during reassociation");
1667                         return;
1668                 }
1669                 wpa_printf(MSG_WARNING, "nl80211: Was expecting local "
1670                            "disconnect but got another disconnect "
1671                            "event first");
1672         }
1673
1674         wpa_printf(MSG_DEBUG, "nl80211: Disconnect event");
1675         nl80211_mark_disconnected(drv);
1676         os_memset(&data, 0, sizeof(data));
1677         if (reason)
1678                 data.deauth_info.reason_code = nla_get_u16(reason);
1679         data.deauth_info.locally_generated = by_ap == NULL;
1680         wpa_supplicant_event(drv->ctx, EVENT_DEAUTH, &data);
1681 }
1682
1683
1684 static int calculate_chan_offset(int width, int freq, int cf1, int cf2)
1685 {
1686         int freq1 = 0;
1687
1688         switch (convert2width(width)) {
1689         case CHAN_WIDTH_20_NOHT:
1690         case CHAN_WIDTH_20:
1691                 return 0;
1692         case CHAN_WIDTH_40:
1693                 freq1 = cf1 - 10;
1694                 break;
1695         case CHAN_WIDTH_80:
1696                 freq1 = cf1 - 30;
1697                 break;
1698         case CHAN_WIDTH_160:
1699                 freq1 = cf1 - 70;
1700                 break;
1701         case CHAN_WIDTH_UNKNOWN:
1702         case CHAN_WIDTH_80P80:
1703                 /* FIXME: implement this */
1704                 return 0;
1705         }
1706
1707         return (abs(freq - freq1) / 20) % 2 == 0 ? 1 : -1;
1708 }
1709
1710
1711 static void mlme_event_ch_switch(struct wpa_driver_nl80211_data *drv,
1712                                  struct nlattr *ifindex, struct nlattr *freq,
1713                                  struct nlattr *type, struct nlattr *bw,
1714                                  struct nlattr *cf1, struct nlattr *cf2)
1715 {
1716         struct i802_bss *bss;
1717         union wpa_event_data data;
1718         int ht_enabled = 1;
1719         int chan_offset = 0;
1720         int ifidx;
1721
1722         wpa_printf(MSG_DEBUG, "nl80211: Channel switch event");
1723
1724         if (!freq)
1725                 return;
1726
1727         ifidx = nla_get_u32(ifindex);
1728         bss = get_bss_ifindex(drv, ifidx);
1729         if (bss == NULL) {
1730                 wpa_printf(MSG_WARNING, "nl80211: Unknown ifindex (%d) for channel switch, ignoring",
1731                            ifidx);
1732                 return;
1733         }
1734
1735         if (type) {
1736                 switch (nla_get_u32(type)) {
1737                 case NL80211_CHAN_NO_HT:
1738                         ht_enabled = 0;
1739                         break;
1740                 case NL80211_CHAN_HT20:
1741                         break;
1742                 case NL80211_CHAN_HT40PLUS:
1743                         chan_offset = 1;
1744                         break;
1745                 case NL80211_CHAN_HT40MINUS:
1746                         chan_offset = -1;
1747                         break;
1748                 }
1749         } else if (bw && cf1) {
1750                 /* This can happen for example with VHT80 ch switch */
1751                 chan_offset = calculate_chan_offset(nla_get_u32(bw),
1752                                                     nla_get_u32(freq),
1753                                                     nla_get_u32(cf1),
1754                                                     cf2 ? nla_get_u32(cf2) : 0);
1755         } else {
1756                 wpa_printf(MSG_WARNING, "nl80211: Unknown secondary channel information - following channel definition calculations may fail");
1757         }
1758
1759         os_memset(&data, 0, sizeof(data));
1760         data.ch_switch.freq = nla_get_u32(freq);
1761         data.ch_switch.ht_enabled = ht_enabled;
1762         data.ch_switch.ch_offset = chan_offset;
1763         if (bw)
1764                 data.ch_switch.ch_width = convert2width(nla_get_u32(bw));
1765         if (cf1)
1766                 data.ch_switch.cf1 = nla_get_u32(cf1);
1767         if (cf2)
1768                 data.ch_switch.cf2 = nla_get_u32(cf2);
1769
1770         bss->freq = data.ch_switch.freq;
1771
1772         wpa_supplicant_event(bss->ctx, EVENT_CH_SWITCH, &data);
1773 }
1774
1775
1776 static void mlme_timeout_event(struct wpa_driver_nl80211_data *drv,
1777                                enum nl80211_commands cmd, struct nlattr *addr)
1778 {
1779         union wpa_event_data event;
1780         enum wpa_event_type ev;
1781
1782         if (nla_len(addr) != ETH_ALEN)
1783                 return;
1784
1785         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d; timeout with " MACSTR,
1786                    cmd, MAC2STR((u8 *) nla_data(addr)));
1787
1788         if (cmd == NL80211_CMD_AUTHENTICATE)
1789                 ev = EVENT_AUTH_TIMED_OUT;
1790         else if (cmd == NL80211_CMD_ASSOCIATE)
1791                 ev = EVENT_ASSOC_TIMED_OUT;
1792         else
1793                 return;
1794
1795         os_memset(&event, 0, sizeof(event));
1796         os_memcpy(event.timeout_event.addr, nla_data(addr), ETH_ALEN);
1797         wpa_supplicant_event(drv->ctx, ev, &event);
1798 }
1799
1800
1801 static void mlme_event_mgmt(struct i802_bss *bss,
1802                             struct nlattr *freq, struct nlattr *sig,
1803                             const u8 *frame, size_t len)
1804 {
1805         struct wpa_driver_nl80211_data *drv = bss->drv;
1806         const struct ieee80211_mgmt *mgmt;
1807         union wpa_event_data event;
1808         u16 fc, stype;
1809         int ssi_signal = 0;
1810         int rx_freq = 0;
1811
1812         wpa_printf(MSG_MSGDUMP, "nl80211: Frame event");
1813         mgmt = (const struct ieee80211_mgmt *) frame;
1814         if (len < 24) {
1815                 wpa_printf(MSG_DEBUG, "nl80211: Too short management frame");
1816                 return;
1817         }
1818
1819         fc = le_to_host16(mgmt->frame_control);
1820         stype = WLAN_FC_GET_STYPE(fc);
1821
1822         if (sig)
1823                 ssi_signal = (s32) nla_get_u32(sig);
1824
1825         os_memset(&event, 0, sizeof(event));
1826         if (freq) {
1827                 event.rx_mgmt.freq = nla_get_u32(freq);
1828                 rx_freq = drv->last_mgmt_freq = event.rx_mgmt.freq;
1829         }
1830         wpa_printf(MSG_DEBUG,
1831                    "nl80211: RX frame sa=" MACSTR
1832                    " freq=%d ssi_signal=%d stype=%u (%s) len=%u",
1833                    MAC2STR(mgmt->sa), rx_freq, ssi_signal, stype, fc2str(fc),
1834                    (unsigned int) len);
1835         event.rx_mgmt.frame = frame;
1836         event.rx_mgmt.frame_len = len;
1837         event.rx_mgmt.ssi_signal = ssi_signal;
1838         event.rx_mgmt.drv_priv = bss;
1839         wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
1840 }
1841
1842
1843 static void mlme_event_mgmt_tx_status(struct wpa_driver_nl80211_data *drv,
1844                                       struct nlattr *cookie, const u8 *frame,
1845                                       size_t len, struct nlattr *ack)
1846 {
1847         union wpa_event_data event;
1848         const struct ieee80211_hdr *hdr;
1849         u16 fc;
1850
1851         wpa_printf(MSG_DEBUG, "nl80211: Frame TX status event");
1852         if (!is_ap_interface(drv->nlmode)) {
1853                 u64 cookie_val;
1854
1855                 if (!cookie)
1856                         return;
1857
1858                 cookie_val = nla_get_u64(cookie);
1859                 wpa_printf(MSG_DEBUG, "nl80211: Action TX status:"
1860                            " cookie=0%llx%s (ack=%d)",
1861                            (long long unsigned int) cookie_val,
1862                            cookie_val == drv->send_action_cookie ?
1863                            " (match)" : " (unknown)", ack != NULL);
1864                 if (cookie_val != drv->send_action_cookie)
1865                         return;
1866         }
1867
1868         hdr = (const struct ieee80211_hdr *) frame;
1869         fc = le_to_host16(hdr->frame_control);
1870
1871         os_memset(&event, 0, sizeof(event));
1872         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
1873         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
1874         event.tx_status.dst = hdr->addr1;
1875         event.tx_status.data = frame;
1876         event.tx_status.data_len = len;
1877         event.tx_status.ack = ack != NULL;
1878         wpa_supplicant_event(drv->ctx, EVENT_TX_STATUS, &event);
1879 }
1880
1881
1882 static void mlme_event_deauth_disassoc(struct wpa_driver_nl80211_data *drv,
1883                                        enum wpa_event_type type,
1884                                        const u8 *frame, size_t len)
1885 {
1886         const struct ieee80211_mgmt *mgmt;
1887         union wpa_event_data event;
1888         const u8 *bssid = NULL;
1889         u16 reason_code = 0;
1890
1891         if (type == EVENT_DEAUTH)
1892                 wpa_printf(MSG_DEBUG, "nl80211: Deauthenticate event");
1893         else
1894                 wpa_printf(MSG_DEBUG, "nl80211: Disassociate event");
1895
1896         mgmt = (const struct ieee80211_mgmt *) frame;
1897         if (len >= 24) {
1898                 bssid = mgmt->bssid;
1899
1900                 if ((drv->capa.flags & WPA_DRIVER_FLAGS_SME) &&
1901                     !drv->associated &&
1902                     os_memcmp(bssid, drv->auth_bssid, ETH_ALEN) != 0 &&
1903                     os_memcmp(bssid, drv->auth_attempt_bssid, ETH_ALEN) != 0 &&
1904                     os_memcmp(bssid, drv->prev_bssid, ETH_ALEN) == 0) {
1905                         /*
1906                          * Avoid issues with some roaming cases where
1907                          * disconnection event for the old AP may show up after
1908                          * we have started connection with the new AP.
1909                          */
1910                         wpa_printf(MSG_DEBUG, "nl80211: Ignore deauth/disassoc event from old AP " MACSTR " when already authenticating with " MACSTR,
1911                                    MAC2STR(bssid),
1912                                    MAC2STR(drv->auth_attempt_bssid));
1913                         return;
1914                 }
1915
1916                 if (drv->associated != 0 &&
1917                     os_memcmp(bssid, drv->bssid, ETH_ALEN) != 0 &&
1918                     os_memcmp(bssid, drv->auth_bssid, ETH_ALEN) != 0) {
1919                         /*
1920                          * We have presumably received this deauth as a
1921                          * response to a clear_state_mismatch() outgoing
1922                          * deauth.  Don't let it take us offline!
1923                          */
1924                         wpa_printf(MSG_DEBUG, "nl80211: Deauth received "
1925                                    "from Unknown BSSID " MACSTR " -- ignoring",
1926                                    MAC2STR(bssid));
1927                         return;
1928                 }
1929         }
1930
1931         nl80211_mark_disconnected(drv);
1932         os_memset(&event, 0, sizeof(event));
1933
1934         /* Note: Same offset for Reason Code in both frame subtypes */
1935         if (len >= 24 + sizeof(mgmt->u.deauth))
1936                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
1937
1938         if (type == EVENT_DISASSOC) {
1939                 event.disassoc_info.locally_generated =
1940                         !os_memcmp(mgmt->sa, drv->first_bss->addr, ETH_ALEN);
1941                 event.disassoc_info.addr = bssid;
1942                 event.disassoc_info.reason_code = reason_code;
1943                 if (frame + len > mgmt->u.disassoc.variable) {
1944                         event.disassoc_info.ie = mgmt->u.disassoc.variable;
1945                         event.disassoc_info.ie_len = frame + len -
1946                                 mgmt->u.disassoc.variable;
1947                 }
1948         } else {
1949                 if (drv->ignore_deauth_event) {
1950                         wpa_printf(MSG_DEBUG, "nl80211: Ignore deauth event due to previous forced deauth-during-auth");
1951                         drv->ignore_deauth_event = 0;
1952                         return;
1953                 }
1954                 event.deauth_info.locally_generated =
1955                         !os_memcmp(mgmt->sa, drv->first_bss->addr, ETH_ALEN);
1956                 if (drv->ignore_next_local_deauth) {
1957                         drv->ignore_next_local_deauth = 0;
1958                         if (event.deauth_info.locally_generated) {
1959                                 wpa_printf(MSG_DEBUG, "nl80211: Ignore deauth event triggered due to own deauth request");
1960                                 return;
1961                         }
1962                         wpa_printf(MSG_WARNING, "nl80211: Was expecting local deauth but got another disconnect event first");
1963                 }
1964                 event.deauth_info.addr = bssid;
1965                 event.deauth_info.reason_code = reason_code;
1966                 if (frame + len > mgmt->u.deauth.variable) {
1967                         event.deauth_info.ie = mgmt->u.deauth.variable;
1968                         event.deauth_info.ie_len = frame + len -
1969                                 mgmt->u.deauth.variable;
1970                 }
1971         }
1972
1973         wpa_supplicant_event(drv->ctx, type, &event);
1974 }
1975
1976
1977 static void mlme_event_unprot_disconnect(struct wpa_driver_nl80211_data *drv,
1978                                          enum wpa_event_type type,
1979                                          const u8 *frame, size_t len)
1980 {
1981         const struct ieee80211_mgmt *mgmt;
1982         union wpa_event_data event;
1983         u16 reason_code = 0;
1984
1985         if (type == EVENT_UNPROT_DEAUTH)
1986                 wpa_printf(MSG_DEBUG, "nl80211: Unprot Deauthenticate event");
1987         else
1988                 wpa_printf(MSG_DEBUG, "nl80211: Unprot Disassociate event");
1989
1990         if (len < 24)
1991                 return;
1992
1993         mgmt = (const struct ieee80211_mgmt *) frame;
1994
1995         os_memset(&event, 0, sizeof(event));
1996         /* Note: Same offset for Reason Code in both frame subtypes */
1997         if (len >= 24 + sizeof(mgmt->u.deauth))
1998                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
1999
2000         if (type == EVENT_UNPROT_DISASSOC) {
2001                 event.unprot_disassoc.sa = mgmt->sa;
2002                 event.unprot_disassoc.da = mgmt->da;
2003                 event.unprot_disassoc.reason_code = reason_code;
2004         } else {
2005                 event.unprot_deauth.sa = mgmt->sa;
2006                 event.unprot_deauth.da = mgmt->da;
2007                 event.unprot_deauth.reason_code = reason_code;
2008         }
2009
2010         wpa_supplicant_event(drv->ctx, type, &event);
2011 }
2012
2013
2014 static void mlme_event(struct i802_bss *bss,
2015                        enum nl80211_commands cmd, struct nlattr *frame,
2016                        struct nlattr *addr, struct nlattr *timed_out,
2017                        struct nlattr *freq, struct nlattr *ack,
2018                        struct nlattr *cookie, struct nlattr *sig)
2019 {
2020         struct wpa_driver_nl80211_data *drv = bss->drv;
2021         const u8 *data;
2022         size_t len;
2023
2024         if (timed_out && addr) {
2025                 mlme_timeout_event(drv, cmd, addr);
2026                 return;
2027         }
2028
2029         if (frame == NULL) {
2030                 wpa_printf(MSG_DEBUG,
2031                            "nl80211: MLME event %d (%s) without frame data",
2032                            cmd, nl80211_command_to_string(cmd));
2033                 return;
2034         }
2035
2036         data = nla_data(frame);
2037         len = nla_len(frame);
2038         if (len < 4 + 2 * ETH_ALEN) {
2039                 wpa_printf(MSG_MSGDUMP, "nl80211: MLME event %d (%s) on %s("
2040                            MACSTR ") - too short",
2041                            cmd, nl80211_command_to_string(cmd), bss->ifname,
2042                            MAC2STR(bss->addr));
2043                 return;
2044         }
2045         wpa_printf(MSG_MSGDUMP, "nl80211: MLME event %d (%s) on %s(" MACSTR
2046                    ") A1=" MACSTR " A2=" MACSTR, cmd,
2047                    nl80211_command_to_string(cmd), bss->ifname,
2048                    MAC2STR(bss->addr), MAC2STR(data + 4),
2049                    MAC2STR(data + 4 + ETH_ALEN));
2050         if (cmd != NL80211_CMD_FRAME_TX_STATUS && !(data[4] & 0x01) &&
2051             os_memcmp(bss->addr, data + 4, ETH_ALEN) != 0 &&
2052             os_memcmp(bss->addr, data + 4 + ETH_ALEN, ETH_ALEN) != 0) {
2053                 wpa_printf(MSG_MSGDUMP, "nl80211: %s: Ignore MLME frame event "
2054                            "for foreign address", bss->ifname);
2055                 return;
2056         }
2057         wpa_hexdump(MSG_MSGDUMP, "nl80211: MLME event frame",
2058                     nla_data(frame), nla_len(frame));
2059
2060         switch (cmd) {
2061         case NL80211_CMD_AUTHENTICATE:
2062                 mlme_event_auth(drv, nla_data(frame), nla_len(frame));
2063                 break;
2064         case NL80211_CMD_ASSOCIATE:
2065                 mlme_event_assoc(drv, nla_data(frame), nla_len(frame));
2066                 break;
2067         case NL80211_CMD_DEAUTHENTICATE:
2068                 mlme_event_deauth_disassoc(drv, EVENT_DEAUTH,
2069                                            nla_data(frame), nla_len(frame));
2070                 break;
2071         case NL80211_CMD_DISASSOCIATE:
2072                 mlme_event_deauth_disassoc(drv, EVENT_DISASSOC,
2073                                            nla_data(frame), nla_len(frame));
2074                 break;
2075         case NL80211_CMD_FRAME:
2076                 mlme_event_mgmt(bss, freq, sig, nla_data(frame),
2077                                 nla_len(frame));
2078                 break;
2079         case NL80211_CMD_FRAME_TX_STATUS:
2080                 mlme_event_mgmt_tx_status(drv, cookie, nla_data(frame),
2081                                           nla_len(frame), ack);
2082                 break;
2083         case NL80211_CMD_UNPROT_DEAUTHENTICATE:
2084                 mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DEAUTH,
2085                                              nla_data(frame), nla_len(frame));
2086                 break;
2087         case NL80211_CMD_UNPROT_DISASSOCIATE:
2088                 mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DISASSOC,
2089                                              nla_data(frame), nla_len(frame));
2090                 break;
2091         default:
2092                 break;
2093         }
2094 }
2095
2096
2097 static void mlme_event_michael_mic_failure(struct i802_bss *bss,
2098                                            struct nlattr *tb[])
2099 {
2100         union wpa_event_data data;
2101
2102         wpa_printf(MSG_DEBUG, "nl80211: MLME event Michael MIC failure");
2103         os_memset(&data, 0, sizeof(data));
2104         if (tb[NL80211_ATTR_MAC]) {
2105                 wpa_hexdump(MSG_DEBUG, "nl80211: Source MAC address",
2106                             nla_data(tb[NL80211_ATTR_MAC]),
2107                             nla_len(tb[NL80211_ATTR_MAC]));
2108                 data.michael_mic_failure.src = nla_data(tb[NL80211_ATTR_MAC]);
2109         }
2110         if (tb[NL80211_ATTR_KEY_SEQ]) {
2111                 wpa_hexdump(MSG_DEBUG, "nl80211: TSC",
2112                             nla_data(tb[NL80211_ATTR_KEY_SEQ]),
2113                             nla_len(tb[NL80211_ATTR_KEY_SEQ]));
2114         }
2115         if (tb[NL80211_ATTR_KEY_TYPE]) {
2116                 enum nl80211_key_type key_type =
2117                         nla_get_u32(tb[NL80211_ATTR_KEY_TYPE]);
2118                 wpa_printf(MSG_DEBUG, "nl80211: Key Type %d", key_type);
2119                 if (key_type == NL80211_KEYTYPE_PAIRWISE)
2120                         data.michael_mic_failure.unicast = 1;
2121         } else
2122                 data.michael_mic_failure.unicast = 1;
2123
2124         if (tb[NL80211_ATTR_KEY_IDX]) {
2125                 u8 key_id = nla_get_u8(tb[NL80211_ATTR_KEY_IDX]);
2126                 wpa_printf(MSG_DEBUG, "nl80211: Key Id %d", key_id);
2127         }
2128
2129         wpa_supplicant_event(bss->ctx, EVENT_MICHAEL_MIC_FAILURE, &data);
2130 }
2131
2132
2133 static void mlme_event_join_ibss(struct wpa_driver_nl80211_data *drv,
2134                                  struct nlattr *tb[])
2135 {
2136         unsigned int freq;
2137
2138         if (tb[NL80211_ATTR_MAC] == NULL) {
2139                 wpa_printf(MSG_DEBUG, "nl80211: No address in IBSS joined "
2140                            "event");
2141                 return;
2142         }
2143         os_memcpy(drv->bssid, nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2144
2145         drv->associated = 1;
2146         wpa_printf(MSG_DEBUG, "nl80211: IBSS " MACSTR " joined",
2147                    MAC2STR(drv->bssid));
2148
2149         freq = nl80211_get_assoc_freq(drv);
2150         if (freq) {
2151                 wpa_printf(MSG_DEBUG, "nl80211: IBSS on frequency %u MHz",
2152                            freq);
2153                 drv->first_bss->freq = freq;
2154         }
2155
2156         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, NULL);
2157 }
2158
2159
2160 static void mlme_event_remain_on_channel(struct wpa_driver_nl80211_data *drv,
2161                                          int cancel_event, struct nlattr *tb[])
2162 {
2163         unsigned int freq, chan_type, duration;
2164         union wpa_event_data data;
2165         u64 cookie;
2166
2167         if (tb[NL80211_ATTR_WIPHY_FREQ])
2168                 freq = nla_get_u32(tb[NL80211_ATTR_WIPHY_FREQ]);
2169         else
2170                 freq = 0;
2171
2172         if (tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE])
2173                 chan_type = nla_get_u32(tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
2174         else
2175                 chan_type = 0;
2176
2177         if (tb[NL80211_ATTR_DURATION])
2178                 duration = nla_get_u32(tb[NL80211_ATTR_DURATION]);
2179         else
2180                 duration = 0;
2181
2182         if (tb[NL80211_ATTR_COOKIE])
2183                 cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
2184         else
2185                 cookie = 0;
2186
2187         wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel event (cancel=%d "
2188                    "freq=%u channel_type=%u duration=%u cookie=0x%llx (%s))",
2189                    cancel_event, freq, chan_type, duration,
2190                    (long long unsigned int) cookie,
2191                    cookie == drv->remain_on_chan_cookie ? "match" : "unknown");
2192
2193         if (cookie != drv->remain_on_chan_cookie)
2194                 return; /* not for us */
2195
2196         if (cancel_event)
2197                 drv->pending_remain_on_chan = 0;
2198
2199         os_memset(&data, 0, sizeof(data));
2200         data.remain_on_channel.freq = freq;
2201         data.remain_on_channel.duration = duration;
2202         wpa_supplicant_event(drv->ctx, cancel_event ?
2203                              EVENT_CANCEL_REMAIN_ON_CHANNEL :
2204                              EVENT_REMAIN_ON_CHANNEL, &data);
2205 }
2206
2207
2208 static void mlme_event_ft_event(struct wpa_driver_nl80211_data *drv,
2209                                 struct nlattr *tb[])
2210 {
2211         union wpa_event_data data;
2212
2213         os_memset(&data, 0, sizeof(data));
2214
2215         if (tb[NL80211_ATTR_IE]) {
2216                 data.ft_ies.ies = nla_data(tb[NL80211_ATTR_IE]);
2217                 data.ft_ies.ies_len = nla_len(tb[NL80211_ATTR_IE]);
2218         }
2219
2220         if (tb[NL80211_ATTR_IE_RIC]) {
2221                 data.ft_ies.ric_ies = nla_data(tb[NL80211_ATTR_IE_RIC]);
2222                 data.ft_ies.ric_ies_len = nla_len(tb[NL80211_ATTR_IE_RIC]);
2223         }
2224
2225         if (tb[NL80211_ATTR_MAC])
2226                 os_memcpy(data.ft_ies.target_ap,
2227                           nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2228
2229         wpa_printf(MSG_DEBUG, "nl80211: FT event target_ap " MACSTR,
2230                    MAC2STR(data.ft_ies.target_ap));
2231
2232         wpa_supplicant_event(drv->ctx, EVENT_FT_RESPONSE, &data);
2233 }
2234
2235
2236 static void send_scan_event(struct wpa_driver_nl80211_data *drv, int aborted,
2237                             struct nlattr *tb[])
2238 {
2239         union wpa_event_data event;
2240         struct nlattr *nl;
2241         int rem;
2242         struct scan_info *info;
2243 #define MAX_REPORT_FREQS 50
2244         int freqs[MAX_REPORT_FREQS];
2245         int num_freqs = 0;
2246
2247         if (drv->scan_for_auth) {
2248                 drv->scan_for_auth = 0;
2249                 wpa_printf(MSG_DEBUG, "nl80211: Scan results for missing "
2250                            "cfg80211 BSS entry");
2251                 wpa_driver_nl80211_authenticate_retry(drv);
2252                 return;
2253         }
2254
2255         os_memset(&event, 0, sizeof(event));
2256         info = &event.scan_info;
2257         info->aborted = aborted;
2258
2259         if (tb[NL80211_ATTR_SCAN_SSIDS]) {
2260                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_SSIDS], rem) {
2261                         struct wpa_driver_scan_ssid *s =
2262                                 &info->ssids[info->num_ssids];
2263                         s->ssid = nla_data(nl);
2264                         s->ssid_len = nla_len(nl);
2265                         wpa_printf(MSG_DEBUG, "nl80211: Scan probed for SSID '%s'",
2266                                    wpa_ssid_txt(s->ssid, s->ssid_len));
2267                         info->num_ssids++;
2268                         if (info->num_ssids == WPAS_MAX_SCAN_SSIDS)
2269                                 break;
2270                 }
2271         }
2272         if (tb[NL80211_ATTR_SCAN_FREQUENCIES]) {
2273                 char msg[200], *pos, *end;
2274                 int res;
2275
2276                 pos = msg;
2277                 end = pos + sizeof(msg);
2278                 *pos = '\0';
2279
2280                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_FREQUENCIES], rem)
2281                 {
2282                         freqs[num_freqs] = nla_get_u32(nl);
2283                         res = os_snprintf(pos, end - pos, " %d",
2284                                           freqs[num_freqs]);
2285                         if (res > 0 && end - pos > res)
2286                                 pos += res;
2287                         num_freqs++;
2288                         if (num_freqs == MAX_REPORT_FREQS - 1)
2289                                 break;
2290                 }
2291                 info->freqs = freqs;
2292                 info->num_freqs = num_freqs;
2293                 wpa_printf(MSG_DEBUG, "nl80211: Scan included frequencies:%s",
2294                            msg);
2295         }
2296         wpa_supplicant_event(drv->ctx, EVENT_SCAN_RESULTS, &event);
2297 }
2298
2299
2300 static int get_link_signal(struct nl_msg *msg, void *arg)
2301 {
2302         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2303         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2304         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
2305         static struct nla_policy policy[NL80211_STA_INFO_MAX + 1] = {
2306                 [NL80211_STA_INFO_SIGNAL] = { .type = NLA_U8 },
2307                 [NL80211_STA_INFO_SIGNAL_AVG] = { .type = NLA_U8 },
2308         };
2309         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
2310         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
2311                 [NL80211_RATE_INFO_BITRATE] = { .type = NLA_U16 },
2312                 [NL80211_RATE_INFO_MCS] = { .type = NLA_U8 },
2313                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG },
2314                 [NL80211_RATE_INFO_SHORT_GI] = { .type = NLA_FLAG },
2315         };
2316         struct wpa_signal_info *sig_change = arg;
2317
2318         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2319                   genlmsg_attrlen(gnlh, 0), NULL);
2320         if (!tb[NL80211_ATTR_STA_INFO] ||
2321             nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
2322                              tb[NL80211_ATTR_STA_INFO], policy))
2323                 return NL_SKIP;
2324         if (!sinfo[NL80211_STA_INFO_SIGNAL])
2325                 return NL_SKIP;
2326
2327         sig_change->current_signal =
2328                 (s8) nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
2329
2330         if (sinfo[NL80211_STA_INFO_SIGNAL_AVG])
2331                 sig_change->avg_signal =
2332                         (s8) nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL_AVG]);
2333         else
2334                 sig_change->avg_signal = 0;
2335
2336         if (sinfo[NL80211_STA_INFO_TX_BITRATE]) {
2337                 if (nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
2338                                      sinfo[NL80211_STA_INFO_TX_BITRATE],
2339                                      rate_policy)) {
2340                         sig_change->current_txrate = 0;
2341                 } else {
2342                         if (rinfo[NL80211_RATE_INFO_BITRATE]) {
2343                                 sig_change->current_txrate =
2344                                         nla_get_u16(rinfo[
2345                                              NL80211_RATE_INFO_BITRATE]) * 100;
2346                         }
2347                 }
2348         }
2349
2350         return NL_SKIP;
2351 }
2352
2353
2354 static int nl80211_get_link_signal(struct wpa_driver_nl80211_data *drv,
2355                                    struct wpa_signal_info *sig)
2356 {
2357         struct nl_msg *msg;
2358
2359         sig->current_signal = -9999;
2360         sig->current_txrate = 0;
2361
2362         msg = nlmsg_alloc();
2363         if (!msg)
2364                 return -ENOMEM;
2365
2366         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
2367
2368         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2369         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
2370
2371         return send_and_recv_msgs(drv, msg, get_link_signal, sig);
2372  nla_put_failure:
2373         nlmsg_free(msg);
2374         return -ENOBUFS;
2375 }
2376
2377
2378 static int get_link_noise(struct nl_msg *msg, void *arg)
2379 {
2380         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2381         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2382         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
2383         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
2384                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
2385                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
2386         };
2387         struct wpa_signal_info *sig_change = arg;
2388
2389         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2390                   genlmsg_attrlen(gnlh, 0), NULL);
2391
2392         if (!tb[NL80211_ATTR_SURVEY_INFO]) {
2393                 wpa_printf(MSG_DEBUG, "nl80211: survey data missing!");
2394                 return NL_SKIP;
2395         }
2396
2397         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
2398                              tb[NL80211_ATTR_SURVEY_INFO],
2399                              survey_policy)) {
2400                 wpa_printf(MSG_DEBUG, "nl80211: failed to parse nested "
2401                            "attributes!");
2402                 return NL_SKIP;
2403         }
2404
2405         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
2406                 return NL_SKIP;
2407
2408         if (nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
2409             sig_change->frequency)
2410                 return NL_SKIP;
2411
2412         if (!sinfo[NL80211_SURVEY_INFO_NOISE])
2413                 return NL_SKIP;
2414
2415         sig_change->current_noise =
2416                 (s8) nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
2417
2418         return NL_SKIP;
2419 }
2420
2421
2422 static int nl80211_get_link_noise(struct wpa_driver_nl80211_data *drv,
2423                                   struct wpa_signal_info *sig_change)
2424 {
2425         struct nl_msg *msg;
2426
2427         sig_change->current_noise = 9999;
2428         sig_change->frequency = drv->assoc_freq;
2429
2430         msg = nlmsg_alloc();
2431         if (!msg)
2432                 return -ENOMEM;
2433
2434         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
2435
2436         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2437
2438         return send_and_recv_msgs(drv, msg, get_link_noise, sig_change);
2439  nla_put_failure:
2440         nlmsg_free(msg);
2441         return -ENOBUFS;
2442 }
2443
2444
2445 static int get_noise_for_scan_results(struct nl_msg *msg, void *arg)
2446 {
2447         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2448         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2449         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
2450         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
2451                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
2452                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
2453         };
2454         struct wpa_scan_results *scan_results = arg;
2455         struct wpa_scan_res *scan_res;
2456         size_t i;
2457
2458         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2459                   genlmsg_attrlen(gnlh, 0), NULL);
2460
2461         if (!tb[NL80211_ATTR_SURVEY_INFO]) {
2462                 wpa_printf(MSG_DEBUG, "nl80211: Survey data missing");
2463                 return NL_SKIP;
2464         }
2465
2466         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
2467                              tb[NL80211_ATTR_SURVEY_INFO],
2468                              survey_policy)) {
2469                 wpa_printf(MSG_DEBUG, "nl80211: Failed to parse nested "
2470                            "attributes");
2471                 return NL_SKIP;
2472         }
2473
2474         if (!sinfo[NL80211_SURVEY_INFO_NOISE])
2475                 return NL_SKIP;
2476
2477         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
2478                 return NL_SKIP;
2479
2480         for (i = 0; i < scan_results->num; ++i) {
2481                 scan_res = scan_results->res[i];
2482                 if (!scan_res)
2483                         continue;
2484                 if ((int) nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
2485                     scan_res->freq)
2486                         continue;
2487                 if (!(scan_res->flags & WPA_SCAN_NOISE_INVALID))
2488                         continue;
2489                 scan_res->noise = (s8)
2490                         nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
2491                 scan_res->flags &= ~WPA_SCAN_NOISE_INVALID;
2492         }
2493
2494         return NL_SKIP;
2495 }
2496
2497
2498 static int nl80211_get_noise_for_scan_results(
2499         struct wpa_driver_nl80211_data *drv,
2500         struct wpa_scan_results *scan_res)
2501 {
2502         struct nl_msg *msg;
2503
2504         msg = nlmsg_alloc();
2505         if (!msg)
2506                 return -ENOMEM;
2507
2508         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
2509
2510         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2511
2512         return send_and_recv_msgs(drv, msg, get_noise_for_scan_results,
2513                                   scan_res);
2514  nla_put_failure:
2515         nlmsg_free(msg);
2516         return -ENOBUFS;
2517 }
2518
2519
2520 static void nl80211_cqm_event(struct wpa_driver_nl80211_data *drv,
2521                               struct nlattr *tb[])
2522 {
2523         static struct nla_policy cqm_policy[NL80211_ATTR_CQM_MAX + 1] = {
2524                 [NL80211_ATTR_CQM_RSSI_THOLD] = { .type = NLA_U32 },
2525                 [NL80211_ATTR_CQM_RSSI_HYST] = { .type = NLA_U8 },
2526                 [NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] = { .type = NLA_U32 },
2527                 [NL80211_ATTR_CQM_PKT_LOSS_EVENT] = { .type = NLA_U32 },
2528         };
2529         struct nlattr *cqm[NL80211_ATTR_CQM_MAX + 1];
2530         enum nl80211_cqm_rssi_threshold_event event;
2531         union wpa_event_data ed;
2532         struct wpa_signal_info sig;
2533         int res;
2534
2535         if (tb[NL80211_ATTR_CQM] == NULL ||
2536             nla_parse_nested(cqm, NL80211_ATTR_CQM_MAX, tb[NL80211_ATTR_CQM],
2537                              cqm_policy)) {
2538                 wpa_printf(MSG_DEBUG, "nl80211: Ignore invalid CQM event");
2539                 return;
2540         }
2541
2542         os_memset(&ed, 0, sizeof(ed));
2543
2544         if (cqm[NL80211_ATTR_CQM_PKT_LOSS_EVENT]) {
2545                 if (!tb[NL80211_ATTR_MAC])
2546                         return;
2547                 os_memcpy(ed.low_ack.addr, nla_data(tb[NL80211_ATTR_MAC]),
2548                           ETH_ALEN);
2549                 wpa_supplicant_event(drv->ctx, EVENT_STATION_LOW_ACK, &ed);
2550                 return;
2551         }
2552
2553         if (cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] == NULL)
2554                 return;
2555         event = nla_get_u32(cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]);
2556
2557         if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH) {
2558                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
2559                            "event: RSSI high");
2560                 ed.signal_change.above_threshold = 1;
2561         } else if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW) {
2562                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
2563                            "event: RSSI low");
2564                 ed.signal_change.above_threshold = 0;
2565         } else
2566                 return;
2567
2568         res = nl80211_get_link_signal(drv, &sig);
2569         if (res == 0) {
2570                 ed.signal_change.current_signal = sig.current_signal;
2571                 ed.signal_change.current_txrate = sig.current_txrate;
2572                 wpa_printf(MSG_DEBUG, "nl80211: Signal: %d dBm  txrate: %d",
2573                            sig.current_signal, sig.current_txrate);
2574         }
2575
2576         res = nl80211_get_link_noise(drv, &sig);
2577         if (res == 0) {
2578                 ed.signal_change.current_noise = sig.current_noise;
2579                 wpa_printf(MSG_DEBUG, "nl80211: Noise: %d dBm",
2580                            sig.current_noise);
2581         }
2582
2583         wpa_supplicant_event(drv->ctx, EVENT_SIGNAL_CHANGE, &ed);
2584 }
2585
2586
2587 static void nl80211_new_station_event(struct wpa_driver_nl80211_data *drv,
2588                                       struct nlattr **tb)
2589 {
2590         u8 *addr;
2591         union wpa_event_data data;
2592
2593         if (tb[NL80211_ATTR_MAC] == NULL)
2594                 return;
2595         addr = nla_data(tb[NL80211_ATTR_MAC]);
2596         wpa_printf(MSG_DEBUG, "nl80211: New station " MACSTR, MAC2STR(addr));
2597
2598         if (is_ap_interface(drv->nlmode) && drv->device_ap_sme) {
2599                 u8 *ies = NULL;
2600                 size_t ies_len = 0;
2601                 if (tb[NL80211_ATTR_IE]) {
2602                         ies = nla_data(tb[NL80211_ATTR_IE]);
2603                         ies_len = nla_len(tb[NL80211_ATTR_IE]);
2604                 }
2605                 wpa_hexdump(MSG_DEBUG, "nl80211: Assoc Req IEs", ies, ies_len);
2606                 drv_event_assoc(drv->ctx, addr, ies, ies_len, 0);
2607                 return;
2608         }
2609
2610         if (drv->nlmode != NL80211_IFTYPE_ADHOC)
2611                 return;
2612
2613         os_memset(&data, 0, sizeof(data));
2614         os_memcpy(data.ibss_rsn_start.peer, addr, ETH_ALEN);
2615         wpa_supplicant_event(drv->ctx, EVENT_IBSS_RSN_START, &data);
2616 }
2617
2618
2619 static void nl80211_del_station_event(struct wpa_driver_nl80211_data *drv,
2620                                       struct nlattr **tb)
2621 {
2622         u8 *addr;
2623         union wpa_event_data data;
2624
2625         if (tb[NL80211_ATTR_MAC] == NULL)
2626                 return;
2627         addr = nla_data(tb[NL80211_ATTR_MAC]);
2628         wpa_printf(MSG_DEBUG, "nl80211: Delete station " MACSTR,
2629                    MAC2STR(addr));
2630
2631         if (is_ap_interface(drv->nlmode) && drv->device_ap_sme) {
2632                 drv_event_disassoc(drv->ctx, addr);
2633                 return;
2634         }
2635
2636         if (drv->nlmode != NL80211_IFTYPE_ADHOC)
2637                 return;
2638
2639         os_memset(&data, 0, sizeof(data));
2640         os_memcpy(data.ibss_peer_lost.peer, addr, ETH_ALEN);
2641         wpa_supplicant_event(drv->ctx, EVENT_IBSS_PEER_LOST, &data);
2642 }
2643
2644
2645 static void nl80211_rekey_offload_event(struct wpa_driver_nl80211_data *drv,
2646                                         struct nlattr **tb)
2647 {
2648         struct nlattr *rekey_info[NUM_NL80211_REKEY_DATA];
2649         static struct nla_policy rekey_policy[NUM_NL80211_REKEY_DATA] = {
2650                 [NL80211_REKEY_DATA_KEK] = {
2651                         .minlen = NL80211_KEK_LEN,
2652                         .maxlen = NL80211_KEK_LEN,
2653                 },
2654                 [NL80211_REKEY_DATA_KCK] = {
2655                         .minlen = NL80211_KCK_LEN,
2656                         .maxlen = NL80211_KCK_LEN,
2657                 },
2658                 [NL80211_REKEY_DATA_REPLAY_CTR] = {
2659                         .minlen = NL80211_REPLAY_CTR_LEN,
2660                         .maxlen = NL80211_REPLAY_CTR_LEN,
2661                 },
2662         };
2663         union wpa_event_data data;
2664
2665         if (!tb[NL80211_ATTR_MAC])
2666                 return;
2667         if (!tb[NL80211_ATTR_REKEY_DATA])
2668                 return;
2669         if (nla_parse_nested(rekey_info, MAX_NL80211_REKEY_DATA,
2670                              tb[NL80211_ATTR_REKEY_DATA], rekey_policy))
2671                 return;
2672         if (!rekey_info[NL80211_REKEY_DATA_REPLAY_CTR])
2673                 return;
2674
2675         os_memset(&data, 0, sizeof(data));
2676         data.driver_gtk_rekey.bssid = nla_data(tb[NL80211_ATTR_MAC]);
2677         wpa_printf(MSG_DEBUG, "nl80211: Rekey offload event for BSSID " MACSTR,
2678                    MAC2STR(data.driver_gtk_rekey.bssid));
2679         data.driver_gtk_rekey.replay_ctr =
2680                 nla_data(rekey_info[NL80211_REKEY_DATA_REPLAY_CTR]);
2681         wpa_hexdump(MSG_DEBUG, "nl80211: Rekey offload - Replay Counter",
2682                     data.driver_gtk_rekey.replay_ctr, NL80211_REPLAY_CTR_LEN);
2683         wpa_supplicant_event(drv->ctx, EVENT_DRIVER_GTK_REKEY, &data);
2684 }
2685
2686
2687 static void nl80211_pmksa_candidate_event(struct wpa_driver_nl80211_data *drv,
2688                                           struct nlattr **tb)
2689 {
2690         struct nlattr *cand[NUM_NL80211_PMKSA_CANDIDATE];
2691         static struct nla_policy cand_policy[NUM_NL80211_PMKSA_CANDIDATE] = {
2692                 [NL80211_PMKSA_CANDIDATE_INDEX] = { .type = NLA_U32 },
2693                 [NL80211_PMKSA_CANDIDATE_BSSID] = {
2694                         .minlen = ETH_ALEN,
2695                         .maxlen = ETH_ALEN,
2696                 },
2697                 [NL80211_PMKSA_CANDIDATE_PREAUTH] = { .type = NLA_FLAG },
2698         };
2699         union wpa_event_data data;
2700
2701         wpa_printf(MSG_DEBUG, "nl80211: PMKSA candidate event");
2702
2703         if (!tb[NL80211_ATTR_PMKSA_CANDIDATE])
2704                 return;
2705         if (nla_parse_nested(cand, MAX_NL80211_PMKSA_CANDIDATE,
2706                              tb[NL80211_ATTR_PMKSA_CANDIDATE], cand_policy))
2707                 return;
2708         if (!cand[NL80211_PMKSA_CANDIDATE_INDEX] ||
2709             !cand[NL80211_PMKSA_CANDIDATE_BSSID])
2710                 return;
2711
2712         os_memset(&data, 0, sizeof(data));
2713         os_memcpy(data.pmkid_candidate.bssid,
2714                   nla_data(cand[NL80211_PMKSA_CANDIDATE_BSSID]), ETH_ALEN);
2715         data.pmkid_candidate.index =
2716                 nla_get_u32(cand[NL80211_PMKSA_CANDIDATE_INDEX]);
2717         data.pmkid_candidate.preauth =
2718                 cand[NL80211_PMKSA_CANDIDATE_PREAUTH] != NULL;
2719         wpa_supplicant_event(drv->ctx, EVENT_PMKID_CANDIDATE, &data);
2720 }
2721
2722
2723 static void nl80211_client_probe_event(struct wpa_driver_nl80211_data *drv,
2724                                        struct nlattr **tb)
2725 {
2726         union wpa_event_data data;
2727
2728         wpa_printf(MSG_DEBUG, "nl80211: Probe client event");
2729
2730         if (!tb[NL80211_ATTR_MAC] || !tb[NL80211_ATTR_ACK])
2731                 return;
2732
2733         os_memset(&data, 0, sizeof(data));
2734         os_memcpy(data.client_poll.addr,
2735                   nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2736
2737         wpa_supplicant_event(drv->ctx, EVENT_DRIVER_CLIENT_POLL_OK, &data);
2738 }
2739
2740
2741 static void nl80211_tdls_oper_event(struct wpa_driver_nl80211_data *drv,
2742                                     struct nlattr **tb)
2743 {
2744         union wpa_event_data data;
2745
2746         wpa_printf(MSG_DEBUG, "nl80211: TDLS operation event");
2747
2748         if (!tb[NL80211_ATTR_MAC] || !tb[NL80211_ATTR_TDLS_OPERATION])
2749                 return;
2750
2751         os_memset(&data, 0, sizeof(data));
2752         os_memcpy(data.tdls.peer, nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2753         switch (nla_get_u8(tb[NL80211_ATTR_TDLS_OPERATION])) {
2754         case NL80211_TDLS_SETUP:
2755                 wpa_printf(MSG_DEBUG, "nl80211: TDLS setup request for peer "
2756                            MACSTR, MAC2STR(data.tdls.peer));
2757                 data.tdls.oper = TDLS_REQUEST_SETUP;
2758                 break;
2759         case NL80211_TDLS_TEARDOWN:
2760                 wpa_printf(MSG_DEBUG, "nl80211: TDLS teardown request for peer "
2761                            MACSTR, MAC2STR(data.tdls.peer));
2762                 data.tdls.oper = TDLS_REQUEST_TEARDOWN;
2763                 break;
2764         default:
2765                 wpa_printf(MSG_DEBUG, "nl80211: Unsupported TDLS operatione "
2766                            "event");
2767                 return;
2768         }
2769         if (tb[NL80211_ATTR_REASON_CODE]) {
2770                 data.tdls.reason_code =
2771                         nla_get_u16(tb[NL80211_ATTR_REASON_CODE]);
2772         }
2773
2774         wpa_supplicant_event(drv->ctx, EVENT_TDLS, &data);
2775 }
2776
2777
2778 static void nl80211_stop_ap(struct wpa_driver_nl80211_data *drv,
2779                             struct nlattr **tb)
2780 {
2781         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_UNAVAILABLE, NULL);
2782 }
2783
2784
2785 static void nl80211_connect_failed_event(struct wpa_driver_nl80211_data *drv,
2786                                          struct nlattr **tb)
2787 {
2788         union wpa_event_data data;
2789         u32 reason;
2790
2791         wpa_printf(MSG_DEBUG, "nl80211: Connect failed event");
2792
2793         if (!tb[NL80211_ATTR_MAC] || !tb[NL80211_ATTR_CONN_FAILED_REASON])
2794                 return;
2795
2796         os_memset(&data, 0, sizeof(data));
2797         os_memcpy(data.connect_failed_reason.addr,
2798                   nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2799
2800         reason = nla_get_u32(tb[NL80211_ATTR_CONN_FAILED_REASON]);
2801         switch (reason) {
2802         case NL80211_CONN_FAIL_MAX_CLIENTS:
2803                 wpa_printf(MSG_DEBUG, "nl80211: Max client reached");
2804                 data.connect_failed_reason.code = MAX_CLIENT_REACHED;
2805                 break;
2806         case NL80211_CONN_FAIL_BLOCKED_CLIENT:
2807                 wpa_printf(MSG_DEBUG, "nl80211: Blocked client " MACSTR
2808                            " tried to connect",
2809                            MAC2STR(data.connect_failed_reason.addr));
2810                 data.connect_failed_reason.code = BLOCKED_CLIENT;
2811                 break;
2812         default:
2813                 wpa_printf(MSG_DEBUG, "nl8021l: Unknown connect failed reason "
2814                            "%u", reason);
2815                 return;
2816         }
2817
2818         wpa_supplicant_event(drv->ctx, EVENT_CONNECT_FAILED_REASON, &data);
2819 }
2820
2821
2822 static void nl80211_radar_event(struct wpa_driver_nl80211_data *drv,
2823                                 struct nlattr **tb)
2824 {
2825         union wpa_event_data data;
2826         enum nl80211_radar_event event_type;
2827
2828         if (!tb[NL80211_ATTR_WIPHY_FREQ] || !tb[NL80211_ATTR_RADAR_EVENT])
2829                 return;
2830
2831         os_memset(&data, 0, sizeof(data));
2832         data.dfs_event.freq = nla_get_u32(tb[NL80211_ATTR_WIPHY_FREQ]);
2833         event_type = nla_get_u32(tb[NL80211_ATTR_RADAR_EVENT]);
2834
2835         /* Check HT params */
2836         if (tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE]) {
2837                 data.dfs_event.ht_enabled = 1;
2838                 data.dfs_event.chan_offset = 0;
2839
2840                 switch (nla_get_u32(tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE])) {
2841                 case NL80211_CHAN_NO_HT:
2842                         data.dfs_event.ht_enabled = 0;
2843                         break;
2844                 case NL80211_CHAN_HT20:
2845                         break;
2846                 case NL80211_CHAN_HT40PLUS:
2847                         data.dfs_event.chan_offset = 1;
2848                         break;
2849                 case NL80211_CHAN_HT40MINUS:
2850                         data.dfs_event.chan_offset = -1;
2851                         break;
2852                 }
2853         }
2854
2855         /* Get VHT params */
2856         if (tb[NL80211_ATTR_CHANNEL_WIDTH])
2857                 data.dfs_event.chan_width =
2858                         convert2width(nla_get_u32(
2859                                               tb[NL80211_ATTR_CHANNEL_WIDTH]));
2860         if (tb[NL80211_ATTR_CENTER_FREQ1])
2861                 data.dfs_event.cf1 = nla_get_u32(tb[NL80211_ATTR_CENTER_FREQ1]);
2862         if (tb[NL80211_ATTR_CENTER_FREQ2])
2863                 data.dfs_event.cf2 = nla_get_u32(tb[NL80211_ATTR_CENTER_FREQ2]);
2864
2865         wpa_printf(MSG_DEBUG, "nl80211: DFS event on freq %d MHz, ht: %d, offset: %d, width: %d, cf1: %dMHz, cf2: %dMHz",
2866                    data.dfs_event.freq, data.dfs_event.ht_enabled,
2867                    data.dfs_event.chan_offset, data.dfs_event.chan_width,
2868                    data.dfs_event.cf1, data.dfs_event.cf2);
2869
2870         switch (event_type) {
2871         case NL80211_RADAR_DETECTED:
2872                 wpa_supplicant_event(drv->ctx, EVENT_DFS_RADAR_DETECTED, &data);
2873                 break;
2874         case NL80211_RADAR_CAC_FINISHED:
2875                 wpa_supplicant_event(drv->ctx, EVENT_DFS_CAC_FINISHED, &data);
2876                 break;
2877         case NL80211_RADAR_CAC_ABORTED:
2878                 wpa_supplicant_event(drv->ctx, EVENT_DFS_CAC_ABORTED, &data);
2879                 break;
2880         case NL80211_RADAR_NOP_FINISHED:
2881                 wpa_supplicant_event(drv->ctx, EVENT_DFS_NOP_FINISHED, &data);
2882                 break;
2883         default:
2884                 wpa_printf(MSG_DEBUG, "nl80211: Unknown radar event %d "
2885                            "received", event_type);
2886                 break;
2887         }
2888 }
2889
2890
2891 static void nl80211_spurious_frame(struct i802_bss *bss, struct nlattr **tb,
2892                                    int wds)
2893 {
2894         struct wpa_driver_nl80211_data *drv = bss->drv;
2895         union wpa_event_data event;
2896
2897         if (!tb[NL80211_ATTR_MAC])
2898                 return;
2899
2900         os_memset(&event, 0, sizeof(event));
2901         event.rx_from_unknown.bssid = bss->addr;
2902         event.rx_from_unknown.addr = nla_data(tb[NL80211_ATTR_MAC]);
2903         event.rx_from_unknown.wds = wds;
2904
2905         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
2906 }
2907
2908
2909 static void qca_nl80211_avoid_freq(struct wpa_driver_nl80211_data *drv,
2910                                    const u8 *data, size_t len)
2911 {
2912         u32 i, count;
2913         union wpa_event_data event;
2914         struct wpa_freq_range *range = NULL;
2915         const struct qca_avoid_freq_list *freq_range;
2916
2917         freq_range = (const struct qca_avoid_freq_list *) data;
2918         if (len < sizeof(freq_range->count))
2919                 return;
2920
2921         count = freq_range->count;
2922         if (len < sizeof(freq_range->count) +
2923             count * sizeof(struct qca_avoid_freq_range)) {
2924                 wpa_printf(MSG_DEBUG, "nl80211: Ignored too short avoid frequency list (len=%u)",
2925                            (unsigned int) len);
2926                 return;
2927         }
2928
2929         if (count > 0) {
2930                 range = os_calloc(count, sizeof(struct wpa_freq_range));
2931                 if (range == NULL)
2932                         return;
2933         }
2934
2935         os_memset(&event, 0, sizeof(event));
2936         for (i = 0; i < count; i++) {
2937                 unsigned int idx = event.freq_range.num;
2938                 range[idx].min = freq_range->range[i].start_freq;
2939                 range[idx].max = freq_range->range[i].end_freq;
2940                 wpa_printf(MSG_DEBUG, "nl80211: Avoid frequency range: %u-%u",
2941                            range[idx].min, range[idx].max);
2942                 if (range[idx].min > range[idx].max) {
2943                         wpa_printf(MSG_DEBUG, "nl80211: Ignore invalid frequency range");
2944                         continue;
2945                 }
2946                 event.freq_range.num++;
2947         }
2948         event.freq_range.range = range;
2949
2950         wpa_supplicant_event(drv->ctx, EVENT_AVOID_FREQUENCIES, &event);
2951
2952         os_free(range);
2953 }
2954
2955
2956 static void nl80211_vendor_event_qca(struct wpa_driver_nl80211_data *drv,
2957                                      u32 subcmd, u8 *data, size_t len)
2958 {
2959         switch (subcmd) {
2960         case QCA_NL80211_VENDOR_SUBCMD_AVOID_FREQUENCY:
2961                 qca_nl80211_avoid_freq(drv, data, len);
2962                 break;
2963         default:
2964                 wpa_printf(MSG_DEBUG,
2965                            "nl80211: Ignore unsupported QCA vendor event %u",
2966                            subcmd);
2967                 break;
2968         }
2969 }
2970
2971
2972 static void nl80211_vendor_event(struct wpa_driver_nl80211_data *drv,
2973                                  struct nlattr **tb)
2974 {
2975         u32 vendor_id, subcmd, wiphy = 0;
2976         int wiphy_idx;
2977         u8 *data = NULL;
2978         size_t len = 0;
2979
2980         if (!tb[NL80211_ATTR_VENDOR_ID] ||
2981             !tb[NL80211_ATTR_VENDOR_SUBCMD])
2982                 return;
2983
2984         vendor_id = nla_get_u32(tb[NL80211_ATTR_VENDOR_ID]);
2985         subcmd = nla_get_u32(tb[NL80211_ATTR_VENDOR_SUBCMD]);
2986
2987         if (tb[NL80211_ATTR_WIPHY])
2988                 wiphy = nla_get_u32(tb[NL80211_ATTR_WIPHY]);
2989
2990         wpa_printf(MSG_DEBUG, "nl80211: Vendor event: wiphy=%u vendor_id=0x%x subcmd=%u",
2991                    wiphy, vendor_id, subcmd);
2992
2993         if (tb[NL80211_ATTR_VENDOR_DATA]) {
2994                 data = nla_data(tb[NL80211_ATTR_VENDOR_DATA]);
2995                 len = nla_len(tb[NL80211_ATTR_VENDOR_DATA]);
2996                 wpa_hexdump(MSG_MSGDUMP, "nl80211: Vendor data", data, len);
2997         }
2998
2999         wiphy_idx = nl80211_get_wiphy_index(drv->first_bss);
3000         if (wiphy_idx >= 0 && wiphy_idx != (int) wiphy) {
3001                 wpa_printf(MSG_DEBUG, "nl80211: Ignore vendor event for foreign wiphy %u (own: %d)",
3002                            wiphy, wiphy_idx);
3003                 return;
3004         }
3005
3006         switch (vendor_id) {
3007         case OUI_QCA:
3008                 nl80211_vendor_event_qca(drv, subcmd, data, len);
3009                 break;
3010         default:
3011                 wpa_printf(MSG_DEBUG, "nl80211: Ignore unsupported vendor event");
3012                 break;
3013         }
3014 }
3015
3016
3017 static void nl80211_reg_change_event(struct wpa_driver_nl80211_data *drv,
3018                                      struct nlattr *tb[])
3019 {
3020         union wpa_event_data data;
3021         enum nl80211_reg_initiator init;
3022
3023         wpa_printf(MSG_DEBUG, "nl80211: Regulatory domain change");
3024
3025         if (tb[NL80211_ATTR_REG_INITIATOR] == NULL)
3026                 return;
3027
3028         os_memset(&data, 0, sizeof(data));
3029         init = nla_get_u8(tb[NL80211_ATTR_REG_INITIATOR]);
3030         wpa_printf(MSG_DEBUG, " * initiator=%d", init);
3031         switch (init) {
3032         case NL80211_REGDOM_SET_BY_CORE:
3033                 data.channel_list_changed.initiator = REGDOM_SET_BY_CORE;
3034                 break;
3035         case NL80211_REGDOM_SET_BY_USER:
3036                 data.channel_list_changed.initiator = REGDOM_SET_BY_USER;
3037                 break;
3038         case NL80211_REGDOM_SET_BY_DRIVER:
3039                 data.channel_list_changed.initiator = REGDOM_SET_BY_DRIVER;
3040                 break;
3041         case NL80211_REGDOM_SET_BY_COUNTRY_IE:
3042                 data.channel_list_changed.initiator = REGDOM_SET_BY_COUNTRY_IE;
3043                 break;
3044         }
3045
3046         if (tb[NL80211_ATTR_REG_TYPE]) {
3047                 enum nl80211_reg_type type;
3048                 type = nla_get_u8(tb[NL80211_ATTR_REG_TYPE]);
3049                 wpa_printf(MSG_DEBUG, " * type=%d", type);
3050                 switch (type) {
3051                 case NL80211_REGDOM_TYPE_COUNTRY:
3052                         data.channel_list_changed.type = REGDOM_TYPE_COUNTRY;
3053                         break;
3054                 case NL80211_REGDOM_TYPE_WORLD:
3055                         data.channel_list_changed.type = REGDOM_TYPE_WORLD;
3056                         break;
3057                 case NL80211_REGDOM_TYPE_CUSTOM_WORLD:
3058                         data.channel_list_changed.type =
3059                                 REGDOM_TYPE_CUSTOM_WORLD;
3060                         break;
3061                 case NL80211_REGDOM_TYPE_INTERSECTION:
3062                         data.channel_list_changed.type =
3063                                 REGDOM_TYPE_INTERSECTION;
3064                         break;
3065                 }
3066         }
3067
3068         if (tb[NL80211_ATTR_REG_ALPHA2]) {
3069                 os_strlcpy(data.channel_list_changed.alpha2,
3070                            nla_get_string(tb[NL80211_ATTR_REG_ALPHA2]),
3071                            sizeof(data.channel_list_changed.alpha2));
3072                 wpa_printf(MSG_DEBUG, " * alpha2=%s",
3073                            data.channel_list_changed.alpha2);
3074         }
3075
3076         wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED, &data);
3077 }
3078
3079
3080 static void do_process_drv_event(struct i802_bss *bss, int cmd,
3081                                  struct nlattr **tb)
3082 {
3083         struct wpa_driver_nl80211_data *drv = bss->drv;
3084         union wpa_event_data data;
3085
3086         wpa_printf(MSG_DEBUG, "nl80211: Drv Event %d (%s) received for %s",
3087                    cmd, nl80211_command_to_string(cmd), bss->ifname);
3088
3089         if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED &&
3090             (cmd == NL80211_CMD_NEW_SCAN_RESULTS ||
3091              cmd == NL80211_CMD_SCAN_ABORTED)) {
3092                 wpa_driver_nl80211_set_mode(drv->first_bss,
3093                                             drv->ap_scan_as_station);
3094                 drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
3095         }
3096
3097         switch (cmd) {
3098         case NL80211_CMD_TRIGGER_SCAN:
3099                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Scan trigger");
3100                 drv->scan_state = SCAN_STARTED;
3101                 if (drv->scan_for_auth) {
3102                         /*
3103                          * Cannot indicate EVENT_SCAN_STARTED here since we skip
3104                          * EVENT_SCAN_RESULTS in scan_for_auth case and the
3105                          * upper layer implementation could get confused about
3106                          * scanning state.
3107                          */
3108                         wpa_printf(MSG_DEBUG, "nl80211: Do not indicate scan-start event due to internal scan_for_auth");
3109                         break;
3110                 }
3111                 wpa_supplicant_event(drv->ctx, EVENT_SCAN_STARTED, NULL);
3112                 break;
3113         case NL80211_CMD_START_SCHED_SCAN:
3114                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Sched scan started");
3115                 drv->scan_state = SCHED_SCAN_STARTED;
3116                 break;
3117         case NL80211_CMD_SCHED_SCAN_STOPPED:
3118                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Sched scan stopped");
3119                 drv->scan_state = SCHED_SCAN_STOPPED;
3120                 wpa_supplicant_event(drv->ctx, EVENT_SCHED_SCAN_STOPPED, NULL);
3121                 break;
3122         case NL80211_CMD_NEW_SCAN_RESULTS:
3123                 wpa_dbg(drv->ctx, MSG_DEBUG,
3124                         "nl80211: New scan results available");
3125                 drv->scan_state = SCAN_COMPLETED;
3126                 drv->scan_complete_events = 1;
3127                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
3128                                      drv->ctx);
3129                 send_scan_event(drv, 0, tb);
3130                 break;
3131         case NL80211_CMD_SCHED_SCAN_RESULTS:
3132                 wpa_dbg(drv->ctx, MSG_DEBUG,
3133                         "nl80211: New sched scan results available");
3134                 drv->scan_state = SCHED_SCAN_RESULTS;
3135                 send_scan_event(drv, 0, tb);
3136                 break;
3137         case NL80211_CMD_SCAN_ABORTED:
3138                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Scan aborted");
3139                 drv->scan_state = SCAN_ABORTED;
3140                 /*
3141                  * Need to indicate that scan results are available in order
3142                  * not to make wpa_supplicant stop its scanning.
3143                  */
3144                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
3145                                      drv->ctx);
3146                 send_scan_event(drv, 1, tb);
3147                 break;
3148         case NL80211_CMD_AUTHENTICATE:
3149         case NL80211_CMD_ASSOCIATE:
3150         case NL80211_CMD_DEAUTHENTICATE:
3151         case NL80211_CMD_DISASSOCIATE:
3152         case NL80211_CMD_FRAME_TX_STATUS:
3153         case NL80211_CMD_UNPROT_DEAUTHENTICATE:
3154         case NL80211_CMD_UNPROT_DISASSOCIATE:
3155                 mlme_event(bss, cmd, tb[NL80211_ATTR_FRAME],
3156                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
3157                            tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
3158                            tb[NL80211_ATTR_COOKIE],
3159                            tb[NL80211_ATTR_RX_SIGNAL_DBM]);
3160                 break;
3161         case NL80211_CMD_CONNECT:
3162         case NL80211_CMD_ROAM:
3163                 mlme_event_connect(drv, cmd,
3164                                    tb[NL80211_ATTR_STATUS_CODE],
3165                                    tb[NL80211_ATTR_MAC],
3166                                    tb[NL80211_ATTR_REQ_IE],
3167                                    tb[NL80211_ATTR_RESP_IE]);
3168                 break;
3169         case NL80211_CMD_CH_SWITCH_NOTIFY:
3170                 mlme_event_ch_switch(drv,
3171                                      tb[NL80211_ATTR_IFINDEX],
3172                                      tb[NL80211_ATTR_WIPHY_FREQ],
3173                                      tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE],
3174                                      tb[NL80211_ATTR_CHANNEL_WIDTH],
3175                                      tb[NL80211_ATTR_CENTER_FREQ1],
3176                                      tb[NL80211_ATTR_CENTER_FREQ2]);
3177                 break;
3178         case NL80211_CMD_DISCONNECT:
3179                 mlme_event_disconnect(drv, tb[NL80211_ATTR_REASON_CODE],
3180                                       tb[NL80211_ATTR_MAC],
3181                                       tb[NL80211_ATTR_DISCONNECTED_BY_AP]);
3182                 break;
3183         case NL80211_CMD_MICHAEL_MIC_FAILURE:
3184                 mlme_event_michael_mic_failure(bss, tb);
3185                 break;
3186         case NL80211_CMD_JOIN_IBSS:
3187                 mlme_event_join_ibss(drv, tb);
3188                 break;
3189         case NL80211_CMD_REMAIN_ON_CHANNEL:
3190                 mlme_event_remain_on_channel(drv, 0, tb);
3191                 break;
3192         case NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL:
3193                 mlme_event_remain_on_channel(drv, 1, tb);
3194                 break;
3195         case NL80211_CMD_NOTIFY_CQM:
3196                 nl80211_cqm_event(drv, tb);
3197                 break;
3198         case NL80211_CMD_REG_CHANGE:
3199                 nl80211_reg_change_event(drv, tb);
3200                 break;
3201         case NL80211_CMD_REG_BEACON_HINT:
3202                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory beacon hint");
3203                 os_memset(&data, 0, sizeof(data));
3204                 data.channel_list_changed.initiator = REGDOM_BEACON_HINT;
3205                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
3206                                      &data);
3207                 break;
3208         case NL80211_CMD_NEW_STATION:
3209                 nl80211_new_station_event(drv, tb);
3210                 break;
3211         case NL80211_CMD_DEL_STATION:
3212                 nl80211_del_station_event(drv, tb);
3213                 break;
3214         case NL80211_CMD_SET_REKEY_OFFLOAD:
3215                 nl80211_rekey_offload_event(drv, tb);
3216                 break;
3217         case NL80211_CMD_PMKSA_CANDIDATE:
3218                 nl80211_pmksa_candidate_event(drv, tb);
3219                 break;
3220         case NL80211_CMD_PROBE_CLIENT:
3221                 nl80211_client_probe_event(drv, tb);
3222                 break;
3223         case NL80211_CMD_TDLS_OPER:
3224                 nl80211_tdls_oper_event(drv, tb);
3225                 break;
3226         case NL80211_CMD_CONN_FAILED:
3227                 nl80211_connect_failed_event(drv, tb);
3228                 break;
3229         case NL80211_CMD_FT_EVENT:
3230                 mlme_event_ft_event(drv, tb);
3231                 break;
3232         case NL80211_CMD_RADAR_DETECT:
3233                 nl80211_radar_event(drv, tb);
3234                 break;
3235         case NL80211_CMD_STOP_AP:
3236                 nl80211_stop_ap(drv, tb);
3237                 break;
3238         case NL80211_CMD_VENDOR:
3239                 nl80211_vendor_event(drv, tb);
3240                 break;
3241         default:
3242                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Ignored unknown event "
3243                         "(cmd=%d)", cmd);
3244                 break;
3245         }
3246 }
3247
3248
3249 static int process_drv_event(struct nl_msg *msg, void *arg)
3250 {
3251         struct wpa_driver_nl80211_data *drv = arg;
3252         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3253         struct nlattr *tb[NL80211_ATTR_MAX + 1];
3254         struct i802_bss *bss;
3255         int ifidx = -1;
3256
3257         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3258                   genlmsg_attrlen(gnlh, 0), NULL);
3259
3260         if (tb[NL80211_ATTR_IFINDEX]) {
3261                 ifidx = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
3262
3263                 for (bss = drv->first_bss; bss; bss = bss->next)
3264                         if (ifidx == -1 || ifidx == bss->ifindex) {
3265                                 do_process_drv_event(bss, gnlh->cmd, tb);
3266                                 return NL_SKIP;
3267                         }
3268                 wpa_printf(MSG_DEBUG,
3269                            "nl80211: Ignored event (cmd=%d) for foreign interface (ifindex %d)",
3270                            gnlh->cmd, ifidx);
3271         } else if (tb[NL80211_ATTR_WDEV]) {
3272                 u64 wdev_id = nla_get_u64(tb[NL80211_ATTR_WDEV]);
3273                 wpa_printf(MSG_DEBUG, "nl80211: Process event on P2P device");
3274                 for (bss = drv->first_bss; bss; bss = bss->next) {
3275                         if (bss->wdev_id_set && wdev_id == bss->wdev_id) {
3276                                 do_process_drv_event(bss, gnlh->cmd, tb);
3277                                 return NL_SKIP;
3278                         }
3279                 }
3280                 wpa_printf(MSG_DEBUG,
3281                            "nl80211: Ignored event (cmd=%d) for foreign interface (wdev 0x%llx)",
3282                            gnlh->cmd, (long long unsigned int) wdev_id);
3283         }
3284
3285         return NL_SKIP;
3286 }
3287
3288
3289 static int process_global_event(struct nl_msg *msg, void *arg)
3290 {
3291         struct nl80211_global *global = arg;
3292         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3293         struct nlattr *tb[NL80211_ATTR_MAX + 1];
3294         struct wpa_driver_nl80211_data *drv, *tmp;
3295         int ifidx = -1;
3296         struct i802_bss *bss;
3297         u64 wdev_id = 0;
3298         int wdev_id_set = 0;
3299
3300         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3301                   genlmsg_attrlen(gnlh, 0), NULL);
3302
3303         if (tb[NL80211_ATTR_IFINDEX])
3304                 ifidx = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
3305         else if (tb[NL80211_ATTR_WDEV]) {
3306                 wdev_id = nla_get_u64(tb[NL80211_ATTR_WDEV]);
3307                 wdev_id_set = 1;
3308         }
3309
3310         dl_list_for_each_safe(drv, tmp, &global->interfaces,
3311                               struct wpa_driver_nl80211_data, list) {
3312                 for (bss = drv->first_bss; bss; bss = bss->next) {
3313                         if ((ifidx == -1 && !wdev_id_set) ||
3314                             ifidx == bss->ifindex ||
3315                             (wdev_id_set && bss->wdev_id_set &&
3316                              wdev_id == bss->wdev_id)) {
3317                                 do_process_drv_event(bss, gnlh->cmd, tb);
3318                                 return NL_SKIP;
3319                         }
3320                 }
3321         }
3322
3323         return NL_SKIP;
3324 }
3325
3326
3327 static int process_bss_event(struct nl_msg *msg, void *arg)
3328 {
3329         struct i802_bss *bss = arg;
3330         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3331         struct nlattr *tb[NL80211_ATTR_MAX + 1];
3332
3333         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3334                   genlmsg_attrlen(gnlh, 0), NULL);
3335
3336         wpa_printf(MSG_DEBUG, "nl80211: BSS Event %d (%s) received for %s",
3337                    gnlh->cmd, nl80211_command_to_string(gnlh->cmd),
3338                    bss->ifname);
3339
3340         switch (gnlh->cmd) {
3341         case NL80211_CMD_FRAME:
3342         case NL80211_CMD_FRAME_TX_STATUS:
3343                 mlme_event(bss, gnlh->cmd, tb[NL80211_ATTR_FRAME],
3344                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
3345                            tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
3346                            tb[NL80211_ATTR_COOKIE],
3347                            tb[NL80211_ATTR_RX_SIGNAL_DBM]);
3348                 break;
3349         case NL80211_CMD_UNEXPECTED_FRAME:
3350                 nl80211_spurious_frame(bss, tb, 0);
3351                 break;
3352         case NL80211_CMD_UNEXPECTED_4ADDR_FRAME:
3353                 nl80211_spurious_frame(bss, tb, 1);
3354                 break;
3355         default:
3356                 wpa_printf(MSG_DEBUG, "nl80211: Ignored unknown event "
3357                            "(cmd=%d)", gnlh->cmd);
3358                 break;
3359         }
3360
3361         return NL_SKIP;
3362 }
3363
3364
3365 static void wpa_driver_nl80211_event_receive(int sock, void *eloop_ctx,
3366                                              void *handle)
3367 {
3368         struct nl_cb *cb = eloop_ctx;
3369         int res;
3370
3371         wpa_printf(MSG_MSGDUMP, "nl80211: Event message available");
3372
3373         res = nl_recvmsgs(handle, cb);
3374         if (res < 0) {
3375                 wpa_printf(MSG_INFO, "nl80211: %s->nl_recvmsgs failed: %d",
3376                            __func__, res);
3377         }
3378 }
3379
3380
3381 /**
3382  * wpa_driver_nl80211_set_country - ask nl80211 to set the regulatory domain
3383  * @priv: driver_nl80211 private data
3384  * @alpha2_arg: country to which to switch to
3385  * Returns: 0 on success, -1 on failure
3386  *
3387  * This asks nl80211 to set the regulatory domain for given
3388  * country ISO / IEC alpha2.
3389  */
3390 static int wpa_driver_nl80211_set_country(void *priv, const char *alpha2_arg)
3391 {
3392         struct i802_bss *bss = priv;
3393         struct wpa_driver_nl80211_data *drv = bss->drv;
3394         char alpha2[3];
3395         struct nl_msg *msg;
3396
3397         msg = nlmsg_alloc();
3398         if (!msg)
3399                 return -ENOMEM;
3400
3401         alpha2[0] = alpha2_arg[0];
3402         alpha2[1] = alpha2_arg[1];
3403         alpha2[2] = '\0';
3404
3405         nl80211_cmd(drv, msg, 0, NL80211_CMD_REQ_SET_REG);
3406
3407         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
3408         if (send_and_recv_msgs(drv, msg, NULL, NULL))
3409                 return -EINVAL;
3410         return 0;
3411 nla_put_failure:
3412         nlmsg_free(msg);
3413         return -EINVAL;
3414 }
3415
3416
3417 static int nl80211_get_country(struct nl_msg *msg, void *arg)
3418 {
3419         char *alpha2 = arg;
3420         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
3421         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3422
3423         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3424                   genlmsg_attrlen(gnlh, 0), NULL);
3425         if (!tb_msg[NL80211_ATTR_REG_ALPHA2]) {
3426                 wpa_printf(MSG_DEBUG, "nl80211: No country information available");
3427                 return NL_SKIP;
3428         }
3429         os_strlcpy(alpha2, nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]), 3);
3430         return NL_SKIP;
3431 }
3432
3433
3434 static int wpa_driver_nl80211_get_country(void *priv, char *alpha2)
3435 {
3436         struct i802_bss *bss = priv;
3437         struct wpa_driver_nl80211_data *drv = bss->drv;
3438         struct nl_msg *msg;
3439         int ret;
3440
3441         msg = nlmsg_alloc();
3442         if (!msg)
3443                 return -ENOMEM;
3444
3445         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_REG);
3446         alpha2[0] = '\0';
3447         ret = send_and_recv_msgs(drv, msg, nl80211_get_country, alpha2);
3448         if (!alpha2[0])
3449                 ret = -1;
3450
3451         return ret;
3452 }
3453
3454
3455 static int protocol_feature_handler(struct nl_msg *msg, void *arg)
3456 {
3457         u32 *feat = arg;
3458         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
3459         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3460
3461         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3462                   genlmsg_attrlen(gnlh, 0), NULL);
3463
3464         if (tb_msg[NL80211_ATTR_PROTOCOL_FEATURES])
3465                 *feat = nla_get_u32(tb_msg[NL80211_ATTR_PROTOCOL_FEATURES]);
3466
3467         return NL_SKIP;
3468 }
3469
3470
3471 static u32 get_nl80211_protocol_features(struct wpa_driver_nl80211_data *drv)
3472 {
3473         u32 feat = 0;
3474         struct nl_msg *msg;
3475
3476         msg = nlmsg_alloc();
3477         if (!msg)
3478                 goto nla_put_failure;
3479
3480         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_PROTOCOL_FEATURES);
3481         if (send_and_recv_msgs(drv, msg, protocol_feature_handler, &feat) == 0)
3482                 return feat;
3483
3484         msg = NULL;
3485 nla_put_failure:
3486         nlmsg_free(msg);
3487         return 0;
3488 }
3489
3490
3491 struct wiphy_info_data {
3492         struct wpa_driver_nl80211_data *drv;
3493         struct wpa_driver_capa *capa;
3494
3495         unsigned int num_multichan_concurrent;
3496
3497         unsigned int error:1;
3498         unsigned int device_ap_sme:1;
3499         unsigned int poll_command_supported:1;
3500         unsigned int data_tx_status:1;
3501         unsigned int monitor_supported:1;
3502         unsigned int auth_supported:1;
3503         unsigned int connect_supported:1;
3504         unsigned int p2p_go_supported:1;
3505         unsigned int p2p_client_supported:1;
3506         unsigned int p2p_concurrent:1;
3507         unsigned int channel_switch_supported:1;
3508         unsigned int set_qos_map_supported:1;
3509         unsigned int have_low_prio_scan:1;
3510 };
3511
3512
3513 static unsigned int probe_resp_offload_support(int supp_protocols)
3514 {
3515         unsigned int prot = 0;
3516
3517         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS)
3518                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS;
3519         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2)
3520                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS2;
3521         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P)
3522                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_P2P;
3523         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_80211U)
3524                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_INTERWORKING;
3525
3526         return prot;
3527 }
3528
3529
3530 static void wiphy_info_supported_iftypes(struct wiphy_info_data *info,
3531                                          struct nlattr *tb)
3532 {
3533         struct nlattr *nl_mode;
3534         int i;
3535
3536         if (tb == NULL)
3537                 return;
3538
3539         nla_for_each_nested(nl_mode, tb, i) {
3540                 switch (nla_type(nl_mode)) {
3541                 case NL80211_IFTYPE_AP:
3542                         info->capa->flags |= WPA_DRIVER_FLAGS_AP;
3543                         break;
3544                 case NL80211_IFTYPE_MESH_POINT:
3545                         info->capa->flags |= WPA_DRIVER_FLAGS_MESH;
3546                         break;
3547                 case NL80211_IFTYPE_ADHOC:
3548                         info->capa->flags |= WPA_DRIVER_FLAGS_IBSS;
3549                         break;
3550                 case NL80211_IFTYPE_P2P_DEVICE:
3551                         info->capa->flags |=
3552                                 WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE;
3553                         break;
3554                 case NL80211_IFTYPE_P2P_GO:
3555                         info->p2p_go_supported = 1;
3556                         break;
3557                 case NL80211_IFTYPE_P2P_CLIENT:
3558                         info->p2p_client_supported = 1;
3559                         break;
3560                 case NL80211_IFTYPE_MONITOR:
3561                         info->monitor_supported = 1;
3562                         break;
3563                 }
3564         }
3565 }
3566
3567
3568 static int wiphy_info_iface_comb_process(struct wiphy_info_data *info,
3569                                          struct nlattr *nl_combi)
3570 {
3571         struct nlattr *tb_comb[NUM_NL80211_IFACE_COMB];
3572         struct nlattr *tb_limit[NUM_NL80211_IFACE_LIMIT];
3573         struct nlattr *nl_limit, *nl_mode;
3574         int err, rem_limit, rem_mode;
3575         int combination_has_p2p = 0, combination_has_mgd = 0;
3576         static struct nla_policy
3577         iface_combination_policy[NUM_NL80211_IFACE_COMB] = {
3578                 [NL80211_IFACE_COMB_LIMITS] = { .type = NLA_NESTED },
3579                 [NL80211_IFACE_COMB_MAXNUM] = { .type = NLA_U32 },
3580                 [NL80211_IFACE_COMB_STA_AP_BI_MATCH] = { .type = NLA_FLAG },
3581                 [NL80211_IFACE_COMB_NUM_CHANNELS] = { .type = NLA_U32 },
3582                 [NL80211_IFACE_COMB_RADAR_DETECT_WIDTHS] = { .type = NLA_U32 },
3583         },
3584         iface_limit_policy[NUM_NL80211_IFACE_LIMIT] = {
3585                 [NL80211_IFACE_LIMIT_TYPES] = { .type = NLA_NESTED },
3586                 [NL80211_IFACE_LIMIT_MAX] = { .type = NLA_U32 },
3587         };
3588
3589         err = nla_parse_nested(tb_comb, MAX_NL80211_IFACE_COMB,
3590                                nl_combi, iface_combination_policy);
3591         if (err || !tb_comb[NL80211_IFACE_COMB_LIMITS] ||
3592             !tb_comb[NL80211_IFACE_COMB_MAXNUM] ||
3593             !tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS])
3594                 return 0; /* broken combination */
3595
3596         if (tb_comb[NL80211_IFACE_COMB_RADAR_DETECT_WIDTHS])
3597                 info->capa->flags |= WPA_DRIVER_FLAGS_RADAR;
3598
3599         nla_for_each_nested(nl_limit, tb_comb[NL80211_IFACE_COMB_LIMITS],
3600                             rem_limit) {
3601                 err = nla_parse_nested(tb_limit, MAX_NL80211_IFACE_LIMIT,
3602                                        nl_limit, iface_limit_policy);
3603                 if (err || !tb_limit[NL80211_IFACE_LIMIT_TYPES])
3604                         return 0; /* broken combination */
3605
3606                 nla_for_each_nested(nl_mode,
3607                                     tb_limit[NL80211_IFACE_LIMIT_TYPES],
3608                                     rem_mode) {
3609                         int ift = nla_type(nl_mode);
3610                         if (ift == NL80211_IFTYPE_P2P_GO ||
3611                             ift == NL80211_IFTYPE_P2P_CLIENT)
3612                                 combination_has_p2p = 1;
3613                         if (ift == NL80211_IFTYPE_STATION)
3614                                 combination_has_mgd = 1;
3615                 }
3616                 if (combination_has_p2p && combination_has_mgd)
3617                         break;
3618         }
3619
3620         if (combination_has_p2p && combination_has_mgd) {
3621                 unsigned int num_channels =
3622                         nla_get_u32(tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS]);
3623
3624                 info->p2p_concurrent = 1;
3625                 if (info->num_multichan_concurrent < num_channels)
3626                         info->num_multichan_concurrent = num_channels;
3627         }
3628
3629         return 0;
3630 }
3631
3632
3633 static void wiphy_info_iface_comb(struct wiphy_info_data *info,
3634                                   struct nlattr *tb)
3635 {
3636         struct nlattr *nl_combi;
3637         int rem_combi;
3638
3639         if (tb == NULL)
3640                 return;
3641
3642         nla_for_each_nested(nl_combi, tb, rem_combi) {
3643                 if (wiphy_info_iface_comb_process(info, nl_combi) > 0)
3644                         break;
3645         }
3646 }
3647
3648
3649 static void wiphy_info_supp_cmds(struct wiphy_info_data *info,
3650                                  struct nlattr *tb)
3651 {
3652         struct nlattr *nl_cmd;
3653         int i;
3654
3655         if (tb == NULL)
3656                 return;
3657
3658         nla_for_each_nested(nl_cmd, tb, i) {
3659                 switch (nla_get_u32(nl_cmd)) {
3660                 case NL80211_CMD_AUTHENTICATE:
3661                         info->auth_supported = 1;
3662                         break;
3663                 case NL80211_CMD_CONNECT:
3664                         info->connect_supported = 1;
3665                         break;
3666                 case NL80211_CMD_START_SCHED_SCAN:
3667                         info->capa->sched_scan_supported = 1;
3668                         break;
3669                 case NL80211_CMD_PROBE_CLIENT:
3670                         info->poll_command_supported = 1;
3671                         break;
3672                 case NL80211_CMD_CHANNEL_SWITCH:
3673                         info->channel_switch_supported = 1;
3674                         break;
3675                 case NL80211_CMD_SET_QOS_MAP:
3676                         info->set_qos_map_supported = 1;
3677                         break;
3678                 }
3679         }
3680 }
3681
3682
3683 static void wiphy_info_cipher_suites(struct wiphy_info_data *info,
3684                                      struct nlattr *tb)
3685 {
3686         int i, num;
3687         u32 *ciphers;
3688
3689         if (tb == NULL)
3690                 return;
3691
3692         num = nla_len(tb) / sizeof(u32);
3693         ciphers = nla_data(tb);
3694         for (i = 0; i < num; i++) {
3695                 u32 c = ciphers[i];
3696
3697                 wpa_printf(MSG_DEBUG, "nl80211: Supported cipher %02x-%02x-%02x:%d",
3698                            c >> 24, (c >> 16) & 0xff,
3699                            (c >> 8) & 0xff, c & 0xff);
3700                 switch (c) {
3701                 case WLAN_CIPHER_SUITE_CCMP_256:
3702                         info->capa->enc |= WPA_DRIVER_CAPA_ENC_CCMP_256;
3703                         break;
3704                 case WLAN_CIPHER_SUITE_GCMP_256:
3705                         info->capa->enc |= WPA_DRIVER_CAPA_ENC_GCMP_256;
3706                         break;
3707                 case WLAN_CIPHER_SUITE_CCMP:
3708                         info->capa->enc |= WPA_DRIVER_CAPA_ENC_CCMP;
3709                         break;
3710                 case WLAN_CIPHER_SUITE_GCMP:
3711                         info->capa->enc |= WPA_DRIVER_CAPA_ENC_GCMP;
3712                         break;
3713                 case WLAN_CIPHER_SUITE_TKIP:
3714                         info->capa->enc |= WPA_DRIVER_CAPA_ENC_TKIP;
3715                         break;
3716                 case WLAN_CIPHER_SUITE_WEP104:
3717                         info->capa->enc |= WPA_DRIVER_CAPA_ENC_WEP104;
3718                         break;
3719                 case WLAN_CIPHER_SUITE_WEP40:
3720                         info->capa->enc |= WPA_DRIVER_CAPA_ENC_WEP40;
3721                         break;
3722                 case WLAN_CIPHER_SUITE_AES_CMAC:
3723                         info->capa->enc |= WPA_DRIVER_CAPA_ENC_BIP;
3724                         break;
3725                 case WLAN_CIPHER_SUITE_BIP_GMAC_128:
3726                         info->capa->enc |= WPA_DRIVER_CAPA_ENC_BIP_GMAC_128;
3727                         break;
3728                 case WLAN_CIPHER_SUITE_BIP_GMAC_256:
3729                         info->capa->enc |= WPA_DRIVER_CAPA_ENC_BIP_GMAC_256;
3730                         break;
3731                 case WLAN_CIPHER_SUITE_BIP_CMAC_256:
3732                         info->capa->enc |= WPA_DRIVER_CAPA_ENC_BIP_CMAC_256;
3733                         break;
3734                 case WLAN_CIPHER_SUITE_NO_GROUP_ADDR:
3735                         info->capa->enc |= WPA_DRIVER_CAPA_ENC_GTK_NOT_USED;
3736                         break;
3737                 }
3738         }
3739 }
3740
3741
3742 static void wiphy_info_max_roc(struct wpa_driver_capa *capa,
3743                                struct nlattr *tb)
3744 {
3745         if (tb)
3746                 capa->max_remain_on_chan = nla_get_u32(tb);
3747 }
3748
3749
3750 static void wiphy_info_tdls(struct wpa_driver_capa *capa, struct nlattr *tdls,
3751                             struct nlattr *ext_setup)
3752 {
3753         if (tdls == NULL)
3754                 return;
3755
3756         wpa_printf(MSG_DEBUG, "nl80211: TDLS supported");
3757         capa->flags |= WPA_DRIVER_FLAGS_TDLS_SUPPORT;
3758
3759         if (ext_setup) {
3760                 wpa_printf(MSG_DEBUG, "nl80211: TDLS external setup");
3761                 capa->flags |= WPA_DRIVER_FLAGS_TDLS_EXTERNAL_SETUP;
3762         }
3763 }
3764
3765
3766 static void wiphy_info_feature_flags(struct wiphy_info_data *info,
3767                                      struct nlattr *tb)
3768 {
3769         u32 flags;
3770         struct wpa_driver_capa *capa = info->capa;
3771
3772         if (tb == NULL)
3773                 return;
3774
3775         flags = nla_get_u32(tb);
3776
3777         if (flags & NL80211_FEATURE_SK_TX_STATUS)
3778                 info->data_tx_status = 1;
3779
3780         if (flags & NL80211_FEATURE_INACTIVITY_TIMER)
3781                 capa->flags |= WPA_DRIVER_FLAGS_INACTIVITY_TIMER;
3782
3783         if (flags & NL80211_FEATURE_SAE)
3784                 capa->flags |= WPA_DRIVER_FLAGS_SAE;
3785
3786         if (flags & NL80211_FEATURE_NEED_OBSS_SCAN)
3787                 capa->flags |= WPA_DRIVER_FLAGS_OBSS_SCAN;
3788
3789         if (flags & NL80211_FEATURE_AP_MODE_CHAN_WIDTH_CHANGE)
3790                 capa->flags |= WPA_DRIVER_FLAGS_HT_2040_COEX;
3791
3792         if (flags & NL80211_FEATURE_LOW_PRIORITY_SCAN)
3793                 info->have_low_prio_scan = 1;
3794 }
3795
3796
3797 static void wiphy_info_probe_resp_offload(struct wpa_driver_capa *capa,
3798                                           struct nlattr *tb)
3799 {
3800         u32 protocols;
3801
3802         if (tb == NULL)
3803                 return;
3804
3805         protocols = nla_get_u32(tb);
3806         wpa_printf(MSG_DEBUG, "nl80211: Supports Probe Response offload in AP "
3807                    "mode");
3808         capa->flags |= WPA_DRIVER_FLAGS_PROBE_RESP_OFFLOAD;
3809         capa->probe_resp_offloads = probe_resp_offload_support(protocols);
3810 }
3811
3812
3813 static void wiphy_info_wowlan_triggers(struct wpa_driver_capa *capa,
3814                                        struct nlattr *tb)
3815 {
3816         struct nlattr *triggers[MAX_NL80211_WOWLAN_TRIG + 1];
3817
3818         if (tb == NULL)
3819                 return;
3820
3821         if (nla_parse_nested(triggers, MAX_NL80211_WOWLAN_TRIG,
3822                              tb, NULL))
3823                 return;
3824
3825         if (triggers[NL80211_WOWLAN_TRIG_ANY])
3826                 capa->wowlan_triggers.any = 1;
3827         if (triggers[NL80211_WOWLAN_TRIG_DISCONNECT])
3828                 capa->wowlan_triggers.disconnect = 1;
3829         if (triggers[NL80211_WOWLAN_TRIG_MAGIC_PKT])
3830                 capa->wowlan_triggers.magic_pkt = 1;
3831         if (triggers[NL80211_WOWLAN_TRIG_GTK_REKEY_FAILURE])
3832                 capa->wowlan_triggers.gtk_rekey_failure = 1;
3833         if (triggers[NL80211_WOWLAN_TRIG_EAP_IDENT_REQUEST])
3834                 capa->wowlan_triggers.eap_identity_req = 1;
3835         if (triggers[NL80211_WOWLAN_TRIG_4WAY_HANDSHAKE])
3836                 capa->wowlan_triggers.four_way_handshake = 1;
3837         if (triggers[NL80211_WOWLAN_TRIG_RFKILL_RELEASE])
3838                 capa->wowlan_triggers.rfkill_release = 1;
3839 }
3840
3841
3842 static int wiphy_info_handler(struct nl_msg *msg, void *arg)
3843 {
3844         struct nlattr *tb[NL80211_ATTR_MAX + 1];
3845         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3846         struct wiphy_info_data *info = arg;
3847         struct wpa_driver_capa *capa = info->capa;
3848         struct wpa_driver_nl80211_data *drv = info->drv;
3849
3850         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3851                   genlmsg_attrlen(gnlh, 0), NULL);
3852
3853         if (tb[NL80211_ATTR_WIPHY_NAME])
3854                 os_strlcpy(drv->phyname,
3855                            nla_get_string(tb[NL80211_ATTR_WIPHY_NAME]),
3856                            sizeof(drv->phyname));
3857         if (tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS])
3858                 capa->max_scan_ssids =
3859                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS]);
3860
3861         if (tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS])
3862                 capa->max_sched_scan_ssids =
3863                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS]);
3864
3865         if (tb[NL80211_ATTR_MAX_MATCH_SETS])
3866                 capa->max_match_sets =
3867                         nla_get_u8(tb[NL80211_ATTR_MAX_MATCH_SETS]);
3868
3869         if (tb[NL80211_ATTR_MAC_ACL_MAX])
3870                 capa->max_acl_mac_addrs =
3871                         nla_get_u8(tb[NL80211_ATTR_MAC_ACL_MAX]);
3872
3873         wiphy_info_supported_iftypes(info, tb[NL80211_ATTR_SUPPORTED_IFTYPES]);
3874         wiphy_info_iface_comb(info, tb[NL80211_ATTR_INTERFACE_COMBINATIONS]);
3875         wiphy_info_supp_cmds(info, tb[NL80211_ATTR_SUPPORTED_COMMANDS]);
3876         wiphy_info_cipher_suites(info, tb[NL80211_ATTR_CIPHER_SUITES]);
3877
3878         if (tb[NL80211_ATTR_OFFCHANNEL_TX_OK]) {
3879                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based "
3880                            "off-channel TX");
3881                 capa->flags |= WPA_DRIVER_FLAGS_OFFCHANNEL_TX;
3882         }
3883
3884         if (tb[NL80211_ATTR_ROAM_SUPPORT]) {
3885                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based roaming");
3886                 capa->flags |= WPA_DRIVER_FLAGS_BSS_SELECTION;
3887         }
3888
3889         wiphy_info_max_roc(capa,
3890                            tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION]);
3891
3892         if (tb[NL80211_ATTR_SUPPORT_AP_UAPSD])
3893                 capa->flags |= WPA_DRIVER_FLAGS_AP_UAPSD;
3894
3895         wiphy_info_tdls(capa, tb[NL80211_ATTR_TDLS_SUPPORT],
3896                         tb[NL80211_ATTR_TDLS_EXTERNAL_SETUP]);
3897
3898         if (tb[NL80211_ATTR_DEVICE_AP_SME])
3899                 info->device_ap_sme = 1;
3900
3901         wiphy_info_feature_flags(info, tb[NL80211_ATTR_FEATURE_FLAGS]);
3902         wiphy_info_probe_resp_offload(capa,
3903                                       tb[NL80211_ATTR_PROBE_RESP_OFFLOAD]);
3904
3905         if (tb[NL80211_ATTR_EXT_CAPA] && tb[NL80211_ATTR_EXT_CAPA_MASK] &&
3906             drv->extended_capa == NULL) {
3907                 drv->extended_capa =
3908                         os_malloc(nla_len(tb[NL80211_ATTR_EXT_CAPA]));
3909                 if (drv->extended_capa) {
3910                         os_memcpy(drv->extended_capa,
3911                                   nla_data(tb[NL80211_ATTR_EXT_CAPA]),
3912                                   nla_len(tb[NL80211_ATTR_EXT_CAPA]));
3913                         drv->extended_capa_len =
3914                                 nla_len(tb[NL80211_ATTR_EXT_CAPA]);
3915                 }
3916                 drv->extended_capa_mask =
3917                         os_malloc(nla_len(tb[NL80211_ATTR_EXT_CAPA]));
3918                 if (drv->extended_capa_mask) {
3919                         os_memcpy(drv->extended_capa_mask,
3920                                   nla_data(tb[NL80211_ATTR_EXT_CAPA]),
3921                                   nla_len(tb[NL80211_ATTR_EXT_CAPA]));
3922                 } else {
3923                         os_free(drv->extended_capa);
3924                         drv->extended_capa = NULL;
3925                         drv->extended_capa_len = 0;
3926                 }
3927         }
3928
3929         if (tb[NL80211_ATTR_VENDOR_DATA]) {
3930                 struct nlattr *nl;
3931                 int rem;
3932
3933                 nla_for_each_nested(nl, tb[NL80211_ATTR_VENDOR_DATA], rem) {
3934                         struct nl80211_vendor_cmd_info *vinfo;
3935                         if (nla_len(nl) != sizeof(*vinfo)) {
3936                                 wpa_printf(MSG_DEBUG, "nl80211: Unexpected vendor data info");
3937                                 continue;
3938                         }
3939                         vinfo = nla_data(nl);
3940                         switch (vinfo->subcmd) {
3941                         case QCA_NL80211_VENDOR_SUBCMD_ROAMING:
3942                                 drv->roaming_vendor_cmd_avail = 1;
3943                                 break;
3944                         case QCA_NL80211_VENDOR_SUBCMD_DFS_CAPABILITY:
3945                                 drv->dfs_vendor_cmd_avail = 1;
3946                                 break;
3947                         }
3948
3949                         wpa_printf(MSG_DEBUG, "nl80211: Supported vendor command: vendor_id=0x%x subcmd=%u",
3950                                    vinfo->vendor_id, vinfo->subcmd);
3951                 }
3952         }
3953
3954         if (tb[NL80211_ATTR_VENDOR_EVENTS]) {
3955                 struct nlattr *nl;
3956                 int rem;
3957
3958                 nla_for_each_nested(nl, tb[NL80211_ATTR_VENDOR_EVENTS], rem) {
3959                         struct nl80211_vendor_cmd_info *vinfo;
3960                         if (nla_len(nl) != sizeof(*vinfo)) {
3961                                 wpa_printf(MSG_DEBUG, "nl80211: Unexpected vendor data info");
3962                                 continue;
3963                         }
3964                         vinfo = nla_data(nl);
3965                         wpa_printf(MSG_DEBUG, "nl80211: Supported vendor event: vendor_id=0x%x subcmd=%u",
3966                                    vinfo->vendor_id, vinfo->subcmd);
3967                 }
3968         }
3969
3970         wiphy_info_wowlan_triggers(capa,
3971                                    tb[NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED]);
3972
3973         if (tb[NL80211_ATTR_MAX_AP_ASSOC_STA])
3974                 capa->max_stations =
3975                         nla_get_u32(tb[NL80211_ATTR_MAX_AP_ASSOC_STA]);
3976
3977         return NL_SKIP;
3978 }
3979
3980
3981 static int wpa_driver_nl80211_get_info(struct wpa_driver_nl80211_data *drv,
3982                                        struct wiphy_info_data *info)
3983 {
3984         u32 feat;
3985         struct nl_msg *msg;
3986
3987         os_memset(info, 0, sizeof(*info));
3988         info->capa = &drv->capa;
3989         info->drv = drv;
3990
3991         msg = nlmsg_alloc();
3992         if (!msg)
3993                 return -1;
3994
3995         feat = get_nl80211_protocol_features(drv);
3996         if (feat & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP)
3997                 nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_WIPHY);
3998         else
3999                 nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
4000
4001         NLA_PUT_FLAG(msg, NL80211_ATTR_SPLIT_WIPHY_DUMP);
4002         if (nl80211_set_iface_id(msg, drv->first_bss) < 0)
4003                 goto nla_put_failure;
4004
4005         if (send_and_recv_msgs(drv, msg, wiphy_info_handler, info))
4006                 return -1;
4007
4008         if (info->auth_supported)
4009                 drv->capa.flags |= WPA_DRIVER_FLAGS_SME;
4010         else if (!info->connect_supported) {
4011                 wpa_printf(MSG_INFO, "nl80211: Driver does not support "
4012                            "authentication/association or connect commands");
4013                 info->error = 1;
4014         }
4015
4016         if (info->p2p_go_supported && info->p2p_client_supported)
4017                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CAPABLE;
4018         if (info->p2p_concurrent) {
4019                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
4020                            "interface (driver advertised support)");
4021                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
4022                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
4023         }
4024         if (info->num_multichan_concurrent > 1) {
4025                 wpa_printf(MSG_DEBUG, "nl80211: Enable multi-channel "
4026                            "concurrent (driver advertised support)");
4027                 drv->capa.num_multichan_concurrent =
4028                         info->num_multichan_concurrent;
4029         }
4030
4031         /* default to 5000 since early versions of mac80211 don't set it */
4032         if (!drv->capa.max_remain_on_chan)
4033                 drv->capa.max_remain_on_chan = 5000;
4034
4035         if (info->channel_switch_supported)
4036                 drv->capa.flags |= WPA_DRIVER_FLAGS_AP_CSA;
4037
4038         return 0;
4039 nla_put_failure:
4040         nlmsg_free(msg);
4041         return -1;
4042 }
4043
4044
4045 static int wpa_driver_nl80211_capa(struct wpa_driver_nl80211_data *drv)
4046 {
4047         struct wiphy_info_data info;
4048         if (wpa_driver_nl80211_get_info(drv, &info))
4049                 return -1;
4050
4051         if (info.error)
4052                 return -1;
4053
4054         drv->has_capability = 1;
4055         drv->capa.key_mgmt = WPA_DRIVER_CAPA_KEY_MGMT_WPA |
4056                 WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK |
4057                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2 |
4058                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK;
4059         drv->capa.auth = WPA_DRIVER_AUTH_OPEN |
4060                 WPA_DRIVER_AUTH_SHARED |
4061                 WPA_DRIVER_AUTH_LEAP;
4062
4063         drv->capa.flags |= WPA_DRIVER_FLAGS_SANE_ERROR_CODES;
4064         drv->capa.flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE;
4065         drv->capa.flags |= WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
4066
4067         /*
4068          * As all cfg80211 drivers must support cases where the AP interface is
4069          * removed without the knowledge of wpa_supplicant/hostapd, e.g., in
4070          * case that the user space daemon has crashed, they must be able to
4071          * cleanup all stations and key entries in the AP tear down flow. Thus,
4072          * this flag can/should always be set for cfg80211 drivers.
4073          */
4074         drv->capa.flags |= WPA_DRIVER_FLAGS_AP_TEARDOWN_SUPPORT;
4075
4076         if (!info.device_ap_sme) {
4077                 drv->capa.flags |= WPA_DRIVER_FLAGS_DEAUTH_TX_STATUS;
4078
4079                 /*
4080                  * No AP SME is currently assumed to also indicate no AP MLME
4081                  * in the driver/firmware.
4082                  */
4083                 drv->capa.flags |= WPA_DRIVER_FLAGS_AP_MLME;
4084         }
4085
4086         drv->device_ap_sme = info.device_ap_sme;
4087         drv->poll_command_supported = info.poll_command_supported;
4088         drv->data_tx_status = info.data_tx_status;
4089         if (info.set_qos_map_supported)
4090                 drv->capa.flags |= WPA_DRIVER_FLAGS_QOS_MAPPING;
4091         drv->have_low_prio_scan = info.have_low_prio_scan;
4092
4093         /*
4094          * If poll command and tx status are supported, mac80211 is new enough
4095          * to have everything we need to not need monitor interfaces.
4096          */
4097         drv->use_monitor = !info.poll_command_supported || !info.data_tx_status;
4098
4099         if (drv->device_ap_sme && drv->use_monitor) {
4100                 /*
4101                  * Non-mac80211 drivers may not support monitor interface.
4102                  * Make sure we do not get stuck with incorrect capability here
4103                  * by explicitly testing this.
4104                  */
4105                 if (!info.monitor_supported) {
4106                         wpa_printf(MSG_DEBUG, "nl80211: Disable use_monitor "
4107                                    "with device_ap_sme since no monitor mode "
4108                                    "support detected");
4109                         drv->use_monitor = 0;
4110                 }
4111         }
4112
4113         /*
4114          * If we aren't going to use monitor interfaces, but the
4115          * driver doesn't support data TX status, we won't get TX
4116          * status for EAPOL frames.
4117          */
4118         if (!drv->use_monitor && !info.data_tx_status)
4119                 drv->capa.flags &= ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
4120
4121         return 0;
4122 }
4123
4124
4125 #ifdef ANDROID
4126 static int android_genl_ctrl_resolve(struct nl_handle *handle,
4127                                      const char *name)
4128 {
4129         /*
4130          * Android ICS has very minimal genl_ctrl_resolve() implementation, so
4131          * need to work around that.
4132          */
4133         struct nl_cache *cache = NULL;
4134         struct genl_family *nl80211 = NULL;
4135         int id = -1;
4136
4137         if (genl_ctrl_alloc_cache(handle, &cache) < 0) {
4138                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
4139                            "netlink cache");
4140                 goto fail;
4141         }
4142
4143         nl80211 = genl_ctrl_search_by_name(cache, name);
4144         if (nl80211 == NULL)
4145                 goto fail;
4146
4147         id = genl_family_get_id(nl80211);
4148
4149 fail:
4150         if (nl80211)
4151                 genl_family_put(nl80211);
4152         if (cache)
4153                 nl_cache_free(cache);
4154
4155         return id;
4156 }
4157 #define genl_ctrl_resolve android_genl_ctrl_resolve
4158 #endif /* ANDROID */
4159
4160
4161 static int wpa_driver_nl80211_init_nl_global(struct nl80211_global *global)
4162 {
4163         int ret;
4164
4165         global->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
4166         if (global->nl_cb == NULL) {
4167                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
4168                            "callbacks");
4169                 return -1;
4170         }
4171
4172         global->nl = nl_create_handle(global->nl_cb, "nl");
4173         if (global->nl == NULL)
4174                 goto err;
4175
4176         global->nl80211_id = genl_ctrl_resolve(global->nl, "nl80211");
4177         if (global->nl80211_id < 0) {
4178                 wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
4179                            "found");
4180                 goto err;
4181         }
4182
4183         global->nl_event = nl_create_handle(global->nl_cb, "event");
4184         if (global->nl_event == NULL)
4185                 goto err;
4186
4187         ret = nl_get_multicast_id(global, "nl80211", "scan");
4188         if (ret >= 0)
4189                 ret = nl_socket_add_membership(global->nl_event, ret);
4190         if (ret < 0) {
4191                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
4192                            "membership for scan events: %d (%s)",
4193                            ret, strerror(-ret));
4194                 goto err;
4195         }
4196
4197         ret = nl_get_multicast_id(global, "nl80211", "mlme");
4198         if (ret >= 0)
4199                 ret = nl_socket_add_membership(global->nl_event, ret);
4200         if (ret < 0) {
4201                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
4202                            "membership for mlme events: %d (%s)",
4203                            ret, strerror(-ret));
4204                 goto err;
4205         }
4206
4207         ret = nl_get_multicast_id(global, "nl80211", "regulatory");
4208         if (ret >= 0)
4209                 ret = nl_socket_add_membership(global->nl_event, ret);
4210         if (ret < 0) {
4211                 wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
4212                            "membership for regulatory events: %d (%s)",
4213                            ret, strerror(-ret));
4214                 /* Continue without regulatory events */
4215         }
4216
4217         ret = nl_get_multicast_id(global, "nl80211", "vendor");
4218         if (ret >= 0)
4219                 ret = nl_socket_add_membership(global->nl_event, ret);
4220         if (ret < 0) {
4221                 wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
4222                            "membership for vendor events: %d (%s)",
4223                            ret, strerror(-ret));
4224                 /* Continue without vendor events */
4225         }
4226
4227         nl_cb_set(global->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
4228                   no_seq_check, NULL);
4229         nl_cb_set(global->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
4230                   process_global_event, global);
4231
4232         nl80211_register_eloop_read(&global->nl_event,
4233                                     wpa_driver_nl80211_event_receive,
4234                                     global->nl_cb);
4235
4236         return 0;
4237
4238 err:
4239         nl_destroy_handles(&global->nl_event);
4240         nl_destroy_handles(&global->nl);
4241         nl_cb_put(global->nl_cb);
4242         global->nl_cb = NULL;
4243         return -1;
4244 }
4245
4246
4247 static int wpa_driver_nl80211_init_nl(struct wpa_driver_nl80211_data *drv)
4248 {
4249         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
4250         if (!drv->nl_cb) {
4251                 wpa_printf(MSG_ERROR, "nl80211: Failed to alloc cb struct");
4252                 return -1;
4253         }
4254
4255         nl_cb_set(drv->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
4256                   no_seq_check, NULL);
4257         nl_cb_set(drv->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
4258                   process_drv_event, drv);
4259
4260         return 0;
4261 }
4262
4263
4264 static void wpa_driver_nl80211_rfkill_blocked(void *ctx)
4265 {
4266         wpa_printf(MSG_DEBUG, "nl80211: RFKILL blocked");
4267         /*
4268          * This may be for any interface; use ifdown event to disable
4269          * interface.
4270          */
4271 }
4272
4273
4274 static void wpa_driver_nl80211_rfkill_unblocked(void *ctx)
4275 {
4276         struct wpa_driver_nl80211_data *drv = ctx;
4277         wpa_printf(MSG_DEBUG, "nl80211: RFKILL unblocked");
4278         if (i802_set_iface_flags(drv->first_bss, 1)) {
4279                 wpa_printf(MSG_DEBUG, "nl80211: Could not set interface UP "
4280                            "after rfkill unblock");
4281                 return;
4282         }
4283         /* rtnetlink ifup handler will report interface as enabled */
4284 }
4285
4286
4287 static void wpa_driver_nl80211_handle_eapol_tx_status(int sock,
4288                                                       void *eloop_ctx,
4289                                                       void *handle)
4290 {
4291         struct wpa_driver_nl80211_data *drv = eloop_ctx;
4292         u8 data[2048];
4293         struct msghdr msg;
4294         struct iovec entry;
4295         u8 control[512];
4296         struct cmsghdr *cmsg;
4297         int res, found_ee = 0, found_wifi = 0, acked = 0;
4298         union wpa_event_data event;
4299
4300         memset(&msg, 0, sizeof(msg));
4301         msg.msg_iov = &entry;
4302         msg.msg_iovlen = 1;
4303         entry.iov_base = data;
4304         entry.iov_len = sizeof(data);
4305         msg.msg_control = &control;
4306         msg.msg_controllen = sizeof(control);
4307
4308         res = recvmsg(sock, &msg, MSG_ERRQUEUE);
4309         /* if error or not fitting 802.3 header, return */
4310         if (res < 14)
4311                 return;
4312
4313         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg))
4314         {
4315                 if (cmsg->cmsg_level == SOL_SOCKET &&
4316                     cmsg->cmsg_type == SCM_WIFI_STATUS) {
4317                         int *ack;
4318
4319                         found_wifi = 1;
4320                         ack = (void *)CMSG_DATA(cmsg);
4321                         acked = *ack;
4322                 }
4323
4324                 if (cmsg->cmsg_level == SOL_PACKET &&
4325                     cmsg->cmsg_type == PACKET_TX_TIMESTAMP) {
4326                         struct sock_extended_err *err =
4327                                 (struct sock_extended_err *)CMSG_DATA(cmsg);
4328
4329                         if (err->ee_origin == SO_EE_ORIGIN_TXSTATUS)
4330                                 found_ee = 1;
4331                 }
4332         }
4333
4334         if (!found_ee || !found_wifi)
4335                 return;
4336
4337         memset(&event, 0, sizeof(event));
4338         event.eapol_tx_status.dst = data;
4339         event.eapol_tx_status.data = data + 14;
4340         event.eapol_tx_status.data_len = res - 14;
4341         event.eapol_tx_status.ack = acked;
4342         wpa_supplicant_event(drv->ctx, EVENT_EAPOL_TX_STATUS, &event);
4343 }
4344
4345
4346 static int nl80211_init_bss(struct i802_bss *bss)
4347 {
4348         bss->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
4349         if (!bss->nl_cb)
4350                 return -1;
4351
4352         nl_cb_set(bss->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
4353                   no_seq_check, NULL);
4354         nl_cb_set(bss->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
4355                   process_bss_event, bss);
4356
4357         return 0;
4358 }
4359
4360
4361 static void nl80211_destroy_bss(struct i802_bss *bss)
4362 {
4363         nl_cb_put(bss->nl_cb);
4364         bss->nl_cb = NULL;
4365 }
4366
4367
4368 static void * wpa_driver_nl80211_drv_init(void *ctx, const char *ifname,
4369                                           void *global_priv, int hostapd,
4370                                           const u8 *set_addr)
4371 {
4372         struct wpa_driver_nl80211_data *drv;
4373         struct rfkill_config *rcfg;
4374         struct i802_bss *bss;
4375
4376         if (global_priv == NULL)
4377                 return NULL;
4378         drv = os_zalloc(sizeof(*drv));
4379         if (drv == NULL)
4380                 return NULL;
4381         drv->global = global_priv;
4382         drv->ctx = ctx;
4383         drv->hostapd = !!hostapd;
4384         drv->eapol_sock = -1;
4385         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
4386         drv->if_indices = drv->default_if_indices;
4387
4388         drv->first_bss = os_zalloc(sizeof(*drv->first_bss));
4389         if (!drv->first_bss) {
4390                 os_free(drv);
4391                 return NULL;
4392         }
4393         bss = drv->first_bss;
4394         bss->drv = drv;
4395         bss->ctx = ctx;
4396
4397         os_strlcpy(bss->ifname, ifname, sizeof(bss->ifname));
4398         drv->monitor_ifidx = -1;
4399         drv->monitor_sock = -1;
4400         drv->eapol_tx_sock = -1;
4401         drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
4402
4403         if (wpa_driver_nl80211_init_nl(drv)) {
4404                 os_free(drv);
4405                 return NULL;
4406         }
4407
4408         if (nl80211_init_bss(bss))
4409                 goto failed;
4410
4411         rcfg = os_zalloc(sizeof(*rcfg));
4412         if (rcfg == NULL)
4413                 goto failed;
4414         rcfg->ctx = drv;
4415         os_strlcpy(rcfg->ifname, ifname, sizeof(rcfg->ifname));
4416         rcfg->blocked_cb = wpa_driver_nl80211_rfkill_blocked;
4417         rcfg->unblocked_cb = wpa_driver_nl80211_rfkill_unblocked;
4418         drv->rfkill = rfkill_init(rcfg);
4419         if (drv->rfkill == NULL) {
4420                 wpa_printf(MSG_DEBUG, "nl80211: RFKILL status not available");
4421                 os_free(rcfg);
4422         }
4423
4424         if (linux_iface_up(drv->global->ioctl_sock, ifname) > 0)
4425                 drv->start_iface_up = 1;
4426
4427         if (wpa_driver_nl80211_finish_drv_init(drv, set_addr, 1))
4428                 goto failed;
4429
4430         drv->eapol_tx_sock = socket(PF_PACKET, SOCK_DGRAM, 0);
4431         if (drv->eapol_tx_sock < 0)
4432                 goto failed;
4433
4434         if (drv->data_tx_status) {
4435                 int enabled = 1;
4436
4437                 if (setsockopt(drv->eapol_tx_sock, SOL_SOCKET, SO_WIFI_STATUS,
4438                                &enabled, sizeof(enabled)) < 0) {
4439                         wpa_printf(MSG_DEBUG,
4440                                 "nl80211: wifi status sockopt failed\n");
4441                         drv->data_tx_status = 0;
4442                         if (!drv->use_monitor)
4443                                 drv->capa.flags &=
4444                                         ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
4445                 } else {
4446                         eloop_register_read_sock(drv->eapol_tx_sock,
4447                                 wpa_driver_nl80211_handle_eapol_tx_status,
4448                                 drv, NULL);
4449                 }
4450         }
4451
4452         if (drv->global) {
4453                 dl_list_add(&drv->global->interfaces, &drv->list);
4454                 drv->in_interface_list = 1;
4455         }
4456
4457         return bss;
4458
4459 failed:
4460         wpa_driver_nl80211_deinit(bss);
4461         return NULL;
4462 }
4463
4464
4465 /**
4466  * wpa_driver_nl80211_init - Initialize nl80211 driver interface
4467  * @ctx: context to be used when calling wpa_supplicant functions,
4468  * e.g., wpa_supplicant_event()
4469  * @ifname: interface name, e.g., wlan0
4470  * @global_priv: private driver global data from global_init()
4471  * Returns: Pointer to private data, %NULL on failure
4472  */
4473 static void * wpa_driver_nl80211_init(void *ctx, const char *ifname,
4474                                       void *global_priv)
4475 {
4476         return wpa_driver_nl80211_drv_init(ctx, ifname, global_priv, 0, NULL);
4477 }
4478
4479
4480 static int nl80211_register_frame(struct i802_bss *bss,
4481                                   struct nl_handle *nl_handle,
4482                                   u16 type, const u8 *match, size_t match_len)
4483 {
4484         struct wpa_driver_nl80211_data *drv = bss->drv;
4485         struct nl_msg *msg;
4486         int ret = -1;
4487         char buf[30];
4488
4489         msg = nlmsg_alloc();
4490         if (!msg)
4491                 return -1;
4492
4493         buf[0] = '\0';
4494         wpa_snprintf_hex(buf, sizeof(buf), match, match_len);
4495         wpa_printf(MSG_DEBUG, "nl80211: Register frame type=0x%x (%s) nl_handle=%p match=%s",
4496                    type, fc2str(type), nl_handle, buf);
4497
4498         nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_ACTION);
4499
4500         if (nl80211_set_iface_id(msg, bss) < 0)
4501                 goto nla_put_failure;
4502
4503         NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE, type);
4504         NLA_PUT(msg, NL80211_ATTR_FRAME_MATCH, match_len, match);
4505
4506         ret = send_and_recv(drv->global, nl_handle, msg, NULL, NULL);
4507         msg = NULL;
4508         if (ret) {
4509                 wpa_printf(MSG_DEBUG, "nl80211: Register frame command "
4510                            "failed (type=%u): ret=%d (%s)",
4511                            type, ret, strerror(-ret));
4512                 wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
4513                             match, match_len);
4514                 goto nla_put_failure;
4515         }
4516         ret = 0;
4517 nla_put_failure:
4518         nlmsg_free(msg);
4519         return ret;
4520 }
4521
4522
4523 static int nl80211_alloc_mgmt_handle(struct i802_bss *bss)
4524 {
4525         struct wpa_driver_nl80211_data *drv = bss->drv;
4526
4527         if (bss->nl_mgmt) {
4528                 wpa_printf(MSG_DEBUG, "nl80211: Mgmt reporting "
4529                            "already on! (nl_mgmt=%p)", bss->nl_mgmt);
4530                 return -1;
4531         }
4532
4533         bss->nl_mgmt = nl_create_handle(drv->nl_cb, "mgmt");
4534         if (bss->nl_mgmt == NULL)
4535                 return -1;
4536
4537         return 0;
4538 }
4539
4540
4541 static void nl80211_mgmt_handle_register_eloop(struct i802_bss *bss)
4542 {
4543         nl80211_register_eloop_read(&bss->nl_mgmt,
4544                                     wpa_driver_nl80211_event_receive,
4545                                     bss->nl_cb);
4546 }
4547
4548
4549 static int nl80211_register_action_frame(struct i802_bss *bss,
4550                                          const u8 *match, size_t match_len)
4551 {
4552         u16 type = (WLAN_FC_TYPE_MGMT << 2) | (WLAN_FC_STYPE_ACTION << 4);
4553         return nl80211_register_frame(bss, bss->nl_mgmt,
4554                                       type, match, match_len);
4555 }
4556
4557
4558 static int nl80211_mgmt_subscribe_non_ap(struct i802_bss *bss)
4559 {
4560         struct wpa_driver_nl80211_data *drv = bss->drv;
4561         int ret = 0;
4562
4563         if (nl80211_alloc_mgmt_handle(bss))
4564                 return -1;
4565         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with non-AP "
4566                    "handle %p", bss->nl_mgmt);
4567
4568         if (drv->nlmode == NL80211_IFTYPE_ADHOC) {
4569                 u16 type = (WLAN_FC_TYPE_MGMT << 2) | (WLAN_FC_STYPE_AUTH << 4);
4570
4571                 /* register for any AUTH message */
4572                 nl80211_register_frame(bss, bss->nl_mgmt, type, NULL, 0);
4573         }
4574
4575 #ifdef CONFIG_INTERWORKING
4576         /* QoS Map Configure */
4577         if (nl80211_register_action_frame(bss, (u8 *) "\x01\x04", 2) < 0)
4578                 ret = -1;
4579 #endif /* CONFIG_INTERWORKING */
4580 #if defined(CONFIG_P2P) || defined(CONFIG_INTERWORKING)
4581         /* GAS Initial Request */
4582         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0a", 2) < 0)
4583                 ret = -1;
4584         /* GAS Initial Response */
4585         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0b", 2) < 0)
4586                 ret = -1;
4587         /* GAS Comeback Request */
4588         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0c", 2) < 0)
4589                 ret = -1;
4590         /* GAS Comeback Response */
4591         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0d", 2) < 0)
4592                 ret = -1;
4593         /* Protected GAS Initial Request */
4594         if (nl80211_register_action_frame(bss, (u8 *) "\x09\x0a", 2) < 0)
4595                 ret = -1;
4596         /* Protected GAS Initial Response */
4597         if (nl80211_register_action_frame(bss, (u8 *) "\x09\x0b", 2) < 0)
4598                 ret = -1;
4599         /* Protected GAS Comeback Request */
4600         if (nl80211_register_action_frame(bss, (u8 *) "\x09\x0c", 2) < 0)
4601                 ret = -1;
4602         /* Protected GAS Comeback Response */
4603         if (nl80211_register_action_frame(bss, (u8 *) "\x09\x0d", 2) < 0)
4604                 ret = -1;
4605 #endif /* CONFIG_P2P || CONFIG_INTERWORKING */
4606 #ifdef CONFIG_P2P
4607         /* P2P Public Action */
4608         if (nl80211_register_action_frame(bss,
4609                                           (u8 *) "\x04\x09\x50\x6f\x9a\x09",
4610                                           6) < 0)
4611                 ret = -1;
4612         /* P2P Action */
4613         if (nl80211_register_action_frame(bss,
4614                                           (u8 *) "\x7f\x50\x6f\x9a\x09",
4615                                           5) < 0)
4616                 ret = -1;
4617 #endif /* CONFIG_P2P */
4618 #ifdef CONFIG_IEEE80211W
4619         /* SA Query Response */
4620         if (nl80211_register_action_frame(bss, (u8 *) "\x08\x01", 2) < 0)
4621                 ret = -1;
4622 #endif /* CONFIG_IEEE80211W */
4623 #ifdef CONFIG_TDLS
4624         if ((drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT)) {
4625                 /* TDLS Discovery Response */
4626                 if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0e", 2) <
4627                     0)
4628                         ret = -1;
4629         }
4630 #endif /* CONFIG_TDLS */
4631
4632         /* FT Action frames */
4633         if (nl80211_register_action_frame(bss, (u8 *) "\x06", 1) < 0)
4634                 ret = -1;
4635         else
4636                 drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_FT |
4637                         WPA_DRIVER_CAPA_KEY_MGMT_FT_PSK;
4638
4639         /* WNM - BSS Transition Management Request */
4640         if (nl80211_register_action_frame(bss, (u8 *) "\x0a\x07", 2) < 0)
4641                 ret = -1;
4642         /* WNM-Sleep Mode Response */
4643         if (nl80211_register_action_frame(bss, (u8 *) "\x0a\x11", 2) < 0)
4644                 ret = -1;
4645
4646 #ifdef CONFIG_HS20
4647         /* WNM-Notification */
4648         if (nl80211_register_action_frame(bss, (u8 *) "\x0a\x1a", 2) < 0)
4649                 ret = -1;
4650 #endif /* CONFIG_HS20 */
4651
4652         nl80211_mgmt_handle_register_eloop(bss);
4653
4654         return ret;
4655 }
4656
4657
4658 static int nl80211_register_spurious_class3(struct i802_bss *bss)
4659 {
4660         struct wpa_driver_nl80211_data *drv = bss->drv;
4661         struct nl_msg *msg;
4662         int ret = -1;
4663
4664         msg = nlmsg_alloc();
4665         if (!msg)
4666                 return -1;
4667
4668         nl80211_cmd(drv, msg, 0, NL80211_CMD_UNEXPECTED_FRAME);
4669
4670         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
4671
4672         ret = send_and_recv(drv->global, bss->nl_mgmt, msg, NULL, NULL);
4673         msg = NULL;
4674         if (ret) {
4675                 wpa_printf(MSG_DEBUG, "nl80211: Register spurious class3 "
4676                            "failed: ret=%d (%s)",
4677                            ret, strerror(-ret));
4678                 goto nla_put_failure;
4679         }
4680         ret = 0;
4681 nla_put_failure:
4682         nlmsg_free(msg);
4683         return ret;
4684 }
4685
4686
4687 static int nl80211_mgmt_subscribe_ap(struct i802_bss *bss)
4688 {
4689         static const int stypes[] = {
4690                 WLAN_FC_STYPE_AUTH,
4691                 WLAN_FC_STYPE_ASSOC_REQ,
4692                 WLAN_FC_STYPE_REASSOC_REQ,
4693                 WLAN_FC_STYPE_DISASSOC,
4694                 WLAN_FC_STYPE_DEAUTH,
4695                 WLAN_FC_STYPE_ACTION,
4696                 WLAN_FC_STYPE_PROBE_REQ,
4697 /* Beacon doesn't work as mac80211 doesn't currently allow
4698  * it, but it wouldn't really be the right thing anyway as
4699  * it isn't per interface ... maybe just dump the scan
4700  * results periodically for OLBC?
4701  */
4702                 /* WLAN_FC_STYPE_BEACON, */
4703         };
4704         unsigned int i;
4705
4706         if (nl80211_alloc_mgmt_handle(bss))
4707                 return -1;
4708         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
4709                    "handle %p", bss->nl_mgmt);
4710
4711         for (i = 0; i < ARRAY_SIZE(stypes); i++) {
4712                 if (nl80211_register_frame(bss, bss->nl_mgmt,
4713                                            (WLAN_FC_TYPE_MGMT << 2) |
4714                                            (stypes[i] << 4),
4715                                            NULL, 0) < 0) {
4716                         goto out_err;
4717                 }
4718         }
4719
4720         if (nl80211_register_spurious_class3(bss))
4721                 goto out_err;
4722
4723         if (nl80211_get_wiphy_data_ap(bss) == NULL)
4724                 goto out_err;
4725
4726         nl80211_mgmt_handle_register_eloop(bss);
4727         return 0;
4728
4729 out_err:
4730         nl_destroy_handles(&bss->nl_mgmt);
4731         return -1;
4732 }
4733
4734
4735 static int nl80211_mgmt_subscribe_ap_dev_sme(struct i802_bss *bss)
4736 {
4737         if (nl80211_alloc_mgmt_handle(bss))
4738                 return -1;
4739         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
4740                    "handle %p (device SME)", bss->nl_mgmt);
4741
4742         if (nl80211_register_frame(bss, bss->nl_mgmt,
4743                                    (WLAN_FC_TYPE_MGMT << 2) |
4744                                    (WLAN_FC_STYPE_ACTION << 4),
4745                                    NULL, 0) < 0)
4746                 goto out_err;
4747
4748         nl80211_mgmt_handle_register_eloop(bss);
4749         return 0;
4750
4751 out_err:
4752         nl_destroy_handles(&bss->nl_mgmt);
4753         return -1;
4754 }
4755
4756
4757 static void nl80211_mgmt_unsubscribe(struct i802_bss *bss, const char *reason)
4758 {
4759         if (bss->nl_mgmt == NULL)
4760                 return;
4761         wpa_printf(MSG_DEBUG, "nl80211: Unsubscribe mgmt frames handle %p "
4762                    "(%s)", bss->nl_mgmt, reason);
4763         nl80211_destroy_eloop_handle(&bss->nl_mgmt);
4764
4765         nl80211_put_wiphy_data_ap(bss);
4766 }
4767
4768
4769 static void wpa_driver_nl80211_send_rfkill(void *eloop_ctx, void *timeout_ctx)
4770 {
4771         wpa_supplicant_event(timeout_ctx, EVENT_INTERFACE_DISABLED, NULL);
4772 }
4773
4774
4775 static void nl80211_del_p2pdev(struct i802_bss *bss)
4776 {
4777         struct wpa_driver_nl80211_data *drv = bss->drv;
4778         struct nl_msg *msg;
4779         int ret;
4780
4781         msg = nlmsg_alloc();
4782         if (!msg)
4783                 return;
4784
4785         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_INTERFACE);
4786         NLA_PUT_U64(msg, NL80211_ATTR_WDEV, bss->wdev_id);
4787
4788         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4789         msg = NULL;
4790
4791         wpa_printf(MSG_DEBUG, "nl80211: Delete P2P Device %s (0x%llx): %s",
4792                    bss->ifname, (long long unsigned int) bss->wdev_id,
4793                    strerror(-ret));
4794
4795 nla_put_failure:
4796         nlmsg_free(msg);
4797 }
4798
4799
4800 static int nl80211_set_p2pdev(struct i802_bss *bss, int start)
4801 {
4802         struct wpa_driver_nl80211_data *drv = bss->drv;
4803         struct nl_msg *msg;
4804         int ret = -1;
4805
4806         msg = nlmsg_alloc();
4807         if (!msg)
4808                 return -1;
4809
4810         if (start)
4811                 nl80211_cmd(drv, msg, 0, NL80211_CMD_START_P2P_DEVICE);
4812         else
4813                 nl80211_cmd(drv, msg, 0, NL80211_CMD_STOP_P2P_DEVICE);
4814
4815         NLA_PUT_U64(msg, NL80211_ATTR_WDEV, bss->wdev_id);
4816
4817         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4818         msg = NULL;
4819
4820         wpa_printf(MSG_DEBUG, "nl80211: %s P2P Device %s (0x%llx): %s",
4821                    start ? "Start" : "Stop",
4822                    bss->ifname, (long long unsigned int) bss->wdev_id,
4823                    strerror(-ret));
4824
4825 nla_put_failure:
4826         nlmsg_free(msg);
4827         return ret;
4828 }
4829
4830
4831 static int i802_set_iface_flags(struct i802_bss *bss, int up)
4832 {
4833         enum nl80211_iftype nlmode;
4834
4835         nlmode = nl80211_get_ifmode(bss);
4836         if (nlmode != NL80211_IFTYPE_P2P_DEVICE) {
4837                 return linux_set_iface_flags(bss->drv->global->ioctl_sock,
4838                                              bss->ifname, up);
4839         }
4840
4841         /* P2P Device has start/stop which is equivalent */
4842         return nl80211_set_p2pdev(bss, up);
4843 }
4844
4845
4846 static int
4847 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv,
4848                                    const u8 *set_addr, int first)
4849 {
4850         struct i802_bss *bss = drv->first_bss;
4851         int send_rfkill_event = 0;
4852         enum nl80211_iftype nlmode;
4853
4854         drv->ifindex = if_nametoindex(bss->ifname);
4855         bss->ifindex = drv->ifindex;
4856         bss->wdev_id = drv->global->if_add_wdevid;
4857         bss->wdev_id_set = drv->global->if_add_wdevid_set;
4858
4859         bss->if_dynamic = drv->ifindex == drv->global->if_add_ifindex;
4860         bss->if_dynamic = bss->if_dynamic || drv->global->if_add_wdevid_set;
4861         drv->global->if_add_wdevid_set = 0;
4862
4863         if (!bss->if_dynamic && nl80211_get_ifmode(bss) == NL80211_IFTYPE_AP)
4864                 bss->static_ap = 1;
4865
4866         if (wpa_driver_nl80211_capa(drv))
4867                 return -1;
4868
4869         wpa_printf(MSG_DEBUG, "nl80211: interface %s in phy %s",
4870                    bss->ifname, drv->phyname);
4871
4872         if (set_addr &&
4873             (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0) ||
4874              linux_set_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
4875                                 set_addr)))
4876                 return -1;
4877
4878         if (first && nl80211_get_ifmode(bss) == NL80211_IFTYPE_AP)
4879                 drv->start_mode_ap = 1;
4880
4881         if (drv->hostapd || bss->static_ap)
4882                 nlmode = NL80211_IFTYPE_AP;
4883         else if (bss->if_dynamic)
4884                 nlmode = nl80211_get_ifmode(bss);
4885         else
4886                 nlmode = NL80211_IFTYPE_STATION;
4887
4888         if (wpa_driver_nl80211_set_mode(bss, nlmode) < 0) {
4889                 wpa_printf(MSG_ERROR, "nl80211: Could not configure driver mode");
4890                 return -1;
4891         }
4892
4893         if (nlmode == NL80211_IFTYPE_P2P_DEVICE)
4894                 nl80211_get_macaddr(bss);
4895
4896         if (!rfkill_is_blocked(drv->rfkill)) {
4897                 int ret = i802_set_iface_flags(bss, 1);
4898                 if (ret) {
4899                         wpa_printf(MSG_ERROR, "nl80211: Could not set "
4900                                    "interface '%s' UP", bss->ifname);
4901                         return ret;
4902                 }
4903                 if (nlmode == NL80211_IFTYPE_P2P_DEVICE)
4904                         return ret;
4905         } else {
4906                 wpa_printf(MSG_DEBUG, "nl80211: Could not yet enable "
4907                            "interface '%s' due to rfkill", bss->ifname);
4908                 if (nlmode == NL80211_IFTYPE_P2P_DEVICE)
4909                         return 0;
4910                 drv->if_disabled = 1;
4911                 send_rfkill_event = 1;
4912         }
4913
4914         if (!drv->hostapd)
4915                 netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
4916                                        1, IF_OPER_DORMANT);
4917
4918         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
4919                                bss->addr))
4920                 return -1;
4921         os_memcpy(drv->perm_addr, bss->addr, ETH_ALEN);
4922
4923         if (send_rfkill_event) {
4924                 eloop_register_timeout(0, 0, wpa_driver_nl80211_send_rfkill,
4925                                        drv, drv->ctx);
4926         }
4927
4928         return 0;
4929 }
4930
4931
4932 static int wpa_driver_nl80211_del_beacon(struct wpa_driver_nl80211_data *drv)
4933 {
4934         struct nl_msg *msg;
4935
4936         msg = nlmsg_alloc();
4937         if (!msg)
4938                 return -ENOMEM;
4939
4940         wpa_printf(MSG_DEBUG, "nl80211: Remove beacon (ifindex=%d)",
4941                    drv->ifindex);
4942         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_BEACON);
4943         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4944
4945         return send_and_recv_msgs(drv, msg, NULL, NULL);
4946  nla_put_failure:
4947         nlmsg_free(msg);
4948         return -ENOBUFS;
4949 }
4950
4951
4952 /**
4953  * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
4954  * @bss: Pointer to private nl80211 data from wpa_driver_nl80211_init()
4955  *
4956  * Shut down driver interface and processing of driver events. Free
4957  * private data buffer if one was allocated in wpa_driver_nl80211_init().
4958  */
4959 static void wpa_driver_nl80211_deinit(struct i802_bss *bss)
4960 {
4961         struct wpa_driver_nl80211_data *drv = bss->drv;
4962
4963         bss->in_deinit = 1;
4964         if (drv->data_tx_status)
4965                 eloop_unregister_read_sock(drv->eapol_tx_sock);
4966         if (drv->eapol_tx_sock >= 0)
4967                 close(drv->eapol_tx_sock);
4968
4969         if (bss->nl_preq)
4970                 wpa_driver_nl80211_probe_req_report(bss, 0);
4971         if (bss->added_if_into_bridge) {
4972                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
4973                                     bss->ifname) < 0)
4974                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
4975                                    "interface %s from bridge %s: %s",
4976                                    bss->ifname, bss->brname, strerror(errno));
4977                 if (drv->rtnl_sk)
4978                         nl80211_handle_destroy(drv->rtnl_sk);
4979         }
4980         if (bss->added_bridge) {
4981                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
4982                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
4983                                    "bridge %s: %s",
4984                                    bss->brname, strerror(errno));
4985         }
4986
4987         nl80211_remove_monitor_interface(drv);
4988
4989         if (is_ap_interface(drv->nlmode))
4990                 wpa_driver_nl80211_del_beacon(drv);
4991
4992         if (drv->eapol_sock >= 0) {
4993                 eloop_unregister_read_sock(drv->eapol_sock);
4994                 close(drv->eapol_sock);
4995         }
4996
4997         if (drv->if_indices != drv->default_if_indices)
4998                 os_free(drv->if_indices);
4999
5000         if (drv->disabled_11b_rates)
5001                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
5002
5003         netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, 0,
5004                                IF_OPER_UP);
5005         eloop_cancel_timeout(wpa_driver_nl80211_send_rfkill, drv, drv->ctx);
5006         rfkill_deinit(drv->rfkill);
5007
5008         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
5009
5010         if (!drv->start_iface_up)
5011                 (void) i802_set_iface_flags(bss, 0);
5012
5013         if (drv->addr_changed) {
5014                 if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname,
5015                                           0) < 0) {
5016                         wpa_printf(MSG_DEBUG,
5017                                    "nl80211: Could not set interface down to restore permanent MAC address");
5018                 }
5019                 if (linux_set_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
5020                                        drv->perm_addr) < 0) {
5021                         wpa_printf(MSG_DEBUG,
5022                                    "nl80211: Could not restore permanent MAC address");
5023                 }
5024         }
5025
5026         if (drv->nlmode != NL80211_IFTYPE_P2P_DEVICE) {
5027                 if (!drv->hostapd || !drv->start_mode_ap)
5028                         wpa_driver_nl80211_set_mode(bss,
5029                                                     NL80211_IFTYPE_STATION);
5030                 nl80211_mgmt_unsubscribe(bss, "deinit");
5031         } else {
5032                 nl80211_mgmt_unsubscribe(bss, "deinit");
5033                 nl80211_del_p2pdev(bss);
5034         }
5035         nl_cb_put(drv->nl_cb);
5036
5037         nl80211_destroy_bss(drv->first_bss);
5038
5039         os_free(drv->filter_ssids);
5040
5041         os_free(drv->auth_ie);
5042
5043         if (drv->in_interface_list)
5044                 dl_list_del(&drv->list);
5045
5046         os_free(drv->extended_capa);
5047         os_free(drv->extended_capa_mask);
5048         os_free(drv->first_bss);
5049         os_free(drv);
5050 }
5051
5052
5053 /**
5054  * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
5055  * @eloop_ctx: Driver private data
5056  * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
5057  *
5058  * This function can be used as registered timeout when starting a scan to
5059  * generate a scan completed event if the driver does not report this.
5060  */
5061 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
5062 {
5063         struct wpa_driver_nl80211_data *drv = eloop_ctx;
5064         if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED) {
5065                 wpa_driver_nl80211_set_mode(drv->first_bss,
5066                                             drv->ap_scan_as_station);
5067                 drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
5068         }
5069         wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
5070         wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
5071 }
5072
5073
5074 static struct nl_msg *
5075 nl80211_scan_common(struct wpa_driver_nl80211_data *drv, u8 cmd,
5076                     struct wpa_driver_scan_params *params, u64 *wdev_id)
5077 {
5078         struct nl_msg *msg;
5079         size_t i;
5080         u32 scan_flags = 0;
5081
5082         msg = nlmsg_alloc();
5083         if (!msg)
5084                 return NULL;
5085
5086         nl80211_cmd(drv, msg, 0, cmd);
5087
5088         if (!wdev_id)
5089                 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5090         else
5091                 NLA_PUT_U64(msg, NL80211_ATTR_WDEV, *wdev_id);
5092
5093         if (params->num_ssids) {
5094                 struct nlattr *ssids;
5095
5096                 ssids = nla_nest_start(msg, NL80211_ATTR_SCAN_SSIDS);
5097                 if (ssids == NULL)
5098                         goto fail;
5099                 for (i = 0; i < params->num_ssids; i++) {
5100                         wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan SSID",
5101                                           params->ssids[i].ssid,
5102                                           params->ssids[i].ssid_len);
5103                         if (nla_put(msg, i + 1, params->ssids[i].ssid_len,
5104                                     params->ssids[i].ssid) < 0)
5105                                 goto fail;
5106                 }
5107                 nla_nest_end(msg, ssids);
5108         }
5109
5110         if (params->extra_ies) {
5111                 wpa_hexdump(MSG_MSGDUMP, "nl80211: Scan extra IEs",
5112                             params->extra_ies, params->extra_ies_len);
5113                 if (nla_put(msg, NL80211_ATTR_IE, params->extra_ies_len,
5114                             params->extra_ies) < 0)
5115                         goto fail;
5116         }
5117
5118         if (params->freqs) {
5119                 struct nlattr *freqs;
5120                 freqs = nla_nest_start(msg, NL80211_ATTR_SCAN_FREQUENCIES);
5121                 if (freqs == NULL)
5122                         goto fail;
5123                 for (i = 0; params->freqs[i]; i++) {
5124                         wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
5125                                    "MHz", params->freqs[i]);
5126                         if (nla_put_u32(msg, i + 1, params->freqs[i]) < 0)
5127                                 goto fail;
5128                 }
5129                 nla_nest_end(msg, freqs);
5130         }
5131
5132         os_free(drv->filter_ssids);
5133         drv->filter_ssids = params->filter_ssids;
5134         params->filter_ssids = NULL;
5135         drv->num_filter_ssids = params->num_filter_ssids;
5136
5137         if (params->only_new_results) {
5138                 wpa_printf(MSG_DEBUG, "nl80211: Add NL80211_SCAN_FLAG_FLUSH");
5139                 scan_flags |= NL80211_SCAN_FLAG_FLUSH;
5140         }
5141
5142         if (params->low_priority && drv->have_low_prio_scan) {
5143                 wpa_printf(MSG_DEBUG,
5144                            "nl80211: Add NL80211_SCAN_FLAG_LOW_PRIORITY");
5145                 scan_flags |= NL80211_SCAN_FLAG_LOW_PRIORITY;
5146         }
5147
5148         if (scan_flags)
5149                 NLA_PUT_U32(msg, NL80211_ATTR_SCAN_FLAGS, scan_flags);
5150
5151         return msg;
5152
5153 fail:
5154 nla_put_failure:
5155         nlmsg_free(msg);
5156         return NULL;
5157 }
5158
5159
5160 /**
5161  * wpa_driver_nl80211_scan - Request the driver to initiate scan
5162  * @bss: Pointer to private driver data from wpa_driver_nl80211_init()
5163  * @params: Scan parameters
5164  * Returns: 0 on success, -1 on failure
5165  */
5166 static int wpa_driver_nl80211_scan(struct i802_bss *bss,
5167                                    struct wpa_driver_scan_params *params)
5168 {
5169         struct wpa_driver_nl80211_data *drv = bss->drv;
5170         int ret = -1, timeout;
5171         struct nl_msg *msg = NULL;
5172
5173         wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: scan request");
5174         drv->scan_for_auth = 0;
5175
5176         msg = nl80211_scan_common(drv, NL80211_CMD_TRIGGER_SCAN, params,
5177                                   bss->wdev_id_set ? &bss->wdev_id : NULL);
5178         if (!msg)
5179                 return -1;
5180
5181         if (params->p2p_probe) {
5182                 struct nlattr *rates;
5183
5184                 wpa_printf(MSG_DEBUG, "nl80211: P2P probe - mask SuppRates");
5185
5186                 rates = nla_nest_start(msg, NL80211_ATTR_SCAN_SUPP_RATES);
5187                 if (rates == NULL)
5188                         goto nla_put_failure;
5189
5190                 /*
5191                  * Remove 2.4 GHz rates 1, 2, 5.5, 11 Mbps from supported rates
5192                  * by masking out everything else apart from the OFDM rates 6,
5193                  * 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS rates. All 5 GHz
5194                  * rates are left enabled.
5195                  */
5196                 NLA_PUT(msg, NL80211_BAND_2GHZ, 8,
5197                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
5198                 nla_nest_end(msg, rates);
5199
5200                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
5201         }
5202
5203         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5204         msg = NULL;
5205         if (ret) {
5206                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
5207                            "(%s)", ret, strerror(-ret));
5208                 if (drv->hostapd && is_ap_interface(drv->nlmode)) {
5209                         enum nl80211_iftype old_mode = drv->nlmode;
5210
5211                         /*
5212                          * mac80211 does not allow scan requests in AP mode, so
5213                          * try to do this in station mode.
5214                          */
5215                         if (wpa_driver_nl80211_set_mode(
5216                                     bss, NL80211_IFTYPE_STATION))
5217                                 goto nla_put_failure;
5218
5219                         if (wpa_driver_nl80211_scan(bss, params)) {
5220                                 wpa_driver_nl80211_set_mode(bss, drv->nlmode);
5221                                 goto nla_put_failure;
5222                         }
5223
5224                         /* Restore AP mode when processing scan results */
5225                         drv->ap_scan_as_station = old_mode;
5226                         ret = 0;
5227                 } else
5228                         goto nla_put_failure;
5229         }
5230
5231         drv->scan_state = SCAN_REQUESTED;
5232         /* Not all drivers generate "scan completed" wireless event, so try to
5233          * read results after a timeout. */
5234         timeout = 10;
5235         if (drv->scan_complete_events) {
5236                 /*
5237                  * The driver seems to deliver events to notify when scan is
5238                  * complete, so use longer timeout to avoid race conditions
5239                  * with scanning and following association request.
5240                  */
5241                 timeout = 30;
5242         }
5243         wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
5244                    "seconds", ret, timeout);
5245         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
5246         eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
5247                                drv, drv->ctx);
5248
5249 nla_put_failure:
5250         nlmsg_free(msg);
5251         return ret;
5252 }
5253
5254
5255 /**
5256  * wpa_driver_nl80211_sched_scan - Initiate a scheduled scan
5257  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
5258  * @params: Scan parameters
5259  * @interval: Interval between scan cycles in milliseconds
5260  * Returns: 0 on success, -1 on failure or if not supported
5261  */
5262 static int wpa_driver_nl80211_sched_scan(void *priv,
5263                                          struct wpa_driver_scan_params *params,
5264                                          u32 interval)
5265 {
5266         struct i802_bss *bss = priv;
5267         struct wpa_driver_nl80211_data *drv = bss->drv;
5268         int ret = -1;
5269         struct nl_msg *msg;
5270         size_t i;
5271
5272         wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: sched_scan request");
5273
5274 #ifdef ANDROID
5275         if (!drv->capa.sched_scan_supported)
5276                 return android_pno_start(bss, params);
5277 #endif /* ANDROID */
5278
5279         msg = nl80211_scan_common(drv, NL80211_CMD_START_SCHED_SCAN, params,
5280                                   bss->wdev_id_set ? &bss->wdev_id : NULL);
5281         if (!msg)
5282                 goto nla_put_failure;
5283
5284         NLA_PUT_U32(msg, NL80211_ATTR_SCHED_SCAN_INTERVAL, interval);
5285
5286         if ((drv->num_filter_ssids &&
5287             (int) drv->num_filter_ssids <= drv->capa.max_match_sets) ||
5288             params->filter_rssi) {
5289                 struct nlattr *match_sets;
5290                 match_sets = nla_nest_start(msg, NL80211_ATTR_SCHED_SCAN_MATCH);
5291                 if (match_sets == NULL)
5292                         goto nla_put_failure;
5293
5294                 for (i = 0; i < drv->num_filter_ssids; i++) {
5295                         struct nlattr *match_set_ssid;
5296                         wpa_hexdump_ascii(MSG_MSGDUMP,
5297                                           "nl80211: Sched scan filter SSID",
5298                                           drv->filter_ssids[i].ssid,
5299                                           drv->filter_ssids[i].ssid_len);
5300
5301                         match_set_ssid = nla_nest_start(msg, i + 1);
5302                         if (match_set_ssid == NULL)
5303                                 goto nla_put_failure;
5304                         NLA_PUT(msg, NL80211_ATTR_SCHED_SCAN_MATCH_SSID,
5305                                 drv->filter_ssids[i].ssid_len,
5306                                 drv->filter_ssids[i].ssid);
5307                         if (params->filter_rssi)
5308                                 NLA_PUT_U32(msg,
5309                                             NL80211_SCHED_SCAN_MATCH_ATTR_RSSI,
5310                                             params->filter_rssi);
5311
5312                         nla_nest_end(msg, match_set_ssid);
5313                 }
5314
5315                 /*
5316                  * Due to backward compatibility code, newer kernels treat this
5317                  * matchset (with only an RSSI filter) as the default for all
5318                  * other matchsets, unless it's the only one, in which case the
5319                  * matchset will actually allow all SSIDs above the RSSI.
5320                  */
5321                 if (params->filter_rssi) {
5322                         struct nlattr *match_set_rssi;
5323                         match_set_rssi = nla_nest_start(msg, 0);
5324                         if (match_set_rssi == NULL)
5325                                 goto nla_put_failure;
5326                         NLA_PUT_U32(msg, NL80211_SCHED_SCAN_MATCH_ATTR_RSSI,
5327                                     params->filter_rssi);
5328                         wpa_printf(MSG_MSGDUMP,
5329                                    "nl80211: Sched scan RSSI filter %d dBm",
5330                                    params->filter_rssi);
5331                         nla_nest_end(msg, match_set_rssi);
5332                 }
5333
5334                 nla_nest_end(msg, match_sets);
5335         }
5336
5337         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5338
5339         /* TODO: if we get an error here, we should fall back to normal scan */
5340
5341         msg = NULL;
5342         if (ret) {
5343                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan start failed: "
5344                            "ret=%d (%s)", ret, strerror(-ret));
5345                 goto nla_put_failure;
5346         }
5347
5348         wpa_printf(MSG_DEBUG, "nl80211: Sched scan requested (ret=%d) - "
5349                    "scan interval %d msec", ret, interval);
5350
5351 nla_put_failure:
5352         nlmsg_free(msg);
5353         return ret;
5354 }
5355
5356
5357 /**
5358  * wpa_driver_nl80211_stop_sched_scan - Stop a scheduled scan
5359  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
5360  * Returns: 0 on success, -1 on failure or if not supported
5361  */
5362 static int wpa_driver_nl80211_stop_sched_scan(void *priv)
5363 {
5364         struct i802_bss *bss = priv;
5365         struct wpa_driver_nl80211_data *drv = bss->drv;
5366         int ret = 0;
5367         struct nl_msg *msg;
5368
5369 #ifdef ANDROID
5370         if (!drv->capa.sched_scan_supported)
5371                 return android_pno_stop(bss);
5372 #endif /* ANDROID */
5373
5374         msg = nlmsg_alloc();
5375         if (!msg)
5376                 return -1;
5377
5378         nl80211_cmd(drv, msg, 0, NL80211_CMD_STOP_SCHED_SCAN);
5379
5380         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5381
5382         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5383         msg = NULL;
5384         if (ret) {
5385                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop failed: "
5386                            "ret=%d (%s)", ret, strerror(-ret));
5387                 goto nla_put_failure;
5388         }
5389
5390         wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop sent (ret=%d)", ret);
5391
5392 nla_put_failure:
5393         nlmsg_free(msg);
5394         return ret;
5395 }
5396
5397
5398 static const u8 * nl80211_get_ie(const u8 *ies, size_t ies_len, u8 ie)
5399 {
5400         const u8 *end, *pos;
5401
5402         if (ies == NULL)
5403                 return NULL;
5404
5405         pos = ies;
5406         end = ies + ies_len;
5407
5408         while (pos + 1 < end) {
5409                 if (pos + 2 + pos[1] > end)
5410                         break;
5411                 if (pos[0] == ie)
5412                         return pos;
5413                 pos += 2 + pos[1];
5414         }
5415
5416         return NULL;
5417 }
5418
5419
5420 static int nl80211_scan_filtered(struct wpa_driver_nl80211_data *drv,
5421                                  const u8 *ie, size_t ie_len)
5422 {
5423         const u8 *ssid;
5424         size_t i;
5425
5426         if (drv->filter_ssids == NULL)
5427                 return 0;
5428
5429         ssid = nl80211_get_ie(ie, ie_len, WLAN_EID_SSID);
5430         if (ssid == NULL)
5431                 return 1;
5432
5433         for (i = 0; i < drv->num_filter_ssids; i++) {
5434                 if (ssid[1] == drv->filter_ssids[i].ssid_len &&
5435                     os_memcmp(ssid + 2, drv->filter_ssids[i].ssid, ssid[1]) ==
5436                     0)
5437                         return 0;
5438         }
5439
5440         return 1;
5441 }
5442
5443
5444 static int bss_info_handler(struct nl_msg *msg, void *arg)
5445 {
5446         struct nlattr *tb[NL80211_ATTR_MAX + 1];
5447         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5448         struct nlattr *bss[NL80211_BSS_MAX + 1];
5449         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
5450                 [NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
5451                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
5452                 [NL80211_BSS_TSF] = { .type = NLA_U64 },
5453                 [NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
5454                 [NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
5455                 [NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
5456                 [NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
5457                 [NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
5458                 [NL80211_BSS_STATUS] = { .type = NLA_U32 },
5459                 [NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
5460                 [NL80211_BSS_BEACON_IES] = { .type = NLA_UNSPEC },
5461         };
5462         struct nl80211_bss_info_arg *_arg = arg;
5463         struct wpa_scan_results *res = _arg->res;
5464         struct wpa_scan_res **tmp;
5465         struct wpa_scan_res *r;
5466         const u8 *ie, *beacon_ie;
5467         size_t ie_len, beacon_ie_len;
5468         u8 *pos;
5469         size_t i;
5470
5471         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5472                   genlmsg_attrlen(gnlh, 0), NULL);
5473         if (!tb[NL80211_ATTR_BSS])
5474                 return NL_SKIP;
5475         if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
5476                              bss_policy))
5477                 return NL_SKIP;
5478         if (bss[NL80211_BSS_STATUS]) {
5479                 enum nl80211_bss_status status;
5480                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
5481                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
5482                     bss[NL80211_BSS_FREQUENCY]) {
5483                         _arg->assoc_freq =
5484                                 nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
5485                         wpa_printf(MSG_DEBUG, "nl80211: Associated on %u MHz",
5486                                    _arg->assoc_freq);
5487                 }
5488                 if (status == NL80211_BSS_STATUS_IBSS_JOINED &&
5489                     bss[NL80211_BSS_FREQUENCY]) {
5490                         _arg->ibss_freq =
5491                                 nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
5492                         wpa_printf(MSG_DEBUG, "nl80211: IBSS-joined on %u MHz",
5493                                    _arg->ibss_freq);
5494                 }
5495                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
5496                     bss[NL80211_BSS_BSSID]) {
5497                         os_memcpy(_arg->assoc_bssid,
5498                                   nla_data(bss[NL80211_BSS_BSSID]), ETH_ALEN);
5499                         wpa_printf(MSG_DEBUG, "nl80211: Associated with "
5500                                    MACSTR, MAC2STR(_arg->assoc_bssid));
5501                 }
5502         }
5503         if (!res)
5504                 return NL_SKIP;
5505         if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
5506                 ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
5507                 ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
5508         } else {
5509                 ie = NULL;
5510                 ie_len = 0;
5511         }
5512         if (bss[NL80211_BSS_BEACON_IES]) {
5513                 beacon_ie = nla_data(bss[NL80211_BSS_BEACON_IES]);
5514                 beacon_ie_len = nla_len(bss[NL80211_BSS_BEACON_IES]);
5515         } else {
5516                 beacon_ie = NULL;
5517                 beacon_ie_len = 0;
5518         }
5519
5520         if (nl80211_scan_filtered(_arg->drv, ie ? ie : beacon_ie,
5521                                   ie ? ie_len : beacon_ie_len))
5522                 return NL_SKIP;
5523
5524         r = os_zalloc(sizeof(*r) + ie_len + beacon_ie_len);
5525         if (r == NULL)
5526                 return NL_SKIP;
5527         if (bss[NL80211_BSS_BSSID])
5528                 os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
5529                           ETH_ALEN);
5530         if (bss[NL80211_BSS_FREQUENCY])
5531                 r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
5532         if (bss[NL80211_BSS_BEACON_INTERVAL])
5533                 r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
5534         if (bss[NL80211_BSS_CAPABILITY])
5535                 r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
5536         r->flags |= WPA_SCAN_NOISE_INVALID;
5537         if (bss[NL80211_BSS_SIGNAL_MBM]) {
5538                 r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
5539                 r->level /= 100; /* mBm to dBm */
5540                 r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
5541         } else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
5542                 r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
5543                 r->flags |= WPA_SCAN_QUAL_INVALID;
5544         } else
5545                 r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
5546         if (bss[NL80211_BSS_TSF])
5547                 r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
5548         if (bss[NL80211_BSS_SEEN_MS_AGO])
5549                 r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
5550         r->ie_len = ie_len;
5551         pos = (u8 *) (r + 1);
5552         if (ie) {
5553                 os_memcpy(pos, ie, ie_len);
5554                 pos += ie_len;
5555         }
5556         r->beacon_ie_len = beacon_ie_len;
5557         if (beacon_ie)
5558                 os_memcpy(pos, beacon_ie, beacon_ie_len);
5559
5560         if (bss[NL80211_BSS_STATUS]) {
5561                 enum nl80211_bss_status status;
5562                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
5563                 switch (status) {
5564                 case NL80211_BSS_STATUS_AUTHENTICATED:
5565                         r->flags |= WPA_SCAN_AUTHENTICATED;
5566                         break;
5567                 case NL80211_BSS_STATUS_ASSOCIATED:
5568                         r->flags |= WPA_SCAN_ASSOCIATED;
5569                         break;
5570                 default:
5571                         break;
5572                 }
5573         }
5574
5575         /*
5576          * cfg80211 maintains separate BSS table entries for APs if the same
5577          * BSSID,SSID pair is seen on multiple channels. wpa_supplicant does
5578          * not use frequency as a separate key in the BSS table, so filter out
5579          * duplicated entries. Prefer associated BSS entry in such a case in
5580          * order to get the correct frequency into the BSS table. Similarly,
5581          * prefer newer entries over older.
5582          */
5583         for (i = 0; i < res->num; i++) {
5584                 const u8 *s1, *s2;
5585                 if (os_memcmp(res->res[i]->bssid, r->bssid, ETH_ALEN) != 0)
5586                         continue;
5587
5588                 s1 = nl80211_get_ie((u8 *) (res->res[i] + 1),
5589                                     res->res[i]->ie_len, WLAN_EID_SSID);
5590                 s2 = nl80211_get_ie((u8 *) (r + 1), r->ie_len, WLAN_EID_SSID);
5591                 if (s1 == NULL || s2 == NULL || s1[1] != s2[1] ||
5592                     os_memcmp(s1, s2, 2 + s1[1]) != 0)
5593                         continue;
5594
5595                 /* Same BSSID,SSID was already included in scan results */
5596                 wpa_printf(MSG_DEBUG, "nl80211: Remove duplicated scan result "
5597                            "for " MACSTR, MAC2STR(r->bssid));
5598
5599                 if (((r->flags & WPA_SCAN_ASSOCIATED) &&
5600                      !(res->res[i]->flags & WPA_SCAN_ASSOCIATED)) ||
5601                     r->age < res->res[i]->age) {
5602                         os_free(res->res[i]);
5603                         res->res[i] = r;
5604                 } else
5605                         os_free(r);
5606                 return NL_SKIP;
5607         }
5608
5609         tmp = os_realloc_array(res->res, res->num + 1,
5610                                sizeof(struct wpa_scan_res *));
5611         if (tmp == NULL) {
5612                 os_free(r);
5613                 return NL_SKIP;
5614         }
5615         tmp[res->num++] = r;
5616         res->res = tmp;
5617
5618         return NL_SKIP;
5619 }
5620
5621
5622 static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
5623                                  const u8 *addr)
5624 {
5625         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
5626                 wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
5627                            "mismatch (" MACSTR ")", MAC2STR(addr));
5628                 wpa_driver_nl80211_mlme(drv, addr,
5629                                         NL80211_CMD_DEAUTHENTICATE,
5630                                         WLAN_REASON_PREV_AUTH_NOT_VALID, 1);
5631         }
5632 }
5633
5634
5635 static void wpa_driver_nl80211_check_bss_status(
5636         struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
5637 {
5638         size_t i;
5639
5640         for (i = 0; i < res->num; i++) {
5641                 struct wpa_scan_res *r = res->res[i];
5642                 if (r->flags & WPA_SCAN_AUTHENTICATED) {
5643                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
5644                                    "indicates BSS status with " MACSTR
5645                                    " as authenticated",
5646                                    MAC2STR(r->bssid));
5647                         if (is_sta_interface(drv->nlmode) &&
5648                             os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
5649                             os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
5650                             0) {
5651                                 wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
5652                                            " in local state (auth=" MACSTR
5653                                            " assoc=" MACSTR ")",
5654                                            MAC2STR(drv->auth_bssid),
5655                                            MAC2STR(drv->bssid));
5656                                 clear_state_mismatch(drv, r->bssid);
5657                         }
5658                 }
5659
5660                 if (r->flags & WPA_SCAN_ASSOCIATED) {
5661                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
5662                                    "indicate BSS status with " MACSTR
5663                                    " as associated",
5664                                    MAC2STR(r->bssid));
5665                         if (is_sta_interface(drv->nlmode) &&
5666                             !drv->associated) {
5667                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
5668                                            "(not associated) does not match "
5669                                            "with BSS state");
5670                                 clear_state_mismatch(drv, r->bssid);
5671                         } else if (is_sta_interface(drv->nlmode) &&
5672                                    os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
5673                                    0) {
5674                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
5675                                            "(associated with " MACSTR ") does "
5676                                            "not match with BSS state",
5677                                            MAC2STR(drv->bssid));
5678                                 clear_state_mismatch(drv, r->bssid);
5679                                 clear_state_mismatch(drv, drv->bssid);
5680                         }
5681                 }
5682         }
5683 }
5684
5685
5686 static struct wpa_scan_results *
5687 nl80211_get_scan_results(struct wpa_driver_nl80211_data *drv)
5688 {
5689         struct nl_msg *msg;
5690         struct wpa_scan_results *res;
5691         int ret;
5692         struct nl80211_bss_info_arg arg;
5693
5694         res = os_zalloc(sizeof(*res));
5695         if (res == NULL)
5696                 return NULL;
5697         msg = nlmsg_alloc();
5698         if (!msg)
5699                 goto nla_put_failure;
5700
5701         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
5702         if (nl80211_set_iface_id(msg, drv->first_bss) < 0)
5703                 goto nla_put_failure;
5704
5705         arg.drv = drv;
5706         arg.res = res;
5707         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
5708         msg = NULL;
5709         if (ret == 0) {
5710                 wpa_printf(MSG_DEBUG, "nl80211: Received scan results (%lu "
5711                            "BSSes)", (unsigned long) res->num);
5712                 nl80211_get_noise_for_scan_results(drv, res);
5713                 return res;
5714         }
5715         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
5716                    "(%s)", ret, strerror(-ret));
5717 nla_put_failure:
5718         nlmsg_free(msg);
5719         wpa_scan_results_free(res);
5720         return NULL;
5721 }
5722
5723
5724 /**
5725  * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
5726  * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
5727  * Returns: Scan results on success, -1 on failure
5728  */
5729 static struct wpa_scan_results *
5730 wpa_driver_nl80211_get_scan_results(void *priv)
5731 {
5732         struct i802_bss *bss = priv;
5733         struct wpa_driver_nl80211_data *drv = bss->drv;
5734         struct wpa_scan_results *res;
5735
5736         res = nl80211_get_scan_results(drv);
5737         if (res)
5738                 wpa_driver_nl80211_check_bss_status(drv, res);
5739         return res;
5740 }
5741
5742
5743 static void nl80211_dump_scan(struct wpa_driver_nl80211_data *drv)
5744 {
5745         struct wpa_scan_results *res;
5746         size_t i;
5747
5748         res = nl80211_get_scan_results(drv);
5749         if (res == NULL) {
5750                 wpa_printf(MSG_DEBUG, "nl80211: Failed to get scan results");
5751                 return;
5752         }
5753
5754         wpa_printf(MSG_DEBUG, "nl80211: Scan result dump");
5755         for (i = 0; i < res->num; i++) {
5756                 struct wpa_scan_res *r = res->res[i];
5757                 wpa_printf(MSG_DEBUG, "nl80211: %d/%d " MACSTR "%s%s",
5758                            (int) i, (int) res->num, MAC2STR(r->bssid),
5759                            r->flags & WPA_SCAN_AUTHENTICATED ? " [auth]" : "",
5760                            r->flags & WPA_SCAN_ASSOCIATED ? " [assoc]" : "");
5761         }
5762
5763         wpa_scan_results_free(res);
5764 }
5765
5766
5767 static u32 wpa_alg_to_cipher_suite(enum wpa_alg alg, size_t key_len)
5768 {
5769         switch (alg) {
5770         case WPA_ALG_WEP:
5771                 if (key_len == 5)
5772                         return WLAN_CIPHER_SUITE_WEP40;
5773                 return WLAN_CIPHER_SUITE_WEP104;
5774         case WPA_ALG_TKIP:
5775                 return WLAN_CIPHER_SUITE_TKIP;
5776         case WPA_ALG_CCMP:
5777                 return WLAN_CIPHER_SUITE_CCMP;
5778         case WPA_ALG_GCMP:
5779                 return WLAN_CIPHER_SUITE_GCMP;
5780         case WPA_ALG_CCMP_256:
5781                 return WLAN_CIPHER_SUITE_CCMP_256;
5782         case WPA_ALG_GCMP_256:
5783                 return WLAN_CIPHER_SUITE_GCMP_256;
5784         case WPA_ALG_IGTK:
5785                 return WLAN_CIPHER_SUITE_AES_CMAC;
5786         case WPA_ALG_BIP_GMAC_128:
5787                 return WLAN_CIPHER_SUITE_BIP_GMAC_128;
5788         case WPA_ALG_BIP_GMAC_256:
5789                 return WLAN_CIPHER_SUITE_BIP_GMAC_256;
5790         case WPA_ALG_BIP_CMAC_256:
5791                 return WLAN_CIPHER_SUITE_BIP_CMAC_256;
5792         case WPA_ALG_SMS4:
5793                 return WLAN_CIPHER_SUITE_SMS4;
5794         case WPA_ALG_KRK:
5795                 return WLAN_CIPHER_SUITE_KRK;
5796         case WPA_ALG_NONE:
5797         case WPA_ALG_PMK:
5798                 wpa_printf(MSG_ERROR, "nl80211: Unexpected encryption algorithm %d",
5799                            alg);
5800                 return 0;
5801         }
5802
5803         wpa_printf(MSG_ERROR, "nl80211: Unsupported encryption algorithm %d",
5804                    alg);
5805         return 0;
5806 }
5807
5808
5809 static u32 wpa_cipher_to_cipher_suite(unsigned int cipher)
5810 {
5811         switch (cipher) {
5812         case WPA_CIPHER_CCMP_256:
5813                 return WLAN_CIPHER_SUITE_CCMP_256;
5814         case WPA_CIPHER_GCMP_256:
5815                 return WLAN_CIPHER_SUITE_GCMP_256;
5816         case WPA_CIPHER_CCMP:
5817                 return WLAN_CIPHER_SUITE_CCMP;
5818         case WPA_CIPHER_GCMP:
5819                 return WLAN_CIPHER_SUITE_GCMP;
5820         case WPA_CIPHER_TKIP:
5821                 return WLAN_CIPHER_SUITE_TKIP;
5822         case WPA_CIPHER_WEP104:
5823                 return WLAN_CIPHER_SUITE_WEP104;
5824         case WPA_CIPHER_WEP40:
5825                 return WLAN_CIPHER_SUITE_WEP40;
5826         case WPA_CIPHER_GTK_NOT_USED:
5827                 return WLAN_CIPHER_SUITE_NO_GROUP_ADDR;
5828         }
5829
5830         return 0;
5831 }
5832
5833
5834 static int wpa_cipher_to_cipher_suites(unsigned int ciphers, u32 suites[],
5835                                        int max_suites)
5836 {
5837         int num_suites = 0;
5838
5839         if (num_suites < max_suites && ciphers & WPA_CIPHER_CCMP_256)
5840                 suites[num_suites++] = WLAN_CIPHER_SUITE_CCMP_256;
5841         if (num_suites < max_suites && ciphers & WPA_CIPHER_GCMP_256)
5842                 suites[num_suites++] = WLAN_CIPHER_SUITE_GCMP_256;
5843         if (num_suites < max_suites && ciphers & WPA_CIPHER_CCMP)
5844                 suites[num_suites++] = WLAN_CIPHER_SUITE_CCMP;
5845         if (num_suites < max_suites && ciphers & WPA_CIPHER_GCMP)
5846                 suites[num_suites++] = WLAN_CIPHER_SUITE_GCMP;
5847         if (num_suites < max_suites && ciphers & WPA_CIPHER_TKIP)
5848                 suites[num_suites++] = WLAN_CIPHER_SUITE_TKIP;
5849         if (num_suites < max_suites && ciphers & WPA_CIPHER_WEP104)
5850                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP104;
5851         if (num_suites < max_suites && ciphers & WPA_CIPHER_WEP40)
5852                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP40;
5853
5854         return num_suites;
5855 }
5856
5857
5858 static int wpa_driver_nl80211_set_key(const char *ifname, struct i802_bss *bss,
5859                                       enum wpa_alg alg, const u8 *addr,
5860                                       int key_idx, int set_tx,
5861                                       const u8 *seq, size_t seq_len,
5862                                       const u8 *key, size_t key_len)
5863 {
5864         struct wpa_driver_nl80211_data *drv = bss->drv;
5865         int ifindex;
5866         struct nl_msg *msg;
5867         int ret;
5868         int tdls = 0;
5869
5870         /* Ignore for P2P Device */
5871         if (drv->nlmode == NL80211_IFTYPE_P2P_DEVICE)
5872                 return 0;
5873
5874         ifindex = if_nametoindex(ifname);
5875         wpa_printf(MSG_DEBUG, "%s: ifindex=%d (%s) alg=%d addr=%p key_idx=%d "
5876                    "set_tx=%d seq_len=%lu key_len=%lu",
5877                    __func__, ifindex, ifname, alg, addr, key_idx, set_tx,
5878                    (unsigned long) seq_len, (unsigned long) key_len);
5879 #ifdef CONFIG_TDLS
5880         if (key_idx == -1) {
5881                 key_idx = 0;
5882                 tdls = 1;
5883         }
5884 #endif /* CONFIG_TDLS */
5885
5886         msg = nlmsg_alloc();
5887         if (!msg)
5888                 return -ENOMEM;
5889
5890         if (alg == WPA_ALG_NONE) {
5891                 nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_KEY);
5892         } else {
5893                 nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_KEY);
5894                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
5895                 wpa_hexdump_key(MSG_DEBUG, "nl80211: KEY_DATA", key, key_len);
5896                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
5897                             wpa_alg_to_cipher_suite(alg, key_len));
5898         }
5899
5900         if (seq && seq_len) {
5901                 NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
5902                 wpa_hexdump(MSG_DEBUG, "nl80211: KEY_SEQ", seq, seq_len);
5903         }
5904
5905         if (addr && !is_broadcast_ether_addr(addr)) {
5906                 wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
5907                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5908
5909                 if (alg != WPA_ALG_WEP && key_idx && !set_tx) {
5910                         wpa_printf(MSG_DEBUG, "   RSN IBSS RX GTK");
5911                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_TYPE,
5912                                     NL80211_KEYTYPE_GROUP);
5913                 }
5914         } else if (addr && is_broadcast_ether_addr(addr)) {
5915                 struct nlattr *types;
5916
5917                 wpa_printf(MSG_DEBUG, "   broadcast key");
5918
5919                 types = nla_nest_start(msg, NL80211_ATTR_KEY_DEFAULT_TYPES);
5920                 if (!types)
5921                         goto nla_put_failure;
5922                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
5923                 nla_nest_end(msg, types);
5924         }
5925         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
5926         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
5927
5928         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5929         if ((ret == -ENOENT || ret == -ENOLINK) && alg == WPA_ALG_NONE)
5930                 ret = 0;
5931         if (ret)
5932                 wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
5933                            ret, strerror(-ret));
5934
5935         /*
5936          * If we failed or don't need to set the default TX key (below),
5937          * we're done here.
5938          */
5939         if (ret || !set_tx || alg == WPA_ALG_NONE || tdls)
5940                 return ret;
5941         if (is_ap_interface(drv->nlmode) && addr &&
5942             !is_broadcast_ether_addr(addr))
5943                 return ret;
5944
5945         msg = nlmsg_alloc();
5946         if (!msg)
5947                 return -ENOMEM;
5948
5949         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_KEY);
5950         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
5951         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
5952         if (alg == WPA_ALG_IGTK)
5953                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
5954         else
5955                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
5956         if (addr && is_broadcast_ether_addr(addr)) {
5957                 struct nlattr *types;
5958
5959                 types = nla_nest_start(msg, NL80211_ATTR_KEY_DEFAULT_TYPES);
5960                 if (!types)
5961                         goto nla_put_failure;
5962                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
5963                 nla_nest_end(msg, types);
5964         } else if (addr) {
5965                 struct nlattr *types;
5966
5967                 types = nla_nest_start(msg, NL80211_ATTR_KEY_DEFAULT_TYPES);
5968                 if (!types)
5969                         goto nla_put_failure;
5970                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_TYPE_UNICAST);
5971                 nla_nest_end(msg, types);
5972         }
5973
5974         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5975         if (ret == -ENOENT)
5976                 ret = 0;
5977         if (ret)
5978                 wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
5979                            "err=%d %s)", ret, strerror(-ret));
5980         return ret;
5981
5982 nla_put_failure:
5983         nlmsg_free(msg);
5984         return -ENOBUFS;
5985 }
5986
5987
5988 static int nl_add_key(struct nl_msg *msg, enum wpa_alg alg,
5989                       int key_idx, int defkey,
5990                       const u8 *seq, size_t seq_len,
5991                       const u8 *key, size_t key_len)
5992 {
5993         struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
5994         if (!key_attr)
5995                 return -1;
5996
5997         if (defkey && alg == WPA_ALG_IGTK)
5998                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
5999         else if (defkey)
6000                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
6001
6002         NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
6003
6004         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
6005                     wpa_alg_to_cipher_suite(alg, key_len));
6006
6007         if (seq && seq_len)
6008                 NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
6009
6010         NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
6011
6012         nla_nest_end(msg, key_attr);
6013
6014         return 0;
6015  nla_put_failure:
6016         return -1;
6017 }
6018
6019
6020 static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
6021                                  struct nl_msg *msg)
6022 {
6023         int i, privacy = 0;
6024         struct nlattr *nl_keys, *nl_key;
6025
6026         for (i = 0; i < 4; i++) {
6027                 if (!params->wep_key[i])
6028                         continue;
6029                 privacy = 1;
6030                 break;
6031         }
6032         if (params->wps == WPS_MODE_PRIVACY)
6033                 privacy = 1;
6034         if (params->pairwise_suite &&
6035             params->pairwise_suite != WPA_CIPHER_NONE)
6036                 privacy = 1;
6037
6038         if (!privacy)
6039                 return 0;
6040
6041         NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
6042
6043         nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
6044         if (!nl_keys)
6045                 goto nla_put_failure;
6046
6047         for (i = 0; i < 4; i++) {
6048                 if (!params->wep_key[i])
6049                         continue;
6050
6051                 nl_key = nla_nest_start(msg, i);
6052                 if (!nl_key)
6053                         goto nla_put_failure;
6054
6055                 NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
6056                         params->wep_key[i]);
6057                 if (params->wep_key_len[i] == 5)
6058                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
6059                                     WLAN_CIPHER_SUITE_WEP40);
6060                 else
6061                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
6062                                     WLAN_CIPHER_SUITE_WEP104);
6063
6064                 NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
6065
6066                 if (i == params->wep_tx_keyidx)
6067                         NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
6068
6069                 nla_nest_end(msg, nl_key);
6070         }
6071         nla_nest_end(msg, nl_keys);
6072
6073         return 0;
6074
6075 nla_put_failure:
6076         return -ENOBUFS;
6077 }
6078
6079
6080 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
6081                                    const u8 *addr, int cmd, u16 reason_code,
6082                                    int local_state_change)
6083 {
6084         int ret = -1;
6085         struct nl_msg *msg;
6086
6087         msg = nlmsg_alloc();
6088         if (!msg)
6089                 return -1;
6090
6091         nl80211_cmd(drv, msg, 0, cmd);
6092
6093         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6094         NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
6095         if (addr)
6096                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
6097         if (local_state_change)
6098                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
6099
6100         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6101         msg = NULL;
6102         if (ret) {
6103                 wpa_dbg(drv->ctx, MSG_DEBUG,
6104                         "nl80211: MLME command failed: reason=%u ret=%d (%s)",
6105                         reason_code, ret, strerror(-ret));
6106                 goto nla_put_failure;
6107         }
6108         ret = 0;
6109
6110 nla_put_failure:
6111         nlmsg_free(msg);
6112         return ret;
6113 }
6114
6115
6116 static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
6117                                          int reason_code)
6118 {
6119         int ret;
6120
6121         wpa_printf(MSG_DEBUG, "%s(reason_code=%d)", __func__, reason_code);
6122         nl80211_mark_disconnected(drv);
6123         /* Disconnect command doesn't need BSSID - it uses cached value */
6124         ret = wpa_driver_nl80211_mlme(drv, NULL, NL80211_CMD_DISCONNECT,
6125                                       reason_code, 0);
6126         /*
6127          * For locally generated disconnect, supplicant already generates a
6128          * DEAUTH event, so ignore the event from NL80211.
6129          */
6130         drv->ignore_next_local_disconnect = ret == 0;
6131
6132         return ret;
6133 }
6134
6135
6136 static int wpa_driver_nl80211_deauthenticate(struct i802_bss *bss,
6137                                              const u8 *addr, int reason_code)
6138 {
6139         struct wpa_driver_nl80211_data *drv = bss->drv;
6140         int ret;
6141
6142         if (drv->nlmode == NL80211_IFTYPE_ADHOC) {
6143                 nl80211_mark_disconnected(drv);
6144                 return nl80211_leave_ibss(drv);
6145         }
6146         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
6147                 return wpa_driver_nl80211_disconnect(drv, reason_code);
6148         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
6149                    __func__, MAC2STR(addr), reason_code);
6150         nl80211_mark_disconnected(drv);
6151         ret = wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
6152                                       reason_code, 0);
6153         /*
6154          * For locally generated deauthenticate, supplicant already generates a
6155          * DEAUTH event, so ignore the event from NL80211.
6156          */
6157         drv->ignore_next_local_deauth = ret == 0;
6158         return ret;
6159 }
6160
6161
6162 static void nl80211_copy_auth_params(struct wpa_driver_nl80211_data *drv,
6163                                      struct wpa_driver_auth_params *params)
6164 {
6165         int i;
6166
6167         drv->auth_freq = params->freq;
6168         drv->auth_alg = params->auth_alg;
6169         drv->auth_wep_tx_keyidx = params->wep_tx_keyidx;
6170         drv->auth_local_state_change = params->local_state_change;
6171         drv->auth_p2p = params->p2p;
6172
6173         if (params->bssid)
6174                 os_memcpy(drv->auth_bssid_, params->bssid, ETH_ALEN);
6175         else
6176                 os_memset(drv->auth_bssid_, 0, ETH_ALEN);
6177
6178         if (params->ssid) {
6179                 os_memcpy(drv->auth_ssid, params->ssid, params->ssid_len);
6180                 drv->auth_ssid_len = params->ssid_len;
6181         } else
6182                 drv->auth_ssid_len = 0;
6183
6184
6185         os_free(drv->auth_ie);
6186         drv->auth_ie = NULL;
6187         drv->auth_ie_len = 0;
6188         if (params->ie) {
6189                 drv->auth_ie = os_malloc(params->ie_len);
6190                 if (drv->auth_ie) {
6191                         os_memcpy(drv->auth_ie, params->ie, params->ie_len);
6192                         drv->auth_ie_len = params->ie_len;
6193                 }
6194         }
6195
6196         for (i = 0; i < 4; i++) {
6197                 if (params->wep_key[i] && params->wep_key_len[i] &&
6198                     params->wep_key_len[i] <= 16) {
6199                         os_memcpy(drv->auth_wep_key[i], params->wep_key[i],
6200                                   params->wep_key_len[i]);
6201                         drv->auth_wep_key_len[i] = params->wep_key_len[i];
6202                 } else
6203                         drv->auth_wep_key_len[i] = 0;
6204         }
6205 }
6206
6207
6208 static int wpa_driver_nl80211_authenticate(
6209         struct i802_bss *bss, struct wpa_driver_auth_params *params)
6210 {
6211         struct wpa_driver_nl80211_data *drv = bss->drv;
6212         int ret = -1, i;
6213         struct nl_msg *msg;
6214         enum nl80211_auth_type type;
6215         enum nl80211_iftype nlmode;
6216         int count = 0;
6217         int is_retry;
6218
6219         is_retry = drv->retry_auth;
6220         drv->retry_auth = 0;
6221         drv->ignore_deauth_event = 0;
6222
6223         nl80211_mark_disconnected(drv);
6224         os_memset(drv->auth_bssid, 0, ETH_ALEN);
6225         if (params->bssid)
6226                 os_memcpy(drv->auth_attempt_bssid, params->bssid, ETH_ALEN);
6227         else
6228                 os_memset(drv->auth_attempt_bssid, 0, ETH_ALEN);
6229         /* FIX: IBSS mode */
6230         nlmode = params->p2p ?
6231                 NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
6232         if (drv->nlmode != nlmode &&
6233             wpa_driver_nl80211_set_mode(bss, nlmode) < 0)
6234                 return -1;
6235
6236 retry:
6237         msg = nlmsg_alloc();
6238         if (!msg)
6239                 return -1;
6240
6241         wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
6242                    drv->ifindex);
6243
6244         nl80211_cmd(drv, msg, 0, NL80211_CMD_AUTHENTICATE);
6245
6246         for (i = 0; i < 4; i++) {
6247                 if (!params->wep_key[i])
6248                         continue;
6249                 wpa_driver_nl80211_set_key(bss->ifname, bss, WPA_ALG_WEP,
6250                                            NULL, i,
6251                                            i == params->wep_tx_keyidx, NULL, 0,
6252                                            params->wep_key[i],
6253                                            params->wep_key_len[i]);
6254                 if (params->wep_tx_keyidx != i)
6255                         continue;
6256                 if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
6257                                params->wep_key[i], params->wep_key_len[i])) {
6258                         nlmsg_free(msg);
6259                         return -1;
6260                 }
6261         }
6262
6263         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6264         if (params->bssid) {
6265                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
6266                            MAC2STR(params->bssid));
6267                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6268         }
6269         if (params->freq) {
6270                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6271                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6272         }
6273         if (params->ssid) {
6274                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6275                                   params->ssid, params->ssid_len);
6276                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6277                         params->ssid);
6278         }
6279         wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
6280         if (params->ie)
6281                 NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
6282         if (params->sae_data) {
6283                 wpa_hexdump(MSG_DEBUG, "  * SAE data", params->sae_data,
6284                             params->sae_data_len);
6285                 NLA_PUT(msg, NL80211_ATTR_SAE_DATA, params->sae_data_len,
6286                         params->sae_data);
6287         }
6288         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
6289                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
6290         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
6291                 type = NL80211_AUTHTYPE_SHARED_KEY;
6292         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
6293                 type = NL80211_AUTHTYPE_NETWORK_EAP;
6294         else if (params->auth_alg & WPA_AUTH_ALG_FT)
6295                 type = NL80211_AUTHTYPE_FT;
6296         else if (params->auth_alg & WPA_AUTH_ALG_SAE)
6297                 type = NL80211_AUTHTYPE_SAE;
6298         else
6299                 goto nla_put_failure;
6300         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
6301         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
6302         if (params->local_state_change) {
6303                 wpa_printf(MSG_DEBUG, "  * Local state change only");
6304                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
6305         }
6306
6307         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6308         msg = NULL;
6309         if (ret) {
6310                 wpa_dbg(drv->ctx, MSG_DEBUG,
6311                         "nl80211: MLME command failed (auth): ret=%d (%s)",
6312                         ret, strerror(-ret));
6313                 count++;
6314                 if (ret == -EALREADY && count == 1 && params->bssid &&
6315                     !params->local_state_change) {
6316                         /*
6317                          * mac80211 does not currently accept new
6318                          * authentication if we are already authenticated. As a
6319                          * workaround, force deauthentication and try again.
6320                          */
6321                         wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
6322                                    "after forced deauthentication");
6323                         drv->ignore_deauth_event = 1;
6324                         wpa_driver_nl80211_deauthenticate(
6325                                 bss, params->bssid,
6326                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
6327                         nlmsg_free(msg);
6328                         goto retry;
6329                 }
6330
6331                 if (ret == -ENOENT && params->freq && !is_retry) {
6332                         /*
6333                          * cfg80211 has likely expired the BSS entry even
6334                          * though it was previously available in our internal
6335                          * BSS table. To recover quickly, start a single
6336                          * channel scan on the specified channel.
6337                          */
6338                         struct wpa_driver_scan_params scan;
6339                         int freqs[2];
6340
6341                         os_memset(&scan, 0, sizeof(scan));
6342                         scan.num_ssids = 1;
6343                         if (params->ssid) {
6344                                 scan.ssids[0].ssid = params->ssid;
6345                                 scan.ssids[0].ssid_len = params->ssid_len;
6346                         }
6347                         freqs[0] = params->freq;
6348                         freqs[1] = 0;
6349                         scan.freqs = freqs;
6350                         wpa_printf(MSG_DEBUG, "nl80211: Trigger single "
6351                                    "channel scan to refresh cfg80211 BSS "
6352                                    "entry");
6353                         ret = wpa_driver_nl80211_scan(bss, &scan);
6354                         if (ret == 0) {
6355                                 nl80211_copy_auth_params(drv, params);
6356                                 drv->scan_for_auth = 1;
6357                         }
6358                 } else if (is_retry) {
6359                         /*
6360                          * Need to indicate this with an event since the return
6361                          * value from the retry is not delivered to core code.
6362                          */
6363                         union wpa_event_data event;
6364                         wpa_printf(MSG_DEBUG, "nl80211: Authentication retry "
6365                                    "failed");
6366                         os_memset(&event, 0, sizeof(event));
6367                         os_memcpy(event.timeout_event.addr, drv->auth_bssid_,
6368                                   ETH_ALEN);
6369                         wpa_supplicant_event(drv->ctx, EVENT_AUTH_TIMED_OUT,
6370                                              &event);
6371                 }
6372
6373                 goto nla_put_failure;
6374         }
6375         ret = 0;
6376         wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
6377                    "successfully");
6378
6379 nla_put_failure:
6380         nlmsg_free(msg);
6381         return ret;
6382 }
6383
6384
6385 static int wpa_driver_nl80211_authenticate_retry(
6386         struct wpa_driver_nl80211_data *drv)
6387 {
6388         struct wpa_driver_auth_params params;
6389         struct i802_bss *bss = drv->first_bss;
6390         int i;
6391
6392         wpa_printf(MSG_DEBUG, "nl80211: Try to authenticate again");
6393
6394         os_memset(&params, 0, sizeof(params));
6395         params.freq = drv->auth_freq;
6396         params.auth_alg = drv->auth_alg;
6397         params.wep_tx_keyidx = drv->auth_wep_tx_keyidx;
6398         params.local_state_change = drv->auth_local_state_change;
6399         params.p2p = drv->auth_p2p;
6400
6401         if (!is_zero_ether_addr(drv->auth_bssid_))
6402                 params.bssid = drv->auth_bssid_;
6403
6404         if (drv->auth_ssid_len) {
6405                 params.ssid = drv->auth_ssid;
6406                 params.ssid_len = drv->auth_ssid_len;
6407         }
6408
6409         params.ie = drv->auth_ie;
6410         params.ie_len = drv->auth_ie_len;
6411
6412         for (i = 0; i < 4; i++) {
6413                 if (drv->auth_wep_key_len[i]) {
6414                         params.wep_key[i] = drv->auth_wep_key[i];
6415                         params.wep_key_len[i] = drv->auth_wep_key_len[i];
6416                 }
6417         }
6418
6419         drv->retry_auth = 1;
6420         return wpa_driver_nl80211_authenticate(bss, &params);
6421 }
6422
6423
6424 struct phy_info_arg {
6425         u16 *num_modes;
6426         struct hostapd_hw_modes *modes;
6427         int last_mode, last_chan_idx;
6428 };
6429
6430 static void phy_info_ht_capa(struct hostapd_hw_modes *mode, struct nlattr *capa,
6431                              struct nlattr *ampdu_factor,
6432                              struct nlattr *ampdu_density,
6433                              struct nlattr *mcs_set)
6434 {
6435         if (capa)
6436                 mode->ht_capab = nla_get_u16(capa);
6437
6438         if (ampdu_factor)
6439                 mode->a_mpdu_params |= nla_get_u8(ampdu_factor) & 0x03;
6440
6441         if (ampdu_density)
6442                 mode->a_mpdu_params |= nla_get_u8(ampdu_density) << 2;
6443
6444         if (mcs_set && nla_len(mcs_set) >= 16) {
6445                 u8 *mcs;
6446                 mcs = nla_data(mcs_set);
6447                 os_memcpy(mode->mcs_set, mcs, 16);
6448         }
6449 }
6450
6451
6452 static void phy_info_vht_capa(struct hostapd_hw_modes *mode,
6453                               struct nlattr *capa,
6454                               struct nlattr *mcs_set)
6455 {
6456         if (capa)
6457                 mode->vht_capab = nla_get_u32(capa);
6458
6459         if (mcs_set && nla_len(mcs_set) >= 8) {
6460                 u8 *mcs;
6461                 mcs = nla_data(mcs_set);
6462                 os_memcpy(mode->vht_mcs_set, mcs, 8);
6463         }
6464 }
6465
6466
6467 static void phy_info_freq(struct hostapd_hw_modes *mode,
6468                           struct hostapd_channel_data *chan,
6469                           struct nlattr *tb_freq[])
6470 {
6471         u8 channel;
6472         chan->freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
6473         chan->flag = 0;
6474         chan->dfs_cac_ms = 0;
6475         if (ieee80211_freq_to_chan(chan->freq, &channel) != NUM_HOSTAPD_MODES)
6476                 chan->chan = channel;
6477
6478         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
6479                 chan->flag |= HOSTAPD_CHAN_DISABLED;
6480         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IR])
6481                 chan->flag |= HOSTAPD_CHAN_PASSIVE_SCAN | HOSTAPD_CHAN_NO_IBSS;
6482         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
6483                 chan->flag |= HOSTAPD_CHAN_RADAR;
6484
6485         if (tb_freq[NL80211_FREQUENCY_ATTR_DFS_STATE]) {
6486                 enum nl80211_dfs_state state =
6487                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_DFS_STATE]);
6488
6489                 switch (state) {
6490                 case NL80211_DFS_USABLE:
6491                         chan->flag |= HOSTAPD_CHAN_DFS_USABLE;
6492                         break;
6493                 case NL80211_DFS_AVAILABLE:
6494                         chan->flag |= HOSTAPD_CHAN_DFS_AVAILABLE;
6495                         break;
6496                 case NL80211_DFS_UNAVAILABLE:
6497                         chan->flag |= HOSTAPD_CHAN_DFS_UNAVAILABLE;
6498                         break;
6499                 }
6500         }
6501
6502         if (tb_freq[NL80211_FREQUENCY_ATTR_DFS_CAC_TIME]) {
6503                 chan->dfs_cac_ms = nla_get_u32(
6504                         tb_freq[NL80211_FREQUENCY_ATTR_DFS_CAC_TIME]);
6505         }
6506 }
6507
6508
6509 static int phy_info_freqs(struct phy_info_arg *phy_info,
6510                           struct hostapd_hw_modes *mode, struct nlattr *tb)
6511 {
6512         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
6513                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
6514                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
6515                 [NL80211_FREQUENCY_ATTR_NO_IR] = { .type = NLA_FLAG },
6516                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
6517                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
6518                 [NL80211_FREQUENCY_ATTR_DFS_STATE] = { .type = NLA_U32 },
6519         };
6520         int new_channels = 0;
6521         struct hostapd_channel_data *channel;
6522         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
6523         struct nlattr *nl_freq;
6524         int rem_freq, idx;
6525
6526         if (tb == NULL)
6527                 return NL_OK;
6528
6529         nla_for_each_nested(nl_freq, tb, rem_freq) {
6530                 nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX,
6531                           nla_data(nl_freq), nla_len(nl_freq), freq_policy);
6532                 if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
6533                         continue;
6534                 new_channels++;
6535         }
6536
6537         channel = os_realloc_array(mode->channels,
6538                                    mode->num_channels + new_channels,
6539                                    sizeof(struct hostapd_channel_data));
6540         if (!channel)
6541                 return NL_SKIP;
6542
6543         mode->channels = channel;
6544         mode->num_channels += new_channels;
6545
6546         idx = phy_info->last_chan_idx;
6547
6548         nla_for_each_nested(nl_freq, tb, rem_freq) {
6549                 nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX,
6550                           nla_data(nl_freq), nla_len(nl_freq), freq_policy);
6551                 if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
6552                         continue;
6553                 phy_info_freq(mode, &mode->channels[idx], tb_freq);
6554                 idx++;
6555         }
6556         phy_info->last_chan_idx = idx;
6557
6558         return NL_OK;
6559 }
6560
6561
6562 static int phy_info_rates(struct hostapd_hw_modes *mode, struct nlattr *tb)
6563 {
6564         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
6565                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
6566                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] =
6567                 { .type = NLA_FLAG },
6568         };
6569         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
6570         struct nlattr *nl_rate;
6571         int rem_rate, idx;
6572
6573         if (tb == NULL)
6574                 return NL_OK;
6575
6576         nla_for_each_nested(nl_rate, tb, rem_rate) {
6577                 nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX,
6578                           nla_data(nl_rate), nla_len(nl_rate),
6579                           rate_policy);
6580                 if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
6581                         continue;
6582                 mode->num_rates++;
6583         }
6584
6585         mode->rates = os_calloc(mode->num_rates, sizeof(int));
6586         if (!mode->rates)
6587                 return NL_SKIP;
6588
6589         idx = 0;
6590
6591         nla_for_each_nested(nl_rate, tb, rem_rate) {
6592                 nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX,
6593                           nla_data(nl_rate), nla_len(nl_rate),
6594                           rate_policy);
6595                 if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
6596                         continue;
6597                 mode->rates[idx] = nla_get_u32(
6598                         tb_rate[NL80211_BITRATE_ATTR_RATE]);
6599                 idx++;
6600         }
6601
6602         return NL_OK;
6603 }
6604
6605
6606 static int phy_info_band(struct phy_info_arg *phy_info, struct nlattr *nl_band)
6607 {
6608         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
6609         struct hostapd_hw_modes *mode;
6610         int ret;
6611
6612         if (phy_info->last_mode != nl_band->nla_type) {
6613                 mode = os_realloc_array(phy_info->modes,
6614                                         *phy_info->num_modes + 1,
6615                                         sizeof(*mode));
6616                 if (!mode)
6617                         return NL_SKIP;
6618                 phy_info->modes = mode;
6619
6620                 mode = &phy_info->modes[*(phy_info->num_modes)];
6621                 os_memset(mode, 0, sizeof(*mode));
6622                 mode->mode = NUM_HOSTAPD_MODES;
6623                 mode->flags = HOSTAPD_MODE_FLAG_HT_INFO_KNOWN |
6624                         HOSTAPD_MODE_FLAG_VHT_INFO_KNOWN;
6625
6626                 /*
6627                  * Unsupported VHT MCS stream is defined as value 3, so the VHT
6628                  * MCS RX/TX map must be initialized with 0xffff to mark all 8
6629                  * possible streams as unsupported. This will be overridden if
6630                  * driver advertises VHT support.
6631                  */
6632                 mode->vht_mcs_set[0] = 0xff;
6633                 mode->vht_mcs_set[1] = 0xff;
6634                 mode->vht_mcs_set[4] = 0xff;
6635                 mode->vht_mcs_set[5] = 0xff;
6636
6637                 *(phy_info->num_modes) += 1;
6638                 phy_info->last_mode = nl_band->nla_type;
6639                 phy_info->last_chan_idx = 0;
6640         } else
6641                 mode = &phy_info->modes[*(phy_info->num_modes) - 1];
6642
6643         nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
6644                   nla_len(nl_band), NULL);
6645
6646         phy_info_ht_capa(mode, tb_band[NL80211_BAND_ATTR_HT_CAPA],
6647                          tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR],
6648                          tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY],
6649                          tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
6650         phy_info_vht_capa(mode, tb_band[NL80211_BAND_ATTR_VHT_CAPA],
6651                           tb_band[NL80211_BAND_ATTR_VHT_MCS_SET]);
6652         ret = phy_info_freqs(phy_info, mode, tb_band[NL80211_BAND_ATTR_FREQS]);
6653         if (ret != NL_OK)
6654                 return ret;
6655         ret = phy_info_rates(mode, tb_band[NL80211_BAND_ATTR_RATES]);
6656         if (ret != NL_OK)
6657                 return ret;
6658
6659         return NL_OK;
6660 }
6661
6662
6663 static int phy_info_handler(struct nl_msg *msg, void *arg)
6664 {
6665         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
6666         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
6667         struct phy_info_arg *phy_info = arg;
6668         struct nlattr *nl_band;
6669         int rem_band;
6670
6671         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
6672                   genlmsg_attrlen(gnlh, 0), NULL);
6673
6674         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
6675                 return NL_SKIP;
6676
6677         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band)
6678         {
6679                 int res = phy_info_band(phy_info, nl_band);
6680                 if (res != NL_OK)
6681                         return res;
6682         }
6683
6684         return NL_SKIP;
6685 }
6686
6687
6688 static struct hostapd_hw_modes *
6689 wpa_driver_nl80211_postprocess_modes(struct hostapd_hw_modes *modes,
6690                                      u16 *num_modes)
6691 {
6692         u16 m;
6693         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
6694         int i, mode11g_idx = -1;
6695
6696         /* heuristic to set up modes */
6697         for (m = 0; m < *num_modes; m++) {
6698                 if (!modes[m].num_channels)
6699                         continue;
6700                 if (modes[m].channels[0].freq < 4000) {
6701                         modes[m].mode = HOSTAPD_MODE_IEEE80211B;
6702                         for (i = 0; i < modes[m].num_rates; i++) {
6703                                 if (modes[m].rates[i] > 200) {
6704                                         modes[m].mode = HOSTAPD_MODE_IEEE80211G;
6705                                         break;
6706                                 }
6707                         }
6708                 } else if (modes[m].channels[0].freq > 50000)
6709                         modes[m].mode = HOSTAPD_MODE_IEEE80211AD;
6710                 else
6711                         modes[m].mode = HOSTAPD_MODE_IEEE80211A;
6712         }
6713
6714         /* If only 802.11g mode is included, use it to construct matching
6715          * 802.11b mode data. */
6716
6717         for (m = 0; m < *num_modes; m++) {
6718                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
6719                         return modes; /* 802.11b already included */
6720                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
6721                         mode11g_idx = m;
6722         }
6723
6724         if (mode11g_idx < 0)
6725                 return modes; /* 2.4 GHz band not supported at all */
6726
6727         nmodes = os_realloc_array(modes, *num_modes + 1, sizeof(*nmodes));
6728         if (nmodes == NULL)
6729                 return modes; /* Could not add 802.11b mode */
6730
6731         mode = &nmodes[*num_modes];
6732         os_memset(mode, 0, sizeof(*mode));
6733         (*num_modes)++;
6734         modes = nmodes;
6735
6736         mode->mode = HOSTAPD_MODE_IEEE80211B;
6737
6738         mode11g = &modes[mode11g_idx];
6739         mode->num_channels = mode11g->num_channels;
6740         mode->channels = os_malloc(mode11g->num_channels *
6741                                    sizeof(struct hostapd_channel_data));
6742         if (mode->channels == NULL) {
6743                 (*num_modes)--;
6744                 return modes; /* Could not add 802.11b mode */
6745         }
6746         os_memcpy(mode->channels, mode11g->channels,
6747                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
6748
6749         mode->num_rates = 0;
6750         mode->rates = os_malloc(4 * sizeof(int));
6751         if (mode->rates == NULL) {
6752                 os_free(mode->channels);
6753                 (*num_modes)--;
6754                 return modes; /* Could not add 802.11b mode */
6755         }
6756
6757         for (i = 0; i < mode11g->num_rates; i++) {
6758                 if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 &&
6759                     mode11g->rates[i] != 55 && mode11g->rates[i] != 110)
6760                         continue;
6761                 mode->rates[mode->num_rates] = mode11g->rates[i];
6762                 mode->num_rates++;
6763                 if (mode->num_rates == 4)
6764                         break;
6765         }
6766
6767         if (mode->num_rates == 0) {
6768                 os_free(mode->channels);
6769                 os_free(mode->rates);
6770                 (*num_modes)--;
6771                 return modes; /* No 802.11b rates */
6772         }
6773
6774         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
6775                    "information");
6776
6777         return modes;
6778 }
6779
6780
6781 static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start,
6782                                   int end)
6783 {
6784         int c;
6785
6786         for (c = 0; c < mode->num_channels; c++) {
6787                 struct hostapd_channel_data *chan = &mode->channels[c];
6788                 if (chan->freq - 10 >= start && chan->freq + 10 <= end)
6789                         chan->flag |= HOSTAPD_CHAN_HT40;
6790         }
6791 }
6792
6793
6794 static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start,
6795                                       int end)
6796 {
6797         int c;
6798
6799         for (c = 0; c < mode->num_channels; c++) {
6800                 struct hostapd_channel_data *chan = &mode->channels[c];
6801                 if (!(chan->flag & HOSTAPD_CHAN_HT40))
6802                         continue;
6803                 if (chan->freq - 30 >= start && chan->freq - 10 <= end)
6804                         chan->flag |= HOSTAPD_CHAN_HT40MINUS;
6805                 if (chan->freq + 10 >= start && chan->freq + 30 <= end)
6806                         chan->flag |= HOSTAPD_CHAN_HT40PLUS;
6807         }
6808 }
6809
6810
6811 static void nl80211_reg_rule_max_eirp(u32 start, u32 end, u32 max_eirp,
6812                                       struct phy_info_arg *results)
6813 {
6814         u16 m;
6815
6816         for (m = 0; m < *results->num_modes; m++) {
6817                 int c;
6818                 struct hostapd_hw_modes *mode = &results->modes[m];
6819
6820                 for (c = 0; c < mode->num_channels; c++) {
6821                         struct hostapd_channel_data *chan = &mode->channels[c];
6822                         if ((u32) chan->freq - 10 >= start &&
6823                             (u32) chan->freq + 10 <= end)
6824                                 chan->max_tx_power = max_eirp;
6825                 }
6826         }
6827 }
6828
6829
6830 static void nl80211_reg_rule_ht40(u32 start, u32 end,
6831                                   struct phy_info_arg *results)
6832 {
6833         u16 m;
6834
6835         for (m = 0; m < *results->num_modes; m++) {
6836                 if (!(results->modes[m].ht_capab &
6837                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
6838                         continue;
6839                 nl80211_set_ht40_mode(&results->modes[m], start, end);
6840         }
6841 }
6842
6843
6844 static void nl80211_reg_rule_sec(struct nlattr *tb[],
6845                                  struct phy_info_arg *results)
6846 {
6847         u32 start, end, max_bw;
6848         u16 m;
6849
6850         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
6851             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
6852             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
6853                 return;
6854
6855         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
6856         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
6857         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
6858
6859         if (max_bw < 20)
6860                 return;
6861
6862         for (m = 0; m < *results->num_modes; m++) {
6863                 if (!(results->modes[m].ht_capab &
6864                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
6865                         continue;
6866                 nl80211_set_ht40_mode_sec(&results->modes[m], start, end);
6867         }
6868 }
6869
6870
6871 static void nl80211_set_vht_mode(struct hostapd_hw_modes *mode, int start,
6872                                  int end)
6873 {
6874         int c;
6875
6876         for (c = 0; c < mode->num_channels; c++) {
6877                 struct hostapd_channel_data *chan = &mode->channels[c];
6878                 if (chan->freq - 10 >= start && chan->freq + 70 <= end)
6879                         chan->flag |= HOSTAPD_CHAN_VHT_10_70;
6880
6881                 if (chan->freq - 30 >= start && chan->freq + 50 <= end)
6882                         chan->flag |= HOSTAPD_CHAN_VHT_30_50;
6883
6884                 if (chan->freq - 50 >= start && chan->freq + 30 <= end)
6885                         chan->flag |= HOSTAPD_CHAN_VHT_50_30;
6886
6887                 if (chan->freq - 70 >= start && chan->freq + 10 <= end)
6888                         chan->flag |= HOSTAPD_CHAN_VHT_70_10;
6889         }
6890 }
6891
6892
6893 static void nl80211_reg_rule_vht(struct nlattr *tb[],
6894                                  struct phy_info_arg *results)
6895 {
6896         u32 start, end, max_bw;
6897         u16 m;
6898
6899         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
6900             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
6901             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
6902                 return;
6903
6904         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
6905         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
6906         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
6907
6908         if (max_bw < 80)
6909                 return;
6910
6911         for (m = 0; m < *results->num_modes; m++) {
6912                 if (!(results->modes[m].ht_capab &
6913                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
6914                         continue;
6915                 /* TODO: use a real VHT support indication */
6916                 if (!results->modes[m].vht_capab)
6917                         continue;
6918
6919                 nl80211_set_vht_mode(&results->modes[m], start, end);
6920         }
6921 }
6922
6923
6924 static const char * dfs_domain_name(enum nl80211_dfs_regions region)
6925 {
6926         switch (region) {
6927         case NL80211_DFS_UNSET:
6928                 return "DFS-UNSET";
6929         case NL80211_DFS_FCC:
6930                 return "DFS-FCC";
6931         case NL80211_DFS_ETSI:
6932                 return "DFS-ETSI";
6933         case NL80211_DFS_JP:
6934                 return "DFS-JP";
6935         default:
6936                 return "DFS-invalid";
6937         }
6938 }
6939
6940
6941 static int nl80211_get_reg(struct nl_msg *msg, void *arg)
6942 {
6943         struct phy_info_arg *results = arg;
6944         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
6945         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
6946         struct nlattr *nl_rule;
6947         struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1];
6948         int rem_rule;
6949         static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
6950                 [NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
6951                 [NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
6952                 [NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
6953                 [NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
6954                 [NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
6955                 [NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
6956         };
6957
6958         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
6959                   genlmsg_attrlen(gnlh, 0), NULL);
6960         if (!tb_msg[NL80211_ATTR_REG_ALPHA2] ||
6961             !tb_msg[NL80211_ATTR_REG_RULES]) {
6962                 wpa_printf(MSG_DEBUG, "nl80211: No regulatory information "
6963                            "available");
6964                 return NL_SKIP;
6965         }
6966
6967         if (tb_msg[NL80211_ATTR_DFS_REGION]) {
6968                 enum nl80211_dfs_regions dfs_domain;
6969                 dfs_domain = nla_get_u8(tb_msg[NL80211_ATTR_DFS_REGION]);
6970                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s (%s)",
6971                            (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]),
6972                            dfs_domain_name(dfs_domain));
6973         } else {
6974                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s",
6975                            (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]));
6976         }
6977
6978         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
6979         {
6980                 u32 start, end, max_eirp = 0, max_bw = 0, flags = 0;
6981                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
6982                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
6983                 if (tb_rule[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
6984                     tb_rule[NL80211_ATTR_FREQ_RANGE_END] == NULL)
6985                         continue;
6986                 start = nla_get_u32(tb_rule[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
6987                 end = nla_get_u32(tb_rule[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
6988                 if (tb_rule[NL80211_ATTR_POWER_RULE_MAX_EIRP])
6989                         max_eirp = nla_get_u32(tb_rule[NL80211_ATTR_POWER_RULE_MAX_EIRP]) / 100;
6990                 if (tb_rule[NL80211_ATTR_FREQ_RANGE_MAX_BW])
6991                         max_bw = nla_get_u32(tb_rule[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
6992                 if (tb_rule[NL80211_ATTR_REG_RULE_FLAGS])
6993                         flags = nla_get_u32(tb_rule[NL80211_ATTR_REG_RULE_FLAGS]);
6994
6995                 wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz %u mBm%s%s%s%s%s%s%s%s",
6996                            start, end, max_bw, max_eirp,
6997                            flags & NL80211_RRF_NO_OFDM ? " (no OFDM)" : "",
6998                            flags & NL80211_RRF_NO_CCK ? " (no CCK)" : "",
6999                            flags & NL80211_RRF_NO_INDOOR ? " (no indoor)" : "",
7000                            flags & NL80211_RRF_NO_OUTDOOR ? " (no outdoor)" :
7001                            "",
7002                            flags & NL80211_RRF_DFS ? " (DFS)" : "",
7003                            flags & NL80211_RRF_PTP_ONLY ? " (PTP only)" : "",
7004                            flags & NL80211_RRF_PTMP_ONLY ? " (PTMP only)" : "",
7005                            flags & NL80211_RRF_NO_IR ? " (no IR)" : "");
7006                 if (max_bw >= 40)
7007                         nl80211_reg_rule_ht40(start, end, results);
7008                 if (tb_rule[NL80211_ATTR_POWER_RULE_MAX_EIRP])
7009                         nl80211_reg_rule_max_eirp(start, end, max_eirp,
7010                                                   results);
7011         }
7012
7013         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
7014         {
7015                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
7016                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
7017                 nl80211_reg_rule_sec(tb_rule, results);
7018         }
7019
7020         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
7021         {
7022                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
7023                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
7024                 nl80211_reg_rule_vht(tb_rule, results);
7025         }
7026
7027         return NL_SKIP;
7028 }
7029
7030
7031 static int nl80211_set_regulatory_flags(struct wpa_driver_nl80211_data *drv,
7032                                         struct phy_info_arg *results)
7033 {
7034         struct nl_msg *msg;
7035
7036         msg = nlmsg_alloc();
7037         if (!msg)
7038                 return -ENOMEM;
7039
7040         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_REG);
7041         return send_and_recv_msgs(drv, msg, nl80211_get_reg, results);
7042 }
7043
7044
7045 static struct hostapd_hw_modes *
7046 wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
7047 {
7048         u32 feat;
7049         struct i802_bss *bss = priv;
7050         struct wpa_driver_nl80211_data *drv = bss->drv;
7051         struct nl_msg *msg;
7052         struct phy_info_arg result = {
7053                 .num_modes = num_modes,
7054                 .modes = NULL,
7055                 .last_mode = -1,
7056         };
7057
7058         *num_modes = 0;
7059         *flags = 0;
7060
7061         msg = nlmsg_alloc();
7062         if (!msg)
7063                 return NULL;
7064
7065         feat = get_nl80211_protocol_features(drv);
7066         if (feat & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP)
7067                 nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_WIPHY);
7068         else
7069                 nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
7070
7071         NLA_PUT_FLAG(msg, NL80211_ATTR_SPLIT_WIPHY_DUMP);
7072         if (nl80211_set_iface_id(msg, bss) < 0)
7073                 goto nla_put_failure;
7074
7075         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) {
7076                 nl80211_set_regulatory_flags(drv, &result);
7077                 return wpa_driver_nl80211_postprocess_modes(result.modes,
7078                                                             num_modes);
7079         }
7080         msg = NULL;
7081  nla_put_failure:
7082         nlmsg_free(msg);
7083         return NULL;
7084 }
7085
7086
7087 static int wpa_driver_nl80211_send_mntr(struct wpa_driver_nl80211_data *drv,
7088                                         const void *data, size_t len,
7089                                         int encrypt, int noack)
7090 {
7091         __u8 rtap_hdr[] = {
7092                 0x00, 0x00, /* radiotap version */
7093                 0x0e, 0x00, /* radiotap length */
7094                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
7095                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
7096                 0x00,       /* padding */
7097                 0x00, 0x00, /* RX and TX flags to indicate that */
7098                 0x00, 0x00, /* this is the injected frame directly */
7099         };
7100         struct iovec iov[2] = {
7101                 {
7102                         .iov_base = &rtap_hdr,
7103                         .iov_len = sizeof(rtap_hdr),
7104                 },
7105                 {
7106                         .iov_base = (void *) data,
7107                         .iov_len = len,
7108                 }
7109         };
7110         struct msghdr msg = {
7111                 .msg_name = NULL,
7112                 .msg_namelen = 0,
7113                 .msg_iov = iov,
7114                 .msg_iovlen = 2,
7115                 .msg_control = NULL,
7116                 .msg_controllen = 0,
7117                 .msg_flags = 0,
7118         };
7119         int res;
7120         u16 txflags = 0;
7121
7122         if (encrypt)
7123                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
7124
7125         if (drv->monitor_sock < 0) {
7126                 wpa_printf(MSG_DEBUG, "nl80211: No monitor socket available "
7127                            "for %s", __func__);
7128                 return -1;
7129         }
7130
7131         if (noack)
7132                 txflags |= IEEE80211_RADIOTAP_F_TX_NOACK;
7133         WPA_PUT_LE16(&rtap_hdr[12], txflags);
7134
7135         res = sendmsg(drv->monitor_sock, &msg, 0);
7136         if (res < 0) {
7137                 wpa_printf(MSG_INFO, "nl80211: sendmsg: %s", strerror(errno));
7138                 return -1;
7139         }
7140         return 0;
7141 }
7142
7143
7144 static int wpa_driver_nl80211_send_frame(struct i802_bss *bss,
7145                                          const void *data, size_t len,
7146                                          int encrypt, int noack,
7147                                          unsigned int freq, int no_cck,
7148                                          int offchanok, unsigned int wait_time)
7149 {
7150         struct wpa_driver_nl80211_data *drv = bss->drv;
7151         u64 cookie;
7152         int res;
7153
7154         if (freq == 0 && drv->nlmode == NL80211_IFTYPE_ADHOC) {
7155                 freq = nl80211_get_assoc_freq(drv);
7156                 wpa_printf(MSG_DEBUG,
7157                            "nl80211: send_frame - Use assoc_freq=%u for IBSS",
7158                            freq);
7159         }
7160         if (freq == 0) {
7161                 wpa_printf(MSG_DEBUG, "nl80211: send_frame - Use bss->freq=%u",
7162                            bss->freq);
7163                 freq = bss->freq;
7164         }
7165
7166         if (drv->use_monitor) {
7167                 wpa_printf(MSG_DEBUG, "nl80211: send_frame(freq=%u bss->freq=%u) -> send_mntr",
7168                            freq, bss->freq);
7169                 return wpa_driver_nl80211_send_mntr(drv, data, len,
7170                                                     encrypt, noack);
7171         }
7172
7173         wpa_printf(MSG_DEBUG, "nl80211: send_frame -> send_frame_cmd");
7174         res = nl80211_send_frame_cmd(bss, freq, wait_time, data, len,
7175                                      &cookie, no_cck, noack, offchanok);
7176         if (res == 0 && !noack) {
7177                 const struct ieee80211_mgmt *mgmt;
7178                 u16 fc;
7179
7180                 mgmt = (const struct ieee80211_mgmt *) data;
7181                 fc = le_to_host16(mgmt->frame_control);
7182                 if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
7183                     WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_ACTION) {
7184                         wpa_printf(MSG_MSGDUMP,
7185                                    "nl80211: Update send_action_cookie from 0x%llx to 0x%llx",
7186                                    (long long unsigned int)
7187                                    drv->send_action_cookie,
7188                                    (long long unsigned int) cookie);
7189                         drv->send_action_cookie = cookie;
7190                 }
7191         }
7192
7193         return res;
7194 }
7195
7196
7197 static int wpa_driver_nl80211_send_mlme(struct i802_bss *bss, const u8 *data,
7198                                         size_t data_len, int noack,
7199                                         unsigned int freq, int no_cck,
7200                                         int offchanok,
7201                                         unsigned int wait_time)
7202 {
7203         struct wpa_driver_nl80211_data *drv = bss->drv;
7204         struct ieee80211_mgmt *mgmt;
7205         int encrypt = 1;
7206         u16 fc;
7207
7208         mgmt = (struct ieee80211_mgmt *) data;
7209         fc = le_to_host16(mgmt->frame_control);
7210         wpa_printf(MSG_DEBUG, "nl80211: send_mlme - da= " MACSTR
7211                    " noack=%d freq=%u no_cck=%d offchanok=%d wait_time=%u fc=0x%x (%s) nlmode=%d",
7212                    MAC2STR(mgmt->da), noack, freq, no_cck, offchanok, wait_time,
7213                    fc, fc2str(fc), drv->nlmode);
7214
7215         if ((is_sta_interface(drv->nlmode) ||
7216              drv->nlmode == NL80211_IFTYPE_P2P_DEVICE) &&
7217             WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
7218             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_PROBE_RESP) {
7219                 /*
7220                  * The use of last_mgmt_freq is a bit of a hack,
7221                  * but it works due to the single-threaded nature
7222                  * of wpa_supplicant.
7223                  */
7224                 if (freq == 0) {
7225                         wpa_printf(MSG_DEBUG, "nl80211: Use last_mgmt_freq=%d",
7226                                    drv->last_mgmt_freq);
7227                         freq = drv->last_mgmt_freq;
7228                 }
7229                 return nl80211_send_frame_cmd(bss, freq, 0,
7230                                               data, data_len, NULL, 1, noack,
7231                                               1);
7232         }
7233
7234         if (drv->device_ap_sme && is_ap_interface(drv->nlmode)) {
7235                 if (freq == 0) {
7236                         wpa_printf(MSG_DEBUG, "nl80211: Use bss->freq=%d",
7237                                    bss->freq);
7238                         freq = bss->freq;
7239                 }
7240                 return nl80211_send_frame_cmd(bss, freq,
7241                                               (int) freq == bss->freq ? 0 :
7242                                               wait_time,
7243                                               data, data_len,
7244                                               &drv->send_action_cookie,
7245                                               no_cck, noack, offchanok);
7246         }
7247
7248         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
7249             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
7250                 /*
7251                  * Only one of the authentication frame types is encrypted.
7252                  * In order for static WEP encryption to work properly (i.e.,
7253                  * to not encrypt the frame), we need to tell mac80211 about
7254                  * the frames that must not be encrypted.
7255                  */
7256                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
7257                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
7258                 if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
7259                         encrypt = 0;
7260         }
7261
7262         wpa_printf(MSG_DEBUG, "nl80211: send_mlme -> send_frame");
7263         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt,
7264                                              noack, freq, no_cck, offchanok,
7265                                              wait_time);
7266 }
7267
7268
7269 static int nl80211_set_bss(struct i802_bss *bss, int cts, int preamble,
7270                            int slot, int ht_opmode, int ap_isolate,
7271                            int *basic_rates)
7272 {
7273         struct wpa_driver_nl80211_data *drv = bss->drv;
7274         struct nl_msg *msg;
7275
7276         msg = nlmsg_alloc();
7277         if (!msg)
7278                 return -ENOMEM;
7279
7280         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_BSS);
7281
7282         if (cts >= 0)
7283                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
7284         if (preamble >= 0)
7285                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
7286         if (slot >= 0)
7287                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
7288         if (ht_opmode >= 0)
7289                 NLA_PUT_U16(msg, NL80211_ATTR_BSS_HT_OPMODE, ht_opmode);
7290         if (ap_isolate >= 0)
7291                 NLA_PUT_U8(msg, NL80211_ATTR_AP_ISOLATE, ap_isolate);
7292
7293         if (basic_rates) {
7294                 u8 rates[NL80211_MAX_SUPP_RATES];
7295                 u8 rates_len = 0;
7296                 int i;
7297
7298                 for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0;
7299                      i++)
7300                         rates[rates_len++] = basic_rates[i] / 5;
7301
7302                 NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
7303         }
7304
7305         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7306
7307         return send_and_recv_msgs(drv, msg, NULL, NULL);
7308  nla_put_failure:
7309         nlmsg_free(msg);
7310         return -ENOBUFS;
7311 }
7312
7313
7314 static int wpa_driver_nl80211_set_acl(void *priv,
7315                                       struct hostapd_acl_params *params)
7316 {
7317         struct i802_bss *bss = priv;
7318         struct wpa_driver_nl80211_data *drv = bss->drv;
7319         struct nl_msg *msg;
7320         struct nlattr *acl;
7321         unsigned int i;
7322         int ret = 0;
7323
7324         if (!(drv->capa.max_acl_mac_addrs))
7325                 return -ENOTSUP;
7326
7327         if (params->num_mac_acl > drv->capa.max_acl_mac_addrs)
7328                 return -ENOTSUP;
7329
7330         msg = nlmsg_alloc();
7331         if (!msg)
7332                 return -ENOMEM;
7333
7334         wpa_printf(MSG_DEBUG, "nl80211: Set %s ACL (num_mac_acl=%u)",
7335                    params->acl_policy ? "Accept" : "Deny", params->num_mac_acl);
7336
7337         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_MAC_ACL);
7338
7339         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7340
7341         NLA_PUT_U32(msg, NL80211_ATTR_ACL_POLICY, params->acl_policy ?
7342                     NL80211_ACL_POLICY_DENY_UNLESS_LISTED :
7343                     NL80211_ACL_POLICY_ACCEPT_UNLESS_LISTED);
7344
7345         acl = nla_nest_start(msg, NL80211_ATTR_MAC_ADDRS);
7346         if (acl == NULL)
7347                 goto nla_put_failure;
7348
7349         for (i = 0; i < params->num_mac_acl; i++)
7350                 NLA_PUT(msg, i + 1, ETH_ALEN, params->mac_acl[i].addr);
7351
7352         nla_nest_end(msg, acl);
7353
7354         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7355         msg = NULL;
7356         if (ret) {
7357                 wpa_printf(MSG_DEBUG, "nl80211: Failed to set MAC ACL: %d (%s)",
7358                            ret, strerror(-ret));
7359         }
7360
7361 nla_put_failure:
7362         nlmsg_free(msg);
7363
7364         return ret;
7365 }
7366
7367
7368 static int wpa_driver_nl80211_set_ap(void *priv,
7369                                      struct wpa_driver_ap_params *params)
7370 {
7371         struct i802_bss *bss = priv;
7372         struct wpa_driver_nl80211_data *drv = bss->drv;
7373         struct nl_msg *msg;
7374         u8 cmd = NL80211_CMD_NEW_BEACON;
7375         int ret;
7376         int beacon_set;
7377         int ifindex = if_nametoindex(bss->ifname);
7378         int num_suites;
7379         u32 suites[10], suite;
7380         u32 ver;
7381
7382         beacon_set = bss->beacon_set;
7383
7384         msg = nlmsg_alloc();
7385         if (!msg)
7386                 return -ENOMEM;
7387
7388         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
7389                    beacon_set);
7390         if (beacon_set)
7391                 cmd = NL80211_CMD_SET_BEACON;
7392
7393         nl80211_cmd(drv, msg, 0, cmd);
7394         wpa_hexdump(MSG_DEBUG, "nl80211: Beacon head",
7395                     params->head, params->head_len);
7396         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, params->head_len, params->head);
7397         wpa_hexdump(MSG_DEBUG, "nl80211: Beacon tail",
7398                     params->tail, params->tail_len);
7399         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, params->tail_len, params->tail);
7400         wpa_printf(MSG_DEBUG, "nl80211: ifindex=%d", ifindex);
7401         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
7402         wpa_printf(MSG_DEBUG, "nl80211: beacon_int=%d", params->beacon_int);
7403         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, params->beacon_int);
7404         wpa_printf(MSG_DEBUG, "nl80211: dtim_period=%d", params->dtim_period);
7405         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, params->dtim_period);
7406         wpa_hexdump_ascii(MSG_DEBUG, "nl80211: ssid",
7407                           params->ssid, params->ssid_len);
7408         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
7409                 params->ssid);
7410         if (params->proberesp && params->proberesp_len) {
7411                 wpa_hexdump(MSG_DEBUG, "nl80211: proberesp (offload)",
7412                             params->proberesp, params->proberesp_len);
7413                 NLA_PUT(msg, NL80211_ATTR_PROBE_RESP, params->proberesp_len,
7414                         params->proberesp);
7415         }
7416         switch (params->hide_ssid) {
7417         case NO_SSID_HIDING:
7418                 wpa_printf(MSG_DEBUG, "nl80211: hidden SSID not in use");
7419                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
7420                             NL80211_HIDDEN_SSID_NOT_IN_USE);
7421                 break;
7422         case HIDDEN_SSID_ZERO_LEN:
7423                 wpa_printf(MSG_DEBUG, "nl80211: hidden SSID zero len");
7424                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
7425                             NL80211_HIDDEN_SSID_ZERO_LEN);
7426                 break;
7427         case HIDDEN_SSID_ZERO_CONTENTS:
7428                 wpa_printf(MSG_DEBUG, "nl80211: hidden SSID zero contents");
7429                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
7430                             NL80211_HIDDEN_SSID_ZERO_CONTENTS);
7431                 break;
7432         }
7433         wpa_printf(MSG_DEBUG, "nl80211: privacy=%d", params->privacy);
7434         if (params->privacy)
7435                 NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
7436         wpa_printf(MSG_DEBUG, "nl80211: auth_algs=0x%x", params->auth_algs);
7437         if ((params->auth_algs & (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) ==
7438             (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) {
7439                 /* Leave out the attribute */
7440         } else if (params->auth_algs & WPA_AUTH_ALG_SHARED)
7441                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
7442                             NL80211_AUTHTYPE_SHARED_KEY);
7443         else
7444                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
7445                             NL80211_AUTHTYPE_OPEN_SYSTEM);
7446
7447         wpa_printf(MSG_DEBUG, "nl80211: wpa_version=0x%x", params->wpa_version);
7448         ver = 0;
7449         if (params->wpa_version & WPA_PROTO_WPA)
7450                 ver |= NL80211_WPA_VERSION_1;
7451         if (params->wpa_version & WPA_PROTO_RSN)
7452                 ver |= NL80211_WPA_VERSION_2;
7453         if (ver)
7454                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
7455
7456         wpa_printf(MSG_DEBUG, "nl80211: key_mgmt_suites=0x%x",
7457                    params->key_mgmt_suites);
7458         num_suites = 0;
7459         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X)
7460                 suites[num_suites++] = WLAN_AKM_SUITE_8021X;
7461         if (params->key_mgmt_suites & WPA_KEY_MGMT_PSK)
7462                 suites[num_suites++] = WLAN_AKM_SUITE_PSK;
7463         if (num_suites) {
7464                 NLA_PUT(msg, NL80211_ATTR_AKM_SUITES,
7465                         num_suites * sizeof(u32), suites);
7466         }
7467
7468         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X &&
7469             params->pairwise_ciphers & (WPA_CIPHER_WEP104 | WPA_CIPHER_WEP40))
7470                 NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT);
7471
7472         wpa_printf(MSG_DEBUG, "nl80211: pairwise_ciphers=0x%x",
7473                    params->pairwise_ciphers);
7474         num_suites = wpa_cipher_to_cipher_suites(params->pairwise_ciphers,
7475                                                  suites, ARRAY_SIZE(suites));
7476         if (num_suites) {
7477                 NLA_PUT(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE,
7478                         num_suites * sizeof(u32), suites);
7479         }
7480
7481         wpa_printf(MSG_DEBUG, "nl80211: group_cipher=0x%x",
7482                    params->group_cipher);
7483         suite = wpa_cipher_to_cipher_suite(params->group_cipher);
7484         if (suite)
7485                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, suite);
7486
7487         if (params->beacon_ies) {
7488                 wpa_hexdump_buf(MSG_DEBUG, "nl80211: beacon_ies",
7489                                 params->beacon_ies);
7490                 NLA_PUT(msg, NL80211_ATTR_IE, wpabuf_len(params->beacon_ies),
7491                         wpabuf_head(params->beacon_ies));
7492         }
7493         if (params->proberesp_ies) {
7494                 wpa_hexdump_buf(MSG_DEBUG, "nl80211: proberesp_ies",
7495                                 params->proberesp_ies);
7496                 NLA_PUT(msg, NL80211_ATTR_IE_PROBE_RESP,
7497                         wpabuf_len(params->proberesp_ies),
7498                         wpabuf_head(params->proberesp_ies));
7499         }
7500         if (params->assocresp_ies) {
7501                 wpa_hexdump_buf(MSG_DEBUG, "nl80211: assocresp_ies",
7502                                 params->assocresp_ies);
7503                 NLA_PUT(msg, NL80211_ATTR_IE_ASSOC_RESP,
7504                         wpabuf_len(params->assocresp_ies),
7505                         wpabuf_head(params->assocresp_ies));
7506         }
7507
7508         if (drv->capa.flags & WPA_DRIVER_FLAGS_INACTIVITY_TIMER)  {
7509                 wpa_printf(MSG_DEBUG, "nl80211: ap_max_inactivity=%d",
7510                            params->ap_max_inactivity);
7511                 NLA_PUT_U16(msg, NL80211_ATTR_INACTIVITY_TIMEOUT,
7512                             params->ap_max_inactivity);
7513         }
7514
7515         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7516         if (ret) {
7517                 wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
7518                            ret, strerror(-ret));
7519         } else {
7520                 bss->beacon_set = 1;
7521                 nl80211_set_bss(bss, params->cts_protect, params->preamble,
7522                                 params->short_slot_time, params->ht_opmode,
7523                                 params->isolate, params->basic_rates);
7524                 if (beacon_set && params->freq &&
7525                     params->freq->bandwidth != bss->bandwidth) {
7526                         wpa_printf(MSG_DEBUG,
7527                                    "nl80211: Update BSS %s bandwidth: %d -> %d",
7528                                    bss->ifname, bss->bandwidth,
7529                                    params->freq->bandwidth);
7530                         ret = nl80211_set_channel(bss, params->freq, 1);
7531                         if (ret) {
7532                                 wpa_printf(MSG_DEBUG,
7533                                            "nl80211: Frequency set failed: %d (%s)",
7534                                            ret, strerror(-ret));
7535                         } else {
7536                                 wpa_printf(MSG_DEBUG,
7537                                            "nl80211: Frequency set succeeded for ht2040 coex");
7538                                 bss->bandwidth = params->freq->bandwidth;
7539                         }
7540                 } else if (!beacon_set) {
7541                         /*
7542                          * cfg80211 updates the driver on frequence change in AP
7543                          * mode only at the point when beaconing is started, so
7544                          * set the initial value here.
7545                          */
7546                         bss->bandwidth = params->freq->bandwidth;
7547                 }
7548         }
7549         return ret;
7550  nla_put_failure:
7551         nlmsg_free(msg);
7552         return -ENOBUFS;
7553 }
7554
7555
7556 static int nl80211_put_freq_params(struct nl_msg *msg,
7557                                    struct hostapd_freq_params *freq)
7558 {
7559         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq->freq);
7560         if (freq->vht_enabled) {
7561                 switch (freq->bandwidth) {
7562                 case 20:
7563                         NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
7564                                     NL80211_CHAN_WIDTH_20);
7565                         break;
7566                 case 40:
7567                         NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
7568                                     NL80211_CHAN_WIDTH_40);
7569                         break;
7570                 case 80:
7571                         if (freq->center_freq2)
7572                                 NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
7573                                             NL80211_CHAN_WIDTH_80P80);
7574                         else
7575                                 NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
7576                                             NL80211_CHAN_WIDTH_80);
7577                         break;
7578                 case 160:
7579                         NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
7580                                     NL80211_CHAN_WIDTH_160);
7581                         break;
7582                 default:
7583                         return -EINVAL;
7584                 }
7585                 NLA_PUT_U32(msg, NL80211_ATTR_CENTER_FREQ1, freq->center_freq1);
7586                 if (freq->center_freq2)
7587                         NLA_PUT_U32(msg, NL80211_ATTR_CENTER_FREQ2,
7588                                     freq->center_freq2);
7589         } else if (freq->ht_enabled) {
7590                 switch (freq->sec_channel_offset) {
7591                 case -1:
7592                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
7593                                     NL80211_CHAN_HT40MINUS);
7594                         break;
7595                 case 1:
7596                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
7597                                     NL80211_CHAN_HT40PLUS);
7598                         break;
7599                 default:
7600                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
7601                                     NL80211_CHAN_HT20);
7602                         break;
7603                 }
7604         }
7605         return 0;
7606
7607 nla_put_failure:
7608         return -ENOBUFS;
7609 }
7610
7611
7612 static int nl80211_set_channel(struct i802_bss *bss,
7613                                struct hostapd_freq_params *freq, int set_chan)
7614 {
7615         struct wpa_driver_nl80211_data *drv = bss->drv;
7616         struct nl_msg *msg;
7617         int ret;
7618
7619         wpa_printf(MSG_DEBUG,
7620                    "nl80211: Set freq %d (ht_enabled=%d, vht_enabled=%d, bandwidth=%d MHz, cf1=%d MHz, cf2=%d MHz)",
7621                    freq->freq, freq->ht_enabled, freq->vht_enabled,
7622                    freq->bandwidth, freq->center_freq1, freq->center_freq2);
7623         msg = nlmsg_alloc();
7624         if (!msg)
7625                 return -1;
7626
7627         nl80211_cmd(drv, msg, 0, set_chan ? NL80211_CMD_SET_CHANNEL :
7628                     NL80211_CMD_SET_WIPHY);
7629
7630         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7631         if (nl80211_put_freq_params(msg, freq) < 0)
7632                 goto nla_put_failure;
7633
7634         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7635         msg = NULL;
7636         if (ret == 0) {
7637                 bss->freq = freq->freq;
7638                 return 0;
7639         }
7640         wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
7641                    "%d (%s)", freq->freq, ret, strerror(-ret));
7642 nla_put_failure:
7643         nlmsg_free(msg);
7644         return -1;
7645 }
7646
7647
7648 static u32 sta_flags_nl80211(int flags)
7649 {
7650         u32 f = 0;
7651
7652         if (flags & WPA_STA_AUTHORIZED)
7653                 f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
7654         if (flags & WPA_STA_WMM)
7655                 f |= BIT(NL80211_STA_FLAG_WME);
7656         if (flags & WPA_STA_SHORT_PREAMBLE)
7657                 f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
7658         if (flags & WPA_STA_MFP)
7659                 f |= BIT(NL80211_STA_FLAG_MFP);
7660         if (flags & WPA_STA_TDLS_PEER)
7661                 f |= BIT(NL80211_STA_FLAG_TDLS_PEER);
7662
7663         return f;
7664 }
7665
7666
7667 static int wpa_driver_nl80211_sta_add(void *priv,
7668                                       struct hostapd_sta_add_params *params)
7669 {
7670         struct i802_bss *bss = priv;
7671         struct wpa_driver_nl80211_data *drv = bss->drv;
7672         struct nl_msg *msg;
7673         struct nl80211_sta_flag_update upd;
7674         int ret = -ENOBUFS;
7675
7676         if ((params->flags & WPA_STA_TDLS_PEER) &&
7677             !(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
7678                 return -EOPNOTSUPP;
7679
7680         msg = nlmsg_alloc();
7681         if (!msg)
7682                 return -ENOMEM;
7683
7684         wpa_printf(MSG_DEBUG, "nl80211: %s STA " MACSTR,
7685                    params->set ? "Set" : "Add", MAC2STR(params->addr));
7686         nl80211_cmd(drv, msg, 0, params->set ? NL80211_CMD_SET_STATION :
7687                     NL80211_CMD_NEW_STATION);
7688
7689         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7690         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
7691         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
7692                 params->supp_rates);
7693         wpa_hexdump(MSG_DEBUG, "  * supported rates", params->supp_rates,
7694                     params->supp_rates_len);
7695         if (!params->set) {
7696                 if (params->aid) {
7697                         wpa_printf(MSG_DEBUG, "  * aid=%u", params->aid);
7698                         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
7699                 } else {
7700                         /*
7701                          * cfg80211 validates that AID is non-zero, so we have
7702                          * to make this a non-zero value for the TDLS case where
7703                          * a dummy STA entry is used for now.
7704                          */
7705                         wpa_printf(MSG_DEBUG, "  * aid=1 (TDLS workaround)");
7706                         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, 1);
7707                 }
7708                 wpa_printf(MSG_DEBUG, "  * listen_interval=%u",
7709                            params->listen_interval);
7710                 NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
7711                             params->listen_interval);
7712         } else if (params->aid && (params->flags & WPA_STA_TDLS_PEER)) {
7713                 wpa_printf(MSG_DEBUG, "  * peer_aid=%u", params->aid);
7714                 NLA_PUT_U16(msg, NL80211_ATTR_PEER_AID, params->aid);
7715         }
7716         if (params->ht_capabilities) {
7717                 wpa_hexdump(MSG_DEBUG, "  * ht_capabilities",
7718                             (u8 *) params->ht_capabilities,
7719                             sizeof(*params->ht_capabilities));
7720                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
7721                         sizeof(*params->ht_capabilities),
7722                         params->ht_capabilities);
7723         }
7724
7725         if (params->vht_capabilities) {
7726                 wpa_hexdump(MSG_DEBUG, "  * vht_capabilities",
7727                             (u8 *) params->vht_capabilities,
7728                             sizeof(*params->vht_capabilities));
7729                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY,
7730                         sizeof(*params->vht_capabilities),
7731                         params->vht_capabilities);
7732         }
7733
7734         if (params->vht_opmode_enabled) {
7735                 wpa_printf(MSG_DEBUG, "  * opmode=%u", params->vht_opmode);
7736                 NLA_PUT_U8(msg, NL80211_ATTR_OPMODE_NOTIF,
7737                            params->vht_opmode);
7738         }
7739
7740         wpa_printf(MSG_DEBUG, "  * capability=0x%x", params->capability);
7741         NLA_PUT_U16(msg, NL80211_ATTR_STA_CAPABILITY, params->capability);
7742
7743         if (params->ext_capab) {
7744                 wpa_hexdump(MSG_DEBUG, "  * ext_capab",
7745                             params->ext_capab, params->ext_capab_len);
7746                 NLA_PUT(msg, NL80211_ATTR_STA_EXT_CAPABILITY,
7747                         params->ext_capab_len, params->ext_capab);
7748         }
7749
7750         if (params->supp_channels) {
7751                 wpa_hexdump(MSG_DEBUG, "  * supported channels",
7752                             params->supp_channels, params->supp_channels_len);
7753                 NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_CHANNELS,
7754                         params->supp_channels_len, params->supp_channels);
7755         }
7756
7757         if (params->supp_oper_classes) {
7758                 wpa_hexdump(MSG_DEBUG, "  * supported operating classes",
7759                             params->supp_oper_classes,
7760                             params->supp_oper_classes_len);
7761                 NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_OPER_CLASSES,
7762                         params->supp_oper_classes_len,
7763                         params->supp_oper_classes);
7764         }
7765
7766         os_memset(&upd, 0, sizeof(upd));
7767         upd.mask = sta_flags_nl80211(params->flags);
7768         upd.set = upd.mask;
7769         wpa_printf(MSG_DEBUG, "  * flags set=0x%x mask=0x%x",
7770                    upd.set, upd.mask);
7771         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
7772
7773         if (params->flags & WPA_STA_WMM) {
7774                 struct nlattr *wme = nla_nest_start(msg, NL80211_ATTR_STA_WME);
7775
7776                 if (!wme)
7777                         goto nla_put_failure;
7778
7779                 wpa_printf(MSG_DEBUG, "  * qosinfo=0x%x", params->qosinfo);
7780                 NLA_PUT_U8(msg, NL80211_STA_WME_UAPSD_QUEUES,
7781                                 params->qosinfo & WMM_QOSINFO_STA_AC_MASK);
7782                 NLA_PUT_U8(msg, NL80211_STA_WME_MAX_SP,
7783                                 (params->qosinfo >> WMM_QOSINFO_STA_SP_SHIFT) &
7784                                 WMM_QOSINFO_STA_SP_MASK);
7785                 nla_nest_end(msg, wme);
7786         }
7787
7788         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7789         msg = NULL;
7790         if (ret)
7791                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_%s_STATION "
7792                            "result: %d (%s)", params->set ? "SET" : "NEW", ret,
7793                            strerror(-ret));
7794         if (ret == -EEXIST)
7795                 ret = 0;
7796  nla_put_failure:
7797         nlmsg_free(msg);
7798         return ret;
7799 }
7800
7801
7802 static void rtnl_neigh_delete_fdb_entry(struct i802_bss *bss, const u8 *addr)
7803 {
7804 #ifdef CONFIG_LIBNL3_ROUTE
7805         struct wpa_driver_nl80211_data *drv = bss->drv;
7806         struct rtnl_neigh *rn;
7807         struct nl_addr *nl_addr;
7808         int err;
7809
7810         rn = rtnl_neigh_alloc();
7811         if (!rn)
7812                 return;
7813
7814         rtnl_neigh_set_family(rn, AF_BRIDGE);
7815         rtnl_neigh_set_ifindex(rn, bss->ifindex);
7816         nl_addr = nl_addr_build(AF_BRIDGE, (void *) addr, ETH_ALEN);
7817         if (!nl_addr) {
7818                 rtnl_neigh_put(rn);
7819                 return;
7820         }
7821         rtnl_neigh_set_lladdr(rn, nl_addr);
7822
7823         err = rtnl_neigh_delete(drv->rtnl_sk, rn, 0);
7824         if (err < 0) {
7825                 wpa_printf(MSG_DEBUG, "nl80211: bridge FDB entry delete for "
7826                            MACSTR " ifindex=%d failed: %s", MAC2STR(addr),
7827                            bss->ifindex, nl_geterror(err));
7828         } else {
7829                 wpa_printf(MSG_DEBUG, "nl80211: deleted bridge FDB entry for "
7830                            MACSTR, MAC2STR(addr));
7831         }
7832
7833         nl_addr_put(nl_addr);
7834         rtnl_neigh_put(rn);
7835 #endif /* CONFIG_LIBNL3_ROUTE */
7836 }
7837
7838
7839 static int wpa_driver_nl80211_sta_remove(struct i802_bss *bss, const u8 *addr,
7840                                          int deauth, u16 reason_code)
7841 {
7842         struct wpa_driver_nl80211_data *drv = bss->drv;
7843         struct nl_msg *msg;
7844         int ret;
7845
7846         msg = nlmsg_alloc();
7847         if (!msg)
7848                 return -ENOMEM;
7849
7850         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
7851
7852         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7853                     if_nametoindex(bss->ifname));
7854         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7855         if (deauth == 0)
7856                 NLA_PUT_U8(msg, NL80211_ATTR_MGMT_SUBTYPE,
7857                            WLAN_FC_STYPE_DISASSOC);
7858         else if (deauth == 1)
7859                 NLA_PUT_U8(msg, NL80211_ATTR_MGMT_SUBTYPE,
7860                            WLAN_FC_STYPE_DEAUTH);
7861         if (reason_code)
7862                 NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
7863
7864         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7865         wpa_printf(MSG_DEBUG, "nl80211: sta_remove -> DEL_STATION %s " MACSTR
7866                    " --> %d (%s)",
7867                    bss->ifname, MAC2STR(addr), ret, strerror(-ret));
7868
7869         if (drv->rtnl_sk)
7870                 rtnl_neigh_delete_fdb_entry(bss, addr);
7871
7872         if (ret == -ENOENT)
7873                 return 0;
7874         return ret;
7875  nla_put_failure:
7876         nlmsg_free(msg);
7877         return -ENOBUFS;
7878 }
7879
7880
7881 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
7882                                  int ifidx)
7883 {
7884         struct nl_msg *msg;
7885         struct wpa_driver_nl80211_data *drv2;
7886
7887         wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
7888
7889         /* stop listening for EAPOL on this interface */
7890         dl_list_for_each(drv2, &drv->global->interfaces,
7891                          struct wpa_driver_nl80211_data, list)
7892                 del_ifidx(drv2, ifidx);
7893
7894         msg = nlmsg_alloc();
7895         if (!msg)
7896                 goto nla_put_failure;
7897
7898         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_INTERFACE);
7899         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
7900
7901         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
7902                 return;
7903         msg = NULL;
7904  nla_put_failure:
7905         nlmsg_free(msg);
7906         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
7907 }
7908
7909
7910 static const char * nl80211_iftype_str(enum nl80211_iftype mode)
7911 {
7912         switch (mode) {
7913         case NL80211_IFTYPE_ADHOC:
7914                 return "ADHOC";
7915         case NL80211_IFTYPE_STATION:
7916                 return "STATION";
7917         case NL80211_IFTYPE_AP:
7918                 return "AP";
7919         case NL80211_IFTYPE_AP_VLAN:
7920                 return "AP_VLAN";
7921         case NL80211_IFTYPE_WDS:
7922                 return "WDS";
7923         case NL80211_IFTYPE_MONITOR:
7924                 return "MONITOR";
7925         case NL80211_IFTYPE_MESH_POINT:
7926                 return "MESH_POINT";
7927         case NL80211_IFTYPE_P2P_CLIENT:
7928                 return "P2P_CLIENT";
7929         case NL80211_IFTYPE_P2P_GO:
7930                 return "P2P_GO";
7931         case NL80211_IFTYPE_P2P_DEVICE:
7932                 return "P2P_DEVICE";
7933         default:
7934                 return "unknown";
7935         }
7936 }
7937
7938
7939 static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
7940                                      const char *ifname,
7941                                      enum nl80211_iftype iftype,
7942                                      const u8 *addr, int wds,
7943                                      int (*handler)(struct nl_msg *, void *),
7944                                      void *arg)
7945 {
7946         struct nl_msg *msg;
7947         int ifidx;
7948         int ret = -ENOBUFS;
7949
7950         wpa_printf(MSG_DEBUG, "nl80211: Create interface iftype %d (%s)",
7951                    iftype, nl80211_iftype_str(iftype));
7952
7953         msg = nlmsg_alloc();
7954         if (!msg)
7955                 return -1;
7956
7957         nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_INTERFACE);
7958         if (nl80211_set_iface_id(msg, drv->first_bss) < 0)
7959                 goto nla_put_failure;
7960         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
7961         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
7962
7963         if (iftype == NL80211_IFTYPE_MONITOR) {
7964                 struct nlattr *flags;
7965
7966                 flags = nla_nest_start(msg, NL80211_ATTR_MNTR_FLAGS);
7967                 if (!flags)
7968                         goto nla_put_failure;
7969
7970                 NLA_PUT_FLAG(msg, NL80211_MNTR_FLAG_COOK_FRAMES);
7971
7972                 nla_nest_end(msg, flags);
7973         } else if (wds) {
7974                 NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
7975         }
7976
7977         /*
7978          * Tell cfg80211 that the interface belongs to the socket that created
7979          * it, and the interface should be deleted when the socket is closed.
7980          */
7981         NLA_PUT_FLAG(msg, NL80211_ATTR_IFACE_SOCKET_OWNER);
7982
7983         ret = send_and_recv_msgs(drv, msg, handler, arg);
7984         msg = NULL;
7985         if (ret) {
7986  nla_put_failure:
7987                 nlmsg_free(msg);
7988                 wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
7989                            ifname, ret, strerror(-ret));
7990                 return ret;
7991         }
7992
7993         if (iftype == NL80211_IFTYPE_P2P_DEVICE)
7994                 return 0;
7995
7996         ifidx = if_nametoindex(ifname);
7997         wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
7998                    ifname, ifidx);
7999
8000         if (ifidx <= 0)
8001                 return -1;
8002
8003         /*
8004          * Some virtual interfaces need to process EAPOL packets and events on
8005          * the parent interface. This is used mainly with hostapd.
8006          */
8007         if (drv->hostapd ||
8008             iftype == NL80211_IFTYPE_AP_VLAN ||
8009             iftype == NL80211_IFTYPE_WDS ||
8010             iftype == NL80211_IFTYPE_MONITOR) {
8011                 /* start listening for EAPOL on this interface */
8012                 add_ifidx(drv, ifidx);
8013         }
8014
8015         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
8016             linux_set_ifhwaddr(drv->global->ioctl_sock, ifname, addr)) {
8017                 nl80211_remove_iface(drv, ifidx);
8018                 return -1;
8019         }
8020
8021         return ifidx;
8022 }
8023
8024
8025 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
8026                                 const char *ifname, enum nl80211_iftype iftype,
8027                                 const u8 *addr, int wds,
8028                                 int (*handler)(struct nl_msg *, void *),
8029                                 void *arg, int use_existing)
8030 {
8031         int ret;
8032
8033         ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds, handler,
8034                                         arg);
8035
8036         /* if error occurred and interface exists already */
8037         if (ret == -ENFILE && if_nametoindex(ifname)) {
8038                 if (use_existing) {
8039                         wpa_printf(MSG_DEBUG, "nl80211: Continue using existing interface %s",
8040                                    ifname);
8041                         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
8042                             linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
8043                                                addr) < 0 &&
8044                             (linux_set_iface_flags(drv->global->ioctl_sock,
8045                                                    ifname, 0) < 0 ||
8046                              linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
8047                                                 addr) < 0 ||
8048                              linux_set_iface_flags(drv->global->ioctl_sock,
8049                                                    ifname, 1) < 0))
8050                                         return -1;
8051                         return -ENFILE;
8052                 }
8053                 wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
8054
8055                 /* Try to remove the interface that was already there. */
8056                 nl80211_remove_iface(drv, if_nametoindex(ifname));
8057
8058                 /* Try to create the interface again */
8059                 ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
8060                                                 wds, handler, arg);
8061         }
8062
8063         if (ret >= 0 && is_p2p_net_interface(iftype))
8064                 nl80211_disable_11b_rates(drv, ret, 1);
8065
8066         return ret;
8067 }
8068
8069
8070 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
8071 {
8072         struct ieee80211_hdr *hdr;
8073         u16 fc;
8074         union wpa_event_data event;
8075
8076         hdr = (struct ieee80211_hdr *) buf;
8077         fc = le_to_host16(hdr->frame_control);
8078
8079         os_memset(&event, 0, sizeof(event));
8080         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
8081         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
8082         event.tx_status.dst = hdr->addr1;
8083         event.tx_status.data = buf;
8084         event.tx_status.data_len = len;
8085         event.tx_status.ack = ok;
8086         wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
8087 }
8088
8089
8090 static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
8091                              u8 *buf, size_t len)
8092 {
8093         struct ieee80211_hdr *hdr = (void *)buf;
8094         u16 fc;
8095         union wpa_event_data event;
8096
8097         if (len < sizeof(*hdr))
8098                 return;
8099
8100         fc = le_to_host16(hdr->frame_control);
8101
8102         os_memset(&event, 0, sizeof(event));
8103         event.rx_from_unknown.bssid = get_hdr_bssid(hdr, len);
8104         event.rx_from_unknown.addr = hdr->addr2;
8105         event.rx_from_unknown.wds = (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) ==
8106                 (WLAN_FC_FROMDS | WLAN_FC_TODS);
8107         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
8108 }
8109
8110
8111 static void handle_frame(struct wpa_driver_nl80211_data *drv,
8112                          u8 *buf, size_t len, int datarate, int ssi_signal)
8113 {
8114         struct ieee80211_hdr *hdr;
8115         u16 fc;
8116         union wpa_event_data event;
8117
8118         hdr = (struct ieee80211_hdr *) buf;
8119         fc = le_to_host16(hdr->frame_control);
8120
8121         switch (WLAN_FC_GET_TYPE(fc)) {
8122         case WLAN_FC_TYPE_MGMT:
8123                 os_memset(&event, 0, sizeof(event));
8124                 event.rx_mgmt.frame = buf;
8125                 event.rx_mgmt.frame_len = len;
8126                 event.rx_mgmt.datarate = datarate;
8127                 event.rx_mgmt.ssi_signal = ssi_signal;
8128                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
8129                 break;
8130         case WLAN_FC_TYPE_CTRL:
8131                 /* can only get here with PS-Poll frames */
8132                 wpa_printf(MSG_DEBUG, "CTRL");
8133                 from_unknown_sta(drv, buf, len);
8134                 break;
8135         case WLAN_FC_TYPE_DATA:
8136                 from_unknown_sta(drv, buf, len);
8137                 break;
8138         }
8139 }
8140
8141
8142 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
8143 {
8144         struct wpa_driver_nl80211_data *drv = eloop_ctx;
8145         int len;
8146         unsigned char buf[3000];
8147         struct ieee80211_radiotap_iterator iter;
8148         int ret;
8149         int datarate = 0, ssi_signal = 0;
8150         int injected = 0, failed = 0, rxflags = 0;
8151
8152         len = recv(sock, buf, sizeof(buf), 0);
8153         if (len < 0) {
8154                 wpa_printf(MSG_ERROR, "nl80211: Monitor socket recv failed: %s",
8155                            strerror(errno));
8156                 return;
8157         }
8158
8159         if (ieee80211_radiotap_iterator_init(&iter, (void *) buf, len, NULL)) {
8160                 wpa_printf(MSG_INFO, "nl80211: received invalid radiotap frame");
8161                 return;
8162         }
8163
8164         while (1) {
8165                 ret = ieee80211_radiotap_iterator_next(&iter);
8166                 if (ret == -ENOENT)
8167                         break;
8168                 if (ret) {
8169                         wpa_printf(MSG_INFO, "nl80211: received invalid radiotap frame (%d)",
8170                                    ret);
8171                         return;
8172                 }
8173                 switch (iter.this_arg_index) {
8174                 case IEEE80211_RADIOTAP_FLAGS:
8175                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
8176                                 len -= 4;
8177                         break;
8178                 case IEEE80211_RADIOTAP_RX_FLAGS:
8179                         rxflags = 1;
8180                         break;
8181                 case IEEE80211_RADIOTAP_TX_FLAGS:
8182                         injected = 1;
8183                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
8184                                         IEEE80211_RADIOTAP_F_TX_FAIL;
8185                         break;
8186                 case IEEE80211_RADIOTAP_DATA_RETRIES:
8187                         break;
8188                 case IEEE80211_RADIOTAP_CHANNEL:
8189                         /* TODO: convert from freq/flags to channel number */
8190                         break;
8191                 case IEEE80211_RADIOTAP_RATE:
8192                         datarate = *iter.this_arg * 5;
8193                         break;
8194                 case IEEE80211_RADIOTAP_DBM_ANTSIGNAL:
8195                         ssi_signal = (s8) *iter.this_arg;
8196                         break;
8197                 }
8198         }
8199
8200         if (rxflags && injected)
8201                 return;
8202
8203         if (!injected)
8204                 handle_frame(drv, buf + iter._max_length,
8205                              len - iter._max_length, datarate, ssi_signal);
8206         else
8207                 handle_tx_callback(drv->ctx, buf + iter._max_length,
8208                                    len - iter._max_length, !failed);
8209 }
8210
8211
8212 /*
8213  * we post-process the filter code later and rewrite
8214  * this to the offset to the last instruction
8215  */
8216 #define PASS    0xFF
8217 #define FAIL    0xFE
8218
8219 static struct sock_filter msock_filter_insns[] = {
8220         /*
8221          * do a little-endian load of the radiotap length field
8222          */
8223         /* load lower byte into A */
8224         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
8225         /* put it into X (== index register) */
8226         BPF_STMT(BPF_MISC| BPF_TAX, 0),
8227         /* load upper byte into A */
8228         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
8229         /* left-shift it by 8 */
8230         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
8231         /* or with X */
8232         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
8233         /* put result into X */
8234         BPF_STMT(BPF_MISC| BPF_TAX, 0),
8235
8236         /*
8237          * Allow management frames through, this also gives us those
8238          * management frames that we sent ourselves with status
8239          */
8240         /* load the lower byte of the IEEE 802.11 frame control field */
8241         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
8242         /* mask off frame type and version */
8243         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
8244         /* accept frame if it's both 0, fall through otherwise */
8245         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
8246
8247         /*
8248          * TODO: add a bit to radiotap RX flags that indicates
8249          * that the sending station is not associated, then
8250          * add a filter here that filters on our DA and that flag
8251          * to allow us to deauth frames to that bad station.
8252          *
8253          * For now allow all To DS data frames through.
8254          */
8255         /* load the IEEE 802.11 frame control field */
8256         BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
8257         /* mask off frame type, version and DS status */
8258         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
8259         /* accept frame if version 0, type 2 and To DS, fall through otherwise
8260          */
8261         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
8262
8263 #if 0
8264         /*
8265          * drop non-data frames
8266          */
8267         /* load the lower byte of the frame control field */
8268         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
8269         /* mask off QoS bit */
8270         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
8271         /* drop non-data frames */
8272         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
8273 #endif
8274         /* load the upper byte of the frame control field */
8275         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
8276         /* mask off toDS/fromDS */
8277         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
8278         /* accept WDS frames */
8279         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
8280
8281         /*
8282          * add header length to index
8283          */
8284         /* load the lower byte of the frame control field */
8285         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
8286         /* mask off QoS bit */
8287         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
8288         /* right shift it by 6 to give 0 or 2 */
8289         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
8290         /* add data frame header length */
8291         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
8292         /* add index, was start of 802.11 header */
8293         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
8294         /* move to index, now start of LL header */
8295         BPF_STMT(BPF_MISC | BPF_TAX, 0),
8296
8297         /*
8298          * Accept empty data frames, we use those for
8299          * polling activity.
8300          */
8301         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
8302         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
8303
8304         /*
8305          * Accept EAPOL frames
8306          */
8307         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
8308         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
8309         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
8310         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
8311
8312         /* keep these last two statements or change the code below */
8313         /* return 0 == "DROP" */
8314         BPF_STMT(BPF_RET | BPF_K, 0),
8315         /* return ~0 == "keep all" */
8316         BPF_STMT(BPF_RET | BPF_K, ~0),
8317 };
8318
8319 static struct sock_fprog msock_filter = {
8320         .len = ARRAY_SIZE(msock_filter_insns),
8321         .filter = msock_filter_insns,
8322 };
8323
8324
8325 static int add_monitor_filter(int s)
8326 {
8327         int idx;
8328
8329         /* rewrite all PASS/FAIL jump offsets */
8330         for (idx = 0; idx < msock_filter.len; idx++) {
8331                 struct sock_filter *insn = &msock_filter_insns[idx];
8332
8333                 if (BPF_CLASS(insn->code) == BPF_JMP) {
8334                         if (insn->code == (BPF_JMP|BPF_JA)) {
8335                                 if (insn->k == PASS)
8336                                         insn->k = msock_filter.len - idx - 2;
8337                                 else if (insn->k == FAIL)
8338                                         insn->k = msock_filter.len - idx - 3;
8339                         }
8340
8341                         if (insn->jt == PASS)
8342                                 insn->jt = msock_filter.len - idx - 2;
8343                         else if (insn->jt == FAIL)
8344                                 insn->jt = msock_filter.len - idx - 3;
8345
8346                         if (insn->jf == PASS)
8347                                 insn->jf = msock_filter.len - idx - 2;
8348                         else if (insn->jf == FAIL)
8349                                 insn->jf = msock_filter.len - idx - 3;
8350                 }
8351         }
8352
8353         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
8354                        &msock_filter, sizeof(msock_filter))) {
8355                 wpa_printf(MSG_ERROR, "nl80211: setsockopt(SO_ATTACH_FILTER) failed: %s",
8356                            strerror(errno));
8357                 return -1;
8358         }
8359
8360         return 0;
8361 }
8362
8363
8364 static void nl80211_remove_monitor_interface(
8365         struct wpa_driver_nl80211_data *drv)
8366 {
8367         if (drv->monitor_refcount > 0)
8368                 drv->monitor_refcount--;
8369         wpa_printf(MSG_DEBUG, "nl80211: Remove monitor interface: refcount=%d",
8370                    drv->monitor_refcount);
8371         if (drv->monitor_refcount > 0)
8372                 return;
8373
8374         if (drv->monitor_ifidx >= 0) {
8375                 nl80211_remove_iface(drv, drv->monitor_ifidx);
8376                 drv->monitor_ifidx = -1;
8377         }
8378         if (drv->monitor_sock >= 0) {
8379                 eloop_unregister_read_sock(drv->monitor_sock);
8380                 close(drv->monitor_sock);
8381                 drv->monitor_sock = -1;
8382         }
8383 }
8384
8385
8386 static int
8387 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
8388 {
8389         char buf[IFNAMSIZ];
8390         struct sockaddr_ll ll;
8391         int optval;
8392         socklen_t optlen;
8393
8394         if (drv->monitor_ifidx >= 0) {
8395                 drv->monitor_refcount++;
8396                 wpa_printf(MSG_DEBUG, "nl80211: Re-use existing monitor interface: refcount=%d",
8397                            drv->monitor_refcount);
8398                 return 0;
8399         }
8400
8401         if (os_strncmp(drv->first_bss->ifname, "p2p-", 4) == 0) {
8402                 /*
8403                  * P2P interface name is of the format p2p-%s-%d. For monitor
8404                  * interface name corresponding to P2P GO, replace "p2p-" with
8405                  * "mon-" to retain the same interface name length and to
8406                  * indicate that it is a monitor interface.
8407                  */
8408                 snprintf(buf, IFNAMSIZ, "mon-%s", drv->first_bss->ifname + 4);
8409         } else {
8410                 /* Non-P2P interface with AP functionality. */
8411                 snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss->ifname);
8412         }
8413
8414         buf[IFNAMSIZ - 1] = '\0';
8415
8416         drv->monitor_ifidx =
8417                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
8418                                      0, NULL, NULL, 0);
8419
8420         if (drv->monitor_ifidx == -EOPNOTSUPP) {
8421                 /*
8422                  * This is backward compatibility for a few versions of
8423                  * the kernel only that didn't advertise the right
8424                  * attributes for the only driver that then supported
8425                  * AP mode w/o monitor -- ath6kl.
8426                  */
8427                 wpa_printf(MSG_DEBUG, "nl80211: Driver does not support "
8428                            "monitor interface type - try to run without it");
8429                 drv->device_ap_sme = 1;
8430         }
8431
8432         if (drv->monitor_ifidx < 0)
8433                 return -1;
8434
8435         if (linux_set_iface_flags(drv->global->ioctl_sock, buf, 1))
8436                 goto error;
8437
8438         memset(&ll, 0, sizeof(ll));
8439         ll.sll_family = AF_PACKET;
8440         ll.sll_ifindex = drv->monitor_ifidx;
8441         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
8442         if (drv->monitor_sock < 0) {
8443                 wpa_printf(MSG_ERROR, "nl80211: socket[PF_PACKET,SOCK_RAW] failed: %s",
8444                            strerror(errno));
8445                 goto error;
8446         }
8447
8448         if (add_monitor_filter(drv->monitor_sock)) {
8449                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
8450                            "interface; do filtering in user space");
8451                 /* This works, but will cost in performance. */
8452         }
8453
8454         if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
8455                 wpa_printf(MSG_ERROR, "nl80211: monitor socket bind failed: %s",
8456                            strerror(errno));
8457                 goto error;
8458         }
8459
8460         optlen = sizeof(optval);
8461         optval = 20;
8462         if (setsockopt
8463             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
8464                 wpa_printf(MSG_ERROR, "nl80211: Failed to set socket priority: %s",
8465                            strerror(errno));
8466                 goto error;
8467         }
8468
8469         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
8470                                      drv, NULL)) {
8471                 wpa_printf(MSG_INFO, "nl80211: Could not register monitor read socket");
8472                 goto error;
8473         }
8474
8475         drv->monitor_refcount++;
8476         return 0;
8477  error:
8478         nl80211_remove_monitor_interface(drv);
8479         return -1;
8480 }
8481
8482
8483 static int nl80211_setup_ap(struct i802_bss *bss)
8484 {
8485         struct wpa_driver_nl80211_data *drv = bss->drv;
8486
8487         wpa_printf(MSG_DEBUG, "nl80211: Setup AP(%s) - device_ap_sme=%d use_monitor=%d",
8488                    bss->ifname, drv->device_ap_sme, drv->use_monitor);
8489
8490         /*
8491          * Disable Probe Request reporting unless we need it in this way for
8492          * devices that include the AP SME, in the other case (unless using
8493          * monitor iface) we'll get it through the nl_mgmt socket instead.
8494          */
8495         if (!drv->device_ap_sme)
8496                 wpa_driver_nl80211_probe_req_report(bss, 0);
8497
8498         if (!drv->device_ap_sme && !drv->use_monitor)
8499                 if (nl80211_mgmt_subscribe_ap(bss))
8500                         return -1;
8501
8502         if (drv->device_ap_sme && !drv->use_monitor)
8503                 if (nl80211_mgmt_subscribe_ap_dev_sme(bss))
8504                         return -1;
8505
8506         if (!drv->device_ap_sme && drv->use_monitor &&
8507             nl80211_create_monitor_interface(drv) &&
8508             !drv->device_ap_sme)
8509                 return -1;
8510
8511         if (drv->device_ap_sme &&
8512             wpa_driver_nl80211_probe_req_report(bss, 1) < 0) {
8513                 wpa_printf(MSG_DEBUG, "nl80211: Failed to enable "
8514                            "Probe Request frame reporting in AP mode");
8515                 /* Try to survive without this */
8516         }
8517
8518         return 0;
8519 }
8520
8521
8522 static void nl80211_teardown_ap(struct i802_bss *bss)
8523 {
8524         struct wpa_driver_nl80211_data *drv = bss->drv;
8525
8526         wpa_printf(MSG_DEBUG, "nl80211: Teardown AP(%s) - device_ap_sme=%d use_monitor=%d",
8527                    bss->ifname, drv->device_ap_sme, drv->use_monitor);
8528         if (drv->device_ap_sme) {
8529                 wpa_driver_nl80211_probe_req_report(bss, 0);
8530                 if (!drv->use_monitor)
8531                         nl80211_mgmt_unsubscribe(bss, "AP teardown (dev SME)");
8532         } else if (drv->use_monitor)
8533                 nl80211_remove_monitor_interface(drv);
8534         else
8535                 nl80211_mgmt_unsubscribe(bss, "AP teardown");
8536
8537         bss->beacon_set = 0;
8538 }
8539
8540
8541 static int nl80211_send_eapol_data(struct i802_bss *bss,
8542                                    const u8 *addr, const u8 *data,
8543                                    size_t data_len)
8544 {
8545         struct sockaddr_ll ll;
8546         int ret;
8547
8548         if (bss->drv->eapol_tx_sock < 0) {
8549                 wpa_printf(MSG_DEBUG, "nl80211: No socket to send EAPOL");
8550                 return -1;
8551         }
8552
8553         os_memset(&ll, 0, sizeof(ll));
8554         ll.sll_family = AF_PACKET;
8555         ll.sll_ifindex = bss->ifindex;
8556         ll.sll_protocol = htons(ETH_P_PAE);
8557         ll.sll_halen = ETH_ALEN;
8558         os_memcpy(ll.sll_addr, addr, ETH_ALEN);
8559         ret = sendto(bss->drv->eapol_tx_sock, data, data_len, 0,
8560                      (struct sockaddr *) &ll, sizeof(ll));
8561         if (ret < 0)
8562                 wpa_printf(MSG_ERROR, "nl80211: EAPOL TX: %s",
8563                            strerror(errno));
8564
8565         return ret;
8566 }
8567
8568
8569 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
8570
8571 static int wpa_driver_nl80211_hapd_send_eapol(
8572         void *priv, const u8 *addr, const u8 *data,
8573         size_t data_len, int encrypt, const u8 *own_addr, u32 flags)
8574 {
8575         struct i802_bss *bss = priv;
8576         struct wpa_driver_nl80211_data *drv = bss->drv;
8577         struct ieee80211_hdr *hdr;
8578         size_t len;
8579         u8 *pos;
8580         int res;
8581         int qos = flags & WPA_STA_WMM;
8582
8583         if (drv->device_ap_sme || !drv->use_monitor)
8584                 return nl80211_send_eapol_data(bss, addr, data, data_len);
8585
8586         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
8587                 data_len;
8588         hdr = os_zalloc(len);
8589         if (hdr == NULL) {
8590                 wpa_printf(MSG_INFO, "nl80211: Failed to allocate EAPOL buffer(len=%lu)",
8591                            (unsigned long) len);
8592                 return -1;
8593         }
8594
8595         hdr->frame_control =
8596                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
8597         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
8598         if (encrypt)
8599                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
8600         if (qos) {
8601                 hdr->frame_control |=
8602                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
8603         }
8604
8605         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
8606         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
8607         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
8608         pos = (u8 *) (hdr + 1);
8609
8610         if (qos) {
8611                 /* Set highest priority in QoS header */
8612                 pos[0] = 7;
8613                 pos[1] = 0;
8614                 pos += 2;
8615         }
8616
8617         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
8618         pos += sizeof(rfc1042_header);
8619         WPA_PUT_BE16(pos, ETH_P_PAE);
8620         pos += 2;
8621         memcpy(pos, data, data_len);
8622
8623         res = wpa_driver_nl80211_send_frame(bss, (u8 *) hdr, len, encrypt, 0,
8624                                             0, 0, 0, 0);
8625         if (res < 0) {
8626                 wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
8627                            "failed: %d (%s)",
8628                            (unsigned long) len, errno, strerror(errno));
8629         }
8630         os_free(hdr);
8631
8632         return res;
8633 }
8634
8635
8636 static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
8637                                             int total_flags,
8638                                             int flags_or, int flags_and)
8639 {
8640         struct i802_bss *bss = priv;
8641         struct wpa_driver_nl80211_data *drv = bss->drv;
8642         struct nl_msg *msg;
8643         struct nlattr *flags;
8644         struct nl80211_sta_flag_update upd;
8645
8646         wpa_printf(MSG_DEBUG, "nl80211: Set STA flags - ifname=%s addr=" MACSTR
8647                    " total_flags=0x%x flags_or=0x%x flags_and=0x%x authorized=%d",
8648                    bss->ifname, MAC2STR(addr), total_flags, flags_or, flags_and,
8649                    !!(total_flags & WPA_STA_AUTHORIZED));
8650
8651         msg = nlmsg_alloc();
8652         if (!msg)
8653                 return -ENOMEM;
8654
8655         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
8656
8657         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
8658                     if_nametoindex(bss->ifname));
8659         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
8660
8661         /*
8662          * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
8663          * can be removed eventually.
8664          */
8665         flags = nla_nest_start(msg, NL80211_ATTR_STA_FLAGS);
8666         if (!flags)
8667                 goto nla_put_failure;
8668         if (total_flags & WPA_STA_AUTHORIZED)
8669                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_AUTHORIZED);
8670
8671         if (total_flags & WPA_STA_WMM)
8672                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_WME);
8673
8674         if (total_flags & WPA_STA_SHORT_PREAMBLE)
8675                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_SHORT_PREAMBLE);
8676
8677         if (total_flags & WPA_STA_MFP)
8678                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_MFP);
8679
8680         if (total_flags & WPA_STA_TDLS_PEER)
8681                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_TDLS_PEER);
8682
8683         nla_nest_end(msg, flags);
8684
8685         os_memset(&upd, 0, sizeof(upd));
8686         upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
8687         upd.set = sta_flags_nl80211(flags_or);
8688         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
8689
8690         return send_and_recv_msgs(drv, msg, NULL, NULL);
8691  nla_put_failure:
8692         nlmsg_free(msg);
8693         return -ENOBUFS;
8694 }
8695
8696
8697 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
8698                                  struct wpa_driver_associate_params *params)
8699 {
8700         enum nl80211_iftype nlmode, old_mode;
8701
8702         if (params->p2p) {
8703                 wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
8704                            "group (GO)");
8705                 nlmode = NL80211_IFTYPE_P2P_GO;
8706         } else
8707                 nlmode = NL80211_IFTYPE_AP;
8708
8709         old_mode = drv->nlmode;
8710         if (wpa_driver_nl80211_set_mode(drv->first_bss, nlmode)) {
8711                 nl80211_remove_monitor_interface(drv);
8712                 return -1;
8713         }
8714
8715         if (nl80211_set_channel(drv->first_bss, &params->freq, 0)) {
8716                 if (old_mode != nlmode)
8717                         wpa_driver_nl80211_set_mode(drv->first_bss, old_mode);
8718                 nl80211_remove_monitor_interface(drv);
8719                 return -1;
8720         }
8721
8722         return 0;
8723 }
8724
8725
8726 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
8727 {
8728         struct nl_msg *msg;
8729         int ret = -1;
8730
8731         msg = nlmsg_alloc();
8732         if (!msg)
8733                 return -1;
8734
8735         nl80211_cmd(drv, msg, 0, NL80211_CMD_LEAVE_IBSS);
8736         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8737         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8738         msg = NULL;
8739         if (ret) {
8740                 wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
8741                            "(%s)", ret, strerror(-ret));
8742                 goto nla_put_failure;
8743         }
8744
8745         ret = 0;
8746         wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
8747
8748 nla_put_failure:
8749         if (wpa_driver_nl80211_set_mode(drv->first_bss,
8750                                         NL80211_IFTYPE_STATION)) {
8751                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
8752                            "station mode");
8753         }
8754
8755         nlmsg_free(msg);
8756         return ret;
8757 }
8758
8759
8760 static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
8761                                    struct wpa_driver_associate_params *params)
8762 {
8763         struct nl_msg *msg;
8764         int ret = -1;
8765         int count = 0;
8766
8767         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
8768
8769         if (wpa_driver_nl80211_set_mode_ibss(drv->first_bss, &params->freq)) {
8770                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
8771                            "IBSS mode");
8772                 return -1;
8773         }
8774
8775 retry:
8776         msg = nlmsg_alloc();
8777         if (!msg)
8778                 return -1;
8779
8780         nl80211_cmd(drv, msg, 0, NL80211_CMD_JOIN_IBSS);
8781         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8782
8783         if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
8784                 goto nla_put_failure;
8785
8786         wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
8787                           params->ssid, params->ssid_len);
8788         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
8789                 params->ssid);
8790         os_memcpy(drv->ssid, params->ssid, params->ssid_len);
8791         drv->ssid_len = params->ssid_len;
8792
8793         wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq.freq);
8794         wpa_printf(MSG_DEBUG, "  * ht_enabled=%d", params->freq.ht_enabled);
8795         wpa_printf(MSG_DEBUG, "  * sec_channel_offset=%d",
8796                    params->freq.sec_channel_offset);
8797         wpa_printf(MSG_DEBUG, "  * vht_enabled=%d", params->freq.vht_enabled);
8798         wpa_printf(MSG_DEBUG, "  * center_freq1=%d", params->freq.center_freq1);
8799         wpa_printf(MSG_DEBUG, "  * center_freq2=%d", params->freq.center_freq2);
8800         wpa_printf(MSG_DEBUG, "  * bandwidth=%d", params->freq.bandwidth);
8801         if (nl80211_put_freq_params(msg, &params->freq) < 0)
8802                 goto nla_put_failure;
8803
8804         if (params->beacon_int > 0) {
8805                 wpa_printf(MSG_DEBUG, "  * beacon_int=%d", params->beacon_int);
8806                 NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL,
8807                             params->beacon_int);
8808         }
8809
8810         ret = nl80211_set_conn_keys(params, msg);
8811         if (ret)
8812                 goto nla_put_failure;
8813
8814         if (params->bssid && params->fixed_bssid) {
8815                 wpa_printf(MSG_DEBUG, "  * BSSID=" MACSTR,
8816                            MAC2STR(params->bssid));
8817                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
8818         }
8819
8820         if (params->key_mgmt_suite == WPA_KEY_MGMT_IEEE8021X ||
8821             params->key_mgmt_suite == WPA_KEY_MGMT_PSK ||
8822             params->key_mgmt_suite == WPA_KEY_MGMT_IEEE8021X_SHA256 ||
8823             params->key_mgmt_suite == WPA_KEY_MGMT_PSK_SHA256) {
8824                 wpa_printf(MSG_DEBUG, "  * control port");
8825                 NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
8826         }
8827
8828         if (params->wpa_ie) {
8829                 wpa_hexdump(MSG_DEBUG,
8830                             "  * Extra IEs for Beacon/Probe Response frames",
8831                             params->wpa_ie, params->wpa_ie_len);
8832                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
8833                         params->wpa_ie);
8834         }
8835
8836         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8837         msg = NULL;
8838         if (ret) {
8839                 wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
8840                            ret, strerror(-ret));
8841                 count++;
8842                 if (ret == -EALREADY && count == 1) {
8843                         wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
8844                                    "forced leave");
8845                         nl80211_leave_ibss(drv);
8846                         nlmsg_free(msg);
8847                         goto retry;
8848                 }
8849
8850                 goto nla_put_failure;
8851         }
8852         ret = 0;
8853         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
8854
8855 nla_put_failure:
8856         nlmsg_free(msg);
8857         return ret;
8858 }
8859
8860
8861 static int nl80211_connect_common(struct wpa_driver_nl80211_data *drv,
8862                                   struct wpa_driver_associate_params *params,
8863                                   struct nl_msg *msg)
8864 {
8865         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8866
8867         if (params->bssid) {
8868                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
8869                            MAC2STR(params->bssid));
8870                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
8871         }
8872
8873         if (params->bssid_hint) {
8874                 wpa_printf(MSG_DEBUG, "  * bssid_hint=" MACSTR,
8875                            MAC2STR(params->bssid_hint));
8876                 NLA_PUT(msg, NL80211_ATTR_MAC_HINT, ETH_ALEN,
8877                         params->bssid_hint);
8878         }
8879
8880         if (params->freq.freq) {
8881                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq.freq);
8882                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq.freq);
8883                 drv->assoc_freq = params->freq.freq;
8884         } else
8885                 drv->assoc_freq = 0;
8886
8887         if (params->freq_hint) {
8888                 wpa_printf(MSG_DEBUG, "  * freq_hint=%d", params->freq_hint);
8889                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ_HINT,
8890                             params->freq_hint);
8891         }
8892
8893         if (params->bg_scan_period >= 0) {
8894                 wpa_printf(MSG_DEBUG, "  * bg scan period=%d",
8895                            params->bg_scan_period);
8896                 NLA_PUT_U16(msg, NL80211_ATTR_BG_SCAN_PERIOD,
8897                             params->bg_scan_period);
8898         }
8899
8900         if (params->ssid) {
8901                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
8902                                   params->ssid, params->ssid_len);
8903                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
8904                         params->ssid);
8905                 if (params->ssid_len > sizeof(drv->ssid))
8906                         goto nla_put_failure;
8907                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
8908                 drv->ssid_len = params->ssid_len;
8909         }
8910
8911         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
8912         if (params->wpa_ie)
8913                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
8914                         params->wpa_ie);
8915
8916         if (params->wpa_proto) {
8917                 enum nl80211_wpa_versions ver = 0;
8918
8919                 if (params->wpa_proto & WPA_PROTO_WPA)
8920                         ver |= NL80211_WPA_VERSION_1;
8921                 if (params->wpa_proto & WPA_PROTO_RSN)
8922                         ver |= NL80211_WPA_VERSION_2;
8923
8924                 wpa_printf(MSG_DEBUG, "  * WPA Versions 0x%x", ver);
8925                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
8926         }
8927
8928         if (params->pairwise_suite != WPA_CIPHER_NONE) {
8929                 u32 cipher = wpa_cipher_to_cipher_suite(params->pairwise_suite);
8930                 wpa_printf(MSG_DEBUG, "  * pairwise=0x%x", cipher);
8931                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
8932         }
8933
8934         if (params->group_suite == WPA_CIPHER_GTK_NOT_USED &&
8935             !(drv->capa.enc & WPA_DRIVER_CAPA_ENC_GTK_NOT_USED)) {
8936                 /*
8937                  * This is likely to work even though many drivers do not
8938                  * advertise support for operations without GTK.
8939                  */
8940                 wpa_printf(MSG_DEBUG, "  * skip group cipher configuration for GTK_NOT_USED due to missing driver support advertisement");
8941         } else if (params->group_suite != WPA_CIPHER_NONE) {
8942                 u32 cipher = wpa_cipher_to_cipher_suite(params->group_suite);
8943                 wpa_printf(MSG_DEBUG, "  * group=0x%x", cipher);
8944                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
8945         }
8946
8947         if (params->key_mgmt_suite == WPA_KEY_MGMT_IEEE8021X ||
8948             params->key_mgmt_suite == WPA_KEY_MGMT_PSK ||
8949             params->key_mgmt_suite == WPA_KEY_MGMT_FT_IEEE8021X ||
8950             params->key_mgmt_suite == WPA_KEY_MGMT_FT_PSK ||
8951             params->key_mgmt_suite == WPA_KEY_MGMT_CCKM ||
8952             params->key_mgmt_suite == WPA_KEY_MGMT_OSEN ||
8953             params->key_mgmt_suite == WPA_KEY_MGMT_IEEE8021X_SHA256 ||
8954             params->key_mgmt_suite == WPA_KEY_MGMT_PSK_SHA256) {
8955                 int mgmt = WLAN_AKM_SUITE_PSK;
8956
8957                 switch (params->key_mgmt_suite) {
8958                 case WPA_KEY_MGMT_CCKM:
8959                         mgmt = WLAN_AKM_SUITE_CCKM;
8960                         break;
8961                 case WPA_KEY_MGMT_IEEE8021X:
8962                         mgmt = WLAN_AKM_SUITE_8021X;
8963                         break;
8964                 case WPA_KEY_MGMT_FT_IEEE8021X:
8965                         mgmt = WLAN_AKM_SUITE_FT_8021X;
8966                         break;
8967                 case WPA_KEY_MGMT_FT_PSK:
8968                         mgmt = WLAN_AKM_SUITE_FT_PSK;
8969                         break;
8970                 case WPA_KEY_MGMT_IEEE8021X_SHA256:
8971                         mgmt = WLAN_AKM_SUITE_8021X_SHA256;
8972                         break;
8973                 case WPA_KEY_MGMT_PSK_SHA256:
8974                         mgmt = WLAN_AKM_SUITE_PSK_SHA256;
8975                         break;
8976                 case WPA_KEY_MGMT_OSEN:
8977                         mgmt = WLAN_AKM_SUITE_OSEN;
8978                         break;
8979                 case WPA_KEY_MGMT_PSK:
8980                 default:
8981                         mgmt = WLAN_AKM_SUITE_PSK;
8982                         break;
8983                 }
8984                 wpa_printf(MSG_DEBUG, "  * akm=0x%x", mgmt);
8985                 NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
8986         }
8987
8988         NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
8989
8990         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
8991                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
8992
8993         if (params->disable_ht)
8994                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
8995
8996         if (params->htcaps && params->htcaps_mask) {
8997                 int sz = sizeof(struct ieee80211_ht_capabilities);
8998                 wpa_hexdump(MSG_DEBUG, "  * htcaps", params->htcaps, sz);
8999                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
9000                 wpa_hexdump(MSG_DEBUG, "  * htcaps_mask",
9001                             params->htcaps_mask, sz);
9002                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
9003                         params->htcaps_mask);
9004         }
9005
9006 #ifdef CONFIG_VHT_OVERRIDES
9007         if (params->disable_vht) {
9008                 wpa_printf(MSG_DEBUG, "  * VHT disabled");
9009                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_VHT);
9010         }
9011
9012         if (params->vhtcaps && params->vhtcaps_mask) {
9013                 int sz = sizeof(struct ieee80211_vht_capabilities);
9014                 wpa_hexdump(MSG_DEBUG, "  * vhtcaps", params->vhtcaps, sz);
9015                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY, sz, params->vhtcaps);
9016                 wpa_hexdump(MSG_DEBUG, "  * vhtcaps_mask",
9017                             params->vhtcaps_mask, sz);
9018                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY_MASK, sz,
9019                         params->vhtcaps_mask);
9020         }
9021 #endif /* CONFIG_VHT_OVERRIDES */
9022
9023         if (params->p2p)
9024                 wpa_printf(MSG_DEBUG, "  * P2P group");
9025
9026         return 0;
9027 nla_put_failure:
9028         return -1;
9029 }
9030
9031
9032 static int wpa_driver_nl80211_try_connect(
9033         struct wpa_driver_nl80211_data *drv,
9034         struct wpa_driver_associate_params *params)
9035 {
9036         struct nl_msg *msg;
9037         enum nl80211_auth_type type;
9038         int ret;
9039         int algs;
9040
9041         msg = nlmsg_alloc();
9042         if (!msg)
9043                 return -1;
9044
9045         wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
9046         nl80211_cmd(drv, msg, 0, NL80211_CMD_CONNECT);
9047
9048         ret = nl80211_connect_common(drv, params, msg);
9049         if (ret)
9050                 goto nla_put_failure;
9051
9052         algs = 0;
9053         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
9054                 algs++;
9055         if (params->auth_alg & WPA_AUTH_ALG_SHARED)
9056                 algs++;
9057         if (params->auth_alg & WPA_AUTH_ALG_LEAP)
9058                 algs++;
9059         if (algs > 1) {
9060                 wpa_printf(MSG_DEBUG, "  * Leave out Auth Type for automatic "
9061                            "selection");
9062                 goto skip_auth_type;
9063         }
9064
9065         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
9066                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
9067         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
9068                 type = NL80211_AUTHTYPE_SHARED_KEY;
9069         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
9070                 type = NL80211_AUTHTYPE_NETWORK_EAP;
9071         else if (params->auth_alg & WPA_AUTH_ALG_FT)
9072                 type = NL80211_AUTHTYPE_FT;
9073         else
9074                 goto nla_put_failure;
9075
9076         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
9077         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
9078
9079 skip_auth_type:
9080         ret = nl80211_set_conn_keys(params, msg);
9081         if (ret)
9082                 goto nla_put_failure;
9083
9084         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9085         msg = NULL;
9086         if (ret) {
9087                 wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
9088                            "(%s)", ret, strerror(-ret));
9089                 goto nla_put_failure;
9090         }
9091         ret = 0;
9092         wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
9093
9094 nla_put_failure:
9095         nlmsg_free(msg);
9096         return ret;
9097
9098 }
9099
9100
9101 static int wpa_driver_nl80211_connect(
9102         struct wpa_driver_nl80211_data *drv,
9103         struct wpa_driver_associate_params *params)
9104 {
9105         int ret = wpa_driver_nl80211_try_connect(drv, params);
9106         if (ret == -EALREADY) {
9107                 /*
9108                  * cfg80211 does not currently accept new connections if
9109                  * we are already connected. As a workaround, force
9110                  * disconnection and try again.
9111                  */
9112                 wpa_printf(MSG_DEBUG, "nl80211: Explicitly "
9113                            "disconnecting before reassociation "
9114                            "attempt");
9115                 if (wpa_driver_nl80211_disconnect(
9116                             drv, WLAN_REASON_PREV_AUTH_NOT_VALID))
9117                         return -1;
9118                 ret = wpa_driver_nl80211_try_connect(drv, params);
9119         }
9120         return ret;
9121 }
9122
9123
9124 static int wpa_driver_nl80211_associate(
9125         void *priv, struct wpa_driver_associate_params *params)
9126 {
9127         struct i802_bss *bss = priv;
9128         struct wpa_driver_nl80211_data *drv = bss->drv;
9129         int ret;
9130         struct nl_msg *msg;
9131
9132         if (params->mode == IEEE80211_MODE_AP)
9133                 return wpa_driver_nl80211_ap(drv, params);
9134
9135         if (params->mode == IEEE80211_MODE_IBSS)
9136                 return wpa_driver_nl80211_ibss(drv, params);
9137
9138         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
9139                 enum nl80211_iftype nlmode = params->p2p ?
9140                         NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
9141
9142                 if (wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
9143                         return -1;
9144                 return wpa_driver_nl80211_connect(drv, params);
9145         }
9146
9147         nl80211_mark_disconnected(drv);
9148
9149         msg = nlmsg_alloc();
9150         if (!msg)
9151                 return -1;
9152
9153         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
9154                    drv->ifindex);
9155         nl80211_cmd(drv, msg, 0, NL80211_CMD_ASSOCIATE);
9156
9157         ret = nl80211_connect_common(drv, params, msg);
9158         if (ret)
9159                 goto nla_put_failure;
9160
9161         if (params->prev_bssid) {
9162                 wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
9163                            MAC2STR(params->prev_bssid));
9164                 NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
9165                         params->prev_bssid);
9166         }
9167
9168         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9169         msg = NULL;
9170         if (ret) {
9171                 wpa_dbg(drv->ctx, MSG_DEBUG,
9172                         "nl80211: MLME command failed (assoc): ret=%d (%s)",
9173                         ret, strerror(-ret));
9174                 nl80211_dump_scan(drv);
9175                 goto nla_put_failure;
9176         }
9177         ret = 0;
9178         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
9179                    "successfully");
9180
9181 nla_put_failure:
9182         nlmsg_free(msg);
9183         return ret;
9184 }
9185
9186
9187 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
9188                             int ifindex, enum nl80211_iftype mode)
9189 {
9190         struct nl_msg *msg;
9191         int ret = -ENOBUFS;
9192
9193         wpa_printf(MSG_DEBUG, "nl80211: Set mode ifindex %d iftype %d (%s)",
9194                    ifindex, mode, nl80211_iftype_str(mode));
9195
9196         msg = nlmsg_alloc();
9197         if (!msg)
9198                 return -ENOMEM;
9199
9200         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_INTERFACE);
9201         if (nl80211_set_iface_id(msg, drv->first_bss) < 0)
9202                 goto nla_put_failure;
9203         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
9204
9205         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9206         msg = NULL;
9207         if (!ret)
9208                 return 0;
9209 nla_put_failure:
9210         nlmsg_free(msg);
9211         wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
9212                    " %d (%s)", ifindex, mode, ret, strerror(-ret));
9213         return ret;
9214 }
9215
9216
9217 static int wpa_driver_nl80211_set_mode_impl(
9218                 struct i802_bss *bss,
9219                 enum nl80211_iftype nlmode,
9220                 struct hostapd_freq_params *desired_freq_params)
9221 {
9222         struct wpa_driver_nl80211_data *drv = bss->drv;
9223         int ret = -1;
9224         int i;
9225         int was_ap = is_ap_interface(drv->nlmode);
9226         int res;
9227         int mode_switch_res;
9228
9229         mode_switch_res = nl80211_set_mode(drv, drv->ifindex, nlmode);
9230         if (mode_switch_res && nlmode == nl80211_get_ifmode(bss))
9231                 mode_switch_res = 0;
9232
9233         if (mode_switch_res == 0) {
9234                 drv->nlmode = nlmode;
9235                 ret = 0;
9236                 goto done;
9237         }
9238
9239         if (mode_switch_res == -ENODEV)
9240                 return -1;
9241
9242         if (nlmode == drv->nlmode) {
9243                 wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
9244                            "requested mode - ignore error");
9245                 ret = 0;
9246                 goto done; /* Already in the requested mode */
9247         }
9248
9249         /* mac80211 doesn't allow mode changes while the device is up, so
9250          * take the device down, try to set the mode again, and bring the
9251          * device back up.
9252          */
9253         wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
9254                    "interface down");
9255         for (i = 0; i < 10; i++) {
9256                 res = i802_set_iface_flags(bss, 0);
9257                 if (res == -EACCES || res == -ENODEV)
9258                         break;
9259                 if (res != 0) {
9260                         wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
9261                                    "interface down");
9262                         os_sleep(0, 100000);
9263                         continue;
9264                 }
9265
9266                 /*
9267                  * Setting the mode will fail for some drivers if the phy is
9268                  * on a frequency that the mode is disallowed in.
9269                  */
9270                 if (desired_freq_params) {
9271                         res = i802_set_freq(bss, desired_freq_params);
9272                         if (res) {
9273                                 wpa_printf(MSG_DEBUG,
9274                                            "nl80211: Failed to set frequency on interface");
9275                         }
9276                 }
9277
9278                 /* Try to set the mode again while the interface is down */
9279                 mode_switch_res = nl80211_set_mode(drv, drv->ifindex, nlmode);
9280                 if (mode_switch_res == -EBUSY) {
9281                         wpa_printf(MSG_DEBUG,
9282                                    "nl80211: Delaying mode set while interface going down");
9283                         os_sleep(0, 100000);
9284                         continue;
9285                 }
9286                 ret = mode_switch_res;
9287                 break;
9288         }
9289
9290         if (!ret) {
9291                 wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
9292                            "interface is down");
9293                 drv->nlmode = nlmode;
9294                 drv->ignore_if_down_event = 1;
9295         }
9296
9297         /* Bring the interface back up */
9298         res = linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1);
9299         if (res != 0) {
9300                 wpa_printf(MSG_DEBUG,
9301                            "nl80211: Failed to set interface up after switching mode");
9302                 ret = -1;
9303         }
9304
9305 done:
9306         if (ret) {
9307                 wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
9308                            "from %d failed", nlmode, drv->nlmode);
9309                 return ret;
9310         }
9311
9312         if (is_p2p_net_interface(nlmode))
9313                 nl80211_disable_11b_rates(drv, drv->ifindex, 1);
9314         else if (drv->disabled_11b_rates)
9315                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
9316
9317         if (is_ap_interface(nlmode)) {
9318                 nl80211_mgmt_unsubscribe(bss, "start AP");
9319                 /* Setup additional AP mode functionality if needed */
9320                 if (nl80211_setup_ap(bss))
9321                         return -1;
9322         } else if (was_ap) {
9323                 /* Remove additional AP mode functionality */
9324                 nl80211_teardown_ap(bss);
9325         } else {
9326                 nl80211_mgmt_unsubscribe(bss, "mode change");
9327         }
9328
9329         if (!bss->in_deinit && !is_ap_interface(nlmode) &&
9330             nl80211_mgmt_subscribe_non_ap(bss) < 0)
9331                 wpa_printf(MSG_DEBUG, "nl80211: Failed to register Action "
9332                            "frame processing - ignore for now");
9333
9334         return 0;
9335 }
9336
9337
9338 static int dfs_info_handler(struct nl_msg *msg, void *arg)
9339 {
9340         struct nlattr *tb[NL80211_ATTR_MAX + 1];
9341         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
9342         int *dfs_capability_ptr = arg;
9343
9344         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
9345                   genlmsg_attrlen(gnlh, 0), NULL);
9346
9347         if (tb[NL80211_ATTR_VENDOR_DATA]) {
9348                 struct nlattr *nl_vend = tb[NL80211_ATTR_VENDOR_DATA];
9349                 struct nlattr *tb_vendor[QCA_WLAN_VENDOR_ATTR_MAX + 1];
9350
9351                 nla_parse(tb_vendor, QCA_WLAN_VENDOR_ATTR_MAX,
9352                           nla_data(nl_vend), nla_len(nl_vend), NULL);
9353
9354                 if (tb_vendor[QCA_WLAN_VENDOR_ATTR_DFS]) {
9355                         u32 val;
9356                         val = nla_get_u32(tb_vendor[QCA_WLAN_VENDOR_ATTR_DFS]);
9357                         wpa_printf(MSG_DEBUG, "nl80211: DFS offload capability: %u",
9358                                    val);
9359                         *dfs_capability_ptr = val;
9360                 }
9361         }
9362
9363         return NL_SKIP;
9364 }
9365
9366
9367 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
9368                                        enum nl80211_iftype nlmode)
9369 {
9370         return wpa_driver_nl80211_set_mode_impl(bss, nlmode, NULL);
9371 }
9372
9373
9374 static int wpa_driver_nl80211_set_mode_ibss(struct i802_bss *bss,
9375                                             struct hostapd_freq_params *freq)
9376 {
9377         return wpa_driver_nl80211_set_mode_impl(bss, NL80211_IFTYPE_ADHOC,
9378                                                 freq);
9379 }
9380
9381
9382 static int wpa_driver_nl80211_get_capa(void *priv,
9383                                        struct wpa_driver_capa *capa)
9384 {
9385         struct i802_bss *bss = priv;
9386         struct wpa_driver_nl80211_data *drv = bss->drv;
9387         struct nl_msg *msg;
9388         int dfs_capability = 0;
9389         int ret = 0;
9390
9391         if (!drv->has_capability)
9392                 return -1;
9393         os_memcpy(capa, &drv->capa, sizeof(*capa));
9394         if (drv->extended_capa && drv->extended_capa_mask) {
9395                 capa->extended_capa = drv->extended_capa;
9396                 capa->extended_capa_mask = drv->extended_capa_mask;
9397                 capa->extended_capa_len = drv->extended_capa_len;
9398         }
9399
9400         if ((capa->flags & WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE) &&
9401             !drv->allow_p2p_device) {
9402                 wpa_printf(MSG_DEBUG, "nl80211: Do not indicate P2P_DEVICE support (p2p_device=1 driver param not specified)");
9403                 capa->flags &= ~WPA_DRIVER_FLAGS_DEDICATED_P2P_DEVICE;
9404         }
9405
9406         if (drv->dfs_vendor_cmd_avail == 1) {
9407                 msg = nlmsg_alloc();
9408                 if (!msg)
9409                         return -ENOMEM;
9410
9411                 nl80211_cmd(drv, msg, 0, NL80211_CMD_VENDOR);
9412
9413                 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9414                 NLA_PUT_U32(msg, NL80211_ATTR_VENDOR_ID, OUI_QCA);
9415                 NLA_PUT_U32(msg, NL80211_ATTR_VENDOR_SUBCMD,
9416                             QCA_NL80211_VENDOR_SUBCMD_DFS_CAPABILITY);
9417
9418                 ret = send_and_recv_msgs(drv, msg, dfs_info_handler,
9419                                          &dfs_capability);
9420                 if (!ret) {
9421                         if (dfs_capability)
9422                                 capa->flags |= WPA_DRIVER_FLAGS_DFS_OFFLOAD;
9423                 }
9424         }
9425
9426         return ret;
9427
9428  nla_put_failure:
9429         nlmsg_free(msg);
9430         return -ENOBUFS;
9431 }
9432
9433
9434 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
9435 {
9436         struct i802_bss *bss = priv;
9437         struct wpa_driver_nl80211_data *drv = bss->drv;
9438
9439         wpa_printf(MSG_DEBUG, "nl80211: Set %s operstate %d->%d (%s)",
9440                    bss->ifname, drv->operstate, state,
9441                    state ? "UP" : "DORMANT");
9442         drv->operstate = state;
9443         return netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, -1,
9444                                       state ? IF_OPER_UP : IF_OPER_DORMANT);
9445 }
9446
9447
9448 static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
9449 {
9450         struct i802_bss *bss = priv;
9451         struct wpa_driver_nl80211_data *drv = bss->drv;
9452         struct nl_msg *msg;
9453         struct nl80211_sta_flag_update upd;
9454         int ret = -ENOBUFS;
9455
9456         if (!drv->associated && is_zero_ether_addr(drv->bssid) && !authorized) {
9457                 wpa_printf(MSG_DEBUG, "nl80211: Skip set_supp_port(unauthorized) while not associated");
9458                 return 0;
9459         }
9460
9461         wpa_printf(MSG_DEBUG, "nl80211: Set supplicant port %sauthorized for "
9462                    MACSTR, authorized ? "" : "un", MAC2STR(drv->bssid));
9463
9464         msg = nlmsg_alloc();
9465         if (!msg)
9466                 return -ENOMEM;
9467
9468         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
9469
9470         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
9471                     if_nametoindex(bss->ifname));
9472         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
9473
9474         os_memset(&upd, 0, sizeof(upd));
9475         upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
9476         if (authorized)
9477                 upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
9478         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
9479
9480         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9481         msg = NULL;
9482         if (!ret)
9483                 return 0;
9484  nla_put_failure:
9485         nlmsg_free(msg);
9486         wpa_printf(MSG_DEBUG, "nl80211: Failed to set STA flag: %d (%s)",
9487                    ret, strerror(-ret));
9488         return ret;
9489 }
9490
9491
9492 /* Set kernel driver on given frequency (MHz) */
9493 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
9494 {
9495         struct i802_bss *bss = priv;
9496         return nl80211_set_channel(bss, freq, 0);
9497 }
9498
9499
9500 static inline int min_int(int a, int b)
9501 {
9502         if (a < b)
9503                 return a;
9504         return b;
9505 }
9506
9507
9508 static int get_key_handler(struct nl_msg *msg, void *arg)
9509 {
9510         struct nlattr *tb[NL80211_ATTR_MAX + 1];
9511         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
9512
9513         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
9514                   genlmsg_attrlen(gnlh, 0), NULL);
9515
9516         /*
9517          * TODO: validate the key index and mac address!
9518          * Otherwise, there's a race condition as soon as
9519          * the kernel starts sending key notifications.
9520          */
9521
9522         if (tb[NL80211_ATTR_KEY_SEQ])
9523                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
9524                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
9525         return NL_SKIP;
9526 }
9527
9528
9529 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
9530                            int idx, u8 *seq)
9531 {
9532         struct i802_bss *bss = priv;
9533         struct wpa_driver_nl80211_data *drv = bss->drv;
9534         struct nl_msg *msg;
9535
9536         msg = nlmsg_alloc();
9537         if (!msg)
9538                 return -ENOMEM;
9539
9540         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_KEY);
9541
9542         if (addr)
9543                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
9544         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
9545         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
9546
9547         memset(seq, 0, 6);
9548
9549         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
9550  nla_put_failure:
9551         nlmsg_free(msg);
9552         return -ENOBUFS;
9553 }
9554
9555
9556 static int i802_set_rts(void *priv, int rts)
9557 {
9558         struct i802_bss *bss = priv;
9559         struct wpa_driver_nl80211_data *drv = bss->drv;
9560         struct nl_msg *msg;
9561         int ret = -ENOBUFS;
9562         u32 val;
9563
9564         msg = nlmsg_alloc();
9565         if (!msg)
9566                 return -ENOMEM;
9567
9568         if (rts >= 2347)
9569                 val = (u32) -1;
9570         else
9571                 val = rts;
9572
9573         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
9574         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9575         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
9576
9577         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9578         msg = NULL;
9579         if (!ret)
9580                 return 0;
9581 nla_put_failure:
9582         nlmsg_free(msg);
9583         wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
9584                    "%d (%s)", rts, ret, strerror(-ret));
9585         return ret;
9586 }
9587
9588
9589 static int i802_set_frag(void *priv, int frag)
9590 {
9591         struct i802_bss *bss = priv;
9592         struct wpa_driver_nl80211_data *drv = bss->drv;
9593         struct nl_msg *msg;
9594         int ret = -ENOBUFS;
9595         u32 val;
9596
9597         msg = nlmsg_alloc();
9598         if (!msg)
9599                 return -ENOMEM;
9600
9601         if (frag >= 2346)
9602                 val = (u32) -1;
9603         else
9604                 val = frag;
9605
9606         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
9607         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9608         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
9609
9610         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9611         msg = NULL;
9612         if (!ret)
9613                 return 0;
9614 nla_put_failure:
9615         nlmsg_free(msg);
9616         wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
9617                    "%d: %d (%s)", frag, ret, strerror(-ret));
9618         return ret;
9619 }
9620
9621
9622 static int i802_flush(void *priv)
9623 {
9624         struct i802_bss *bss = priv;
9625         struct wpa_driver_nl80211_data *drv = bss->drv;
9626         struct nl_msg *msg;
9627         int res;
9628
9629         msg = nlmsg_alloc();
9630         if (!msg)
9631                 return -1;
9632
9633         wpa_printf(MSG_DEBUG, "nl80211: flush -> DEL_STATION %s (all)",
9634                    bss->ifname);
9635         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
9636
9637         /*
9638          * XXX: FIX! this needs to flush all VLANs too
9639          */
9640         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
9641                     if_nametoindex(bss->ifname));
9642
9643         res = send_and_recv_msgs(drv, msg, NULL, NULL);
9644         if (res) {
9645                 wpa_printf(MSG_DEBUG, "nl80211: Station flush failed: ret=%d "
9646                            "(%s)", res, strerror(-res));
9647         }
9648         return res;
9649  nla_put_failure:
9650         nlmsg_free(msg);
9651         return -ENOBUFS;
9652 }
9653
9654
9655 static int get_sta_handler(struct nl_msg *msg, void *arg)
9656 {
9657         struct nlattr *tb[NL80211_ATTR_MAX + 1];
9658         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
9659         struct hostap_sta_driver_data *data = arg;
9660         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
9661         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
9662                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
9663                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
9664                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
9665                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
9666                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
9667                 [NL80211_STA_INFO_TX_FAILED] = { .type = NLA_U32 },
9668         };
9669
9670         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
9671                   genlmsg_attrlen(gnlh, 0), NULL);
9672
9673         /*
9674          * TODO: validate the interface and mac address!
9675          * Otherwise, there's a race condition as soon as
9676          * the kernel starts sending station notifications.
9677          */
9678
9679         if (!tb[NL80211_ATTR_STA_INFO]) {
9680                 wpa_printf(MSG_DEBUG, "sta stats missing!");
9681                 return NL_SKIP;
9682         }
9683         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
9684                              tb[NL80211_ATTR_STA_INFO],
9685                              stats_policy)) {
9686                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
9687                 return NL_SKIP;
9688         }
9689
9690         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
9691                 data->inactive_msec =
9692                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
9693         if (stats[NL80211_STA_INFO_RX_BYTES])
9694                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
9695         if (stats[NL80211_STA_INFO_TX_BYTES])
9696                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
9697         if (stats[NL80211_STA_INFO_RX_PACKETS])
9698                 data->rx_packets =
9699                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
9700         if (stats[NL80211_STA_INFO_TX_PACKETS])
9701                 data->tx_packets =
9702                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
9703         if (stats[NL80211_STA_INFO_TX_FAILED])
9704                 data->tx_retry_failed =
9705                         nla_get_u32(stats[NL80211_STA_INFO_TX_FAILED]);
9706
9707         return NL_SKIP;
9708 }
9709
9710 static int i802_read_sta_data(struct i802_bss *bss,
9711                               struct hostap_sta_driver_data *data,
9712                               const u8 *addr)
9713 {
9714         struct wpa_driver_nl80211_data *drv = bss->drv;
9715         struct nl_msg *msg;
9716
9717         os_memset(data, 0, sizeof(*data));
9718         msg = nlmsg_alloc();
9719         if (!msg)
9720                 return -ENOMEM;
9721
9722         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
9723
9724         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
9725         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
9726
9727         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
9728  nla_put_failure:
9729         nlmsg_free(msg);
9730         return -ENOBUFS;
9731 }
9732
9733
9734 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
9735                                     int cw_min, int cw_max, int burst_time)
9736 {
9737         struct i802_bss *bss = priv;
9738         struct wpa_driver_nl80211_data *drv = bss->drv;
9739         struct nl_msg *msg;
9740         struct nlattr *txq, *params;
9741
9742         msg = nlmsg_alloc();
9743         if (!msg)
9744                 return -1;
9745
9746         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
9747
9748         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
9749
9750         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
9751         if (!txq)
9752                 goto nla_put_failure;
9753
9754         /* We are only sending parameters for a single TXQ at a time */
9755         params = nla_nest_start(msg, 1);
9756         if (!params)
9757                 goto nla_put_failure;
9758
9759         switch (queue) {
9760         case 0:
9761                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
9762                 break;
9763         case 1:
9764                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
9765                 break;
9766         case 2:
9767                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
9768                 break;
9769         case 3:
9770                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
9771                 break;
9772         }
9773         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
9774          * 32 usec, so need to convert the value here. */
9775         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
9776         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
9777         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
9778         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
9779
9780         nla_nest_end(msg, params);
9781
9782         nla_nest_end(msg, txq);
9783
9784         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
9785                 return 0;
9786         msg = NULL;
9787  nla_put_failure:
9788         nlmsg_free(msg);
9789         return -1;
9790 }
9791
9792
9793 static int i802_set_sta_vlan(struct i802_bss *bss, const u8 *addr,
9794                              const char *ifname, int vlan_id)
9795 {
9796         struct wpa_driver_nl80211_data *drv = bss->drv;
9797         struct nl_msg *msg;
9798         int ret = -ENOBUFS;
9799
9800         msg = nlmsg_alloc();
9801         if (!msg)
9802                 return -ENOMEM;
9803
9804         wpa_printf(MSG_DEBUG, "nl80211: %s[%d]: set_sta_vlan(" MACSTR
9805                    ", ifname=%s[%d], vlan_id=%d)",
9806                    bss->ifname, if_nametoindex(bss->ifname),
9807                    MAC2STR(addr), ifname, if_nametoindex(ifname), vlan_id);
9808         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
9809
9810         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
9811                     if_nametoindex(bss->ifname));
9812         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
9813         NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
9814                     if_nametoindex(ifname));
9815
9816         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9817         msg = NULL;
9818         if (ret < 0) {
9819                 wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
9820                            MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
9821                            MAC2STR(addr), ifname, vlan_id, ret,
9822                            strerror(-ret));
9823         }
9824  nla_put_failure:
9825         nlmsg_free(msg);
9826         return ret;
9827 }
9828
9829
9830 static int i802_get_inact_sec(void *priv, const u8 *addr)
9831 {
9832         struct hostap_sta_driver_data data;
9833         int ret;
9834
9835         data.inactive_msec = (unsigned long) -1;
9836         ret = i802_read_sta_data(priv, &data, addr);
9837         if (ret || data.inactive_msec == (unsigned long) -1)
9838                 return -1;
9839         return data.inactive_msec / 1000;
9840 }
9841
9842
9843 static int i802_sta_clear_stats(void *priv, const u8 *addr)
9844 {
9845 #if 0
9846         /* TODO */
9847 #endif
9848         return 0;
9849 }
9850
9851
9852 static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
9853                            int reason)
9854 {
9855         struct i802_bss *bss = priv;
9856         struct wpa_driver_nl80211_data *drv = bss->drv;
9857         struct ieee80211_mgmt mgmt;
9858
9859         if (drv->device_ap_sme)
9860                 return wpa_driver_nl80211_sta_remove(bss, addr, 1, reason);
9861
9862         memset(&mgmt, 0, sizeof(mgmt));
9863         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
9864                                           WLAN_FC_STYPE_DEAUTH);
9865         memcpy(mgmt.da, addr, ETH_ALEN);
9866         memcpy(mgmt.sa, own_addr, ETH_ALEN);
9867         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
9868         mgmt.u.deauth.reason_code = host_to_le16(reason);
9869         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
9870                                             IEEE80211_HDRLEN +
9871                                             sizeof(mgmt.u.deauth), 0, 0, 0, 0,
9872                                             0);
9873 }
9874
9875
9876 static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
9877                              int reason)
9878 {
9879         struct i802_bss *bss = priv;
9880         struct wpa_driver_nl80211_data *drv = bss->drv;
9881         struct ieee80211_mgmt mgmt;
9882
9883         if (drv->device_ap_sme)
9884                 return wpa_driver_nl80211_sta_remove(bss, addr, 0, reason);
9885
9886         memset(&mgmt, 0, sizeof(mgmt));
9887         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
9888                                           WLAN_FC_STYPE_DISASSOC);
9889         memcpy(mgmt.da, addr, ETH_ALEN);
9890         memcpy(mgmt.sa, own_addr, ETH_ALEN);
9891         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
9892         mgmt.u.disassoc.reason_code = host_to_le16(reason);
9893         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
9894                                             IEEE80211_HDRLEN +
9895                                             sizeof(mgmt.u.disassoc), 0, 0, 0, 0,
9896                                             0);
9897 }
9898
9899
9900 static void dump_ifidx(struct wpa_driver_nl80211_data *drv)
9901 {
9902         char buf[200], *pos, *end;
9903         int i, res;
9904
9905         pos = buf;
9906         end = pos + sizeof(buf);
9907
9908         for (i = 0; i < drv->num_if_indices; i++) {
9909                 if (!drv->if_indices[i])
9910                         continue;
9911                 res = os_snprintf(pos, end - pos, " %d", drv->if_indices[i]);
9912                 if (res < 0 || res >= end - pos)
9913                         break;
9914                 pos += res;
9915         }
9916         *pos = '\0';
9917
9918         wpa_printf(MSG_DEBUG, "nl80211: if_indices[%d]:%s",
9919                    drv->num_if_indices, buf);
9920 }
9921
9922
9923 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
9924 {
9925         int i;
9926         int *old;
9927
9928         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
9929                    ifidx);
9930         if (have_ifidx(drv, ifidx)) {
9931                 wpa_printf(MSG_DEBUG, "nl80211: ifindex %d already in the list",
9932                            ifidx);
9933                 return;
9934         }
9935         for (i = 0; i < drv->num_if_indices; i++) {
9936                 if (drv->if_indices[i] == 0) {
9937                         drv->if_indices[i] = ifidx;
9938                         dump_ifidx(drv);
9939                         return;
9940                 }
9941         }
9942
9943         if (drv->if_indices != drv->default_if_indices)
9944                 old = drv->if_indices;
9945         else
9946                 old = NULL;
9947
9948         drv->if_indices = os_realloc_array(old, drv->num_if_indices + 1,
9949                                            sizeof(int));
9950         if (!drv->if_indices) {
9951                 if (!old)
9952                         drv->if_indices = drv->default_if_indices;
9953                 else
9954                         drv->if_indices = old;
9955                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
9956                            "interfaces");
9957                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
9958                 return;
9959         } else if (!old)
9960                 os_memcpy(drv->if_indices, drv->default_if_indices,
9961                           sizeof(drv->default_if_indices));
9962         drv->if_indices[drv->num_if_indices] = ifidx;
9963         drv->num_if_indices++;
9964         dump_ifidx(drv);
9965 }
9966
9967
9968 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
9969 {
9970         int i;
9971
9972         for (i = 0; i < drv->num_if_indices; i++) {
9973                 if (drv->if_indices[i] == ifidx) {
9974                         drv->if_indices[i] = 0;
9975                         break;
9976                 }
9977         }
9978         dump_ifidx(drv);
9979 }
9980
9981
9982 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
9983 {
9984         int i;
9985
9986         for (i = 0; i < drv->num_if_indices; i++)
9987                 if (drv->if_indices[i] == ifidx)
9988                         return 1;
9989
9990         return 0;
9991 }
9992
9993
9994 static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
9995                             const char *bridge_ifname, char *ifname_wds)
9996 {
9997         struct i802_bss *bss = priv;
9998         struct wpa_driver_nl80211_data *drv = bss->drv;
9999         char name[IFNAMSIZ + 1];
10000
10001         os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
10002         if (ifname_wds)
10003                 os_strlcpy(ifname_wds, name, IFNAMSIZ + 1);
10004
10005         wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
10006                    " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
10007         if (val) {
10008                 if (!if_nametoindex(name)) {
10009                         if (nl80211_create_iface(drv, name,
10010                                                  NL80211_IFTYPE_AP_VLAN,
10011                                                  bss->addr, 1, NULL, NULL, 0) <
10012                             0)
10013                                 return -1;
10014                         if (bridge_ifname &&
10015                             linux_br_add_if(drv->global->ioctl_sock,
10016                                             bridge_ifname, name) < 0)
10017                                 return -1;
10018                 }
10019                 if (linux_set_iface_flags(drv->global->ioctl_sock, name, 1)) {
10020                         wpa_printf(MSG_ERROR, "nl80211: Failed to set WDS STA "
10021                                    "interface %s up", name);
10022                 }
10023                 return i802_set_sta_vlan(priv, addr, name, 0);
10024         } else {
10025                 if (bridge_ifname)
10026                         linux_br_del_if(drv->global->ioctl_sock, bridge_ifname,
10027                                         name);
10028
10029                 i802_set_sta_vlan(priv, addr, bss->ifname, 0);
10030                 nl80211_remove_iface(drv, if_nametoindex(name));
10031                 return 0;
10032         }
10033 }
10034
10035
10036 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
10037 {
10038         struct wpa_driver_nl80211_data *drv = eloop_ctx;
10039         struct sockaddr_ll lladdr;
10040         unsigned char buf[3000];
10041         int len;
10042         socklen_t fromlen = sizeof(lladdr);
10043
10044         len = recvfrom(sock, buf, sizeof(buf), 0,
10045                        (struct sockaddr *)&lladdr, &fromlen);
10046         if (len < 0) {
10047                 wpa_printf(MSG_ERROR, "nl80211: EAPOL recv failed: %s",
10048                            strerror(errno));
10049                 return;
10050         }
10051
10052         if (have_ifidx(drv, lladdr.sll_ifindex))
10053                 drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
10054 }
10055
10056
10057 static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
10058                              struct i802_bss *bss,
10059                              const char *brname, const char *ifname)
10060 {
10061         int ifindex;
10062         char in_br[IFNAMSIZ];
10063
10064         os_strlcpy(bss->brname, brname, IFNAMSIZ);
10065         ifindex = if_nametoindex(brname);
10066         if (ifindex == 0) {
10067                 /*
10068                  * Bridge was configured, but the bridge device does
10069                  * not exist. Try to add it now.
10070                  */
10071                 if (linux_br_add(drv->global->ioctl_sock, brname) < 0) {
10072                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
10073                                    "bridge interface %s: %s",
10074                                    brname, strerror(errno));
10075                         return -1;
10076                 }
10077                 bss->added_bridge = 1;
10078                 add_ifidx(drv, if_nametoindex(brname));
10079         }
10080
10081         if (linux_br_get(in_br, ifname) == 0) {
10082                 if (os_strcmp(in_br, brname) == 0)
10083                         return 0; /* already in the bridge */
10084
10085                 wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
10086                            "bridge %s", ifname, in_br);
10087                 if (linux_br_del_if(drv->global->ioctl_sock, in_br, ifname) <
10088                     0) {
10089                         wpa_printf(MSG_ERROR, "nl80211: Failed to "
10090                                    "remove interface %s from bridge "
10091                                    "%s: %s",
10092                                    ifname, brname, strerror(errno));
10093                         return -1;
10094                 }
10095         }
10096
10097         wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
10098                    ifname, brname);
10099         if (linux_br_add_if(drv->global->ioctl_sock, brname, ifname) < 0) {
10100                 wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
10101                            "into bridge %s: %s",
10102                            ifname, brname, strerror(errno));
10103                 return -1;
10104         }
10105         bss->added_if_into_bridge = 1;
10106
10107         return 0;
10108 }
10109
10110
10111 static void *i802_init(struct hostapd_data *hapd,
10112                        struct wpa_init_params *params)
10113 {
10114         struct wpa_driver_nl80211_data *drv;
10115         struct i802_bss *bss;
10116         size_t i;
10117         char brname[IFNAMSIZ];
10118         int ifindex, br_ifindex;
10119         int br_added = 0;
10120
10121         bss = wpa_driver_nl80211_drv_init(hapd, params->ifname,
10122                                           params->global_priv, 1,
10123                                           params->bssid);
10124         if (bss == NULL)
10125                 return NULL;
10126
10127         drv = bss->drv;
10128
10129         if (linux_br_get(brname, params->ifname) == 0) {
10130                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
10131                            params->ifname, brname);
10132                 br_ifindex = if_nametoindex(brname);
10133         } else {
10134                 brname[0] = '\0';
10135                 br_ifindex = 0;
10136         }
10137
10138         for (i = 0; i < params->num_bridge; i++) {
10139                 if (params->bridge[i]) {
10140                         ifindex = if_nametoindex(params->bridge[i]);
10141                         if (ifindex)
10142                                 add_ifidx(drv, ifindex);
10143                         if (ifindex == br_ifindex)
10144                                 br_added = 1;
10145                 }
10146         }
10147         if (!br_added && br_ifindex &&
10148             (params->num_bridge == 0 || !params->bridge[0]))
10149                 add_ifidx(drv, br_ifindex);
10150
10151         /* start listening for EAPOL on the default AP interface */
10152         add_ifidx(drv, drv->ifindex);
10153
10154         if (params->num_bridge && params->bridge[0] &&
10155             i802_check_bridge(drv, bss, params->bridge[0], params->ifname) < 0)
10156                 goto failed;
10157
10158 #ifdef CONFIG_LIBNL3_ROUTE
10159         if (bss->added_if_into_bridge) {
10160                 drv->rtnl_sk = nl_socket_alloc();
10161                 if (drv->rtnl_sk == NULL) {
10162                         wpa_printf(MSG_ERROR, "nl80211: Failed to allocate nl_sock");
10163                         goto failed;
10164                 }
10165
10166                 if (nl_connect(drv->rtnl_sk, NETLINK_ROUTE)) {
10167                         wpa_printf(MSG_ERROR, "nl80211: Failed to connect nl_sock to NETLINK_ROUTE: %s",
10168                                    strerror(errno));
10169                         goto failed;
10170                 }
10171         }
10172 #endif /* CONFIG_LIBNL3_ROUTE */
10173
10174         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
10175         if (drv->eapol_sock < 0) {
10176                 wpa_printf(MSG_ERROR, "nl80211: socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE) failed: %s",
10177                            strerror(errno));
10178                 goto failed;
10179         }
10180
10181         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
10182         {
10183                 wpa_printf(MSG_INFO, "nl80211: Could not register read socket for eapol");
10184                 goto failed;
10185         }
10186
10187         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
10188                                params->own_addr))
10189                 goto failed;
10190         os_memcpy(drv->perm_addr, params->own_addr, ETH_ALEN);
10191
10192         memcpy(bss->addr, params->own_addr, ETH_ALEN);
10193
10194         return bss;
10195
10196 failed:
10197         wpa_driver_nl80211_deinit(bss);
10198         return NULL;
10199 }
10200
10201
10202 static void i802_deinit(void *priv)
10203 {
10204         struct i802_bss *bss = priv;
10205         wpa_driver_nl80211_deinit(bss);
10206 }
10207
10208
10209 static enum nl80211_iftype wpa_driver_nl80211_if_type(
10210         enum wpa_driver_if_type type)
10211 {
10212         switch (type) {
10213         case WPA_IF_STATION:
10214                 return NL80211_IFTYPE_STATION;
10215         case WPA_IF_P2P_CLIENT:
10216         case WPA_IF_P2P_GROUP:
10217                 return NL80211_IFTYPE_P2P_CLIENT;
10218         case WPA_IF_AP_VLAN:
10219                 return NL80211_IFTYPE_AP_VLAN;
10220         case WPA_IF_AP_BSS:
10221                 return NL80211_IFTYPE_AP;
10222         case WPA_IF_P2P_GO:
10223                 return NL80211_IFTYPE_P2P_GO;
10224         case WPA_IF_P2P_DEVICE:
10225                 return NL80211_IFTYPE_P2P_DEVICE;
10226         }
10227         return -1;
10228 }
10229
10230
10231 #ifdef CONFIG_P2P
10232
10233 static int nl80211_addr_in_use(struct nl80211_global *global, const u8 *addr)
10234 {
10235         struct wpa_driver_nl80211_data *drv;
10236         dl_list_for_each(drv, &global->interfaces,
10237                          struct wpa_driver_nl80211_data, list) {
10238                 if (os_memcmp(addr, drv->first_bss->addr, ETH_ALEN) == 0)
10239                         return 1;
10240         }
10241         return 0;
10242 }
10243
10244
10245 static int nl80211_p2p_interface_addr(struct wpa_driver_nl80211_data *drv,
10246                                       u8 *new_addr)
10247 {
10248         unsigned int idx;
10249
10250         if (!drv->global)
10251                 return -1;
10252
10253         os_memcpy(new_addr, drv->first_bss->addr, ETH_ALEN);
10254         for (idx = 0; idx < 64; idx++) {
10255                 new_addr[0] = drv->first_bss->addr[0] | 0x02;
10256                 new_addr[0] ^= idx << 2;
10257                 if (!nl80211_addr_in_use(drv->global, new_addr))
10258                         break;
10259         }
10260         if (idx == 64)
10261                 return -1;
10262
10263         wpa_printf(MSG_DEBUG, "nl80211: Assigned new P2P Interface Address "
10264                    MACSTR, MAC2STR(new_addr));
10265
10266         return 0;
10267 }
10268
10269 #endif /* CONFIG_P2P */
10270
10271
10272 struct wdev_info {
10273         u64 wdev_id;
10274         int wdev_id_set;
10275         u8 macaddr[ETH_ALEN];
10276 };
10277
10278 static int nl80211_wdev_handler(struct nl_msg *msg, void *arg)
10279 {
10280         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
10281         struct nlattr *tb[NL80211_ATTR_MAX + 1];
10282         struct wdev_info *wi = arg;
10283
10284         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
10285                   genlmsg_attrlen(gnlh, 0), NULL);
10286         if (tb[NL80211_ATTR_WDEV]) {
10287                 wi->wdev_id = nla_get_u64(tb[NL80211_ATTR_WDEV]);
10288                 wi->wdev_id_set = 1;
10289         }
10290
10291         if (tb[NL80211_ATTR_MAC])
10292                 os_memcpy(wi->macaddr, nla_data(tb[NL80211_ATTR_MAC]),
10293                           ETH_ALEN);
10294
10295         return NL_SKIP;
10296 }
10297
10298
10299 static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
10300                                      const char *ifname, const u8 *addr,
10301                                      void *bss_ctx, void **drv_priv,
10302                                      char *force_ifname, u8 *if_addr,
10303                                      const char *bridge, int use_existing)
10304 {
10305         enum nl80211_iftype nlmode;
10306         struct i802_bss *bss = priv;
10307         struct wpa_driver_nl80211_data *drv = bss->drv;
10308         int ifidx;
10309         int added = 1;
10310
10311         if (addr)
10312                 os_memcpy(if_addr, addr, ETH_ALEN);
10313         nlmode = wpa_driver_nl80211_if_type(type);
10314         if (nlmode == NL80211_IFTYPE_P2P_DEVICE) {
10315                 struct wdev_info p2pdev_info;
10316
10317                 os_memset(&p2pdev_info, 0, sizeof(p2pdev_info));
10318                 ifidx = nl80211_create_iface(drv, ifname, nlmode, addr,
10319                                              0, nl80211_wdev_handler,
10320                                              &p2pdev_info, use_existing);
10321                 if (!p2pdev_info.wdev_id_set || ifidx != 0) {
10322                         wpa_printf(MSG_ERROR, "nl80211: Failed to create a P2P Device interface %s",
10323                                    ifname);
10324                         return -1;
10325                 }
10326
10327                 drv->global->if_add_wdevid = p2pdev_info.wdev_id;
10328                 drv->global->if_add_wdevid_set = p2pdev_info.wdev_id_set;
10329                 if (!is_zero_ether_addr(p2pdev_info.macaddr))
10330                         os_memcpy(if_addr, p2pdev_info.macaddr, ETH_ALEN);
10331                 wpa_printf(MSG_DEBUG, "nl80211: New P2P Device interface %s (0x%llx) created",
10332                            ifname,
10333                            (long long unsigned int) p2pdev_info.wdev_id);
10334         } else {
10335                 ifidx = nl80211_create_iface(drv, ifname, nlmode, addr,
10336                                              0, NULL, NULL, use_existing);
10337                 if (use_existing && ifidx == -ENFILE) {
10338                         added = 0;
10339                         ifidx = if_nametoindex(ifname);
10340                 } else if (ifidx < 0) {
10341                         return -1;
10342                 }
10343         }
10344
10345         if (!addr) {
10346                 if (drv->nlmode == NL80211_IFTYPE_P2P_DEVICE)
10347                         os_memcpy(if_addr, bss->addr, ETH_ALEN);
10348                 else if (linux_get_ifhwaddr(drv->global->ioctl_sock,
10349                                             bss->ifname, if_addr) < 0) {
10350                         if (added)
10351                                 nl80211_remove_iface(drv, ifidx);
10352                         return -1;
10353                 }
10354         }
10355
10356 #ifdef CONFIG_P2P
10357         if (!addr &&
10358             (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
10359              type == WPA_IF_P2P_GO)) {
10360                 /* Enforce unique P2P Interface Address */
10361                 u8 new_addr[ETH_ALEN];
10362
10363                 if (linux_get_ifhwaddr(drv->global->ioctl_sock, ifname,
10364                                        new_addr) < 0) {
10365                         if (added)
10366                                 nl80211_remove_iface(drv, ifidx);
10367                         return -1;
10368                 }
10369                 if (nl80211_addr_in_use(drv->global, new_addr)) {
10370                         wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
10371                                    "for P2P group interface");
10372                         if (nl80211_p2p_interface_addr(drv, new_addr) < 0) {
10373                                 if (added)
10374                                         nl80211_remove_iface(drv, ifidx);
10375                                 return -1;
10376                         }
10377                         if (linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
10378                                                new_addr) < 0) {
10379                                 if (added)
10380                                         nl80211_remove_iface(drv, ifidx);
10381                                 return -1;
10382                         }
10383                 }
10384                 os_memcpy(if_addr, new_addr, ETH_ALEN);
10385         }
10386 #endif /* CONFIG_P2P */
10387
10388         if (type == WPA_IF_AP_BSS) {
10389                 struct i802_bss *new_bss = os_zalloc(sizeof(*new_bss));
10390                 if (new_bss == NULL) {
10391                         if (added)
10392                                 nl80211_remove_iface(drv, ifidx);
10393                         return -1;
10394                 }
10395
10396                 if (bridge &&
10397                     i802_check_bridge(drv, new_bss, bridge, ifname) < 0) {
10398                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the new "
10399                                    "interface %s to a bridge %s",
10400                                    ifname, bridge);
10401                         if (added)
10402                                 nl80211_remove_iface(drv, ifidx);
10403                         os_free(new_bss);
10404                         return -1;
10405                 }
10406
10407                 if (linux_set_iface_flags(drv->global->ioctl_sock, ifname, 1))
10408                 {
10409                         if (added)
10410                                 nl80211_remove_iface(drv, ifidx);
10411                         os_free(new_bss);
10412                         return -1;
10413                 }
10414                 os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
10415                 os_memcpy(new_bss->addr, if_addr, ETH_ALEN);
10416                 new_bss->ifindex = ifidx;
10417                 new_bss->drv = drv;
10418                 new_bss->next = drv->first_bss->next;
10419                 new_bss->freq = drv->first_bss->freq;
10420                 new_bss->ctx = bss_ctx;
10421                 new_bss->added_if = added;
10422                 drv->first_bss->next = new_bss;
10423                 if (drv_priv)
10424                         *drv_priv = new_bss;
10425                 nl80211_init_bss(new_bss);
10426
10427                 /* Subscribe management frames for this WPA_IF_AP_BSS */
10428                 if (nl80211_setup_ap(new_bss))
10429                         return -1;
10430         }
10431
10432         if (drv->global)
10433                 drv->global->if_add_ifindex = ifidx;
10434
10435         /*
10436          * Some virtual interfaces need to process EAPOL packets and events on
10437          * the parent interface. This is used mainly with hostapd.
10438          */
10439         if (ifidx > 0 &&
10440             (drv->hostapd ||
10441              nlmode == NL80211_IFTYPE_AP_VLAN ||
10442              nlmode == NL80211_IFTYPE_WDS ||
10443              nlmode == NL80211_IFTYPE_MONITOR))
10444                 add_ifidx(drv, ifidx);
10445
10446         return 0;
10447 }
10448
10449
10450 static int wpa_driver_nl80211_if_remove(struct i802_bss *bss,
10451                                         enum wpa_driver_if_type type,
10452                                         const char *ifname)
10453 {
10454         struct wpa_driver_nl80211_data *drv = bss->drv;
10455         int ifindex = if_nametoindex(ifname);
10456
10457         wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d added_if=%d",
10458                    __func__, type, ifname, ifindex, bss->added_if);
10459         if (ifindex > 0 && (bss->added_if || bss->ifindex != ifindex))
10460                 nl80211_remove_iface(drv, ifindex);
10461         else if (ifindex > 0 && !bss->added_if) {
10462                 struct wpa_driver_nl80211_data *drv2;
10463                 dl_list_for_each(drv2, &drv->global->interfaces,
10464                                  struct wpa_driver_nl80211_data, list)
10465                         del_ifidx(drv2, ifindex);
10466         }
10467
10468         if (type != WPA_IF_AP_BSS)
10469                 return 0;
10470
10471         if (bss->added_if_into_bridge) {
10472                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
10473                                     bss->ifname) < 0)
10474                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
10475                                    "interface %s from bridge %s: %s",
10476                                    bss->ifname, bss->brname, strerror(errno));
10477         }
10478         if (bss->added_bridge) {
10479                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
10480                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
10481                                    "bridge %s: %s",
10482                                    bss->brname, strerror(errno));
10483         }
10484
10485         if (bss != drv->first_bss) {
10486                 struct i802_bss *tbss;
10487
10488                 wpa_printf(MSG_DEBUG, "nl80211: Not the first BSS - remove it");
10489                 for (tbss = drv->first_bss; tbss; tbss = tbss->next) {
10490                         if (tbss->next == bss) {
10491                                 tbss->next = bss->next;
10492                                 /* Unsubscribe management frames */
10493                                 nl80211_teardown_ap(bss);
10494                                 nl80211_destroy_bss(bss);
10495                                 if (!bss->added_if)
10496                                         i802_set_iface_flags(bss, 0);
10497                                 os_free(bss);
10498                                 bss = NULL;
10499                                 break;
10500                         }
10501                 }
10502                 if (bss)
10503                         wpa_printf(MSG_INFO, "nl80211: %s - could not find "
10504                                    "BSS %p in the list", __func__, bss);
10505         } else {
10506                 wpa_printf(MSG_DEBUG, "nl80211: First BSS - reassign context");
10507                 nl80211_teardown_ap(bss);
10508                 if (!bss->added_if && !drv->first_bss->next)
10509                         wpa_driver_nl80211_del_beacon(drv);
10510                 nl80211_destroy_bss(bss);
10511                 if (!bss->added_if)
10512                         i802_set_iface_flags(bss, 0);
10513                 if (drv->first_bss->next) {
10514                         drv->first_bss = drv->first_bss->next;
10515                         drv->ctx = drv->first_bss->ctx;
10516                         os_free(bss);
10517                 } else {
10518                         wpa_printf(MSG_DEBUG, "nl80211: No second BSS to reassign context to");
10519                 }
10520         }
10521
10522         return 0;
10523 }
10524
10525
10526 static int cookie_handler(struct nl_msg *msg, void *arg)
10527 {
10528         struct nlattr *tb[NL80211_ATTR_MAX + 1];
10529         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
10530         u64 *cookie = arg;
10531         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
10532                   genlmsg_attrlen(gnlh, 0), NULL);
10533         if (tb[NL80211_ATTR_COOKIE])
10534                 *cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
10535         return NL_SKIP;
10536 }
10537
10538
10539 static int nl80211_send_frame_cmd(struct i802_bss *bss,
10540                                   unsigned int freq, unsigned int wait,
10541                                   const u8 *buf, size_t buf_len,
10542                                   u64 *cookie_out, int no_cck, int no_ack,
10543                                   int offchanok)
10544 {
10545         struct wpa_driver_nl80211_data *drv = bss->drv;
10546         struct nl_msg *msg;
10547         u64 cookie;
10548         int ret = -1;
10549
10550         msg = nlmsg_alloc();
10551         if (!msg)
10552                 return -1;
10553
10554         wpa_printf(MSG_MSGDUMP, "nl80211: CMD_FRAME freq=%u wait=%u no_cck=%d "
10555                    "no_ack=%d offchanok=%d",
10556                    freq, wait, no_cck, no_ack, offchanok);
10557         wpa_hexdump(MSG_MSGDUMP, "CMD_FRAME", buf, buf_len);
10558         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME);
10559
10560         if (nl80211_set_iface_id(msg, bss) < 0)
10561                 goto nla_put_failure;
10562         if (freq)
10563                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
10564         if (wait)
10565                 NLA_PUT_U32(msg, NL80211_ATTR_DURATION, wait);
10566         if (offchanok && ((drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX) ||
10567                           drv->test_use_roc_tx))
10568                 NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
10569         if (no_cck)
10570                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
10571         if (no_ack)
10572                 NLA_PUT_FLAG(msg, NL80211_ATTR_DONT_WAIT_FOR_ACK);
10573
10574         NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
10575
10576         cookie = 0;
10577         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
10578         msg = NULL;
10579         if (ret) {
10580                 wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
10581                            "(%s) (freq=%u wait=%u)", ret, strerror(-ret),
10582                            freq, wait);
10583                 goto nla_put_failure;
10584         }
10585         wpa_printf(MSG_MSGDUMP, "nl80211: Frame TX command accepted%s; "
10586                    "cookie 0x%llx", no_ack ? " (no ACK)" : "",
10587                    (long long unsigned int) cookie);
10588
10589         if (cookie_out)
10590                 *cookie_out = no_ack ? (u64) -1 : cookie;
10591
10592 nla_put_failure:
10593         nlmsg_free(msg);
10594         return ret;
10595 }
10596
10597
10598 static int wpa_driver_nl80211_send_action(struct i802_bss *bss,
10599                                           unsigned int freq,
10600                                           unsigned int wait_time,
10601                                           const u8 *dst, const u8 *src,
10602                                           const u8 *bssid,
10603                                           const u8 *data, size_t data_len,
10604                                           int no_cck)
10605 {
10606         struct wpa_driver_nl80211_data *drv = bss->drv;
10607         int ret = -1;
10608         u8 *buf;
10609         struct ieee80211_hdr *hdr;
10610
10611         wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d, "
10612                    "freq=%u MHz wait=%d ms no_cck=%d)",
10613                    drv->ifindex, freq, wait_time, no_cck);
10614
10615         buf = os_zalloc(24 + data_len);
10616         if (buf == NULL)
10617                 return ret;
10618         os_memcpy(buf + 24, data, data_len);
10619         hdr = (struct ieee80211_hdr *) buf;
10620         hdr->frame_control =
10621                 IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
10622         os_memcpy(hdr->addr1, dst, ETH_ALEN);
10623         os_memcpy(hdr->addr2, src, ETH_ALEN);
10624         os_memcpy(hdr->addr3, bssid, ETH_ALEN);
10625
10626         if (is_ap_interface(drv->nlmode) &&
10627             (!(drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX) ||
10628              (int) freq == bss->freq || drv->device_ap_sme ||
10629              !drv->use_monitor))
10630                 ret = wpa_driver_nl80211_send_mlme(bss, buf, 24 + data_len,
10631                                                    0, freq, no_cck, 1,
10632                                                    wait_time);
10633         else
10634                 ret = nl80211_send_frame_cmd(bss, freq, wait_time, buf,
10635                                              24 + data_len,
10636                                              &drv->send_action_cookie,
10637                                              no_cck, 0, 1);
10638
10639         os_free(buf);
10640         return ret;
10641 }
10642
10643
10644 static void wpa_driver_nl80211_send_action_cancel_wait(void *priv)
10645 {
10646         struct i802_bss *bss = priv;
10647         struct wpa_driver_nl80211_data *drv = bss->drv;
10648         struct nl_msg *msg;
10649         int ret;
10650
10651         msg = nlmsg_alloc();
10652         if (!msg)
10653                 return;
10654
10655         wpa_printf(MSG_DEBUG, "nl80211: Cancel TX frame wait: cookie=0x%llx",
10656                    (long long unsigned int) drv->send_action_cookie);
10657         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME_WAIT_CANCEL);
10658
10659         if (nl80211_set_iface_id(msg, bss) < 0)
10660                 goto nla_put_failure;
10661         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->send_action_cookie);
10662
10663         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
10664         msg = NULL;
10665         if (ret)
10666                 wpa_printf(MSG_DEBUG, "nl80211: wait cancel failed: ret=%d "
10667                            "(%s)", ret, strerror(-ret));
10668
10669  nla_put_failure:
10670         nlmsg_free(msg);
10671 }
10672
10673
10674 static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
10675                                                 unsigned int duration)
10676 {
10677         struct i802_bss *bss = priv;
10678         struct wpa_driver_nl80211_data *drv = bss->drv;
10679         struct nl_msg *msg;
10680         int ret;
10681         u64 cookie;
10682
10683         msg = nlmsg_alloc();
10684         if (!msg)
10685                 return -1;
10686
10687         nl80211_cmd(drv, msg, 0, NL80211_CMD_REMAIN_ON_CHANNEL);
10688
10689         if (nl80211_set_iface_id(msg, bss) < 0)
10690                 goto nla_put_failure;
10691
10692         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
10693         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
10694
10695         cookie = 0;
10696         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
10697         msg = NULL;
10698         if (ret == 0) {
10699                 wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
10700                            "0x%llx for freq=%u MHz duration=%u",
10701                            (long long unsigned int) cookie, freq, duration);
10702                 drv->remain_on_chan_cookie = cookie;
10703                 drv->pending_remain_on_chan = 1;
10704                 return 0;
10705         }
10706         wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
10707                    "(freq=%d duration=%u): %d (%s)",
10708                    freq, duration, ret, strerror(-ret));
10709 nla_put_failure:
10710         nlmsg_free(msg);
10711         return -1;
10712 }
10713
10714
10715 static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
10716 {
10717         struct i802_bss *bss = priv;
10718         struct wpa_driver_nl80211_data *drv = bss->drv;
10719         struct nl_msg *msg;
10720         int ret;
10721
10722         if (!drv->pending_remain_on_chan) {
10723                 wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
10724                            "to cancel");
10725                 return -1;
10726         }
10727
10728         wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
10729                    "0x%llx",
10730                    (long long unsigned int) drv->remain_on_chan_cookie);
10731
10732         msg = nlmsg_alloc();
10733         if (!msg)
10734                 return -1;
10735
10736         nl80211_cmd(drv, msg, 0, NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL);
10737
10738         if (nl80211_set_iface_id(msg, bss) < 0)
10739                 goto nla_put_failure;
10740
10741         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
10742
10743         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
10744         msg = NULL;
10745         if (ret == 0)
10746                 return 0;
10747         wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
10748                    "%d (%s)", ret, strerror(-ret));
10749 nla_put_failure:
10750         nlmsg_free(msg);
10751         return -1;
10752 }
10753
10754
10755 static int wpa_driver_nl80211_probe_req_report(struct i802_bss *bss, int report)
10756 {
10757         struct wpa_driver_nl80211_data *drv = bss->drv;
10758
10759         if (!report) {
10760                 if (bss->nl_preq && drv->device_ap_sme &&
10761                     is_ap_interface(drv->nlmode) && !bss->in_deinit &&
10762                     !bss->static_ap) {
10763                         /*
10764                          * Do not disable Probe Request reporting that was
10765                          * enabled in nl80211_setup_ap().
10766                          */
10767                         wpa_printf(MSG_DEBUG, "nl80211: Skip disabling of "
10768                                    "Probe Request reporting nl_preq=%p while "
10769                                    "in AP mode", bss->nl_preq);
10770                 } else if (bss->nl_preq) {
10771                         wpa_printf(MSG_DEBUG, "nl80211: Disable Probe Request "
10772                                    "reporting nl_preq=%p", bss->nl_preq);
10773                         nl80211_destroy_eloop_handle(&bss->nl_preq);
10774                 }
10775                 return 0;
10776         }
10777
10778         if (bss->nl_preq) {
10779                 wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
10780                            "already on! nl_preq=%p", bss->nl_preq);
10781                 return 0;
10782         }
10783
10784         bss->nl_preq = nl_create_handle(drv->global->nl_cb, "preq");
10785         if (bss->nl_preq == NULL)
10786                 return -1;
10787         wpa_printf(MSG_DEBUG, "nl80211: Enable Probe Request "
10788                    "reporting nl_preq=%p", bss->nl_preq);
10789
10790         if (nl80211_register_frame(bss, bss->nl_preq,
10791                                    (WLAN_FC_TYPE_MGMT << 2) |
10792                                    (WLAN_FC_STYPE_PROBE_REQ << 4),
10793                                    NULL, 0) < 0)
10794                 goto out_err;
10795
10796         nl80211_register_eloop_read(&bss->nl_preq,
10797                                     wpa_driver_nl80211_event_receive,
10798                                     bss->nl_cb);
10799
10800         return 0;
10801
10802  out_err:
10803         nl_destroy_handles(&bss->nl_preq);
10804         return -1;
10805 }
10806
10807
10808 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
10809                                      int ifindex, int disabled)
10810 {
10811         struct nl_msg *msg;
10812         struct nlattr *bands, *band;
10813         int ret;
10814
10815         msg = nlmsg_alloc();
10816         if (!msg)
10817                 return -1;
10818
10819         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_TX_BITRATE_MASK);
10820         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
10821
10822         bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
10823         if (!bands)
10824                 goto nla_put_failure;
10825
10826         /*
10827          * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
10828          * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
10829          * rates. All 5 GHz rates are left enabled.
10830          */
10831         band = nla_nest_start(msg, NL80211_BAND_2GHZ);
10832         if (!band)
10833                 goto nla_put_failure;
10834         if (disabled) {
10835                 NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
10836                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
10837         }
10838         nla_nest_end(msg, band);
10839
10840         nla_nest_end(msg, bands);
10841
10842         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
10843         msg = NULL;
10844         if (ret) {
10845                 wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
10846                            "(%s)", ret, strerror(-ret));
10847         } else
10848                 drv->disabled_11b_rates = disabled;
10849
10850         return ret;
10851
10852 nla_put_failure:
10853         nlmsg_free(msg);
10854         return -1;
10855 }
10856
10857
10858 static int wpa_driver_nl80211_deinit_ap(void *priv)
10859 {
10860         struct i802_bss *bss = priv;
10861         struct wpa_driver_nl80211_data *drv = bss->drv;
10862         if (!is_ap_interface(drv->nlmode))
10863                 return -1;
10864         wpa_driver_nl80211_del_beacon(drv);
10865
10866         /*
10867          * If the P2P GO interface was dynamically added, then it is
10868          * possible that the interface change to station is not possible.
10869          */
10870         if (drv->nlmode == NL80211_IFTYPE_P2P_GO && bss->if_dynamic)
10871                 return 0;
10872
10873         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
10874 }
10875
10876
10877 static int wpa_driver_nl80211_stop_ap(void *priv)
10878 {
10879         struct i802_bss *bss = priv;
10880         struct wpa_driver_nl80211_data *drv = bss->drv;
10881         if (!is_ap_interface(drv->nlmode))
10882                 return -1;
10883         wpa_driver_nl80211_del_beacon(drv);
10884         bss->beacon_set = 0;
10885         return 0;
10886 }
10887
10888
10889 static int wpa_driver_nl80211_deinit_p2p_cli(void *priv)
10890 {
10891         struct i802_bss *bss = priv;
10892         struct wpa_driver_nl80211_data *drv = bss->drv;
10893         if (drv->nlmode != NL80211_IFTYPE_P2P_CLIENT)
10894                 return -1;
10895
10896         /*
10897          * If the P2P Client interface was dynamically added, then it is
10898          * possible that the interface change to station is not possible.
10899          */
10900         if (bss->if_dynamic)
10901                 return 0;
10902
10903         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
10904 }
10905
10906
10907 static void wpa_driver_nl80211_resume(void *priv)
10908 {
10909         struct i802_bss *bss = priv;
10910
10911         if (i802_set_iface_flags(bss, 1))
10912                 wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on resume event");
10913 }
10914
10915
10916 static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
10917                                   const u8 *ies, size_t ies_len)
10918 {
10919         struct i802_bss *bss = priv;
10920         struct wpa_driver_nl80211_data *drv = bss->drv;
10921         int ret;
10922         u8 *data, *pos;
10923         size_t data_len;
10924         const u8 *own_addr = bss->addr;
10925
10926         if (action != 1) {
10927                 wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
10928                            "action %d", action);
10929                 return -1;
10930         }
10931
10932         /*
10933          * Action frame payload:
10934          * Category[1] = 6 (Fast BSS Transition)
10935          * Action[1] = 1 (Fast BSS Transition Request)
10936          * STA Address
10937          * Target AP Address
10938          * FT IEs
10939          */
10940
10941         data_len = 2 + 2 * ETH_ALEN + ies_len;
10942         data = os_malloc(data_len);
10943         if (data == NULL)
10944                 return -1;
10945         pos = data;
10946         *pos++ = 0x06; /* FT Action category */
10947         *pos++ = action;
10948         os_memcpy(pos, own_addr, ETH_ALEN);
10949         pos += ETH_ALEN;
10950         os_memcpy(pos, target_ap, ETH_ALEN);
10951         pos += ETH_ALEN;
10952         os_memcpy(pos, ies, ies_len);
10953
10954         ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, 0,
10955                                              drv->bssid, own_addr, drv->bssid,
10956                                              data, data_len, 0);
10957         os_free(data);
10958
10959         return ret;
10960 }
10961
10962
10963 static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
10964 {
10965         struct i802_bss *bss = priv;
10966         struct wpa_driver_nl80211_data *drv = bss->drv;
10967         struct nl_msg *msg;
10968         struct nlattr *cqm;
10969         int ret = -1;
10970
10971         wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
10972                    "hysteresis=%d", threshold, hysteresis);
10973
10974         msg = nlmsg_alloc();
10975         if (!msg)
10976                 return -1;
10977
10978         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_CQM);
10979
10980         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
10981
10982         cqm = nla_nest_start(msg, NL80211_ATTR_CQM);
10983         if (cqm == NULL)
10984                 goto nla_put_failure;
10985
10986         NLA_PUT_U32(msg, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
10987         NLA_PUT_U32(msg, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
10988         nla_nest_end(msg, cqm);
10989
10990         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
10991         msg = NULL;
10992
10993 nla_put_failure:
10994         nlmsg_free(msg);
10995         return ret;
10996 }
10997
10998
10999 static int get_channel_width(struct nl_msg *msg, void *arg)
11000 {
11001         struct nlattr *tb[NL80211_ATTR_MAX + 1];
11002         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
11003         struct wpa_signal_info *sig_change = arg;
11004
11005         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
11006                   genlmsg_attrlen(gnlh, 0), NULL);
11007
11008         sig_change->center_frq1 = -1;
11009         sig_change->center_frq2 = -1;
11010         sig_change->chanwidth = CHAN_WIDTH_UNKNOWN;
11011
11012         if (tb[NL80211_ATTR_CHANNEL_WIDTH]) {
11013                 sig_change->chanwidth = convert2width(
11014                         nla_get_u32(tb[NL80211_ATTR_CHANNEL_WIDTH]));
11015                 if (tb[NL80211_ATTR_CENTER_FREQ1])
11016                         sig_change->center_frq1 =
11017                                 nla_get_u32(tb[NL80211_ATTR_CENTER_FREQ1]);
11018                 if (tb[NL80211_ATTR_CENTER_FREQ2])
11019                         sig_change->center_frq2 =
11020                                 nla_get_u32(tb[NL80211_ATTR_CENTER_FREQ2]);
11021         }
11022
11023         return NL_SKIP;
11024 }
11025
11026
11027 static int nl80211_get_channel_width(struct wpa_driver_nl80211_data *drv,
11028                                      struct wpa_signal_info *sig)
11029 {
11030         struct nl_msg *msg;
11031
11032         msg = nlmsg_alloc();
11033         if (!msg)
11034                 return -ENOMEM;
11035
11036         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_INTERFACE);
11037         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
11038
11039         return send_and_recv_msgs(drv, msg, get_channel_width, sig);
11040
11041 nla_put_failure:
11042         nlmsg_free(msg);
11043         return -ENOBUFS;
11044 }
11045
11046
11047 static int nl80211_signal_poll(void *priv, struct wpa_signal_info *si)
11048 {
11049         struct i802_bss *bss = priv;
11050         struct wpa_driver_nl80211_data *drv = bss->drv;
11051         int res;
11052
11053         os_memset(si, 0, sizeof(*si));
11054         res = nl80211_get_link_signal(drv, si);
11055         if (res != 0)
11056                 return res;
11057
11058         res = nl80211_get_channel_width(drv, si);
11059         if (res != 0)
11060                 return res;
11061
11062         return nl80211_get_link_noise(drv, si);
11063 }
11064
11065
11066 static int wpa_driver_nl80211_shared_freq(void *priv)
11067 {
11068         struct i802_bss *bss = priv;
11069         struct wpa_driver_nl80211_data *drv = bss->drv;
11070         struct wpa_driver_nl80211_data *driver;
11071         int freq = 0;
11072
11073         /*
11074          * If the same PHY is in connected state with some other interface,
11075          * then retrieve the assoc freq.
11076          */
11077         wpa_printf(MSG_DEBUG, "nl80211: Get shared freq for PHY %s",
11078                    drv->phyname);
11079
11080         dl_list_for_each(driver, &drv->global->interfaces,
11081                          struct wpa_driver_nl80211_data, list) {
11082                 if (drv == driver ||
11083                     os_strcmp(drv->phyname, driver->phyname) != 0 ||
11084                     !driver->associated)
11085                         continue;
11086
11087                 wpa_printf(MSG_DEBUG, "nl80211: Found a match for PHY %s - %s "
11088                            MACSTR,
11089                            driver->phyname, driver->first_bss->ifname,
11090                            MAC2STR(driver->first_bss->addr));
11091                 if (is_ap_interface(driver->nlmode))
11092                         freq = driver->first_bss->freq;
11093                 else
11094                         freq = nl80211_get_assoc_freq(driver);
11095                 wpa_printf(MSG_DEBUG, "nl80211: Shared freq for PHY %s: %d",
11096                            drv->phyname, freq);
11097         }
11098
11099         if (!freq)
11100                 wpa_printf(MSG_DEBUG, "nl80211: No shared interface for "
11101                            "PHY (%s) in associated state", drv->phyname);
11102
11103         return freq;
11104 }
11105
11106
11107 static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
11108                               int encrypt)
11109 {
11110         struct i802_bss *bss = priv;
11111         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt, 0,
11112                                              0, 0, 0, 0);
11113 }
11114
11115
11116 static int nl80211_set_param(void *priv, const char *param)
11117 {
11118         wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
11119         if (param == NULL)
11120                 return 0;
11121
11122 #ifdef CONFIG_P2P
11123         if (os_strstr(param, "use_p2p_group_interface=1")) {
11124                 struct i802_bss *bss = priv;
11125                 struct wpa_driver_nl80211_data *drv = bss->drv;
11126
11127                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
11128                            "interface");
11129                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
11130                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
11131         }
11132
11133         if (os_strstr(param, "p2p_device=1")) {
11134                 struct i802_bss *bss = priv;
11135                 struct wpa_driver_nl80211_data *drv = bss->drv;
11136                 drv->allow_p2p_device = 1;
11137         }
11138 #endif /* CONFIG_P2P */
11139
11140         if (os_strstr(param, "use_monitor=1")) {
11141                 struct i802_bss *bss = priv;
11142                 struct wpa_driver_nl80211_data *drv = bss->drv;
11143                 drv->use_monitor = 1;
11144         }
11145
11146         if (os_strstr(param, "force_connect_cmd=1")) {
11147                 struct i802_bss *bss = priv;
11148                 struct wpa_driver_nl80211_data *drv = bss->drv;
11149                 drv->capa.flags &= ~WPA_DRIVER_FLAGS_SME;
11150                 drv->force_connect_cmd = 1;
11151         }
11152
11153         if (os_strstr(param, "no_offchannel_tx=1")) {
11154                 struct i802_bss *bss = priv;
11155                 struct wpa_driver_nl80211_data *drv = bss->drv;
11156                 drv->capa.flags &= ~WPA_DRIVER_FLAGS_OFFCHANNEL_TX;
11157                 drv->test_use_roc_tx = 1;
11158         }
11159
11160         return 0;
11161 }
11162
11163
11164 static void * nl80211_global_init(void)
11165 {
11166         struct nl80211_global *global;
11167         struct netlink_config *cfg;
11168
11169         global = os_zalloc(sizeof(*global));
11170         if (global == NULL)
11171                 return NULL;
11172         global->ioctl_sock = -1;
11173         dl_list_init(&global->interfaces);
11174         global->if_add_ifindex = -1;
11175
11176         cfg = os_zalloc(sizeof(*cfg));
11177         if (cfg == NULL)
11178                 goto err;
11179
11180         cfg->ctx = global;
11181         cfg->newlink_cb = wpa_driver_nl80211_event_rtm_newlink;
11182         cfg->dellink_cb = wpa_driver_nl80211_event_rtm_dellink;
11183         global->netlink = netlink_init(cfg);
11184         if (global->netlink == NULL) {
11185                 os_free(cfg);
11186                 goto err;
11187         }
11188
11189         if (wpa_driver_nl80211_init_nl_global(global) < 0)
11190                 goto err;
11191
11192         global->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
11193         if (global->ioctl_sock < 0) {
11194                 wpa_printf(MSG_ERROR, "nl80211: socket(PF_INET,SOCK_DGRAM) failed: %s",
11195                            strerror(errno));
11196                 goto err;
11197         }
11198
11199         return global;
11200
11201 err:
11202         nl80211_global_deinit(global);
11203         return NULL;
11204 }
11205
11206
11207 static void nl80211_global_deinit(void *priv)
11208 {
11209         struct nl80211_global *global = priv;
11210         if (global == NULL)
11211                 return;
11212         if (!dl_list_empty(&global->interfaces)) {
11213                 wpa_printf(MSG_ERROR, "nl80211: %u interface(s) remain at "
11214                            "nl80211_global_deinit",
11215                            dl_list_len(&global->interfaces));
11216         }
11217
11218         if (global->netlink)
11219                 netlink_deinit(global->netlink);
11220
11221         nl_destroy_handles(&global->nl);
11222
11223         if (global->nl_event)
11224                 nl80211_destroy_eloop_handle(&global->nl_event);
11225
11226         nl_cb_put(global->nl_cb);
11227
11228         if (global->ioctl_sock >= 0)
11229                 close(global->ioctl_sock);
11230
11231         os_free(global);
11232 }
11233
11234
11235 static const char * nl80211_get_radio_name(void *priv)
11236 {
11237         struct i802_bss *bss = priv;
11238         struct wpa_driver_nl80211_data *drv = bss->drv;
11239         return drv->phyname;
11240 }
11241
11242
11243 static int nl80211_pmkid(struct i802_bss *bss, int cmd, const u8 *bssid,
11244                          const u8 *pmkid)
11245 {
11246         struct nl_msg *msg;
11247
11248         msg = nlmsg_alloc();
11249         if (!msg)
11250                 return -ENOMEM;
11251
11252         nl80211_cmd(bss->drv, msg, 0, cmd);
11253
11254         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
11255         if (pmkid)
11256                 NLA_PUT(msg, NL80211_ATTR_PMKID, 16, pmkid);
11257         if (bssid)
11258                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
11259
11260         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
11261  nla_put_failure:
11262         nlmsg_free(msg);
11263         return -ENOBUFS;
11264 }
11265
11266
11267 static int nl80211_add_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
11268 {
11269         struct i802_bss *bss = priv;
11270         wpa_printf(MSG_DEBUG, "nl80211: Add PMKID for " MACSTR, MAC2STR(bssid));
11271         return nl80211_pmkid(bss, NL80211_CMD_SET_PMKSA, bssid, pmkid);
11272 }
11273
11274
11275 static int nl80211_remove_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
11276 {
11277         struct i802_bss *bss = priv;
11278         wpa_printf(MSG_DEBUG, "nl80211: Delete PMKID for " MACSTR,
11279                    MAC2STR(bssid));
11280         return nl80211_pmkid(bss, NL80211_CMD_DEL_PMKSA, bssid, pmkid);
11281 }
11282
11283
11284 static int nl80211_flush_pmkid(void *priv)
11285 {
11286         struct i802_bss *bss = priv;
11287         wpa_printf(MSG_DEBUG, "nl80211: Flush PMKIDs");
11288         return nl80211_pmkid(bss, NL80211_CMD_FLUSH_PMKSA, NULL, NULL);
11289 }
11290
11291
11292 static void clean_survey_results(struct survey_results *survey_results)
11293 {
11294         struct freq_survey *survey, *tmp;
11295
11296         if (dl_list_empty(&survey_results->survey_list))
11297                 return;
11298
11299         dl_list_for_each_safe(survey, tmp, &survey_results->survey_list,
11300                               struct freq_survey, list) {
11301                 dl_list_del(&survey->list);
11302                 os_free(survey);
11303         }
11304 }
11305
11306
11307 static void add_survey(struct nlattr **sinfo, u32 ifidx,
11308                        struct dl_list *survey_list)
11309 {
11310         struct freq_survey *survey;
11311
11312         survey = os_zalloc(sizeof(struct freq_survey));
11313         if  (!survey)
11314                 return;
11315
11316         survey->ifidx = ifidx;
11317         survey->freq = nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]);
11318         survey->filled = 0;
11319
11320         if (sinfo[NL80211_SURVEY_INFO_NOISE]) {
11321                 survey->nf = (int8_t)
11322                         nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
11323                 survey->filled |= SURVEY_HAS_NF;
11324         }
11325
11326         if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME]) {
11327                 survey->channel_time =
11328                         nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME]);
11329                 survey->filled |= SURVEY_HAS_CHAN_TIME;
11330         }
11331
11332         if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_BUSY]) {
11333                 survey->channel_time_busy =
11334                         nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_BUSY]);
11335                 survey->filled |= SURVEY_HAS_CHAN_TIME_BUSY;
11336         }
11337
11338         if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_RX]) {
11339                 survey->channel_time_rx =
11340                         nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_RX]);
11341                 survey->filled |= SURVEY_HAS_CHAN_TIME_RX;
11342         }
11343
11344         if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_TX]) {
11345                 survey->channel_time_tx =
11346                         nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_TX]);
11347                 survey->filled |= SURVEY_HAS_CHAN_TIME_TX;
11348         }
11349
11350         wpa_printf(MSG_DEBUG, "nl80211: Freq survey dump event (freq=%d MHz noise=%d channel_time=%ld busy_time=%ld tx_time=%ld rx_time=%ld filled=%04x)",
11351                    survey->freq,
11352                    survey->nf,
11353                    (unsigned long int) survey->channel_time,
11354                    (unsigned long int) survey->channel_time_busy,
11355                    (unsigned long int) survey->channel_time_tx,
11356                    (unsigned long int) survey->channel_time_rx,
11357                    survey->filled);
11358
11359         dl_list_add_tail(survey_list, &survey->list);
11360 }
11361
11362
11363 static int check_survey_ok(struct nlattr **sinfo, u32 surveyed_freq,
11364                            unsigned int freq_filter)
11365 {
11366         if (!freq_filter)
11367                 return 1;
11368
11369         return freq_filter == surveyed_freq;
11370 }
11371
11372
11373 static int survey_handler(struct nl_msg *msg, void *arg)
11374 {
11375         struct nlattr *tb[NL80211_ATTR_MAX + 1];
11376         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
11377         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
11378         struct survey_results *survey_results;
11379         u32 surveyed_freq = 0;
11380         u32 ifidx;
11381
11382         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
11383                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
11384                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
11385         };
11386
11387         survey_results = (struct survey_results *) arg;
11388
11389         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
11390                   genlmsg_attrlen(gnlh, 0), NULL);
11391
11392         if (!tb[NL80211_ATTR_IFINDEX])
11393                 return NL_SKIP;
11394
11395         ifidx = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
11396
11397         if (!tb[NL80211_ATTR_SURVEY_INFO])
11398                 return NL_SKIP;
11399
11400         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
11401                              tb[NL80211_ATTR_SURVEY_INFO],
11402                              survey_policy))
11403                 return NL_SKIP;
11404
11405         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY]) {
11406                 wpa_printf(MSG_ERROR, "nl80211: Invalid survey data");
11407                 return NL_SKIP;
11408         }
11409
11410         surveyed_freq = nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]);
11411
11412         if (!check_survey_ok(sinfo, surveyed_freq,
11413                              survey_results->freq_filter))
11414                 return NL_SKIP;
11415
11416         if (survey_results->freq_filter &&
11417             survey_results->freq_filter != surveyed_freq) {
11418                 wpa_printf(MSG_EXCESSIVE, "nl80211: Ignoring survey data for freq %d MHz",
11419                            surveyed_freq);
11420                 return NL_SKIP;
11421         }
11422
11423         add_survey(sinfo, ifidx, &survey_results->survey_list);
11424
11425         return NL_SKIP;
11426 }
11427
11428
11429 static int wpa_driver_nl80211_get_survey(void *priv, unsigned int freq)
11430 {
11431         struct i802_bss *bss = priv;
11432         struct wpa_driver_nl80211_data *drv = bss->drv;
11433         struct nl_msg *msg;
11434         int err = -ENOBUFS;
11435         union wpa_event_data data;
11436         struct survey_results *survey_results;
11437
11438         os_memset(&data, 0, sizeof(data));
11439         survey_results = &data.survey_results;
11440
11441         dl_list_init(&survey_results->survey_list);
11442
11443         msg = nlmsg_alloc();
11444         if (!msg)
11445                 goto nla_put_failure;
11446
11447         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
11448
11449         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
11450
11451         if (freq)
11452                 data.survey_results.freq_filter = freq;
11453
11454         do {
11455                 wpa_printf(MSG_DEBUG, "nl80211: Fetch survey data");
11456                 err = send_and_recv_msgs(drv, msg, survey_handler,
11457                                          survey_results);
11458         } while (err > 0);
11459
11460         if (err) {
11461                 wpa_printf(MSG_ERROR, "nl80211: Failed to process survey data");
11462                 goto out_clean;
11463         }
11464
11465         wpa_supplicant_event(drv->ctx, EVENT_SURVEY, &data);
11466
11467 out_clean:
11468         clean_survey_results(survey_results);
11469 nla_put_failure:
11470         return err;
11471 }
11472
11473
11474 static void nl80211_set_rekey_info(void *priv, const u8 *kek, const u8 *kck,
11475                                    const u8 *replay_ctr)
11476 {
11477         struct i802_bss *bss = priv;
11478         struct wpa_driver_nl80211_data *drv = bss->drv;
11479         struct nlattr *replay_nested;
11480         struct nl_msg *msg;
11481
11482         msg = nlmsg_alloc();
11483         if (!msg)
11484                 return;
11485
11486         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_REKEY_OFFLOAD);
11487
11488         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
11489
11490         replay_nested = nla_nest_start(msg, NL80211_ATTR_REKEY_DATA);
11491         if (!replay_nested)
11492                 goto nla_put_failure;
11493
11494         NLA_PUT(msg, NL80211_REKEY_DATA_KEK, NL80211_KEK_LEN, kek);
11495         NLA_PUT(msg, NL80211_REKEY_DATA_KCK, NL80211_KCK_LEN, kck);
11496         NLA_PUT(msg, NL80211_REKEY_DATA_REPLAY_CTR, NL80211_REPLAY_CTR_LEN,
11497                 replay_ctr);
11498
11499         nla_nest_end(msg, replay_nested);
11500
11501         send_and_recv_msgs(drv, msg, NULL, NULL);
11502         return;
11503  nla_put_failure:
11504         nlmsg_free(msg);
11505 }
11506
11507
11508 static void nl80211_send_null_frame(struct i802_bss *bss, const u8 *own_addr,
11509                                     const u8 *addr, int qos)
11510 {
11511         /* send data frame to poll STA and check whether
11512          * this frame is ACKed */
11513         struct {
11514                 struct ieee80211_hdr hdr;
11515                 u16 qos_ctl;
11516         } STRUCT_PACKED nulldata;
11517         size_t size;
11518
11519         /* Send data frame to poll STA and check whether this frame is ACKed */
11520
11521         os_memset(&nulldata, 0, sizeof(nulldata));
11522
11523         if (qos) {
11524                 nulldata.hdr.frame_control =
11525                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
11526                                      WLAN_FC_STYPE_QOS_NULL);
11527                 size = sizeof(nulldata);
11528         } else {
11529                 nulldata.hdr.frame_control =
11530                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
11531                                      WLAN_FC_STYPE_NULLFUNC);
11532                 size = sizeof(struct ieee80211_hdr);
11533         }
11534
11535         nulldata.hdr.frame_control |= host_to_le16(WLAN_FC_FROMDS);
11536         os_memcpy(nulldata.hdr.IEEE80211_DA_FROMDS, addr, ETH_ALEN);
11537         os_memcpy(nulldata.hdr.IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
11538         os_memcpy(nulldata.hdr.IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
11539
11540         if (wpa_driver_nl80211_send_mlme(bss, (u8 *) &nulldata, size, 0, 0, 0,
11541                                          0, 0) < 0)
11542                 wpa_printf(MSG_DEBUG, "nl80211_send_null_frame: Failed to "
11543                            "send poll frame");
11544 }
11545
11546 static void nl80211_poll_client(void *priv, const u8 *own_addr, const u8 *addr,
11547                                 int qos)
11548 {
11549         struct i802_bss *bss = priv;
11550         struct wpa_driver_nl80211_data *drv = bss->drv;
11551         struct nl_msg *msg;
11552
11553         if (!drv->poll_command_supported) {
11554                 nl80211_send_null_frame(bss, own_addr, addr, qos);
11555                 return;
11556         }
11557
11558         msg = nlmsg_alloc();
11559         if (!msg)
11560                 return;
11561
11562         nl80211_cmd(drv, msg, 0, NL80211_CMD_PROBE_CLIENT);
11563
11564         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
11565         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
11566
11567         send_and_recv_msgs(drv, msg, NULL, NULL);
11568         return;
11569  nla_put_failure:
11570         nlmsg_free(msg);
11571 }
11572
11573
11574 static int nl80211_set_power_save(struct i802_bss *bss, int enabled)
11575 {
11576         struct nl_msg *msg;
11577
11578         msg = nlmsg_alloc();
11579         if (!msg)
11580                 return -ENOMEM;
11581
11582         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_SET_POWER_SAVE);
11583         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
11584         NLA_PUT_U32(msg, NL80211_ATTR_PS_STATE,
11585                     enabled ? NL80211_PS_ENABLED : NL80211_PS_DISABLED);
11586         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
11587 nla_put_failure:
11588         nlmsg_free(msg);
11589         return -ENOBUFS;
11590 }
11591
11592
11593 static int nl80211_set_p2p_powersave(void *priv, int legacy_ps, int opp_ps,
11594                                      int ctwindow)
11595 {
11596         struct i802_bss *bss = priv;
11597
11598         wpa_printf(MSG_DEBUG, "nl80211: set_p2p_powersave (legacy_ps=%d "
11599                    "opp_ps=%d ctwindow=%d)", legacy_ps, opp_ps, ctwindow);
11600
11601         if (opp_ps != -1 || ctwindow != -1) {
11602 #ifdef ANDROID_P2P
11603                 wpa_driver_set_p2p_ps(priv, legacy_ps, opp_ps, ctwindow);
11604 #else /* ANDROID_P2P */
11605                 return -1; /* Not yet supported */
11606 #endif /* ANDROID_P2P */
11607         }
11608
11609         if (legacy_ps == -1)
11610                 return 0;
11611         if (legacy_ps != 0 && legacy_ps != 1)
11612                 return -1; /* Not yet supported */
11613
11614         return nl80211_set_power_save(bss, legacy_ps);
11615 }
11616
11617
11618 static int nl80211_start_radar_detection(void *priv,
11619                                          struct hostapd_freq_params *freq)
11620 {
11621         struct i802_bss *bss = priv;
11622         struct wpa_driver_nl80211_data *drv = bss->drv;
11623         struct nl_msg *msg;
11624         int ret;
11625
11626         wpa_printf(MSG_DEBUG, "nl80211: Start radar detection (CAC) %d MHz (ht_enabled=%d, vht_enabled=%d, bandwidth=%d MHz, cf1=%d MHz, cf2=%d MHz)",
11627                    freq->freq, freq->ht_enabled, freq->vht_enabled,
11628                    freq->bandwidth, freq->center_freq1, freq->center_freq2);
11629
11630         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_RADAR)) {
11631                 wpa_printf(MSG_DEBUG, "nl80211: Driver does not support radar "
11632                            "detection");
11633                 return -1;
11634         }
11635
11636         msg = nlmsg_alloc();
11637         if (!msg)
11638                 return -1;
11639
11640         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_RADAR_DETECT);
11641         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
11642
11643         if (nl80211_put_freq_params(msg, freq) < 0)
11644                 goto nla_put_failure;
11645
11646         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
11647         msg = NULL;
11648         if (ret == 0)
11649                 return 0;
11650         wpa_printf(MSG_DEBUG, "nl80211: Failed to start radar detection: "
11651                    "%d (%s)", ret, strerror(-ret));
11652 nla_put_failure:
11653         nlmsg_free(msg);
11654         return -1;
11655 }
11656
11657 #ifdef CONFIG_TDLS
11658
11659 static int nl80211_send_tdls_mgmt(void *priv, const u8 *dst, u8 action_code,
11660                                   u8 dialog_token, u16 status_code,
11661                                   u32 peer_capab, int initiator, const u8 *buf,
11662                                   size_t len)
11663 {
11664         struct i802_bss *bss = priv;
11665         struct wpa_driver_nl80211_data *drv = bss->drv;
11666         struct nl_msg *msg;
11667
11668         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
11669                 return -EOPNOTSUPP;
11670
11671         if (!dst)
11672                 return -EINVAL;
11673
11674         msg = nlmsg_alloc();
11675         if (!msg)
11676                 return -ENOMEM;
11677
11678         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_MGMT);
11679         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
11680         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, dst);
11681         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_ACTION, action_code);
11682         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_DIALOG_TOKEN, dialog_token);
11683         NLA_PUT_U16(msg, NL80211_ATTR_STATUS_CODE, status_code);
11684         if (peer_capab) {
11685                 /*
11686                  * The internal enum tdls_peer_capability definition is
11687                  * currently identical with the nl80211 enum
11688                  * nl80211_tdls_peer_capability, so no conversion is needed
11689                  * here.
11690                  */
11691                 NLA_PUT_U32(msg, NL80211_ATTR_TDLS_PEER_CAPABILITY, peer_capab);
11692         }
11693         if (initiator)
11694                 NLA_PUT_FLAG(msg, NL80211_ATTR_TDLS_INITIATOR);
11695         NLA_PUT(msg, NL80211_ATTR_IE, len, buf);
11696
11697         return send_and_recv_msgs(drv, msg, NULL, NULL);
11698
11699 nla_put_failure:
11700         nlmsg_free(msg);
11701         return -ENOBUFS;
11702 }
11703
11704
11705 static int nl80211_tdls_oper(void *priv, enum tdls_oper oper, const u8 *peer)
11706 {
11707         struct i802_bss *bss = priv;
11708         struct wpa_driver_nl80211_data *drv = bss->drv;
11709         struct nl_msg *msg;
11710         enum nl80211_tdls_operation nl80211_oper;
11711
11712         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
11713                 return -EOPNOTSUPP;
11714
11715         switch (oper) {
11716         case TDLS_DISCOVERY_REQ:
11717                 nl80211_oper = NL80211_TDLS_DISCOVERY_REQ;
11718                 break;
11719         case TDLS_SETUP:
11720                 nl80211_oper = NL80211_TDLS_SETUP;
11721                 break;
11722         case TDLS_TEARDOWN:
11723                 nl80211_oper = NL80211_TDLS_TEARDOWN;
11724                 break;
11725         case TDLS_ENABLE_LINK:
11726                 nl80211_oper = NL80211_TDLS_ENABLE_LINK;
11727                 break;
11728         case TDLS_DISABLE_LINK:
11729                 nl80211_oper = NL80211_TDLS_DISABLE_LINK;
11730                 break;
11731         case TDLS_ENABLE:
11732                 return 0;
11733         case TDLS_DISABLE:
11734                 return 0;
11735         default:
11736                 return -EINVAL;
11737         }
11738
11739         msg = nlmsg_alloc();
11740         if (!msg)
11741                 return -ENOMEM;
11742
11743         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_OPER);
11744         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_OPERATION, nl80211_oper);
11745         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
11746         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, peer);
11747
11748         return send_and_recv_msgs(drv, msg, NULL, NULL);
11749
11750 nla_put_failure:
11751         nlmsg_free(msg);
11752         return -ENOBUFS;
11753 }
11754
11755 #endif /* CONFIG TDLS */
11756
11757
11758 #ifdef ANDROID
11759
11760 typedef struct android_wifi_priv_cmd {
11761         char *buf;
11762         int used_len;
11763         int total_len;
11764 } android_wifi_priv_cmd;
11765
11766 static int drv_errors = 0;
11767
11768 static void wpa_driver_send_hang_msg(struct wpa_driver_nl80211_data *drv)
11769 {
11770         drv_errors++;
11771         if (drv_errors > DRV_NUMBER_SEQUENTIAL_ERRORS) {
11772                 drv_errors = 0;
11773                 wpa_msg(drv->ctx, MSG_INFO, WPA_EVENT_DRIVER_STATE "HANGED");
11774         }
11775 }
11776
11777
11778 static int android_priv_cmd(struct i802_bss *bss, const char *cmd)
11779 {
11780         struct wpa_driver_nl80211_data *drv = bss->drv;
11781         struct ifreq ifr;
11782         android_wifi_priv_cmd priv_cmd;
11783         char buf[MAX_DRV_CMD_SIZE];
11784         int ret;
11785
11786         os_memset(&ifr, 0, sizeof(ifr));
11787         os_memset(&priv_cmd, 0, sizeof(priv_cmd));
11788         os_strlcpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
11789
11790         os_memset(buf, 0, sizeof(buf));
11791         os_strlcpy(buf, cmd, sizeof(buf));
11792
11793         priv_cmd.buf = buf;
11794         priv_cmd.used_len = sizeof(buf);
11795         priv_cmd.total_len = sizeof(buf);
11796         ifr.ifr_data = &priv_cmd;
11797
11798         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
11799         if (ret < 0) {
11800                 wpa_printf(MSG_ERROR, "%s: failed to issue private commands",
11801                            __func__);
11802                 wpa_driver_send_hang_msg(drv);
11803                 return ret;
11804         }
11805
11806         drv_errors = 0;
11807         return 0;
11808 }
11809
11810
11811 static int android_pno_start(struct i802_bss *bss,
11812                              struct wpa_driver_scan_params *params)
11813 {
11814         struct wpa_driver_nl80211_data *drv = bss->drv;
11815         struct ifreq ifr;
11816         android_wifi_priv_cmd priv_cmd;
11817         int ret = 0, i = 0, bp;
11818         char buf[WEXT_PNO_MAX_COMMAND_SIZE];
11819
11820         bp = WEXT_PNOSETUP_HEADER_SIZE;
11821         os_memcpy(buf, WEXT_PNOSETUP_HEADER, bp);
11822         buf[bp++] = WEXT_PNO_TLV_PREFIX;
11823         buf[bp++] = WEXT_PNO_TLV_VERSION;
11824         buf[bp++] = WEXT_PNO_TLV_SUBVERSION;
11825         buf[bp++] = WEXT_PNO_TLV_RESERVED;
11826
11827         while (i < WEXT_PNO_AMOUNT && (size_t) i < params->num_ssids) {
11828                 /* Check that there is enough space needed for 1 more SSID, the
11829                  * other sections and null termination */
11830                 if ((bp + WEXT_PNO_SSID_HEADER_SIZE + MAX_SSID_LEN +
11831                      WEXT_PNO_NONSSID_SECTIONS_SIZE + 1) >= (int) sizeof(buf))
11832                         break;
11833                 wpa_hexdump_ascii(MSG_DEBUG, "For PNO Scan",
11834                                   params->ssids[i].ssid,
11835                                   params->ssids[i].ssid_len);
11836                 buf[bp++] = WEXT_PNO_SSID_SECTION;
11837                 buf[bp++] = params->ssids[i].ssid_len;
11838                 os_memcpy(&buf[bp], params->ssids[i].ssid,
11839                           params->ssids[i].ssid_len);
11840                 bp += params->ssids[i].ssid_len;
11841                 i++;
11842         }
11843
11844         buf[bp++] = WEXT_PNO_SCAN_INTERVAL_SECTION;
11845         os_snprintf(&buf[bp], WEXT_PNO_SCAN_INTERVAL_LENGTH + 1, "%x",
11846                     WEXT_PNO_SCAN_INTERVAL);
11847         bp += WEXT_PNO_SCAN_INTERVAL_LENGTH;
11848
11849         buf[bp++] = WEXT_PNO_REPEAT_SECTION;
11850         os_snprintf(&buf[bp], WEXT_PNO_REPEAT_LENGTH + 1, "%x",
11851                     WEXT_PNO_REPEAT);
11852         bp += WEXT_PNO_REPEAT_LENGTH;
11853
11854         buf[bp++] = WEXT_PNO_MAX_REPEAT_SECTION;
11855         os_snprintf(&buf[bp], WEXT_PNO_MAX_REPEAT_LENGTH + 1, "%x",
11856                     WEXT_PNO_MAX_REPEAT);
11857         bp += WEXT_PNO_MAX_REPEAT_LENGTH + 1;
11858
11859         memset(&ifr, 0, sizeof(ifr));
11860         memset(&priv_cmd, 0, sizeof(priv_cmd));
11861         os_strlcpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
11862
11863         priv_cmd.buf = buf;
11864         priv_cmd.used_len = bp;
11865         priv_cmd.total_len = bp;
11866         ifr.ifr_data = &priv_cmd;
11867
11868         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
11869
11870         if (ret < 0) {
11871                 wpa_printf(MSG_ERROR, "ioctl[SIOCSIWPRIV] (pnosetup): %d",
11872                            ret);
11873                 wpa_driver_send_hang_msg(drv);
11874                 return ret;
11875         }
11876
11877         drv_errors = 0;
11878
11879         return android_priv_cmd(bss, "PNOFORCE 1");
11880 }
11881
11882
11883 static int android_pno_stop(struct i802_bss *bss)
11884 {
11885         return android_priv_cmd(bss, "PNOFORCE 0");
11886 }
11887
11888 #endif /* ANDROID */
11889
11890
11891 static int driver_nl80211_set_key(const char *ifname, void *priv,
11892                                   enum wpa_alg alg, const u8 *addr,
11893                                   int key_idx, int set_tx,
11894                                   const u8 *seq, size_t seq_len,
11895                                   const u8 *key, size_t key_len)
11896 {
11897         struct i802_bss *bss = priv;
11898         return wpa_driver_nl80211_set_key(ifname, bss, alg, addr, key_idx,
11899                                           set_tx, seq, seq_len, key, key_len);
11900 }
11901
11902
11903 static int driver_nl80211_scan2(void *priv,
11904                                 struct wpa_driver_scan_params *params)
11905 {
11906         struct i802_bss *bss = priv;
11907         return wpa_driver_nl80211_scan(bss, params);
11908 }
11909
11910
11911 static int driver_nl80211_deauthenticate(void *priv, const u8 *addr,
11912                                          int reason_code)
11913 {
11914         struct i802_bss *bss = priv;
11915         return wpa_driver_nl80211_deauthenticate(bss, addr, reason_code);
11916 }
11917
11918
11919 static int driver_nl80211_authenticate(void *priv,
11920                                        struct wpa_driver_auth_params *params)
11921 {
11922         struct i802_bss *bss = priv;
11923         return wpa_driver_nl80211_authenticate(bss, params);
11924 }
11925
11926
11927 static void driver_nl80211_deinit(void *priv)
11928 {
11929         struct i802_bss *bss = priv;
11930         wpa_driver_nl80211_deinit(bss);
11931 }
11932
11933
11934 static int driver_nl80211_if_remove(void *priv, enum wpa_driver_if_type type,
11935                                     const char *ifname)
11936 {
11937         struct i802_bss *bss = priv;
11938         return wpa_driver_nl80211_if_remove(bss, type, ifname);
11939 }
11940
11941
11942 static int driver_nl80211_send_mlme(void *priv, const u8 *data,
11943                                     size_t data_len, int noack)
11944 {
11945         struct i802_bss *bss = priv;
11946         return wpa_driver_nl80211_send_mlme(bss, data, data_len, noack,
11947                                             0, 0, 0, 0);
11948 }
11949
11950
11951 static int driver_nl80211_sta_remove(void *priv, const u8 *addr)
11952 {
11953         struct i802_bss *bss = priv;
11954         return wpa_driver_nl80211_sta_remove(bss, addr, -1, 0);
11955 }
11956
11957
11958 static int driver_nl80211_set_sta_vlan(void *priv, const u8 *addr,
11959                                        const char *ifname, int vlan_id)
11960 {
11961         struct i802_bss *bss = priv;
11962         return i802_set_sta_vlan(bss, addr, ifname, vlan_id);
11963 }
11964
11965
11966 static int driver_nl80211_read_sta_data(void *priv,
11967                                         struct hostap_sta_driver_data *data,
11968                                         const u8 *addr)
11969 {
11970         struct i802_bss *bss = priv;
11971         return i802_read_sta_data(bss, data, addr);
11972 }
11973
11974
11975 static int driver_nl80211_send_action(void *priv, unsigned int freq,
11976                                       unsigned int wait_time,
11977                                       const u8 *dst, const u8 *src,
11978                                       const u8 *bssid,
11979                                       const u8 *data, size_t data_len,
11980                                       int no_cck)
11981 {
11982         struct i802_bss *bss = priv;
11983         return wpa_driver_nl80211_send_action(bss, freq, wait_time, dst, src,
11984                                               bssid, data, data_len, no_cck);
11985 }
11986
11987
11988 static int driver_nl80211_probe_req_report(void *priv, int report)
11989 {
11990         struct i802_bss *bss = priv;
11991         return wpa_driver_nl80211_probe_req_report(bss, report);
11992 }
11993
11994
11995 static int wpa_driver_nl80211_update_ft_ies(void *priv, const u8 *md,
11996                                             const u8 *ies, size_t ies_len)
11997 {
11998         int ret;
11999         struct nl_msg *msg;
12000         struct i802_bss *bss = priv;
12001         struct wpa_driver_nl80211_data *drv = bss->drv;
12002         u16 mdid = WPA_GET_LE16(md);
12003
12004         msg = nlmsg_alloc();
12005         if (!msg)
12006                 return -ENOMEM;
12007
12008         wpa_printf(MSG_DEBUG, "nl80211: Updating FT IEs");
12009         nl80211_cmd(drv, msg, 0, NL80211_CMD_UPDATE_FT_IES);
12010         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
12011         NLA_PUT(msg, NL80211_ATTR_IE, ies_len, ies);
12012         NLA_PUT_U16(msg, NL80211_ATTR_MDID, mdid);
12013
12014         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
12015         if (ret) {
12016                 wpa_printf(MSG_DEBUG, "nl80211: update_ft_ies failed "
12017                            "err=%d (%s)", ret, strerror(-ret));
12018         }
12019
12020         return ret;
12021
12022 nla_put_failure:
12023         nlmsg_free(msg);
12024         return -ENOBUFS;
12025 }
12026
12027
12028 const u8 * wpa_driver_nl80211_get_macaddr(void *priv)
12029 {
12030         struct i802_bss *bss = priv;
12031         struct wpa_driver_nl80211_data *drv = bss->drv;
12032
12033         if (drv->nlmode != NL80211_IFTYPE_P2P_DEVICE)
12034                 return NULL;
12035
12036         return bss->addr;
12037 }
12038
12039
12040 static const char * scan_state_str(enum scan_states scan_state)
12041 {
12042         switch (scan_state) {
12043         case NO_SCAN:
12044                 return "NO_SCAN";
12045         case SCAN_REQUESTED:
12046                 return "SCAN_REQUESTED";
12047         case SCAN_STARTED:
12048                 return "SCAN_STARTED";
12049         case SCAN_COMPLETED:
12050                 return "SCAN_COMPLETED";
12051         case SCAN_ABORTED:
12052                 return "SCAN_ABORTED";
12053         case SCHED_SCAN_STARTED:
12054                 return "SCHED_SCAN_STARTED";
12055         case SCHED_SCAN_STOPPED:
12056                 return "SCHED_SCAN_STOPPED";
12057         case SCHED_SCAN_RESULTS:
12058                 return "SCHED_SCAN_RESULTS";
12059         }
12060
12061         return "??";
12062 }
12063
12064
12065 static int wpa_driver_nl80211_status(void *priv, char *buf, size_t buflen)
12066 {
12067         struct i802_bss *bss = priv;
12068         struct wpa_driver_nl80211_data *drv = bss->drv;
12069         int res;
12070         char *pos, *end;
12071
12072         pos = buf;
12073         end = buf + buflen;
12074
12075         res = os_snprintf(pos, end - pos,
12076                           "ifindex=%d\n"
12077                           "ifname=%s\n"
12078                           "brname=%s\n"
12079                           "addr=" MACSTR "\n"
12080                           "freq=%d\n"
12081                           "%s%s%s%s%s",
12082                           bss->ifindex,
12083                           bss->ifname,
12084                           bss->brname,
12085                           MAC2STR(bss->addr),
12086                           bss->freq,
12087                           bss->beacon_set ? "beacon_set=1\n" : "",
12088                           bss->added_if_into_bridge ?
12089                           "added_if_into_bridge=1\n" : "",
12090                           bss->added_bridge ? "added_bridge=1\n" : "",
12091                           bss->in_deinit ? "in_deinit=1\n" : "",
12092                           bss->if_dynamic ? "if_dynamic=1\n" : "");
12093         if (res < 0 || res >= end - pos)
12094                 return pos - buf;
12095         pos += res;
12096
12097         if (bss->wdev_id_set) {
12098                 res = os_snprintf(pos, end - pos, "wdev_id=%llu\n",
12099                                   (unsigned long long) bss->wdev_id);
12100                 if (res < 0 || res >= end - pos)
12101                         return pos - buf;
12102                 pos += res;
12103         }
12104
12105         res = os_snprintf(pos, end - pos,
12106                           "phyname=%s\n"
12107                           "perm_addr=" MACSTR "\n"
12108                           "drv_ifindex=%d\n"
12109                           "operstate=%d\n"
12110                           "scan_state=%s\n"
12111                           "auth_bssid=" MACSTR "\n"
12112                           "auth_attempt_bssid=" MACSTR "\n"
12113                           "bssid=" MACSTR "\n"
12114                           "prev_bssid=" MACSTR "\n"
12115                           "associated=%d\n"
12116                           "assoc_freq=%u\n"
12117                           "monitor_sock=%d\n"
12118                           "monitor_ifidx=%d\n"
12119                           "monitor_refcount=%d\n"
12120                           "last_mgmt_freq=%u\n"
12121                           "eapol_tx_sock=%d\n"
12122                           "%s%s%s%s%s%s%s%s%s%s%s%s%s%s",
12123                           drv->phyname,
12124                           MAC2STR(drv->perm_addr),
12125                           drv->ifindex,
12126                           drv->operstate,
12127                           scan_state_str(drv->scan_state),
12128                           MAC2STR(drv->auth_bssid),
12129                           MAC2STR(drv->auth_attempt_bssid),
12130                           MAC2STR(drv->bssid),
12131                           MAC2STR(drv->prev_bssid),
12132                           drv->associated,
12133                           drv->assoc_freq,
12134                           drv->monitor_sock,
12135                           drv->monitor_ifidx,
12136                           drv->monitor_refcount,
12137                           drv->last_mgmt_freq,
12138                           drv->eapol_tx_sock,
12139                           drv->ignore_if_down_event ?
12140                           "ignore_if_down_event=1\n" : "",
12141                           drv->scan_complete_events ?
12142                           "scan_complete_events=1\n" : "",
12143                           drv->disabled_11b_rates ?
12144                           "disabled_11b_rates=1\n" : "",
12145                           drv->pending_remain_on_chan ?
12146                           "pending_remain_on_chan=1\n" : "",
12147                           drv->in_interface_list ? "in_interface_list=1\n" : "",
12148                           drv->device_ap_sme ? "device_ap_sme=1\n" : "",
12149                           drv->poll_command_supported ?
12150                           "poll_command_supported=1\n" : "",
12151                           drv->data_tx_status ? "data_tx_status=1\n" : "",
12152                           drv->scan_for_auth ? "scan_for_auth=1\n" : "",
12153                           drv->retry_auth ? "retry_auth=1\n" : "",
12154                           drv->use_monitor ? "use_monitor=1\n" : "",
12155                           drv->ignore_next_local_disconnect ?
12156                           "ignore_next_local_disconnect=1\n" : "",
12157                           drv->ignore_next_local_deauth ?
12158                           "ignore_next_local_deauth=1\n" : "",
12159                           drv->allow_p2p_device ? "allow_p2p_device=1\n" : "");
12160         if (res < 0 || res >= end - pos)
12161                 return pos - buf;
12162         pos += res;
12163
12164         if (drv->has_capability) {
12165                 res = os_snprintf(pos, end - pos,
12166                                   "capa.key_mgmt=0x%x\n"
12167                                   "capa.enc=0x%x\n"
12168                                   "capa.auth=0x%x\n"
12169                                   "capa.flags=0x%llx\n"
12170                                   "capa.max_scan_ssids=%d\n"
12171                                   "capa.max_sched_scan_ssids=%d\n"
12172                                   "capa.sched_scan_supported=%d\n"
12173                                   "capa.max_match_sets=%d\n"
12174                                   "capa.max_remain_on_chan=%u\n"
12175                                   "capa.max_stations=%u\n"
12176                                   "capa.probe_resp_offloads=0x%x\n"
12177                                   "capa.max_acl_mac_addrs=%u\n"
12178                                   "capa.num_multichan_concurrent=%u\n",
12179                                   drv->capa.key_mgmt,
12180                                   drv->capa.enc,
12181                                   drv->capa.auth,
12182                                   (unsigned long long) drv->capa.flags,
12183                                   drv->capa.max_scan_ssids,
12184                                   drv->capa.max_sched_scan_ssids,
12185                                   drv->capa.sched_scan_supported,
12186                                   drv->capa.max_match_sets,
12187                                   drv->capa.max_remain_on_chan,
12188                                   drv->capa.max_stations,
12189                                   drv->capa.probe_resp_offloads,
12190                                   drv->capa.max_acl_mac_addrs,
12191                                   drv->capa.num_multichan_concurrent);
12192                 if (res < 0 || res >= end - pos)
12193                         return pos - buf;
12194                 pos += res;
12195         }
12196
12197         return pos - buf;
12198 }
12199
12200
12201 static int set_beacon_data(struct nl_msg *msg, struct beacon_data *settings)
12202 {
12203         if (settings->head)
12204                 NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD,
12205                         settings->head_len, settings->head);
12206
12207         if (settings->tail)
12208                 NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL,
12209                         settings->tail_len, settings->tail);
12210
12211         if (settings->beacon_ies)
12212                 NLA_PUT(msg, NL80211_ATTR_IE,
12213                         settings->beacon_ies_len, settings->beacon_ies);
12214
12215         if (settings->proberesp_ies)
12216                 NLA_PUT(msg, NL80211_ATTR_IE_PROBE_RESP,
12217                         settings->proberesp_ies_len, settings->proberesp_ies);
12218
12219         if (settings->assocresp_ies)
12220                 NLA_PUT(msg,
12221                         NL80211_ATTR_IE_ASSOC_RESP,
12222                         settings->assocresp_ies_len, settings->assocresp_ies);
12223
12224         if (settings->probe_resp)
12225                 NLA_PUT(msg, NL80211_ATTR_PROBE_RESP,
12226                         settings->probe_resp_len, settings->probe_resp);
12227
12228         return 0;
12229
12230 nla_put_failure:
12231         return -ENOBUFS;
12232 }
12233
12234
12235 static int nl80211_switch_channel(void *priv, struct csa_settings *settings)
12236 {
12237         struct nl_msg *msg;
12238         struct i802_bss *bss = priv;
12239         struct wpa_driver_nl80211_data *drv = bss->drv;
12240         struct nlattr *beacon_csa;
12241         int ret = -ENOBUFS;
12242
12243         wpa_printf(MSG_DEBUG, "nl80211: Channel switch request (cs_count=%u block_tx=%u freq=%d width=%d cf1=%d cf2=%d)",
12244                    settings->cs_count, settings->block_tx,
12245                    settings->freq_params.freq, settings->freq_params.bandwidth,
12246                    settings->freq_params.center_freq1,
12247                    settings->freq_params.center_freq2);
12248
12249         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_AP_CSA)) {
12250                 wpa_printf(MSG_DEBUG, "nl80211: Driver does not support channel switch command");
12251                 return -EOPNOTSUPP;
12252         }
12253
12254         if ((drv->nlmode != NL80211_IFTYPE_AP) &&
12255             (drv->nlmode != NL80211_IFTYPE_P2P_GO))
12256                 return -EOPNOTSUPP;
12257
12258         /* check settings validity */
12259         if (!settings->beacon_csa.tail ||
12260             ((settings->beacon_csa.tail_len <=
12261               settings->counter_offset_beacon) ||
12262              (settings->beacon_csa.tail[settings->counter_offset_beacon] !=
12263               settings->cs_count)))
12264                 return -EINVAL;
12265
12266         if (settings->beacon_csa.probe_resp &&
12267             ((settings->beacon_csa.probe_resp_len <=
12268               settings->counter_offset_presp) ||
12269              (settings->beacon_csa.probe_resp[settings->counter_offset_presp] !=
12270               settings->cs_count)))
12271                 return -EINVAL;
12272
12273         msg = nlmsg_alloc();
12274         if (!msg)
12275                 return -ENOMEM;
12276
12277         nl80211_cmd(drv, msg, 0, NL80211_CMD_CHANNEL_SWITCH);
12278         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
12279         NLA_PUT_U32(msg, NL80211_ATTR_CH_SWITCH_COUNT, settings->cs_count);
12280         ret = nl80211_put_freq_params(msg, &settings->freq_params);
12281         if (ret)
12282                 goto error;
12283
12284         if (settings->block_tx)
12285                 NLA_PUT_FLAG(msg, NL80211_ATTR_CH_SWITCH_BLOCK_TX);
12286
12287         /* beacon_after params */
12288         ret = set_beacon_data(msg, &settings->beacon_after);
12289         if (ret)
12290                 goto error;
12291
12292         /* beacon_csa params */
12293         beacon_csa = nla_nest_start(msg, NL80211_ATTR_CSA_IES);
12294         if (!beacon_csa)
12295                 goto nla_put_failure;
12296
12297         ret = set_beacon_data(msg, &settings->beacon_csa);
12298         if (ret)
12299                 goto error;
12300
12301         NLA_PUT_U16(msg, NL80211_ATTR_CSA_C_OFF_BEACON,
12302                     settings->counter_offset_beacon);
12303
12304         if (settings->beacon_csa.probe_resp)
12305                 NLA_PUT_U16(msg, NL80211_ATTR_CSA_C_OFF_PRESP,
12306                             settings->counter_offset_presp);
12307
12308         nla_nest_end(msg, beacon_csa);
12309         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
12310         if (ret) {
12311                 wpa_printf(MSG_DEBUG, "nl80211: switch_channel failed err=%d (%s)",
12312                            ret, strerror(-ret));
12313         }
12314         return ret;
12315
12316 nla_put_failure:
12317         ret = -ENOBUFS;
12318 error:
12319         nlmsg_free(msg);
12320         wpa_printf(MSG_DEBUG, "nl80211: Could not build channel switch request");
12321         return ret;
12322 }
12323
12324
12325 #ifdef CONFIG_TESTING_OPTIONS
12326 static int cmd_reply_handler(struct nl_msg *msg, void *arg)
12327 {
12328         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
12329         struct wpabuf *buf = arg;
12330
12331         if (!buf)
12332                 return NL_SKIP;
12333
12334         if ((size_t) genlmsg_attrlen(gnlh, 0) > wpabuf_tailroom(buf)) {
12335                 wpa_printf(MSG_INFO, "nl80211: insufficient buffer space for reply");
12336                 return NL_SKIP;
12337         }
12338
12339         wpabuf_put_data(buf, genlmsg_attrdata(gnlh, 0),
12340                         genlmsg_attrlen(gnlh, 0));
12341
12342         return NL_SKIP;
12343 }
12344 #endif /* CONFIG_TESTING_OPTIONS */
12345
12346
12347 static int vendor_reply_handler(struct nl_msg *msg, void *arg)
12348 {
12349         struct nlattr *tb[NL80211_ATTR_MAX + 1];
12350         struct nlattr *nl_vendor_reply, *nl;
12351         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
12352         struct wpabuf *buf = arg;
12353         int rem;
12354
12355         if (!buf)
12356                 return NL_SKIP;
12357
12358         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
12359                   genlmsg_attrlen(gnlh, 0), NULL);
12360         nl_vendor_reply = tb[NL80211_ATTR_VENDOR_DATA];
12361
12362         if (!nl_vendor_reply)
12363                 return NL_SKIP;
12364
12365         if ((size_t) nla_len(nl_vendor_reply) > wpabuf_tailroom(buf)) {
12366                 wpa_printf(MSG_INFO, "nl80211: Vendor command: insufficient buffer space for reply");
12367                 return NL_SKIP;
12368         }
12369
12370         nla_for_each_nested(nl, nl_vendor_reply, rem) {
12371                 wpabuf_put_data(buf, nla_data(nl), nla_len(nl));
12372         }
12373
12374         return NL_SKIP;
12375 }
12376
12377
12378 static int nl80211_vendor_cmd(void *priv, unsigned int vendor_id,
12379                               unsigned int subcmd, const u8 *data,
12380                               size_t data_len, struct wpabuf *buf)
12381 {
12382         struct i802_bss *bss = priv;
12383         struct wpa_driver_nl80211_data *drv = bss->drv;
12384         struct nl_msg *msg;
12385         int ret;
12386
12387         msg = nlmsg_alloc();
12388         if (!msg)
12389                 return -ENOMEM;
12390
12391 #ifdef CONFIG_TESTING_OPTIONS
12392         if (vendor_id == 0xffffffff) {
12393                 nl80211_cmd(drv, msg, 0, subcmd);
12394                 if (nlmsg_append(msg, (void *) data, data_len, NLMSG_ALIGNTO) <
12395                     0)
12396                         goto nla_put_failure;
12397                 ret = send_and_recv_msgs(drv, msg, cmd_reply_handler, buf);
12398                 if (ret)
12399                         wpa_printf(MSG_DEBUG, "nl80211: command failed err=%d",
12400                                    ret);
12401                 return ret;
12402         }
12403 #endif /* CONFIG_TESTING_OPTIONS */
12404
12405         nl80211_cmd(drv, msg, 0, NL80211_CMD_VENDOR);
12406         if (nl80211_set_iface_id(msg, bss) < 0)
12407                 goto nla_put_failure;
12408         NLA_PUT_U32(msg, NL80211_ATTR_VENDOR_ID, vendor_id);
12409         NLA_PUT_U32(msg, NL80211_ATTR_VENDOR_SUBCMD, subcmd);
12410         if (data)
12411                 NLA_PUT(msg, NL80211_ATTR_VENDOR_DATA, data_len, data);
12412
12413         ret = send_and_recv_msgs(drv, msg, vendor_reply_handler, buf);
12414         if (ret)
12415                 wpa_printf(MSG_DEBUG, "nl80211: vendor command failed err=%d",
12416                            ret);
12417         return ret;
12418
12419 nla_put_failure:
12420         nlmsg_free(msg);
12421         return -ENOBUFS;
12422 }
12423
12424
12425 static int nl80211_set_qos_map(void *priv, const u8 *qos_map_set,
12426                                u8 qos_map_set_len)
12427 {
12428         struct i802_bss *bss = priv;
12429         struct wpa_driver_nl80211_data *drv = bss->drv;
12430         struct nl_msg *msg;
12431         int ret;
12432
12433         msg = nlmsg_alloc();
12434         if (!msg)
12435                 return -ENOMEM;
12436
12437         wpa_hexdump(MSG_DEBUG, "nl80211: Setting QoS Map",
12438                     qos_map_set, qos_map_set_len);
12439
12440         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_QOS_MAP);
12441         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
12442         NLA_PUT(msg, NL80211_ATTR_QOS_MAP, qos_map_set_len, qos_map_set);
12443
12444         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
12445         if (ret)
12446                 wpa_printf(MSG_DEBUG, "nl80211: Setting QoS Map failed");
12447
12448         return ret;
12449
12450 nla_put_failure:
12451         nlmsg_free(msg);
12452         return -ENOBUFS;
12453 }
12454
12455
12456 static int nl80211_set_wowlan(void *priv,
12457                               const struct wowlan_triggers *triggers)
12458 {
12459         struct i802_bss *bss = priv;
12460         struct wpa_driver_nl80211_data *drv = bss->drv;
12461         struct nl_msg *msg;
12462         struct nlattr *wowlan_triggers;
12463         int ret;
12464
12465         msg = nlmsg_alloc();
12466         if (!msg)
12467                 return -ENOMEM;
12468
12469         wpa_printf(MSG_DEBUG, "nl80211: Setting wowlan");
12470
12471         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WOWLAN);
12472         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
12473
12474         wowlan_triggers = nla_nest_start(msg, NL80211_ATTR_WOWLAN_TRIGGERS);
12475         if (!wowlan_triggers)
12476                 goto nla_put_failure;
12477
12478         if (triggers->any)
12479                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_ANY);
12480         if (triggers->disconnect)
12481                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_DISCONNECT);
12482         if (triggers->magic_pkt)
12483                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_MAGIC_PKT);
12484         if (triggers->gtk_rekey_failure)
12485                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_GTK_REKEY_FAILURE);
12486         if (triggers->eap_identity_req)
12487                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_EAP_IDENT_REQUEST);
12488         if (triggers->four_way_handshake)
12489                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_4WAY_HANDSHAKE);
12490         if (triggers->rfkill_release)
12491                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_RFKILL_RELEASE);
12492
12493         nla_nest_end(msg, wowlan_triggers);
12494
12495         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
12496         if (ret)
12497                 wpa_printf(MSG_DEBUG, "nl80211: Setting wowlan failed");
12498
12499         return ret;
12500
12501 nla_put_failure:
12502         nlmsg_free(msg);
12503         return -ENOBUFS;
12504 }
12505
12506
12507 static int nl80211_roaming(void *priv, int allowed, const u8 *bssid)
12508 {
12509         struct i802_bss *bss = priv;
12510         struct wpa_driver_nl80211_data *drv = bss->drv;
12511         struct nl_msg *msg;
12512         struct nlattr *params;
12513
12514         wpa_printf(MSG_DEBUG, "nl80211: Roaming policy: allowed=%d", allowed);
12515
12516         if (!drv->roaming_vendor_cmd_avail) {
12517                 wpa_printf(MSG_DEBUG,
12518                            "nl80211: Ignore roaming policy change since driver does not provide command for setting it");
12519                 return -1;
12520         }
12521
12522         msg = nlmsg_alloc();
12523         if (!msg)
12524                 return -ENOMEM;
12525
12526         nl80211_cmd(drv, msg, 0, NL80211_CMD_VENDOR);
12527
12528         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
12529         NLA_PUT_U32(msg, NL80211_ATTR_VENDOR_ID, OUI_QCA);
12530         NLA_PUT_U32(msg, NL80211_ATTR_VENDOR_SUBCMD,
12531                     QCA_NL80211_VENDOR_SUBCMD_ROAMING);
12532
12533         params = nla_nest_start(msg, NL80211_ATTR_VENDOR_DATA);
12534         if (!params)
12535                 goto nla_put_failure;
12536         NLA_PUT_U32(msg, QCA_WLAN_VENDOR_ATTR_ROAMING_POLICY,
12537                     allowed ? QCA_ROAMING_ALLOWED_WITHIN_ESS :
12538                     QCA_ROAMING_NOT_ALLOWED);
12539         if (bssid)
12540                 NLA_PUT(msg, QCA_WLAN_VENDOR_ATTR_MAC_ADDR, ETH_ALEN, bssid);
12541         nla_nest_end(msg, params);
12542
12543         return send_and_recv_msgs(drv, msg, NULL, NULL);
12544
12545  nla_put_failure:
12546         nlmsg_free(msg);
12547         return -1;
12548 }
12549
12550
12551 static int nl80211_set_mac_addr(void *priv, const u8 *addr)
12552 {
12553         struct i802_bss *bss = priv;
12554         struct wpa_driver_nl80211_data *drv = bss->drv;
12555         int new_addr = addr != NULL;
12556
12557         if (!addr)
12558                 addr = drv->perm_addr;
12559
12560         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0) < 0)
12561                 return -1;
12562
12563         if (linux_set_ifhwaddr(drv->global->ioctl_sock, bss->ifname, addr) < 0)
12564         {
12565                 wpa_printf(MSG_DEBUG,
12566                            "nl80211: failed to set_mac_addr for %s to " MACSTR,
12567                            bss->ifname, MAC2STR(addr));
12568                 if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname,
12569                                           1) < 0) {
12570                         wpa_printf(MSG_DEBUG,
12571                                    "nl80211: Could not restore interface UP after failed set_mac_addr");
12572                 }
12573                 return -1;
12574         }
12575
12576         wpa_printf(MSG_DEBUG, "nl80211: set_mac_addr for %s to " MACSTR,
12577                    bss->ifname, MAC2STR(addr));
12578         drv->addr_changed = new_addr;
12579         os_memcpy(bss->addr, addr, ETH_ALEN);
12580
12581         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1) < 0)
12582         {
12583                 wpa_printf(MSG_DEBUG,
12584                            "nl80211: Could not restore interface UP after set_mac_addr");
12585         }
12586
12587         return 0;
12588 }
12589
12590
12591 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
12592         .name = "nl80211",
12593         .desc = "Linux nl80211/cfg80211",
12594         .get_bssid = wpa_driver_nl80211_get_bssid,
12595         .get_ssid = wpa_driver_nl80211_get_ssid,
12596         .set_key = driver_nl80211_set_key,
12597         .scan2 = driver_nl80211_scan2,
12598         .sched_scan = wpa_driver_nl80211_sched_scan,
12599         .stop_sched_scan = wpa_driver_nl80211_stop_sched_scan,
12600         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
12601         .deauthenticate = driver_nl80211_deauthenticate,
12602         .authenticate = driver_nl80211_authenticate,
12603         .associate = wpa_driver_nl80211_associate,
12604         .global_init = nl80211_global_init,
12605         .global_deinit = nl80211_global_deinit,
12606         .init2 = wpa_driver_nl80211_init,
12607         .deinit = driver_nl80211_deinit,
12608         .get_capa = wpa_driver_nl80211_get_capa,
12609         .set_operstate = wpa_driver_nl80211_set_operstate,
12610         .set_supp_port = wpa_driver_nl80211_set_supp_port,
12611         .set_country = wpa_driver_nl80211_set_country,
12612         .get_country = wpa_driver_nl80211_get_country,
12613         .set_ap = wpa_driver_nl80211_set_ap,
12614         .set_acl = wpa_driver_nl80211_set_acl,
12615         .if_add = wpa_driver_nl80211_if_add,
12616         .if_remove = driver_nl80211_if_remove,
12617         .send_mlme = driver_nl80211_send_mlme,
12618         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
12619         .sta_add = wpa_driver_nl80211_sta_add,
12620         .sta_remove = driver_nl80211_sta_remove,
12621         .hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
12622         .sta_set_flags = wpa_driver_nl80211_sta_set_flags,
12623         .hapd_init = i802_init,
12624         .hapd_deinit = i802_deinit,
12625         .set_wds_sta = i802_set_wds_sta,
12626         .get_seqnum = i802_get_seqnum,
12627         .flush = i802_flush,
12628         .get_inact_sec = i802_get_inact_sec,
12629         .sta_clear_stats = i802_sta_clear_stats,
12630         .set_rts = i802_set_rts,
12631         .set_frag = i802_set_frag,
12632         .set_tx_queue_params = i802_set_tx_queue_params,
12633         .set_sta_vlan = driver_nl80211_set_sta_vlan,
12634         .sta_deauth = i802_sta_deauth,
12635         .sta_disassoc = i802_sta_disassoc,
12636         .read_sta_data = driver_nl80211_read_sta_data,
12637         .set_freq = i802_set_freq,
12638         .send_action = driver_nl80211_send_action,
12639         .send_action_cancel_wait = wpa_driver_nl80211_send_action_cancel_wait,
12640         .remain_on_channel = wpa_driver_nl80211_remain_on_channel,
12641         .cancel_remain_on_channel =
12642         wpa_driver_nl80211_cancel_remain_on_channel,
12643         .probe_req_report = driver_nl80211_probe_req_report,
12644         .deinit_ap = wpa_driver_nl80211_deinit_ap,
12645         .deinit_p2p_cli = wpa_driver_nl80211_deinit_p2p_cli,
12646         .resume = wpa_driver_nl80211_resume,
12647         .send_ft_action = nl80211_send_ft_action,
12648         .signal_monitor = nl80211_signal_monitor,
12649         .signal_poll = nl80211_signal_poll,
12650         .send_frame = nl80211_send_frame,
12651         .shared_freq = wpa_driver_nl80211_shared_freq,
12652         .set_param = nl80211_set_param,
12653         .get_radio_name = nl80211_get_radio_name,
12654         .add_pmkid = nl80211_add_pmkid,
12655         .remove_pmkid = nl80211_remove_pmkid,
12656         .flush_pmkid = nl80211_flush_pmkid,
12657         .set_rekey_info = nl80211_set_rekey_info,
12658         .poll_client = nl80211_poll_client,
12659         .set_p2p_powersave = nl80211_set_p2p_powersave,
12660         .start_dfs_cac = nl80211_start_radar_detection,
12661         .stop_ap = wpa_driver_nl80211_stop_ap,
12662 #ifdef CONFIG_TDLS
12663         .send_tdls_mgmt = nl80211_send_tdls_mgmt,
12664         .tdls_oper = nl80211_tdls_oper,
12665 #endif /* CONFIG_TDLS */
12666         .update_ft_ies = wpa_driver_nl80211_update_ft_ies,
12667         .get_mac_addr = wpa_driver_nl80211_get_macaddr,
12668         .get_survey = wpa_driver_nl80211_get_survey,
12669         .status = wpa_driver_nl80211_status,
12670         .switch_channel = nl80211_switch_channel,
12671 #ifdef ANDROID_P2P
12672         .set_noa = wpa_driver_set_p2p_noa,
12673         .get_noa = wpa_driver_get_p2p_noa,
12674         .set_ap_wps_ie = wpa_driver_set_ap_wps_p2p_ie,
12675 #endif /* ANDROID_P2P */
12676 #ifdef ANDROID
12677         .driver_cmd = wpa_driver_nl80211_driver_cmd,
12678 #endif /* ANDROID */
12679         .vendor_cmd = nl80211_vendor_cmd,
12680         .set_qos_map = nl80211_set_qos_map,
12681         .set_wowlan = nl80211_set_wowlan,
12682         .roaming = nl80211_roaming,
12683         .set_mac_addr = nl80211_set_mac_addr,
12684 };