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