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