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