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