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