wpa_supplicant: Use the 'no_ir' notation
[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_NO_IR;
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         if (flags & WPA_STA_AUTHENTICATED)
7876                 f |= BIT(NL80211_STA_FLAG_AUTHENTICATED);
7877
7878         return f;
7879 }
7880
7881
7882 #ifdef CONFIG_MESH
7883 static u32 sta_plink_state_nl80211(enum mesh_plink_state state)
7884 {
7885         switch (state) {
7886         case PLINK_LISTEN:
7887                 return NL80211_PLINK_LISTEN;
7888         case PLINK_OPEN_SENT:
7889                 return NL80211_PLINK_OPN_SNT;
7890         case PLINK_OPEN_RCVD:
7891                 return NL80211_PLINK_OPN_RCVD;
7892         case PLINK_CNF_RCVD:
7893                 return NL80211_PLINK_CNF_RCVD;
7894         case PLINK_ESTAB:
7895                 return NL80211_PLINK_ESTAB;
7896         case PLINK_HOLDING:
7897                 return NL80211_PLINK_HOLDING;
7898         case PLINK_BLOCKED:
7899                 return NL80211_PLINK_BLOCKED;
7900         default:
7901                 wpa_printf(MSG_ERROR, "nl80211: Invalid mesh plink state %d",
7902                            state);
7903         }
7904         return -1;
7905 }
7906 #endif /* CONFIG_MESH */
7907
7908
7909 static int wpa_driver_nl80211_sta_add(void *priv,
7910                                       struct hostapd_sta_add_params *params)
7911 {
7912         struct i802_bss *bss = priv;
7913         struct wpa_driver_nl80211_data *drv = bss->drv;
7914         struct nl_msg *msg;
7915         struct nl80211_sta_flag_update upd;
7916         int ret = -ENOBUFS;
7917
7918         if ((params->flags & WPA_STA_TDLS_PEER) &&
7919             !(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
7920                 return -EOPNOTSUPP;
7921
7922         msg = nlmsg_alloc();
7923         if (!msg)
7924                 return -ENOMEM;
7925
7926         wpa_printf(MSG_DEBUG, "nl80211: %s STA " MACSTR,
7927                    params->set ? "Set" : "Add", MAC2STR(params->addr));
7928         nl80211_cmd(drv, msg, 0, params->set ? NL80211_CMD_SET_STATION :
7929                     NL80211_CMD_NEW_STATION);
7930
7931         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7932         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
7933
7934         if (!params->set || (params->flags & WPA_STA_TDLS_PEER)) {
7935                 NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES,
7936                         params->supp_rates_len, params->supp_rates);
7937                 wpa_hexdump(MSG_DEBUG, "  * supported rates",
7938                             params->supp_rates, params->supp_rates_len);
7939         }
7940         if (!params->set) {
7941                 if (params->aid) {
7942                         wpa_printf(MSG_DEBUG, "  * aid=%u", params->aid);
7943                         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
7944                 } else {
7945                         /*
7946                          * cfg80211 validates that AID is non-zero, so we have
7947                          * to make this a non-zero value for the TDLS case where
7948                          * a dummy STA entry is used for now.
7949                          */
7950                         wpa_printf(MSG_DEBUG, "  * aid=1 (TDLS workaround)");
7951                         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, 1);
7952                 }
7953                 wpa_printf(MSG_DEBUG, "  * listen_interval=%u",
7954                            params->listen_interval);
7955                 NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
7956                             params->listen_interval);
7957         } else if (params->aid && (params->flags & WPA_STA_TDLS_PEER)) {
7958                 wpa_printf(MSG_DEBUG, "  * peer_aid=%u", params->aid);
7959                 NLA_PUT_U16(msg, NL80211_ATTR_PEER_AID, params->aid);
7960         }
7961         if (params->ht_capabilities) {
7962                 wpa_hexdump(MSG_DEBUG, "  * ht_capabilities",
7963                             (u8 *) params->ht_capabilities,
7964                             sizeof(*params->ht_capabilities));
7965                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
7966                         sizeof(*params->ht_capabilities),
7967                         params->ht_capabilities);
7968         }
7969
7970         if (params->vht_capabilities) {
7971                 wpa_hexdump(MSG_DEBUG, "  * vht_capabilities",
7972                             (u8 *) params->vht_capabilities,
7973                             sizeof(*params->vht_capabilities));
7974                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY,
7975                         sizeof(*params->vht_capabilities),
7976                         params->vht_capabilities);
7977         }
7978
7979         if (params->vht_opmode_enabled) {
7980                 wpa_printf(MSG_DEBUG, "  * opmode=%u", params->vht_opmode);
7981                 NLA_PUT_U8(msg, NL80211_ATTR_OPMODE_NOTIF,
7982                            params->vht_opmode);
7983         }
7984
7985         wpa_printf(MSG_DEBUG, "  * capability=0x%x", params->capability);
7986         NLA_PUT_U16(msg, NL80211_ATTR_STA_CAPABILITY, params->capability);
7987
7988         if (params->ext_capab) {
7989                 wpa_hexdump(MSG_DEBUG, "  * ext_capab",
7990                             params->ext_capab, params->ext_capab_len);
7991                 NLA_PUT(msg, NL80211_ATTR_STA_EXT_CAPABILITY,
7992                         params->ext_capab_len, params->ext_capab);
7993         }
7994
7995         if (params->supp_channels) {
7996                 wpa_hexdump(MSG_DEBUG, "  * supported channels",
7997                             params->supp_channels, params->supp_channels_len);
7998                 NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_CHANNELS,
7999                         params->supp_channels_len, params->supp_channels);
8000         }
8001
8002         if (params->supp_oper_classes) {
8003                 wpa_hexdump(MSG_DEBUG, "  * supported operating classes",
8004                             params->supp_oper_classes,
8005                             params->supp_oper_classes_len);
8006                 NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_OPER_CLASSES,
8007                         params->supp_oper_classes_len,
8008                         params->supp_oper_classes);
8009         }
8010
8011         os_memset(&upd, 0, sizeof(upd));
8012         upd.set = sta_flags_nl80211(params->flags);
8013         upd.mask = upd.set | sta_flags_nl80211(params->flags_mask);
8014         wpa_printf(MSG_DEBUG, "  * flags set=0x%x mask=0x%x",
8015                    upd.set, upd.mask);
8016         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
8017
8018 #ifdef CONFIG_MESH
8019         if (params->plink_state)
8020                 NLA_PUT_U8(msg, NL80211_ATTR_STA_PLINK_STATE,
8021                            sta_plink_state_nl80211(params->plink_state));
8022 #endif /* CONFIG_MESH */
8023
8024         if (params->flags & WPA_STA_WMM) {
8025                 struct nlattr *wme = nla_nest_start(msg, NL80211_ATTR_STA_WME);
8026
8027                 if (!wme)
8028                         goto nla_put_failure;
8029
8030                 wpa_printf(MSG_DEBUG, "  * qosinfo=0x%x", params->qosinfo);
8031                 NLA_PUT_U8(msg, NL80211_STA_WME_UAPSD_QUEUES,
8032                                 params->qosinfo & WMM_QOSINFO_STA_AC_MASK);
8033                 NLA_PUT_U8(msg, NL80211_STA_WME_MAX_SP,
8034                                 (params->qosinfo >> WMM_QOSINFO_STA_SP_SHIFT) &
8035                                 WMM_QOSINFO_STA_SP_MASK);
8036                 nla_nest_end(msg, wme);
8037         }
8038
8039         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8040         msg = NULL;
8041         if (ret)
8042                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_%s_STATION "
8043                            "result: %d (%s)", params->set ? "SET" : "NEW", ret,
8044                            strerror(-ret));
8045         if (ret == -EEXIST)
8046                 ret = 0;
8047  nla_put_failure:
8048         nlmsg_free(msg);
8049         return ret;
8050 }
8051
8052
8053 static void rtnl_neigh_delete_fdb_entry(struct i802_bss *bss, const u8 *addr)
8054 {
8055 #ifdef CONFIG_LIBNL3_ROUTE
8056         struct wpa_driver_nl80211_data *drv = bss->drv;
8057         struct rtnl_neigh *rn;
8058         struct nl_addr *nl_addr;
8059         int err;
8060
8061         rn = rtnl_neigh_alloc();
8062         if (!rn)
8063                 return;
8064
8065         rtnl_neigh_set_family(rn, AF_BRIDGE);
8066         rtnl_neigh_set_ifindex(rn, bss->ifindex);
8067         nl_addr = nl_addr_build(AF_BRIDGE, (void *) addr, ETH_ALEN);
8068         if (!nl_addr) {
8069                 rtnl_neigh_put(rn);
8070                 return;
8071         }
8072         rtnl_neigh_set_lladdr(rn, nl_addr);
8073
8074         err = rtnl_neigh_delete(drv->rtnl_sk, rn, 0);
8075         if (err < 0) {
8076                 wpa_printf(MSG_DEBUG, "nl80211: bridge FDB entry delete for "
8077                            MACSTR " ifindex=%d failed: %s", MAC2STR(addr),
8078                            bss->ifindex, nl_geterror(err));
8079         } else {
8080                 wpa_printf(MSG_DEBUG, "nl80211: deleted bridge FDB entry for "
8081                            MACSTR, MAC2STR(addr));
8082         }
8083
8084         nl_addr_put(nl_addr);
8085         rtnl_neigh_put(rn);
8086 #endif /* CONFIG_LIBNL3_ROUTE */
8087 }
8088
8089
8090 static int wpa_driver_nl80211_sta_remove(struct i802_bss *bss, const u8 *addr,
8091                                          int deauth, u16 reason_code)
8092 {
8093         struct wpa_driver_nl80211_data *drv = bss->drv;
8094         struct nl_msg *msg;
8095         int ret;
8096
8097         msg = nlmsg_alloc();
8098         if (!msg)
8099                 return -ENOMEM;
8100
8101         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
8102
8103         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
8104                     if_nametoindex(bss->ifname));
8105         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
8106         if (deauth == 0)
8107                 NLA_PUT_U8(msg, NL80211_ATTR_MGMT_SUBTYPE,
8108                            WLAN_FC_STYPE_DISASSOC);
8109         else if (deauth == 1)
8110                 NLA_PUT_U8(msg, NL80211_ATTR_MGMT_SUBTYPE,
8111                            WLAN_FC_STYPE_DEAUTH);
8112         if (reason_code)
8113                 NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
8114
8115         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8116         wpa_printf(MSG_DEBUG, "nl80211: sta_remove -> DEL_STATION %s " MACSTR
8117                    " --> %d (%s)",
8118                    bss->ifname, MAC2STR(addr), ret, strerror(-ret));
8119
8120         if (drv->rtnl_sk)
8121                 rtnl_neigh_delete_fdb_entry(bss, addr);
8122
8123         if (ret == -ENOENT)
8124                 return 0;
8125         return ret;
8126  nla_put_failure:
8127         nlmsg_free(msg);
8128         return -ENOBUFS;
8129 }
8130
8131
8132 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
8133                                  int ifidx)
8134 {
8135         struct nl_msg *msg;
8136         struct wpa_driver_nl80211_data *drv2;
8137
8138         wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
8139
8140         /* stop listening for EAPOL on this interface */
8141         dl_list_for_each(drv2, &drv->global->interfaces,
8142                          struct wpa_driver_nl80211_data, list)
8143                 del_ifidx(drv2, ifidx);
8144
8145         msg = nlmsg_alloc();
8146         if (!msg)
8147                 goto nla_put_failure;
8148
8149         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_INTERFACE);
8150         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
8151
8152         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
8153                 return;
8154         msg = NULL;
8155  nla_put_failure:
8156         nlmsg_free(msg);
8157         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
8158 }
8159
8160
8161 static const char * nl80211_iftype_str(enum nl80211_iftype mode)
8162 {
8163         switch (mode) {
8164         case NL80211_IFTYPE_ADHOC:
8165                 return "ADHOC";
8166         case NL80211_IFTYPE_STATION:
8167                 return "STATION";
8168         case NL80211_IFTYPE_AP:
8169                 return "AP";
8170         case NL80211_IFTYPE_AP_VLAN:
8171                 return "AP_VLAN";
8172         case NL80211_IFTYPE_WDS:
8173                 return "WDS";
8174         case NL80211_IFTYPE_MONITOR:
8175                 return "MONITOR";
8176         case NL80211_IFTYPE_MESH_POINT:
8177                 return "MESH_POINT";
8178         case NL80211_IFTYPE_P2P_CLIENT:
8179                 return "P2P_CLIENT";
8180         case NL80211_IFTYPE_P2P_GO:
8181                 return "P2P_GO";
8182         case NL80211_IFTYPE_P2P_DEVICE:
8183                 return "P2P_DEVICE";
8184         default:
8185                 return "unknown";
8186         }
8187 }
8188
8189
8190 static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
8191                                      const char *ifname,
8192                                      enum nl80211_iftype iftype,
8193                                      const u8 *addr, int wds,
8194                                      int (*handler)(struct nl_msg *, void *),
8195                                      void *arg)
8196 {
8197         struct nl_msg *msg;
8198         int ifidx;
8199         int ret = -ENOBUFS;
8200
8201         wpa_printf(MSG_DEBUG, "nl80211: Create interface iftype %d (%s)",
8202                    iftype, nl80211_iftype_str(iftype));
8203
8204         msg = nlmsg_alloc();
8205         if (!msg)
8206                 return -1;
8207
8208         nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_INTERFACE);
8209         if (nl80211_set_iface_id(msg, drv->first_bss) < 0)
8210                 goto nla_put_failure;
8211         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
8212         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
8213
8214         if (iftype == NL80211_IFTYPE_MONITOR) {
8215                 struct nlattr *flags;
8216
8217                 flags = nla_nest_start(msg, NL80211_ATTR_MNTR_FLAGS);
8218                 if (!flags)
8219                         goto nla_put_failure;
8220
8221                 NLA_PUT_FLAG(msg, NL80211_MNTR_FLAG_COOK_FRAMES);
8222
8223                 nla_nest_end(msg, flags);
8224         } else if (wds) {
8225                 NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
8226         }
8227
8228         /*
8229          * Tell cfg80211 that the interface belongs to the socket that created
8230          * it, and the interface should be deleted when the socket is closed.
8231          */
8232         NLA_PUT_FLAG(msg, NL80211_ATTR_IFACE_SOCKET_OWNER);
8233
8234         ret = send_and_recv_msgs(drv, msg, handler, arg);
8235         msg = NULL;
8236         if (ret) {
8237  nla_put_failure:
8238                 nlmsg_free(msg);
8239                 wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
8240                            ifname, ret, strerror(-ret));
8241                 return ret;
8242         }
8243
8244         if (iftype == NL80211_IFTYPE_P2P_DEVICE)
8245                 return 0;
8246
8247         ifidx = if_nametoindex(ifname);
8248         wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
8249                    ifname, ifidx);
8250
8251         if (ifidx <= 0)
8252                 return -1;
8253
8254         /*
8255          * Some virtual interfaces need to process EAPOL packets and events on
8256          * the parent interface. This is used mainly with hostapd.
8257          */
8258         if (drv->hostapd ||
8259             iftype == NL80211_IFTYPE_AP_VLAN ||
8260             iftype == NL80211_IFTYPE_WDS ||
8261             iftype == NL80211_IFTYPE_MONITOR) {
8262                 /* start listening for EAPOL on this interface */
8263                 add_ifidx(drv, ifidx);
8264         }
8265
8266         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
8267             linux_set_ifhwaddr(drv->global->ioctl_sock, ifname, addr)) {
8268                 nl80211_remove_iface(drv, ifidx);
8269                 return -1;
8270         }
8271
8272         return ifidx;
8273 }
8274
8275
8276 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
8277                                 const char *ifname, enum nl80211_iftype iftype,
8278                                 const u8 *addr, int wds,
8279                                 int (*handler)(struct nl_msg *, void *),
8280                                 void *arg, int use_existing)
8281 {
8282         int ret;
8283
8284         ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds, handler,
8285                                         arg);
8286
8287         /* if error occurred and interface exists already */
8288         if (ret == -ENFILE && if_nametoindex(ifname)) {
8289                 if (use_existing) {
8290                         wpa_printf(MSG_DEBUG, "nl80211: Continue using existing interface %s",
8291                                    ifname);
8292                         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
8293                             linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
8294                                                addr) < 0 &&
8295                             (linux_set_iface_flags(drv->global->ioctl_sock,
8296                                                    ifname, 0) < 0 ||
8297                              linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
8298                                                 addr) < 0 ||
8299                              linux_set_iface_flags(drv->global->ioctl_sock,
8300                                                    ifname, 1) < 0))
8301                                         return -1;
8302                         return -ENFILE;
8303                 }
8304                 wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
8305
8306                 /* Try to remove the interface that was already there. */
8307                 nl80211_remove_iface(drv, if_nametoindex(ifname));
8308
8309                 /* Try to create the interface again */
8310                 ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
8311                                                 wds, handler, arg);
8312         }
8313
8314         if (ret >= 0 && is_p2p_net_interface(iftype))
8315                 nl80211_disable_11b_rates(drv, ret, 1);
8316
8317         return ret;
8318 }
8319
8320
8321 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
8322 {
8323         struct ieee80211_hdr *hdr;
8324         u16 fc;
8325         union wpa_event_data event;
8326
8327         hdr = (struct ieee80211_hdr *) buf;
8328         fc = le_to_host16(hdr->frame_control);
8329
8330         os_memset(&event, 0, sizeof(event));
8331         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
8332         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
8333         event.tx_status.dst = hdr->addr1;
8334         event.tx_status.data = buf;
8335         event.tx_status.data_len = len;
8336         event.tx_status.ack = ok;
8337         wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
8338 }
8339
8340
8341 static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
8342                              u8 *buf, size_t len)
8343 {
8344         struct ieee80211_hdr *hdr = (void *)buf;
8345         u16 fc;
8346         union wpa_event_data event;
8347
8348         if (len < sizeof(*hdr))
8349                 return;
8350
8351         fc = le_to_host16(hdr->frame_control);
8352
8353         os_memset(&event, 0, sizeof(event));
8354         event.rx_from_unknown.bssid = get_hdr_bssid(hdr, len);
8355         event.rx_from_unknown.addr = hdr->addr2;
8356         event.rx_from_unknown.wds = (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) ==
8357                 (WLAN_FC_FROMDS | WLAN_FC_TODS);
8358         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
8359 }
8360
8361
8362 static void handle_frame(struct wpa_driver_nl80211_data *drv,
8363                          u8 *buf, size_t len, int datarate, int ssi_signal)
8364 {
8365         struct ieee80211_hdr *hdr;
8366         u16 fc;
8367         union wpa_event_data event;
8368
8369         hdr = (struct ieee80211_hdr *) buf;
8370         fc = le_to_host16(hdr->frame_control);
8371
8372         switch (WLAN_FC_GET_TYPE(fc)) {
8373         case WLAN_FC_TYPE_MGMT:
8374                 os_memset(&event, 0, sizeof(event));
8375                 event.rx_mgmt.frame = buf;
8376                 event.rx_mgmt.frame_len = len;
8377                 event.rx_mgmt.datarate = datarate;
8378                 event.rx_mgmt.ssi_signal = ssi_signal;
8379                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
8380                 break;
8381         case WLAN_FC_TYPE_CTRL:
8382                 /* can only get here with PS-Poll frames */
8383                 wpa_printf(MSG_DEBUG, "CTRL");
8384                 from_unknown_sta(drv, buf, len);
8385                 break;
8386         case WLAN_FC_TYPE_DATA:
8387                 from_unknown_sta(drv, buf, len);
8388                 break;
8389         }
8390 }
8391
8392
8393 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
8394 {
8395         struct wpa_driver_nl80211_data *drv = eloop_ctx;
8396         int len;
8397         unsigned char buf[3000];
8398         struct ieee80211_radiotap_iterator iter;
8399         int ret;
8400         int datarate = 0, ssi_signal = 0;
8401         int injected = 0, failed = 0, rxflags = 0;
8402
8403         len = recv(sock, buf, sizeof(buf), 0);
8404         if (len < 0) {
8405                 wpa_printf(MSG_ERROR, "nl80211: Monitor socket recv failed: %s",
8406                            strerror(errno));
8407                 return;
8408         }
8409
8410         if (ieee80211_radiotap_iterator_init(&iter, (void *) buf, len, NULL)) {
8411                 wpa_printf(MSG_INFO, "nl80211: received invalid radiotap frame");
8412                 return;
8413         }
8414
8415         while (1) {
8416                 ret = ieee80211_radiotap_iterator_next(&iter);
8417                 if (ret == -ENOENT)
8418                         break;
8419                 if (ret) {
8420                         wpa_printf(MSG_INFO, "nl80211: received invalid radiotap frame (%d)",
8421                                    ret);
8422                         return;
8423                 }
8424                 switch (iter.this_arg_index) {
8425                 case IEEE80211_RADIOTAP_FLAGS:
8426                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
8427                                 len -= 4;
8428                         break;
8429                 case IEEE80211_RADIOTAP_RX_FLAGS:
8430                         rxflags = 1;
8431                         break;
8432                 case IEEE80211_RADIOTAP_TX_FLAGS:
8433                         injected = 1;
8434                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
8435                                         IEEE80211_RADIOTAP_F_TX_FAIL;
8436                         break;
8437                 case IEEE80211_RADIOTAP_DATA_RETRIES:
8438                         break;
8439                 case IEEE80211_RADIOTAP_CHANNEL:
8440                         /* TODO: convert from freq/flags to channel number */
8441                         break;
8442                 case IEEE80211_RADIOTAP_RATE:
8443                         datarate = *iter.this_arg * 5;
8444                         break;
8445                 case IEEE80211_RADIOTAP_DBM_ANTSIGNAL:
8446                         ssi_signal = (s8) *iter.this_arg;
8447                         break;
8448                 }
8449         }
8450
8451         if (rxflags && injected)
8452                 return;
8453
8454         if (!injected)
8455                 handle_frame(drv, buf + iter._max_length,
8456                              len - iter._max_length, datarate, ssi_signal);
8457         else
8458                 handle_tx_callback(drv->ctx, buf + iter._max_length,
8459                                    len - iter._max_length, !failed);
8460 }
8461
8462
8463 /*
8464  * we post-process the filter code later and rewrite
8465  * this to the offset to the last instruction
8466  */
8467 #define PASS    0xFF
8468 #define FAIL    0xFE
8469
8470 static struct sock_filter msock_filter_insns[] = {
8471         /*
8472          * do a little-endian load of the radiotap length field
8473          */
8474         /* load lower byte into A */
8475         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
8476         /* put it into X (== index register) */
8477         BPF_STMT(BPF_MISC| BPF_TAX, 0),
8478         /* load upper byte into A */
8479         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
8480         /* left-shift it by 8 */
8481         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
8482         /* or with X */
8483         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
8484         /* put result into X */
8485         BPF_STMT(BPF_MISC| BPF_TAX, 0),
8486
8487         /*
8488          * Allow management frames through, this also gives us those
8489          * management frames that we sent ourselves with status
8490          */
8491         /* load the lower byte of the IEEE 802.11 frame control field */
8492         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
8493         /* mask off frame type and version */
8494         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
8495         /* accept frame if it's both 0, fall through otherwise */
8496         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
8497
8498         /*
8499          * TODO: add a bit to radiotap RX flags that indicates
8500          * that the sending station is not associated, then
8501          * add a filter here that filters on our DA and that flag
8502          * to allow us to deauth frames to that bad station.
8503          *
8504          * For now allow all To DS data frames through.
8505          */
8506         /* load the IEEE 802.11 frame control field */
8507         BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
8508         /* mask off frame type, version and DS status */
8509         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
8510         /* accept frame if version 0, type 2 and To DS, fall through otherwise
8511          */
8512         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
8513
8514 #if 0
8515         /*
8516          * drop non-data frames
8517          */
8518         /* load the lower byte of the frame control field */
8519         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
8520         /* mask off QoS bit */
8521         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
8522         /* drop non-data frames */
8523         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
8524 #endif
8525         /* load the upper byte of the frame control field */
8526         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
8527         /* mask off toDS/fromDS */
8528         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
8529         /* accept WDS frames */
8530         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
8531
8532         /*
8533          * add header length to index
8534          */
8535         /* load the lower byte of the frame control field */
8536         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
8537         /* mask off QoS bit */
8538         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
8539         /* right shift it by 6 to give 0 or 2 */
8540         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
8541         /* add data frame header length */
8542         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
8543         /* add index, was start of 802.11 header */
8544         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
8545         /* move to index, now start of LL header */
8546         BPF_STMT(BPF_MISC | BPF_TAX, 0),
8547
8548         /*
8549          * Accept empty data frames, we use those for
8550          * polling activity.
8551          */
8552         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
8553         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
8554
8555         /*
8556          * Accept EAPOL frames
8557          */
8558         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
8559         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
8560         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
8561         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
8562
8563         /* keep these last two statements or change the code below */
8564         /* return 0 == "DROP" */
8565         BPF_STMT(BPF_RET | BPF_K, 0),
8566         /* return ~0 == "keep all" */
8567         BPF_STMT(BPF_RET | BPF_K, ~0),
8568 };
8569
8570 static struct sock_fprog msock_filter = {
8571         .len = ARRAY_SIZE(msock_filter_insns),
8572         .filter = msock_filter_insns,
8573 };
8574
8575
8576 static int add_monitor_filter(int s)
8577 {
8578         int idx;
8579
8580         /* rewrite all PASS/FAIL jump offsets */
8581         for (idx = 0; idx < msock_filter.len; idx++) {
8582                 struct sock_filter *insn = &msock_filter_insns[idx];
8583
8584                 if (BPF_CLASS(insn->code) == BPF_JMP) {
8585                         if (insn->code == (BPF_JMP|BPF_JA)) {
8586                                 if (insn->k == PASS)
8587                                         insn->k = msock_filter.len - idx - 2;
8588                                 else if (insn->k == FAIL)
8589                                         insn->k = msock_filter.len - idx - 3;
8590                         }
8591
8592                         if (insn->jt == PASS)
8593                                 insn->jt = msock_filter.len - idx - 2;
8594                         else if (insn->jt == FAIL)
8595                                 insn->jt = msock_filter.len - idx - 3;
8596
8597                         if (insn->jf == PASS)
8598                                 insn->jf = msock_filter.len - idx - 2;
8599                         else if (insn->jf == FAIL)
8600                                 insn->jf = msock_filter.len - idx - 3;
8601                 }
8602         }
8603
8604         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
8605                        &msock_filter, sizeof(msock_filter))) {
8606                 wpa_printf(MSG_ERROR, "nl80211: setsockopt(SO_ATTACH_FILTER) failed: %s",
8607                            strerror(errno));
8608                 return -1;
8609         }
8610
8611         return 0;
8612 }
8613
8614
8615 static void nl80211_remove_monitor_interface(
8616         struct wpa_driver_nl80211_data *drv)
8617 {
8618         if (drv->monitor_refcount > 0)
8619                 drv->monitor_refcount--;
8620         wpa_printf(MSG_DEBUG, "nl80211: Remove monitor interface: refcount=%d",
8621                    drv->monitor_refcount);
8622         if (drv->monitor_refcount > 0)
8623                 return;
8624
8625         if (drv->monitor_ifidx >= 0) {
8626                 nl80211_remove_iface(drv, drv->monitor_ifidx);
8627                 drv->monitor_ifidx = -1;
8628         }
8629         if (drv->monitor_sock >= 0) {
8630                 eloop_unregister_read_sock(drv->monitor_sock);
8631                 close(drv->monitor_sock);
8632                 drv->monitor_sock = -1;
8633         }
8634 }
8635
8636
8637 static int
8638 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
8639 {
8640         char buf[IFNAMSIZ];
8641         struct sockaddr_ll ll;
8642         int optval;
8643         socklen_t optlen;
8644
8645         if (drv->monitor_ifidx >= 0) {
8646                 drv->monitor_refcount++;
8647                 wpa_printf(MSG_DEBUG, "nl80211: Re-use existing monitor interface: refcount=%d",
8648                            drv->monitor_refcount);
8649                 return 0;
8650         }
8651
8652         if (os_strncmp(drv->first_bss->ifname, "p2p-", 4) == 0) {
8653                 /*
8654                  * P2P interface name is of the format p2p-%s-%d. For monitor
8655                  * interface name corresponding to P2P GO, replace "p2p-" with
8656                  * "mon-" to retain the same interface name length and to
8657                  * indicate that it is a monitor interface.
8658                  */
8659                 snprintf(buf, IFNAMSIZ, "mon-%s", drv->first_bss->ifname + 4);
8660         } else {
8661                 /* Non-P2P interface with AP functionality. */
8662                 snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss->ifname);
8663         }
8664
8665         buf[IFNAMSIZ - 1] = '\0';
8666
8667         drv->monitor_ifidx =
8668                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
8669                                      0, NULL, NULL, 0);
8670
8671         if (drv->monitor_ifidx == -EOPNOTSUPP) {
8672                 /*
8673                  * This is backward compatibility for a few versions of
8674                  * the kernel only that didn't advertise the right
8675                  * attributes for the only driver that then supported
8676                  * AP mode w/o monitor -- ath6kl.
8677                  */
8678                 wpa_printf(MSG_DEBUG, "nl80211: Driver does not support "
8679                            "monitor interface type - try to run without it");
8680                 drv->device_ap_sme = 1;
8681         }
8682
8683         if (drv->monitor_ifidx < 0)
8684                 return -1;
8685
8686         if (linux_set_iface_flags(drv->global->ioctl_sock, buf, 1))
8687                 goto error;
8688
8689         memset(&ll, 0, sizeof(ll));
8690         ll.sll_family = AF_PACKET;
8691         ll.sll_ifindex = drv->monitor_ifidx;
8692         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
8693         if (drv->monitor_sock < 0) {
8694                 wpa_printf(MSG_ERROR, "nl80211: socket[PF_PACKET,SOCK_RAW] failed: %s",
8695                            strerror(errno));
8696                 goto error;
8697         }
8698
8699         if (add_monitor_filter(drv->monitor_sock)) {
8700                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
8701                            "interface; do filtering in user space");
8702                 /* This works, but will cost in performance. */
8703         }
8704
8705         if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
8706                 wpa_printf(MSG_ERROR, "nl80211: monitor socket bind failed: %s",
8707                            strerror(errno));
8708                 goto error;
8709         }
8710
8711         optlen = sizeof(optval);
8712         optval = 20;
8713         if (setsockopt
8714             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
8715                 wpa_printf(MSG_ERROR, "nl80211: Failed to set socket priority: %s",
8716                            strerror(errno));
8717                 goto error;
8718         }
8719
8720         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
8721                                      drv, NULL)) {
8722                 wpa_printf(MSG_INFO, "nl80211: Could not register monitor read socket");
8723                 goto error;
8724         }
8725
8726         drv->monitor_refcount++;
8727         return 0;
8728  error:
8729         nl80211_remove_monitor_interface(drv);
8730         return -1;
8731 }
8732
8733
8734 static int nl80211_setup_ap(struct i802_bss *bss)
8735 {
8736         struct wpa_driver_nl80211_data *drv = bss->drv;
8737
8738         wpa_printf(MSG_DEBUG, "nl80211: Setup AP(%s) - device_ap_sme=%d use_monitor=%d",
8739                    bss->ifname, drv->device_ap_sme, drv->use_monitor);
8740
8741         /*
8742          * Disable Probe Request reporting unless we need it in this way for
8743          * devices that include the AP SME, in the other case (unless using
8744          * monitor iface) we'll get it through the nl_mgmt socket instead.
8745          */
8746         if (!drv->device_ap_sme)
8747                 wpa_driver_nl80211_probe_req_report(bss, 0);
8748
8749         if (!drv->device_ap_sme && !drv->use_monitor)
8750                 if (nl80211_mgmt_subscribe_ap(bss))
8751                         return -1;
8752
8753         if (drv->device_ap_sme && !drv->use_monitor)
8754                 if (nl80211_mgmt_subscribe_ap_dev_sme(bss))
8755                         return -1;
8756
8757         if (!drv->device_ap_sme && drv->use_monitor &&
8758             nl80211_create_monitor_interface(drv) &&
8759             !drv->device_ap_sme)
8760                 return -1;
8761
8762         if (drv->device_ap_sme &&
8763             wpa_driver_nl80211_probe_req_report(bss, 1) < 0) {
8764                 wpa_printf(MSG_DEBUG, "nl80211: Failed to enable "
8765                            "Probe Request frame reporting in AP mode");
8766                 /* Try to survive without this */
8767         }
8768
8769         return 0;
8770 }
8771
8772
8773 static void nl80211_teardown_ap(struct i802_bss *bss)
8774 {
8775         struct wpa_driver_nl80211_data *drv = bss->drv;
8776
8777         wpa_printf(MSG_DEBUG, "nl80211: Teardown AP(%s) - device_ap_sme=%d use_monitor=%d",
8778                    bss->ifname, drv->device_ap_sme, drv->use_monitor);
8779         if (drv->device_ap_sme) {
8780                 wpa_driver_nl80211_probe_req_report(bss, 0);
8781                 if (!drv->use_monitor)
8782                         nl80211_mgmt_unsubscribe(bss, "AP teardown (dev SME)");
8783         } else if (drv->use_monitor)
8784                 nl80211_remove_monitor_interface(drv);
8785         else
8786                 nl80211_mgmt_unsubscribe(bss, "AP teardown");
8787
8788         bss->beacon_set = 0;
8789 }
8790
8791
8792 static int nl80211_send_eapol_data(struct i802_bss *bss,
8793                                    const u8 *addr, const u8 *data,
8794                                    size_t data_len)
8795 {
8796         struct sockaddr_ll ll;
8797         int ret;
8798
8799         if (bss->drv->eapol_tx_sock < 0) {
8800                 wpa_printf(MSG_DEBUG, "nl80211: No socket to send EAPOL");
8801                 return -1;
8802         }
8803
8804         os_memset(&ll, 0, sizeof(ll));
8805         ll.sll_family = AF_PACKET;
8806         ll.sll_ifindex = bss->ifindex;
8807         ll.sll_protocol = htons(ETH_P_PAE);
8808         ll.sll_halen = ETH_ALEN;
8809         os_memcpy(ll.sll_addr, addr, ETH_ALEN);
8810         ret = sendto(bss->drv->eapol_tx_sock, data, data_len, 0,
8811                      (struct sockaddr *) &ll, sizeof(ll));
8812         if (ret < 0)
8813                 wpa_printf(MSG_ERROR, "nl80211: EAPOL TX: %s",
8814                            strerror(errno));
8815
8816         return ret;
8817 }
8818
8819
8820 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
8821
8822 static int wpa_driver_nl80211_hapd_send_eapol(
8823         void *priv, const u8 *addr, const u8 *data,
8824         size_t data_len, int encrypt, const u8 *own_addr, u32 flags)
8825 {
8826         struct i802_bss *bss = priv;
8827         struct wpa_driver_nl80211_data *drv = bss->drv;
8828         struct ieee80211_hdr *hdr;
8829         size_t len;
8830         u8 *pos;
8831         int res;
8832         int qos = flags & WPA_STA_WMM;
8833
8834         if (drv->device_ap_sme || !drv->use_monitor)
8835                 return nl80211_send_eapol_data(bss, addr, data, data_len);
8836
8837         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
8838                 data_len;
8839         hdr = os_zalloc(len);
8840         if (hdr == NULL) {
8841                 wpa_printf(MSG_INFO, "nl80211: Failed to allocate EAPOL buffer(len=%lu)",
8842                            (unsigned long) len);
8843                 return -1;
8844         }
8845
8846         hdr->frame_control =
8847                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
8848         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
8849         if (encrypt)
8850                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
8851         if (qos) {
8852                 hdr->frame_control |=
8853                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
8854         }
8855
8856         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
8857         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
8858         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
8859         pos = (u8 *) (hdr + 1);
8860
8861         if (qos) {
8862                 /* Set highest priority in QoS header */
8863                 pos[0] = 7;
8864                 pos[1] = 0;
8865                 pos += 2;
8866         }
8867
8868         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
8869         pos += sizeof(rfc1042_header);
8870         WPA_PUT_BE16(pos, ETH_P_PAE);
8871         pos += 2;
8872         memcpy(pos, data, data_len);
8873
8874         res = wpa_driver_nl80211_send_frame(bss, (u8 *) hdr, len, encrypt, 0,
8875                                             0, 0, 0, 0);
8876         if (res < 0) {
8877                 wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
8878                            "failed: %d (%s)",
8879                            (unsigned long) len, errno, strerror(errno));
8880         }
8881         os_free(hdr);
8882
8883         return res;
8884 }
8885
8886
8887 static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
8888                                             int total_flags,
8889                                             int flags_or, int flags_and)
8890 {
8891         struct i802_bss *bss = priv;
8892         struct wpa_driver_nl80211_data *drv = bss->drv;
8893         struct nl_msg *msg;
8894         struct nlattr *flags;
8895         struct nl80211_sta_flag_update upd;
8896
8897         wpa_printf(MSG_DEBUG, "nl80211: Set STA flags - ifname=%s addr=" MACSTR
8898                    " total_flags=0x%x flags_or=0x%x flags_and=0x%x authorized=%d",
8899                    bss->ifname, MAC2STR(addr), total_flags, flags_or, flags_and,
8900                    !!(total_flags & WPA_STA_AUTHORIZED));
8901
8902         msg = nlmsg_alloc();
8903         if (!msg)
8904                 return -ENOMEM;
8905
8906         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
8907
8908         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
8909                     if_nametoindex(bss->ifname));
8910         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
8911
8912         /*
8913          * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
8914          * can be removed eventually.
8915          */
8916         flags = nla_nest_start(msg, NL80211_ATTR_STA_FLAGS);
8917         if (!flags)
8918                 goto nla_put_failure;
8919         if (total_flags & WPA_STA_AUTHORIZED)
8920                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_AUTHORIZED);
8921
8922         if (total_flags & WPA_STA_WMM)
8923                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_WME);
8924
8925         if (total_flags & WPA_STA_SHORT_PREAMBLE)
8926                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_SHORT_PREAMBLE);
8927
8928         if (total_flags & WPA_STA_MFP)
8929                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_MFP);
8930
8931         if (total_flags & WPA_STA_TDLS_PEER)
8932                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_TDLS_PEER);
8933
8934         nla_nest_end(msg, flags);
8935
8936         os_memset(&upd, 0, sizeof(upd));
8937         upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
8938         upd.set = sta_flags_nl80211(flags_or);
8939         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
8940
8941         return send_and_recv_msgs(drv, msg, NULL, NULL);
8942  nla_put_failure:
8943         nlmsg_free(msg);
8944         return -ENOBUFS;
8945 }
8946
8947
8948 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
8949                                  struct wpa_driver_associate_params *params)
8950 {
8951         enum nl80211_iftype nlmode, old_mode;
8952
8953         if (params->p2p) {
8954                 wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
8955                            "group (GO)");
8956                 nlmode = NL80211_IFTYPE_P2P_GO;
8957         } else
8958                 nlmode = NL80211_IFTYPE_AP;
8959
8960         old_mode = drv->nlmode;
8961         if (wpa_driver_nl80211_set_mode(drv->first_bss, nlmode)) {
8962                 nl80211_remove_monitor_interface(drv);
8963                 return -1;
8964         }
8965
8966         if (nl80211_set_channel(drv->first_bss, &params->freq, 0)) {
8967                 if (old_mode != nlmode)
8968                         wpa_driver_nl80211_set_mode(drv->first_bss, old_mode);
8969                 nl80211_remove_monitor_interface(drv);
8970                 return -1;
8971         }
8972
8973         return 0;
8974 }
8975
8976
8977 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
8978 {
8979         struct nl_msg *msg;
8980         int ret = -1;
8981
8982         msg = nlmsg_alloc();
8983         if (!msg)
8984                 return -1;
8985
8986         nl80211_cmd(drv, msg, 0, NL80211_CMD_LEAVE_IBSS);
8987         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8988         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8989         msg = NULL;
8990         if (ret) {
8991                 wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
8992                            "(%s)", ret, strerror(-ret));
8993                 goto nla_put_failure;
8994         }
8995
8996         ret = 0;
8997         wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
8998
8999 nla_put_failure:
9000         if (wpa_driver_nl80211_set_mode(drv->first_bss,
9001                                         NL80211_IFTYPE_STATION)) {
9002                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
9003                            "station mode");
9004         }
9005
9006         nlmsg_free(msg);
9007         return ret;
9008 }
9009
9010
9011 static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
9012                                    struct wpa_driver_associate_params *params)
9013 {
9014         struct nl_msg *msg;
9015         int ret = -1;
9016         int count = 0;
9017
9018         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
9019
9020         if (wpa_driver_nl80211_set_mode_ibss(drv->first_bss, &params->freq)) {
9021                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
9022                            "IBSS mode");
9023                 return -1;
9024         }
9025
9026 retry:
9027         msg = nlmsg_alloc();
9028         if (!msg)
9029                 return -1;
9030
9031         nl80211_cmd(drv, msg, 0, NL80211_CMD_JOIN_IBSS);
9032         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9033
9034         if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
9035                 goto nla_put_failure;
9036
9037         wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
9038                           params->ssid, params->ssid_len);
9039         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
9040                 params->ssid);
9041         os_memcpy(drv->ssid, params->ssid, params->ssid_len);
9042         drv->ssid_len = params->ssid_len;
9043
9044         wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq.freq);
9045         wpa_printf(MSG_DEBUG, "  * ht_enabled=%d", params->freq.ht_enabled);
9046         wpa_printf(MSG_DEBUG, "  * sec_channel_offset=%d",
9047                    params->freq.sec_channel_offset);
9048         wpa_printf(MSG_DEBUG, "  * vht_enabled=%d", params->freq.vht_enabled);
9049         wpa_printf(MSG_DEBUG, "  * center_freq1=%d", params->freq.center_freq1);
9050         wpa_printf(MSG_DEBUG, "  * center_freq2=%d", params->freq.center_freq2);
9051         wpa_printf(MSG_DEBUG, "  * bandwidth=%d", params->freq.bandwidth);
9052         if (nl80211_put_freq_params(msg, &params->freq) < 0)
9053                 goto nla_put_failure;
9054
9055         if (params->beacon_int > 0) {
9056                 wpa_printf(MSG_DEBUG, "  * beacon_int=%d", params->beacon_int);
9057                 NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL,
9058                             params->beacon_int);
9059         }
9060
9061         ret = nl80211_set_conn_keys(params, msg);
9062         if (ret)
9063                 goto nla_put_failure;
9064
9065         if (params->bssid && params->fixed_bssid) {
9066                 wpa_printf(MSG_DEBUG, "  * BSSID=" MACSTR,
9067                            MAC2STR(params->bssid));
9068                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
9069         }
9070
9071         if (params->key_mgmt_suite == WPA_KEY_MGMT_IEEE8021X ||
9072             params->key_mgmt_suite == WPA_KEY_MGMT_PSK ||
9073             params->key_mgmt_suite == WPA_KEY_MGMT_IEEE8021X_SHA256 ||
9074             params->key_mgmt_suite == WPA_KEY_MGMT_PSK_SHA256) {
9075                 wpa_printf(MSG_DEBUG, "  * control port");
9076                 NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
9077         }
9078
9079         if (params->wpa_ie) {
9080                 wpa_hexdump(MSG_DEBUG,
9081                             "  * Extra IEs for Beacon/Probe Response frames",
9082                             params->wpa_ie, params->wpa_ie_len);
9083                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
9084                         params->wpa_ie);
9085         }
9086
9087         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9088         msg = NULL;
9089         if (ret) {
9090                 wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
9091                            ret, strerror(-ret));
9092                 count++;
9093                 if (ret == -EALREADY && count == 1) {
9094                         wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
9095                                    "forced leave");
9096                         nl80211_leave_ibss(drv);
9097                         nlmsg_free(msg);
9098                         goto retry;
9099                 }
9100
9101                 goto nla_put_failure;
9102         }
9103         ret = 0;
9104         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
9105
9106 nla_put_failure:
9107         nlmsg_free(msg);
9108         return ret;
9109 }
9110
9111
9112 static int nl80211_connect_common(struct wpa_driver_nl80211_data *drv,
9113                                   struct wpa_driver_associate_params *params,
9114                                   struct nl_msg *msg)
9115 {
9116         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9117
9118         if (params->bssid) {
9119                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
9120                            MAC2STR(params->bssid));
9121                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
9122         }
9123
9124         if (params->bssid_hint) {
9125                 wpa_printf(MSG_DEBUG, "  * bssid_hint=" MACSTR,
9126                            MAC2STR(params->bssid_hint));
9127                 NLA_PUT(msg, NL80211_ATTR_MAC_HINT, ETH_ALEN,
9128                         params->bssid_hint);
9129         }
9130
9131         if (params->freq.freq) {
9132                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq.freq);
9133                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq.freq);
9134                 drv->assoc_freq = params->freq.freq;
9135         } else
9136                 drv->assoc_freq = 0;
9137
9138         if (params->freq_hint) {
9139                 wpa_printf(MSG_DEBUG, "  * freq_hint=%d", params->freq_hint);
9140                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ_HINT,
9141                             params->freq_hint);
9142         }
9143
9144         if (params->bg_scan_period >= 0) {
9145                 wpa_printf(MSG_DEBUG, "  * bg scan period=%d",
9146                            params->bg_scan_period);
9147                 NLA_PUT_U16(msg, NL80211_ATTR_BG_SCAN_PERIOD,
9148                             params->bg_scan_period);
9149         }
9150
9151         if (params->ssid) {
9152                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
9153                                   params->ssid, params->ssid_len);
9154                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
9155                         params->ssid);
9156                 if (params->ssid_len > sizeof(drv->ssid))
9157                         goto nla_put_failure;
9158                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
9159                 drv->ssid_len = params->ssid_len;
9160         }
9161
9162         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
9163         if (params->wpa_ie)
9164                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
9165                         params->wpa_ie);
9166
9167         if (params->wpa_proto) {
9168                 enum nl80211_wpa_versions ver = 0;
9169
9170                 if (params->wpa_proto & WPA_PROTO_WPA)
9171                         ver |= NL80211_WPA_VERSION_1;
9172                 if (params->wpa_proto & WPA_PROTO_RSN)
9173                         ver |= NL80211_WPA_VERSION_2;
9174
9175                 wpa_printf(MSG_DEBUG, "  * WPA Versions 0x%x", ver);
9176                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
9177         }
9178
9179         if (params->pairwise_suite != WPA_CIPHER_NONE) {
9180                 u32 cipher = wpa_cipher_to_cipher_suite(params->pairwise_suite);
9181                 wpa_printf(MSG_DEBUG, "  * pairwise=0x%x", cipher);
9182                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
9183         }
9184
9185         if (params->group_suite == WPA_CIPHER_GTK_NOT_USED &&
9186             !(drv->capa.enc & WPA_DRIVER_CAPA_ENC_GTK_NOT_USED)) {
9187                 /*
9188                  * This is likely to work even though many drivers do not
9189                  * advertise support for operations without GTK.
9190                  */
9191                 wpa_printf(MSG_DEBUG, "  * skip group cipher configuration for GTK_NOT_USED due to missing driver support advertisement");
9192         } else if (params->group_suite != WPA_CIPHER_NONE) {
9193                 u32 cipher = wpa_cipher_to_cipher_suite(params->group_suite);
9194                 wpa_printf(MSG_DEBUG, "  * group=0x%x", cipher);
9195                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
9196         }
9197
9198         if (params->key_mgmt_suite == WPA_KEY_MGMT_IEEE8021X ||
9199             params->key_mgmt_suite == WPA_KEY_MGMT_PSK ||
9200             params->key_mgmt_suite == WPA_KEY_MGMT_FT_IEEE8021X ||
9201             params->key_mgmt_suite == WPA_KEY_MGMT_FT_PSK ||
9202             params->key_mgmt_suite == WPA_KEY_MGMT_CCKM ||
9203             params->key_mgmt_suite == WPA_KEY_MGMT_OSEN ||
9204             params->key_mgmt_suite == WPA_KEY_MGMT_IEEE8021X_SHA256 ||
9205             params->key_mgmt_suite == WPA_KEY_MGMT_PSK_SHA256) {
9206                 int mgmt = WLAN_AKM_SUITE_PSK;
9207
9208                 switch (params->key_mgmt_suite) {
9209                 case WPA_KEY_MGMT_CCKM:
9210                         mgmt = WLAN_AKM_SUITE_CCKM;
9211                         break;
9212                 case WPA_KEY_MGMT_IEEE8021X:
9213                         mgmt = WLAN_AKM_SUITE_8021X;
9214                         break;
9215                 case WPA_KEY_MGMT_FT_IEEE8021X:
9216                         mgmt = WLAN_AKM_SUITE_FT_8021X;
9217                         break;
9218                 case WPA_KEY_MGMT_FT_PSK:
9219                         mgmt = WLAN_AKM_SUITE_FT_PSK;
9220                         break;
9221                 case WPA_KEY_MGMT_IEEE8021X_SHA256:
9222                         mgmt = WLAN_AKM_SUITE_8021X_SHA256;
9223                         break;
9224                 case WPA_KEY_MGMT_PSK_SHA256:
9225                         mgmt = WLAN_AKM_SUITE_PSK_SHA256;
9226                         break;
9227                 case WPA_KEY_MGMT_OSEN:
9228                         mgmt = WLAN_AKM_SUITE_OSEN;
9229                         break;
9230                 case WPA_KEY_MGMT_PSK:
9231                 default:
9232                         mgmt = WLAN_AKM_SUITE_PSK;
9233                         break;
9234                 }
9235                 wpa_printf(MSG_DEBUG, "  * akm=0x%x", mgmt);
9236                 NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
9237         }
9238
9239         NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
9240
9241         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
9242                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
9243
9244         if (params->disable_ht)
9245                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
9246
9247         if (params->htcaps && params->htcaps_mask) {
9248                 int sz = sizeof(struct ieee80211_ht_capabilities);
9249                 wpa_hexdump(MSG_DEBUG, "  * htcaps", params->htcaps, sz);
9250                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
9251                 wpa_hexdump(MSG_DEBUG, "  * htcaps_mask",
9252                             params->htcaps_mask, sz);
9253                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
9254                         params->htcaps_mask);
9255         }
9256
9257 #ifdef CONFIG_VHT_OVERRIDES
9258         if (params->disable_vht) {
9259                 wpa_printf(MSG_DEBUG, "  * VHT disabled");
9260                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_VHT);
9261         }
9262
9263         if (params->vhtcaps && params->vhtcaps_mask) {
9264                 int sz = sizeof(struct ieee80211_vht_capabilities);
9265                 wpa_hexdump(MSG_DEBUG, "  * vhtcaps", params->vhtcaps, sz);
9266                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY, sz, params->vhtcaps);
9267                 wpa_hexdump(MSG_DEBUG, "  * vhtcaps_mask",
9268                             params->vhtcaps_mask, sz);
9269                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY_MASK, sz,
9270                         params->vhtcaps_mask);
9271         }
9272 #endif /* CONFIG_VHT_OVERRIDES */
9273
9274         if (params->p2p)
9275                 wpa_printf(MSG_DEBUG, "  * P2P group");
9276
9277         return 0;
9278 nla_put_failure:
9279         return -1;
9280 }
9281
9282
9283 static int wpa_driver_nl80211_try_connect(
9284         struct wpa_driver_nl80211_data *drv,
9285         struct wpa_driver_associate_params *params)
9286 {
9287         struct nl_msg *msg;
9288         enum nl80211_auth_type type;
9289         int ret;
9290         int algs;
9291
9292         if (params->req_key_mgmt_offload && params->psk &&
9293             (params->key_mgmt_suite == WPA_KEY_MGMT_PSK ||
9294              params->key_mgmt_suite == WPA_KEY_MGMT_PSK_SHA256 ||
9295              params->key_mgmt_suite == WPA_KEY_MGMT_FT_PSK)) {
9296                 wpa_printf(MSG_DEBUG, "nl80211: Key management set PSK");
9297                 ret = issue_key_mgmt_set_key(drv, params->psk, 32);
9298                 if (ret)
9299                         return ret;
9300         }
9301
9302         msg = nlmsg_alloc();
9303         if (!msg)
9304                 return -1;
9305
9306         wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
9307         nl80211_cmd(drv, msg, 0, NL80211_CMD_CONNECT);
9308
9309         ret = nl80211_connect_common(drv, params, msg);
9310         if (ret)
9311                 goto nla_put_failure;
9312
9313         algs = 0;
9314         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
9315                 algs++;
9316         if (params->auth_alg & WPA_AUTH_ALG_SHARED)
9317                 algs++;
9318         if (params->auth_alg & WPA_AUTH_ALG_LEAP)
9319                 algs++;
9320         if (algs > 1) {
9321                 wpa_printf(MSG_DEBUG, "  * Leave out Auth Type for automatic "
9322                            "selection");
9323                 goto skip_auth_type;
9324         }
9325
9326         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
9327                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
9328         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
9329                 type = NL80211_AUTHTYPE_SHARED_KEY;
9330         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
9331                 type = NL80211_AUTHTYPE_NETWORK_EAP;
9332         else if (params->auth_alg & WPA_AUTH_ALG_FT)
9333                 type = NL80211_AUTHTYPE_FT;
9334         else
9335                 goto nla_put_failure;
9336
9337         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
9338         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
9339
9340 skip_auth_type:
9341         ret = nl80211_set_conn_keys(params, msg);
9342         if (ret)
9343                 goto nla_put_failure;
9344
9345         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9346         msg = NULL;
9347         if (ret) {
9348                 wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
9349                            "(%s)", ret, strerror(-ret));
9350                 goto nla_put_failure;
9351         }
9352         ret = 0;
9353         wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
9354
9355 nla_put_failure:
9356         nlmsg_free(msg);
9357         return ret;
9358
9359 }
9360
9361
9362 static int wpa_driver_nl80211_connect(
9363         struct wpa_driver_nl80211_data *drv,
9364         struct wpa_driver_associate_params *params)
9365 {
9366         int ret = wpa_driver_nl80211_try_connect(drv, params);
9367         if (ret == -EALREADY) {
9368                 /*
9369                  * cfg80211 does not currently accept new connections if
9370                  * we are already connected. As a workaround, force
9371                  * disconnection and try again.
9372                  */
9373                 wpa_printf(MSG_DEBUG, "nl80211: Explicitly "
9374                            "disconnecting before reassociation "
9375                            "attempt");
9376                 if (wpa_driver_nl80211_disconnect(
9377                             drv, WLAN_REASON_PREV_AUTH_NOT_VALID))
9378                         return -1;
9379                 ret = wpa_driver_nl80211_try_connect(drv, params);
9380         }
9381         return ret;
9382 }
9383
9384
9385 static int wpa_driver_nl80211_associate(
9386         void *priv, struct wpa_driver_associate_params *params)
9387 {
9388         struct i802_bss *bss = priv;
9389         struct wpa_driver_nl80211_data *drv = bss->drv;
9390         int ret;
9391         struct nl_msg *msg;
9392
9393         if (params->mode == IEEE80211_MODE_AP)
9394                 return wpa_driver_nl80211_ap(drv, params);
9395
9396         if (params->mode == IEEE80211_MODE_IBSS)
9397                 return wpa_driver_nl80211_ibss(drv, params);
9398
9399         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
9400                 enum nl80211_iftype nlmode = params->p2p ?
9401                         NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
9402
9403                 if (wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
9404                         return -1;
9405                 return wpa_driver_nl80211_connect(drv, params);
9406         }
9407
9408         nl80211_mark_disconnected(drv);
9409
9410         msg = nlmsg_alloc();
9411         if (!msg)
9412                 return -1;
9413
9414         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
9415                    drv->ifindex);
9416         nl80211_cmd(drv, msg, 0, NL80211_CMD_ASSOCIATE);
9417
9418         ret = nl80211_connect_common(drv, params, msg);
9419         if (ret)
9420                 goto nla_put_failure;
9421
9422         if (params->prev_bssid) {
9423                 wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
9424                            MAC2STR(params->prev_bssid));
9425                 NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
9426                         params->prev_bssid);
9427         }
9428
9429         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9430         msg = NULL;
9431         if (ret) {
9432                 wpa_dbg(drv->ctx, MSG_DEBUG,
9433                         "nl80211: MLME command failed (assoc): ret=%d (%s)",
9434                         ret, strerror(-ret));
9435                 nl80211_dump_scan(drv);
9436                 goto nla_put_failure;
9437         }
9438         ret = 0;
9439         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
9440                    "successfully");
9441
9442 nla_put_failure:
9443         nlmsg_free(msg);
9444         return ret;
9445 }
9446
9447
9448 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
9449                             int ifindex, enum nl80211_iftype mode)
9450 {
9451         struct nl_msg *msg;
9452         int ret = -ENOBUFS;
9453
9454         wpa_printf(MSG_DEBUG, "nl80211: Set mode ifindex %d iftype %d (%s)",
9455                    ifindex, mode, nl80211_iftype_str(mode));
9456
9457         msg = nlmsg_alloc();
9458         if (!msg)
9459                 return -ENOMEM;
9460
9461         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_INTERFACE);
9462         if (nl80211_set_iface_id(msg, drv->first_bss) < 0)
9463                 goto nla_put_failure;
9464         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
9465
9466         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9467         msg = NULL;
9468         if (!ret)
9469                 return 0;
9470 nla_put_failure:
9471         nlmsg_free(msg);
9472         wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
9473                    " %d (%s)", ifindex, mode, ret, strerror(-ret));
9474         return ret;
9475 }
9476
9477
9478 static int wpa_driver_nl80211_set_mode_impl(
9479                 struct i802_bss *bss,
9480                 enum nl80211_iftype nlmode,
9481                 struct hostapd_freq_params *desired_freq_params)
9482 {
9483         struct wpa_driver_nl80211_data *drv = bss->drv;
9484         int ret = -1;
9485         int i;
9486         int was_ap = is_ap_interface(drv->nlmode);
9487         int res;
9488         int mode_switch_res;
9489
9490         mode_switch_res = nl80211_set_mode(drv, drv->ifindex, nlmode);
9491         if (mode_switch_res && nlmode == nl80211_get_ifmode(bss))
9492                 mode_switch_res = 0;
9493
9494         if (mode_switch_res == 0) {
9495                 drv->nlmode = nlmode;
9496                 ret = 0;
9497                 goto done;
9498         }
9499
9500         if (mode_switch_res == -ENODEV)
9501                 return -1;
9502
9503         if (nlmode == drv->nlmode) {
9504                 wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
9505                            "requested mode - ignore error");
9506                 ret = 0;
9507                 goto done; /* Already in the requested mode */
9508         }
9509
9510         /* mac80211 doesn't allow mode changes while the device is up, so
9511          * take the device down, try to set the mode again, and bring the
9512          * device back up.
9513          */
9514         wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
9515                    "interface down");
9516         for (i = 0; i < 10; i++) {
9517                 res = i802_set_iface_flags(bss, 0);
9518                 if (res == -EACCES || res == -ENODEV)
9519                         break;
9520                 if (res != 0) {
9521                         wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
9522                                    "interface down");
9523                         os_sleep(0, 100000);
9524                         continue;
9525                 }
9526
9527                 /*
9528                  * Setting the mode will fail for some drivers if the phy is
9529                  * on a frequency that the mode is disallowed in.
9530                  */
9531                 if (desired_freq_params) {
9532                         res = i802_set_freq(bss, desired_freq_params);
9533                         if (res) {
9534                                 wpa_printf(MSG_DEBUG,
9535                                            "nl80211: Failed to set frequency on interface");
9536                         }
9537                 }
9538
9539                 /* Try to set the mode again while the interface is down */
9540                 mode_switch_res = nl80211_set_mode(drv, drv->ifindex, nlmode);
9541                 if (mode_switch_res == -EBUSY) {
9542                         wpa_printf(MSG_DEBUG,
9543                                    "nl80211: Delaying mode set while interface going down");
9544                         os_sleep(0, 100000);
9545                         continue;
9546                 }
9547                 ret = mode_switch_res;
9548                 break;
9549         }
9550
9551         if (!ret) {
9552                 wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
9553                            "interface is down");
9554                 drv->nlmode = nlmode;
9555                 drv->ignore_if_down_event = 1;
9556         }
9557
9558         /* Bring the interface back up */
9559         res = linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1);
9560         if (res != 0) {
9561                 wpa_printf(MSG_DEBUG,
9562                            "nl80211: Failed to set interface up after switching mode");
9563                 ret = -1;
9564         }
9565
9566 done:
9567         if (ret) {
9568                 wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
9569                            "from %d failed", nlmode, drv->nlmode);
9570                 return ret;
9571         }
9572
9573         if (is_p2p_net_interface(nlmode))
9574                 nl80211_disable_11b_rates(drv, drv->ifindex, 1);
9575         else if (drv->disabled_11b_rates)
9576                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
9577
9578         if (is_ap_interface(nlmode)) {
9579                 nl80211_mgmt_unsubscribe(bss, "start AP");
9580                 /* Setup additional AP mode functionality if needed */
9581                 if (nl80211_setup_ap(bss))
9582                         return -1;
9583         } else if (was_ap) {
9584                 /* Remove additional AP mode functionality */
9585                 nl80211_teardown_ap(bss);
9586         } else {
9587                 nl80211_mgmt_unsubscribe(bss, "mode change");
9588         }
9589
9590         if (is_mesh_interface(nlmode) &&
9591             nl80211_mgmt_subscribe_mesh(bss))
9592                 return -1;
9593
9594         if (!bss->in_deinit && !is_ap_interface(nlmode) &&
9595             !is_mesh_interface(nlmode) &&
9596             nl80211_mgmt_subscribe_non_ap(bss) < 0)
9597                 wpa_printf(MSG_DEBUG, "nl80211: Failed to register Action "
9598                            "frame processing - ignore for now");
9599
9600         return 0;
9601 }
9602
9603
9604 static int dfs_info_handler(struct nl_msg *msg, void *arg)
9605 {
9606         struct nlattr *tb[NL80211_ATTR_MAX + 1];
9607         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
9608         int *dfs_capability_ptr = arg;
9609
9610         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
9611                   genlmsg_attrlen(gnlh, 0), NULL);
9612
9613         if (tb[NL80211_ATTR_VENDOR_DATA]) {
9614                 struct nlattr *nl_vend = tb[NL80211_ATTR_VENDOR_DATA];
9615                 struct nlattr *tb_vendor[QCA_WLAN_VENDOR_ATTR_MAX + 1];
9616
9617                 nla_parse(tb_vendor, QCA_WLAN_VENDOR_ATTR_MAX,
9618                           nla_data(nl_vend), nla_len(nl_vend), NULL);
9619
9620                 if (tb_vendor[QCA_WLAN_VENDOR_ATTR_DFS]) {
9621                         u32 val;
9622                         val = nla_get_u32(tb_vendor[QCA_WLAN_VENDOR_ATTR_DFS]);
9623                         wpa_printf(MSG_DEBUG, "nl80211: DFS offload capability: %u",
9624                                    val);
9625                         *dfs_capability_ptr = val;
9626                 }
9627         }
9628
9629         return NL_SKIP;
9630 }
9631
9632
9633 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
9634                                        enum nl80211_iftype nlmode)
9635 {
9636         return wpa_driver_nl80211_set_mode_impl(bss, nlmode, NULL);
9637 }
9638
9639
9640 static int wpa_driver_nl80211_set_mode_ibss(struct i802_bss *bss,
9641                                             struct hostapd_freq_params *freq)
9642 {
9643         return wpa_driver_nl80211_set_mode_impl(bss, NL80211_IFTYPE_ADHOC,
9644                                                 freq);
9645 }
9646
9647
9648 static int wpa_driver_nl80211_get_capa(void *priv,
9649                                        struct wpa_driver_capa *capa)
9650 {
9651         struct i802_bss *bss = priv;
9652         struct wpa_driver_nl80211_data *drv = bss->drv;
9653         struct nl_msg *msg;
9654         int dfs_capability = 0;
9655         int ret = 0;
9656
9657         if (!drv->has_capability)
9658                 return -1;
9659         os_memcpy(capa, &drv->capa, sizeof(*capa));
9660         if (drv->extended_capa && drv->extended_capa_mask) {
9661                 capa->extended_capa = drv->extended_capa;
9662                 capa->extended_capa_mask = drv->extended_capa_mask;
9663                 capa->extended_capa_len = drv->extended_capa_len;
9664         }
9665
9666         if (drv->dfs_vendor_cmd_avail == 1) {
9667                 msg = nlmsg_alloc();
9668                 if (!msg)
9669                         return -ENOMEM;
9670
9671                 nl80211_cmd(drv, msg, 0, NL80211_CMD_VENDOR);
9672
9673                 NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9674                 NLA_PUT_U32(msg, NL80211_ATTR_VENDOR_ID, OUI_QCA);
9675                 NLA_PUT_U32(msg, NL80211_ATTR_VENDOR_SUBCMD,
9676                             QCA_NL80211_VENDOR_SUBCMD_DFS_CAPABILITY);
9677
9678                 ret = send_and_recv_msgs(drv, msg, dfs_info_handler,
9679                                          &dfs_capability);
9680                 if (!ret) {
9681                         if (dfs_capability)
9682                                 capa->flags |= WPA_DRIVER_FLAGS_DFS_OFFLOAD;
9683                 }
9684         }
9685
9686         return ret;
9687
9688  nla_put_failure:
9689         nlmsg_free(msg);
9690         return -ENOBUFS;
9691 }
9692
9693
9694 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
9695 {
9696         struct i802_bss *bss = priv;
9697         struct wpa_driver_nl80211_data *drv = bss->drv;
9698
9699         wpa_printf(MSG_DEBUG, "nl80211: Set %s operstate %d->%d (%s)",
9700                    bss->ifname, drv->operstate, state,
9701                    state ? "UP" : "DORMANT");
9702         drv->operstate = state;
9703         return netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, -1,
9704                                       state ? IF_OPER_UP : IF_OPER_DORMANT);
9705 }
9706
9707
9708 static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
9709 {
9710         struct i802_bss *bss = priv;
9711         struct wpa_driver_nl80211_data *drv = bss->drv;
9712         struct nl_msg *msg;
9713         struct nl80211_sta_flag_update upd;
9714         int ret = -ENOBUFS;
9715
9716         if (!drv->associated && is_zero_ether_addr(drv->bssid) && !authorized) {
9717                 wpa_printf(MSG_DEBUG, "nl80211: Skip set_supp_port(unauthorized) while not associated");
9718                 return 0;
9719         }
9720
9721         wpa_printf(MSG_DEBUG, "nl80211: Set supplicant port %sauthorized for "
9722                    MACSTR, authorized ? "" : "un", MAC2STR(drv->bssid));
9723
9724         msg = nlmsg_alloc();
9725         if (!msg)
9726                 return -ENOMEM;
9727
9728         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
9729
9730         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
9731                     if_nametoindex(bss->ifname));
9732         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
9733
9734         os_memset(&upd, 0, sizeof(upd));
9735         upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
9736         if (authorized)
9737                 upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
9738         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
9739
9740         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9741         msg = NULL;
9742         if (!ret)
9743                 return 0;
9744  nla_put_failure:
9745         nlmsg_free(msg);
9746         wpa_printf(MSG_DEBUG, "nl80211: Failed to set STA flag: %d (%s)",
9747                    ret, strerror(-ret));
9748         return ret;
9749 }
9750
9751
9752 /* Set kernel driver on given frequency (MHz) */
9753 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
9754 {
9755         struct i802_bss *bss = priv;
9756         return nl80211_set_channel(bss, freq, 0);
9757 }
9758
9759
9760 static inline int min_int(int a, int b)
9761 {
9762         if (a < b)
9763                 return a;
9764         return b;
9765 }
9766
9767
9768 static int get_key_handler(struct nl_msg *msg, void *arg)
9769 {
9770         struct nlattr *tb[NL80211_ATTR_MAX + 1];
9771         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
9772
9773         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
9774                   genlmsg_attrlen(gnlh, 0), NULL);
9775
9776         /*
9777          * TODO: validate the key index and mac address!
9778          * Otherwise, there's a race condition as soon as
9779          * the kernel starts sending key notifications.
9780          */
9781
9782         if (tb[NL80211_ATTR_KEY_SEQ])
9783                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
9784                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
9785         return NL_SKIP;
9786 }
9787
9788
9789 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
9790                            int idx, u8 *seq)
9791 {
9792         struct i802_bss *bss = priv;
9793         struct wpa_driver_nl80211_data *drv = bss->drv;
9794         struct nl_msg *msg;
9795
9796         msg = nlmsg_alloc();
9797         if (!msg)
9798                 return -ENOMEM;
9799
9800         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_KEY);
9801
9802         if (addr)
9803                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
9804         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
9805         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
9806
9807         memset(seq, 0, 6);
9808
9809         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
9810  nla_put_failure:
9811         nlmsg_free(msg);
9812         return -ENOBUFS;
9813 }
9814
9815
9816 static int i802_set_rts(void *priv, int rts)
9817 {
9818         struct i802_bss *bss = priv;
9819         struct wpa_driver_nl80211_data *drv = bss->drv;
9820         struct nl_msg *msg;
9821         int ret = -ENOBUFS;
9822         u32 val;
9823
9824         msg = nlmsg_alloc();
9825         if (!msg)
9826                 return -ENOMEM;
9827
9828         if (rts >= 2347)
9829                 val = (u32) -1;
9830         else
9831                 val = rts;
9832
9833         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
9834         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9835         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
9836
9837         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9838         msg = NULL;
9839         if (!ret)
9840                 return 0;
9841 nla_put_failure:
9842         nlmsg_free(msg);
9843         wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
9844                    "%d (%s)", rts, ret, strerror(-ret));
9845         return ret;
9846 }
9847
9848
9849 static int i802_set_frag(void *priv, int frag)
9850 {
9851         struct i802_bss *bss = priv;
9852         struct wpa_driver_nl80211_data *drv = bss->drv;
9853         struct nl_msg *msg;
9854         int ret = -ENOBUFS;
9855         u32 val;
9856
9857         msg = nlmsg_alloc();
9858         if (!msg)
9859                 return -ENOMEM;
9860
9861         if (frag >= 2346)
9862                 val = (u32) -1;
9863         else
9864                 val = frag;
9865
9866         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
9867         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9868         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
9869
9870         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9871         msg = NULL;
9872         if (!ret)
9873                 return 0;
9874 nla_put_failure:
9875         nlmsg_free(msg);
9876         wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
9877                    "%d: %d (%s)", frag, ret, strerror(-ret));
9878         return ret;
9879 }
9880
9881
9882 static int i802_flush(void *priv)
9883 {
9884         struct i802_bss *bss = priv;
9885         struct wpa_driver_nl80211_data *drv = bss->drv;
9886         struct nl_msg *msg;
9887         int res;
9888
9889         msg = nlmsg_alloc();
9890         if (!msg)
9891                 return -1;
9892
9893         wpa_printf(MSG_DEBUG, "nl80211: flush -> DEL_STATION %s (all)",
9894                    bss->ifname);
9895         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
9896
9897         /*
9898          * XXX: FIX! this needs to flush all VLANs too
9899          */
9900         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
9901                     if_nametoindex(bss->ifname));
9902
9903         res = send_and_recv_msgs(drv, msg, NULL, NULL);
9904         if (res) {
9905                 wpa_printf(MSG_DEBUG, "nl80211: Station flush failed: ret=%d "
9906                            "(%s)", res, strerror(-res));
9907         }
9908         return res;
9909  nla_put_failure:
9910         nlmsg_free(msg);
9911         return -ENOBUFS;
9912 }
9913
9914
9915 static int get_sta_handler(struct nl_msg *msg, void *arg)
9916 {
9917         struct nlattr *tb[NL80211_ATTR_MAX + 1];
9918         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
9919         struct hostap_sta_driver_data *data = arg;
9920         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
9921         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
9922                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
9923                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
9924                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
9925                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
9926                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
9927                 [NL80211_STA_INFO_TX_FAILED] = { .type = NLA_U32 },
9928         };
9929
9930         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
9931                   genlmsg_attrlen(gnlh, 0), NULL);
9932
9933         /*
9934          * TODO: validate the interface and mac address!
9935          * Otherwise, there's a race condition as soon as
9936          * the kernel starts sending station notifications.
9937          */
9938
9939         if (!tb[NL80211_ATTR_STA_INFO]) {
9940                 wpa_printf(MSG_DEBUG, "sta stats missing!");
9941                 return NL_SKIP;
9942         }
9943         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
9944                              tb[NL80211_ATTR_STA_INFO],
9945                              stats_policy)) {
9946                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
9947                 return NL_SKIP;
9948         }
9949
9950         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
9951                 data->inactive_msec =
9952                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
9953         if (stats[NL80211_STA_INFO_RX_BYTES])
9954                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
9955         if (stats[NL80211_STA_INFO_TX_BYTES])
9956                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
9957         if (stats[NL80211_STA_INFO_RX_PACKETS])
9958                 data->rx_packets =
9959                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
9960         if (stats[NL80211_STA_INFO_TX_PACKETS])
9961                 data->tx_packets =
9962                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
9963         if (stats[NL80211_STA_INFO_TX_FAILED])
9964                 data->tx_retry_failed =
9965                         nla_get_u32(stats[NL80211_STA_INFO_TX_FAILED]);
9966
9967         return NL_SKIP;
9968 }
9969
9970 static int i802_read_sta_data(struct i802_bss *bss,
9971                               struct hostap_sta_driver_data *data,
9972                               const u8 *addr)
9973 {
9974         struct wpa_driver_nl80211_data *drv = bss->drv;
9975         struct nl_msg *msg;
9976
9977         os_memset(data, 0, sizeof(*data));
9978         msg = nlmsg_alloc();
9979         if (!msg)
9980                 return -ENOMEM;
9981
9982         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
9983
9984         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
9985         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
9986
9987         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
9988  nla_put_failure:
9989         nlmsg_free(msg);
9990         return -ENOBUFS;
9991 }
9992
9993
9994 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
9995                                     int cw_min, int cw_max, int burst_time)
9996 {
9997         struct i802_bss *bss = priv;
9998         struct wpa_driver_nl80211_data *drv = bss->drv;
9999         struct nl_msg *msg;
10000         struct nlattr *txq, *params;
10001
10002         msg = nlmsg_alloc();
10003         if (!msg)
10004                 return -1;
10005
10006         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
10007
10008         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
10009
10010         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
10011         if (!txq)
10012                 goto nla_put_failure;
10013
10014         /* We are only sending parameters for a single TXQ at a time */
10015         params = nla_nest_start(msg, 1);
10016         if (!params)
10017                 goto nla_put_failure;
10018
10019         switch (queue) {
10020         case 0:
10021                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
10022                 break;
10023         case 1:
10024                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
10025                 break;
10026         case 2:
10027                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
10028                 break;
10029         case 3:
10030                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
10031                 break;
10032         }
10033         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
10034          * 32 usec, so need to convert the value here. */
10035         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
10036         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
10037         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
10038         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
10039
10040         nla_nest_end(msg, params);
10041
10042         nla_nest_end(msg, txq);
10043
10044         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
10045                 return 0;
10046         msg = NULL;
10047  nla_put_failure:
10048         nlmsg_free(msg);
10049         return -1;
10050 }
10051
10052
10053 static int i802_set_sta_vlan(struct i802_bss *bss, const u8 *addr,
10054                              const char *ifname, int vlan_id)
10055 {
10056         struct wpa_driver_nl80211_data *drv = bss->drv;
10057         struct nl_msg *msg;
10058         int ret = -ENOBUFS;
10059
10060         msg = nlmsg_alloc();
10061         if (!msg)
10062                 return -ENOMEM;
10063
10064         wpa_printf(MSG_DEBUG, "nl80211: %s[%d]: set_sta_vlan(" MACSTR
10065                    ", ifname=%s[%d], vlan_id=%d)",
10066                    bss->ifname, if_nametoindex(bss->ifname),
10067                    MAC2STR(addr), ifname, if_nametoindex(ifname), vlan_id);
10068         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
10069
10070         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
10071                     if_nametoindex(bss->ifname));
10072         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
10073         NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
10074                     if_nametoindex(ifname));
10075
10076         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
10077         msg = NULL;
10078         if (ret < 0) {
10079                 wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
10080                            MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
10081                            MAC2STR(addr), ifname, vlan_id, ret,
10082                            strerror(-ret));
10083         }
10084  nla_put_failure:
10085         nlmsg_free(msg);
10086         return ret;
10087 }
10088
10089
10090 static int i802_get_inact_sec(void *priv, const u8 *addr)
10091 {
10092         struct hostap_sta_driver_data data;
10093         int ret;
10094
10095         data.inactive_msec = (unsigned long) -1;
10096         ret = i802_read_sta_data(priv, &data, addr);
10097         if (ret || data.inactive_msec == (unsigned long) -1)
10098                 return -1;
10099         return data.inactive_msec / 1000;
10100 }
10101
10102
10103 static int i802_sta_clear_stats(void *priv, const u8 *addr)
10104 {
10105 #if 0
10106         /* TODO */
10107 #endif
10108         return 0;
10109 }
10110
10111
10112 static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
10113                            int reason)
10114 {
10115         struct i802_bss *bss = priv;
10116         struct wpa_driver_nl80211_data *drv = bss->drv;
10117         struct ieee80211_mgmt mgmt;
10118
10119         if (is_mesh_interface(drv->nlmode))
10120                 return -1;
10121
10122         if (drv->device_ap_sme)
10123                 return wpa_driver_nl80211_sta_remove(bss, addr, 1, reason);
10124
10125         memset(&mgmt, 0, sizeof(mgmt));
10126         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
10127                                           WLAN_FC_STYPE_DEAUTH);
10128         memcpy(mgmt.da, addr, ETH_ALEN);
10129         memcpy(mgmt.sa, own_addr, ETH_ALEN);
10130         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
10131         mgmt.u.deauth.reason_code = host_to_le16(reason);
10132         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
10133                                             IEEE80211_HDRLEN +
10134                                             sizeof(mgmt.u.deauth), 0, 0, 0, 0,
10135                                             0);
10136 }
10137
10138
10139 static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
10140                              int reason)
10141 {
10142         struct i802_bss *bss = priv;
10143         struct wpa_driver_nl80211_data *drv = bss->drv;
10144         struct ieee80211_mgmt mgmt;
10145
10146         if (is_mesh_interface(drv->nlmode))
10147                 return -1;
10148
10149         if (drv->device_ap_sme)
10150                 return wpa_driver_nl80211_sta_remove(bss, addr, 0, reason);
10151
10152         memset(&mgmt, 0, sizeof(mgmt));
10153         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
10154                                           WLAN_FC_STYPE_DISASSOC);
10155         memcpy(mgmt.da, addr, ETH_ALEN);
10156         memcpy(mgmt.sa, own_addr, ETH_ALEN);
10157         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
10158         mgmt.u.disassoc.reason_code = host_to_le16(reason);
10159         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
10160                                             IEEE80211_HDRLEN +
10161                                             sizeof(mgmt.u.disassoc), 0, 0, 0, 0,
10162                                             0);
10163 }
10164
10165
10166 static void dump_ifidx(struct wpa_driver_nl80211_data *drv)
10167 {
10168         char buf[200], *pos, *end;
10169         int i, res;
10170
10171         pos = buf;
10172         end = pos + sizeof(buf);
10173
10174         for (i = 0; i < drv->num_if_indices; i++) {
10175                 if (!drv->if_indices[i])
10176                         continue;
10177                 res = os_snprintf(pos, end - pos, " %d", drv->if_indices[i]);
10178                 if (res < 0 || res >= end - pos)
10179                         break;
10180                 pos += res;
10181         }
10182         *pos = '\0';
10183
10184         wpa_printf(MSG_DEBUG, "nl80211: if_indices[%d]:%s",
10185                    drv->num_if_indices, buf);
10186 }
10187
10188
10189 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
10190 {
10191         int i;
10192         int *old;
10193
10194         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
10195                    ifidx);
10196         if (have_ifidx(drv, ifidx)) {
10197                 wpa_printf(MSG_DEBUG, "nl80211: ifindex %d already in the list",
10198                            ifidx);
10199                 return;
10200         }
10201         for (i = 0; i < drv->num_if_indices; i++) {
10202                 if (drv->if_indices[i] == 0) {
10203                         drv->if_indices[i] = ifidx;
10204                         dump_ifidx(drv);
10205                         return;
10206                 }
10207         }
10208
10209         if (drv->if_indices != drv->default_if_indices)
10210                 old = drv->if_indices;
10211         else
10212                 old = NULL;
10213
10214         drv->if_indices = os_realloc_array(old, drv->num_if_indices + 1,
10215                                            sizeof(int));
10216         if (!drv->if_indices) {
10217                 if (!old)
10218                         drv->if_indices = drv->default_if_indices;
10219                 else
10220                         drv->if_indices = old;
10221                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
10222                            "interfaces");
10223                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
10224                 return;
10225         } else if (!old)
10226                 os_memcpy(drv->if_indices, drv->default_if_indices,
10227                           sizeof(drv->default_if_indices));
10228         drv->if_indices[drv->num_if_indices] = ifidx;
10229         drv->num_if_indices++;
10230         dump_ifidx(drv);
10231 }
10232
10233
10234 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
10235 {
10236         int i;
10237
10238         for (i = 0; i < drv->num_if_indices; i++) {
10239                 if (drv->if_indices[i] == ifidx) {
10240                         drv->if_indices[i] = 0;
10241                         break;
10242                 }
10243         }
10244         dump_ifidx(drv);
10245 }
10246
10247
10248 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
10249 {
10250         int i;
10251
10252         for (i = 0; i < drv->num_if_indices; i++)
10253                 if (drv->if_indices[i] == ifidx)
10254                         return 1;
10255
10256         return 0;
10257 }
10258
10259
10260 static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
10261                             const char *bridge_ifname, char *ifname_wds)
10262 {
10263         struct i802_bss *bss = priv;
10264         struct wpa_driver_nl80211_data *drv = bss->drv;
10265         char name[IFNAMSIZ + 1];
10266
10267         os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
10268         if (ifname_wds)
10269                 os_strlcpy(ifname_wds, name, IFNAMSIZ + 1);
10270
10271         wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
10272                    " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
10273         if (val) {
10274                 if (!if_nametoindex(name)) {
10275                         if (nl80211_create_iface(drv, name,
10276                                                  NL80211_IFTYPE_AP_VLAN,
10277                                                  bss->addr, 1, NULL, NULL, 0) <
10278                             0)
10279                                 return -1;
10280                         if (bridge_ifname &&
10281                             linux_br_add_if(drv->global->ioctl_sock,
10282                                             bridge_ifname, name) < 0)
10283                                 return -1;
10284                 }
10285                 if (linux_set_iface_flags(drv->global->ioctl_sock, name, 1)) {
10286                         wpa_printf(MSG_ERROR, "nl80211: Failed to set WDS STA "
10287                                    "interface %s up", name);
10288                 }
10289                 return i802_set_sta_vlan(priv, addr, name, 0);
10290         } else {
10291                 if (bridge_ifname)
10292                         linux_br_del_if(drv->global->ioctl_sock, bridge_ifname,
10293                                         name);
10294
10295                 i802_set_sta_vlan(priv, addr, bss->ifname, 0);
10296                 nl80211_remove_iface(drv, if_nametoindex(name));
10297                 return 0;
10298         }
10299 }
10300
10301
10302 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
10303 {
10304         struct wpa_driver_nl80211_data *drv = eloop_ctx;
10305         struct sockaddr_ll lladdr;
10306         unsigned char buf[3000];
10307         int len;
10308         socklen_t fromlen = sizeof(lladdr);
10309
10310         len = recvfrom(sock, buf, sizeof(buf), 0,
10311                        (struct sockaddr *)&lladdr, &fromlen);
10312         if (len < 0) {
10313                 wpa_printf(MSG_ERROR, "nl80211: EAPOL recv failed: %s",
10314                            strerror(errno));
10315                 return;
10316         }
10317
10318         if (have_ifidx(drv, lladdr.sll_ifindex))
10319                 drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
10320 }
10321
10322
10323 static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
10324                              struct i802_bss *bss,
10325                              const char *brname, const char *ifname)
10326 {
10327         int ifindex;
10328         char in_br[IFNAMSIZ];
10329
10330         os_strlcpy(bss->brname, brname, IFNAMSIZ);
10331         ifindex = if_nametoindex(brname);
10332         if (ifindex == 0) {
10333                 /*
10334                  * Bridge was configured, but the bridge device does
10335                  * not exist. Try to add it now.
10336                  */
10337                 if (linux_br_add(drv->global->ioctl_sock, brname) < 0) {
10338                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
10339                                    "bridge interface %s: %s",
10340                                    brname, strerror(errno));
10341                         return -1;
10342                 }
10343                 bss->added_bridge = 1;
10344                 add_ifidx(drv, if_nametoindex(brname));
10345         }
10346
10347         if (linux_br_get(in_br, ifname) == 0) {
10348                 if (os_strcmp(in_br, brname) == 0)
10349                         return 0; /* already in the bridge */
10350
10351                 wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
10352                            "bridge %s", ifname, in_br);
10353                 if (linux_br_del_if(drv->global->ioctl_sock, in_br, ifname) <
10354                     0) {
10355                         wpa_printf(MSG_ERROR, "nl80211: Failed to "
10356                                    "remove interface %s from bridge "
10357                                    "%s: %s",
10358                                    ifname, brname, strerror(errno));
10359                         return -1;
10360                 }
10361         }
10362
10363         wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
10364                    ifname, brname);
10365         if (linux_br_add_if(drv->global->ioctl_sock, brname, ifname) < 0) {
10366                 wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
10367                            "into bridge %s: %s",
10368                            ifname, brname, strerror(errno));
10369                 return -1;
10370         }
10371         bss->added_if_into_bridge = 1;
10372
10373         return 0;
10374 }
10375
10376
10377 static void *i802_init(struct hostapd_data *hapd,
10378                        struct wpa_init_params *params)
10379 {
10380         struct wpa_driver_nl80211_data *drv;
10381         struct i802_bss *bss;
10382         size_t i;
10383         char brname[IFNAMSIZ];
10384         int ifindex, br_ifindex;
10385         int br_added = 0;
10386
10387         bss = wpa_driver_nl80211_drv_init(hapd, params->ifname,
10388                                           params->global_priv, 1,
10389                                           params->bssid);
10390         if (bss == NULL)
10391                 return NULL;
10392
10393         drv = bss->drv;
10394
10395         if (linux_br_get(brname, params->ifname) == 0) {
10396                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
10397                            params->ifname, brname);
10398                 br_ifindex = if_nametoindex(brname);
10399         } else {
10400                 brname[0] = '\0';
10401                 br_ifindex = 0;
10402         }
10403
10404         for (i = 0; i < params->num_bridge; i++) {
10405                 if (params->bridge[i]) {
10406                         ifindex = if_nametoindex(params->bridge[i]);
10407                         if (ifindex)
10408                                 add_ifidx(drv, ifindex);
10409                         if (ifindex == br_ifindex)
10410                                 br_added = 1;
10411                 }
10412         }
10413         if (!br_added && br_ifindex &&
10414             (params->num_bridge == 0 || !params->bridge[0]))
10415                 add_ifidx(drv, br_ifindex);
10416
10417         /* start listening for EAPOL on the default AP interface */
10418         add_ifidx(drv, drv->ifindex);
10419
10420         if (params->num_bridge && params->bridge[0] &&
10421             i802_check_bridge(drv, bss, params->bridge[0], params->ifname) < 0)
10422                 goto failed;
10423
10424 #ifdef CONFIG_LIBNL3_ROUTE
10425         if (bss->added_if_into_bridge) {
10426                 drv->rtnl_sk = nl_socket_alloc();
10427                 if (drv->rtnl_sk == NULL) {
10428                         wpa_printf(MSG_ERROR, "nl80211: Failed to allocate nl_sock");
10429                         goto failed;
10430                 }
10431
10432                 if (nl_connect(drv->rtnl_sk, NETLINK_ROUTE)) {
10433                         wpa_printf(MSG_ERROR, "nl80211: Failed to connect nl_sock to NETLINK_ROUTE: %s",
10434                                    strerror(errno));
10435                         goto failed;
10436                 }
10437         }
10438 #endif /* CONFIG_LIBNL3_ROUTE */
10439
10440         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
10441         if (drv->eapol_sock < 0) {
10442                 wpa_printf(MSG_ERROR, "nl80211: socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE) failed: %s",
10443                            strerror(errno));
10444                 goto failed;
10445         }
10446
10447         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
10448         {
10449                 wpa_printf(MSG_INFO, "nl80211: Could not register read socket for eapol");
10450                 goto failed;
10451         }
10452
10453         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
10454                                params->own_addr))
10455                 goto failed;
10456         os_memcpy(drv->perm_addr, params->own_addr, ETH_ALEN);
10457
10458         memcpy(bss->addr, params->own_addr, ETH_ALEN);
10459
10460         return bss;
10461
10462 failed:
10463         wpa_driver_nl80211_deinit(bss);
10464         return NULL;
10465 }
10466
10467
10468 static void i802_deinit(void *priv)
10469 {
10470         struct i802_bss *bss = priv;
10471         wpa_driver_nl80211_deinit(bss);
10472 }
10473
10474
10475 static enum nl80211_iftype wpa_driver_nl80211_if_type(
10476         enum wpa_driver_if_type type)
10477 {
10478         switch (type) {
10479         case WPA_IF_STATION:
10480                 return NL80211_IFTYPE_STATION;
10481         case WPA_IF_P2P_CLIENT:
10482         case WPA_IF_P2P_GROUP:
10483                 return NL80211_IFTYPE_P2P_CLIENT;
10484         case WPA_IF_AP_VLAN:
10485                 return NL80211_IFTYPE_AP_VLAN;
10486         case WPA_IF_AP_BSS:
10487                 return NL80211_IFTYPE_AP;
10488         case WPA_IF_P2P_GO:
10489                 return NL80211_IFTYPE_P2P_GO;
10490         case WPA_IF_P2P_DEVICE:
10491                 return NL80211_IFTYPE_P2P_DEVICE;
10492         }
10493         return -1;
10494 }
10495
10496
10497 #ifdef CONFIG_P2P
10498
10499 static int nl80211_addr_in_use(struct nl80211_global *global, const u8 *addr)
10500 {
10501         struct wpa_driver_nl80211_data *drv;
10502         dl_list_for_each(drv, &global->interfaces,
10503                          struct wpa_driver_nl80211_data, list) {
10504                 if (os_memcmp(addr, drv->first_bss->addr, ETH_ALEN) == 0)
10505                         return 1;
10506         }
10507         return 0;
10508 }
10509
10510
10511 static int nl80211_p2p_interface_addr(struct wpa_driver_nl80211_data *drv,
10512                                       u8 *new_addr)
10513 {
10514         unsigned int idx;
10515
10516         if (!drv->global)
10517                 return -1;
10518
10519         os_memcpy(new_addr, drv->first_bss->addr, ETH_ALEN);
10520         for (idx = 0; idx < 64; idx++) {
10521                 new_addr[0] = drv->first_bss->addr[0] | 0x02;
10522                 new_addr[0] ^= idx << 2;
10523                 if (!nl80211_addr_in_use(drv->global, new_addr))
10524                         break;
10525         }
10526         if (idx == 64)
10527                 return -1;
10528
10529         wpa_printf(MSG_DEBUG, "nl80211: Assigned new P2P Interface Address "
10530                    MACSTR, MAC2STR(new_addr));
10531
10532         return 0;
10533 }
10534
10535 #endif /* CONFIG_P2P */
10536
10537
10538 struct wdev_info {
10539         u64 wdev_id;
10540         int wdev_id_set;
10541         u8 macaddr[ETH_ALEN];
10542 };
10543
10544 static int nl80211_wdev_handler(struct nl_msg *msg, void *arg)
10545 {
10546         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
10547         struct nlattr *tb[NL80211_ATTR_MAX + 1];
10548         struct wdev_info *wi = arg;
10549
10550         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
10551                   genlmsg_attrlen(gnlh, 0), NULL);
10552         if (tb[NL80211_ATTR_WDEV]) {
10553                 wi->wdev_id = nla_get_u64(tb[NL80211_ATTR_WDEV]);
10554                 wi->wdev_id_set = 1;
10555         }
10556
10557         if (tb[NL80211_ATTR_MAC])
10558                 os_memcpy(wi->macaddr, nla_data(tb[NL80211_ATTR_MAC]),
10559                           ETH_ALEN);
10560
10561         return NL_SKIP;
10562 }
10563
10564
10565 static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
10566                                      const char *ifname, const u8 *addr,
10567                                      void *bss_ctx, void **drv_priv,
10568                                      char *force_ifname, u8 *if_addr,
10569                                      const char *bridge, int use_existing)
10570 {
10571         enum nl80211_iftype nlmode;
10572         struct i802_bss *bss = priv;
10573         struct wpa_driver_nl80211_data *drv = bss->drv;
10574         int ifidx;
10575         int added = 1;
10576
10577         if (addr)
10578                 os_memcpy(if_addr, addr, ETH_ALEN);
10579         nlmode = wpa_driver_nl80211_if_type(type);
10580         if (nlmode == NL80211_IFTYPE_P2P_DEVICE) {
10581                 struct wdev_info p2pdev_info;
10582
10583                 os_memset(&p2pdev_info, 0, sizeof(p2pdev_info));
10584                 ifidx = nl80211_create_iface(drv, ifname, nlmode, addr,
10585                                              0, nl80211_wdev_handler,
10586                                              &p2pdev_info, use_existing);
10587                 if (!p2pdev_info.wdev_id_set || ifidx != 0) {
10588                         wpa_printf(MSG_ERROR, "nl80211: Failed to create a P2P Device interface %s",
10589                                    ifname);
10590                         return -1;
10591                 }
10592
10593                 drv->global->if_add_wdevid = p2pdev_info.wdev_id;
10594                 drv->global->if_add_wdevid_set = p2pdev_info.wdev_id_set;
10595                 if (!is_zero_ether_addr(p2pdev_info.macaddr))
10596                         os_memcpy(if_addr, p2pdev_info.macaddr, ETH_ALEN);
10597                 wpa_printf(MSG_DEBUG, "nl80211: New P2P Device interface %s (0x%llx) created",
10598                            ifname,
10599                            (long long unsigned int) p2pdev_info.wdev_id);
10600         } else {
10601                 ifidx = nl80211_create_iface(drv, ifname, nlmode, addr,
10602                                              0, NULL, NULL, use_existing);
10603                 if (use_existing && ifidx == -ENFILE) {
10604                         added = 0;
10605                         ifidx = if_nametoindex(ifname);
10606                 } else if (ifidx < 0) {
10607                         return -1;
10608                 }
10609         }
10610
10611         if (!addr) {
10612                 if (drv->nlmode == NL80211_IFTYPE_P2P_DEVICE)
10613                         os_memcpy(if_addr, bss->addr, ETH_ALEN);
10614                 else if (linux_get_ifhwaddr(drv->global->ioctl_sock,
10615                                             bss->ifname, if_addr) < 0) {
10616                         if (added)
10617                                 nl80211_remove_iface(drv, ifidx);
10618                         return -1;
10619                 }
10620         }
10621
10622 #ifdef CONFIG_P2P
10623         if (!addr &&
10624             (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
10625              type == WPA_IF_P2P_GO)) {
10626                 /* Enforce unique P2P Interface Address */
10627                 u8 new_addr[ETH_ALEN];
10628
10629                 if (linux_get_ifhwaddr(drv->global->ioctl_sock, ifname,
10630                                        new_addr) < 0) {
10631                         if (added)
10632                                 nl80211_remove_iface(drv, ifidx);
10633                         return -1;
10634                 }
10635                 if (nl80211_addr_in_use(drv->global, new_addr)) {
10636                         wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
10637                                    "for P2P group interface");
10638                         if (nl80211_p2p_interface_addr(drv, new_addr) < 0) {
10639                                 if (added)
10640                                         nl80211_remove_iface(drv, ifidx);
10641                                 return -1;
10642                         }
10643                         if (linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
10644                                                new_addr) < 0) {
10645                                 if (added)
10646                                         nl80211_remove_iface(drv, ifidx);
10647                                 return -1;
10648                         }
10649                 }
10650                 os_memcpy(if_addr, new_addr, ETH_ALEN);
10651         }
10652 #endif /* CONFIG_P2P */
10653
10654         if (type == WPA_IF_AP_BSS) {
10655                 struct i802_bss *new_bss = os_zalloc(sizeof(*new_bss));
10656                 if (new_bss == NULL) {
10657                         if (added)
10658                                 nl80211_remove_iface(drv, ifidx);
10659                         return -1;
10660                 }
10661
10662                 if (bridge &&
10663                     i802_check_bridge(drv, new_bss, bridge, ifname) < 0) {
10664                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the new "
10665                                    "interface %s to a bridge %s",
10666                                    ifname, bridge);
10667                         if (added)
10668                                 nl80211_remove_iface(drv, ifidx);
10669                         os_free(new_bss);
10670                         return -1;
10671                 }
10672
10673                 if (linux_set_iface_flags(drv->global->ioctl_sock, ifname, 1))
10674                 {
10675                         if (added)
10676                                 nl80211_remove_iface(drv, ifidx);
10677                         os_free(new_bss);
10678                         return -1;
10679                 }
10680                 os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
10681                 os_memcpy(new_bss->addr, if_addr, ETH_ALEN);
10682                 new_bss->ifindex = ifidx;
10683                 new_bss->drv = drv;
10684                 new_bss->next = drv->first_bss->next;
10685                 new_bss->freq = drv->first_bss->freq;
10686                 new_bss->ctx = bss_ctx;
10687                 new_bss->added_if = added;
10688                 drv->first_bss->next = new_bss;
10689                 if (drv_priv)
10690                         *drv_priv = new_bss;
10691                 nl80211_init_bss(new_bss);
10692
10693                 /* Subscribe management frames for this WPA_IF_AP_BSS */
10694                 if (nl80211_setup_ap(new_bss))
10695                         return -1;
10696         }
10697
10698         if (drv->global)
10699                 drv->global->if_add_ifindex = ifidx;
10700
10701         /*
10702          * Some virtual interfaces need to process EAPOL packets and events on
10703          * the parent interface. This is used mainly with hostapd.
10704          */
10705         if (ifidx > 0 &&
10706             (drv->hostapd ||
10707              nlmode == NL80211_IFTYPE_AP_VLAN ||
10708              nlmode == NL80211_IFTYPE_WDS ||
10709              nlmode == NL80211_IFTYPE_MONITOR))
10710                 add_ifidx(drv, ifidx);
10711
10712         return 0;
10713 }
10714
10715
10716 static int wpa_driver_nl80211_if_remove(struct i802_bss *bss,
10717                                         enum wpa_driver_if_type type,
10718                                         const char *ifname)
10719 {
10720         struct wpa_driver_nl80211_data *drv = bss->drv;
10721         int ifindex = if_nametoindex(ifname);
10722
10723         wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d added_if=%d",
10724                    __func__, type, ifname, ifindex, bss->added_if);
10725         if (ifindex > 0 && (bss->added_if || bss->ifindex != ifindex))
10726                 nl80211_remove_iface(drv, ifindex);
10727         else if (ifindex > 0 && !bss->added_if) {
10728                 struct wpa_driver_nl80211_data *drv2;
10729                 dl_list_for_each(drv2, &drv->global->interfaces,
10730                                  struct wpa_driver_nl80211_data, list)
10731                         del_ifidx(drv2, ifindex);
10732         }
10733
10734         if (type != WPA_IF_AP_BSS)
10735                 return 0;
10736
10737         if (bss->added_if_into_bridge) {
10738                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
10739                                     bss->ifname) < 0)
10740                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
10741                                    "interface %s from bridge %s: %s",
10742                                    bss->ifname, bss->brname, strerror(errno));
10743         }
10744         if (bss->added_bridge) {
10745                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
10746                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
10747                                    "bridge %s: %s",
10748                                    bss->brname, strerror(errno));
10749         }
10750
10751         if (bss != drv->first_bss) {
10752                 struct i802_bss *tbss;
10753
10754                 wpa_printf(MSG_DEBUG, "nl80211: Not the first BSS - remove it");
10755                 for (tbss = drv->first_bss; tbss; tbss = tbss->next) {
10756                         if (tbss->next == bss) {
10757                                 tbss->next = bss->next;
10758                                 /* Unsubscribe management frames */
10759                                 nl80211_teardown_ap(bss);
10760                                 nl80211_destroy_bss(bss);
10761                                 if (!bss->added_if)
10762                                         i802_set_iface_flags(bss, 0);
10763                                 os_free(bss);
10764                                 bss = NULL;
10765                                 break;
10766                         }
10767                 }
10768                 if (bss)
10769                         wpa_printf(MSG_INFO, "nl80211: %s - could not find "
10770                                    "BSS %p in the list", __func__, bss);
10771         } else {
10772                 wpa_printf(MSG_DEBUG, "nl80211: First BSS - reassign context");
10773                 nl80211_teardown_ap(bss);
10774                 if (!bss->added_if && !drv->first_bss->next)
10775                         wpa_driver_nl80211_del_beacon(drv);
10776                 nl80211_destroy_bss(bss);
10777                 if (!bss->added_if)
10778                         i802_set_iface_flags(bss, 0);
10779                 if (drv->first_bss->next) {
10780                         drv->first_bss = drv->first_bss->next;
10781                         drv->ctx = drv->first_bss->ctx;
10782                         os_free(bss);
10783                 } else {
10784                         wpa_printf(MSG_DEBUG, "nl80211: No second BSS to reassign context to");
10785                 }
10786         }
10787
10788         return 0;
10789 }
10790
10791
10792 static int cookie_handler(struct nl_msg *msg, void *arg)
10793 {
10794         struct nlattr *tb[NL80211_ATTR_MAX + 1];
10795         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
10796         u64 *cookie = arg;
10797         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
10798                   genlmsg_attrlen(gnlh, 0), NULL);
10799         if (tb[NL80211_ATTR_COOKIE])
10800                 *cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
10801         return NL_SKIP;
10802 }
10803
10804
10805 static int nl80211_send_frame_cmd(struct i802_bss *bss,
10806                                   unsigned int freq, unsigned int wait,
10807                                   const u8 *buf, size_t buf_len,
10808                                   u64 *cookie_out, int no_cck, int no_ack,
10809                                   int offchanok)
10810 {
10811         struct wpa_driver_nl80211_data *drv = bss->drv;
10812         struct nl_msg *msg;
10813         u64 cookie;
10814         int ret = -1;
10815
10816         msg = nlmsg_alloc();
10817         if (!msg)
10818                 return -1;
10819
10820         wpa_printf(MSG_MSGDUMP, "nl80211: CMD_FRAME freq=%u wait=%u no_cck=%d "
10821                    "no_ack=%d offchanok=%d",
10822                    freq, wait, no_cck, no_ack, offchanok);
10823         wpa_hexdump(MSG_MSGDUMP, "CMD_FRAME", buf, buf_len);
10824         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME);
10825
10826         if (nl80211_set_iface_id(msg, bss) < 0)
10827                 goto nla_put_failure;
10828         if (freq)
10829                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
10830         if (wait)
10831                 NLA_PUT_U32(msg, NL80211_ATTR_DURATION, wait);
10832         if (offchanok && ((drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX) ||
10833                           drv->test_use_roc_tx))
10834                 NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
10835         if (no_cck)
10836                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
10837         if (no_ack)
10838                 NLA_PUT_FLAG(msg, NL80211_ATTR_DONT_WAIT_FOR_ACK);
10839
10840         NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
10841
10842         cookie = 0;
10843         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
10844         msg = NULL;
10845         if (ret) {
10846                 wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
10847                            "(%s) (freq=%u wait=%u)", ret, strerror(-ret),
10848                            freq, wait);
10849                 goto nla_put_failure;
10850         }
10851         wpa_printf(MSG_MSGDUMP, "nl80211: Frame TX command accepted%s; "
10852                    "cookie 0x%llx", no_ack ? " (no ACK)" : "",
10853                    (long long unsigned int) cookie);
10854
10855         if (cookie_out)
10856                 *cookie_out = no_ack ? (u64) -1 : cookie;
10857
10858 nla_put_failure:
10859         nlmsg_free(msg);
10860         return ret;
10861 }
10862
10863
10864 static int wpa_driver_nl80211_send_action(struct i802_bss *bss,
10865                                           unsigned int freq,
10866                                           unsigned int wait_time,
10867                                           const u8 *dst, const u8 *src,
10868                                           const u8 *bssid,
10869                                           const u8 *data, size_t data_len,
10870                                           int no_cck)
10871 {
10872         struct wpa_driver_nl80211_data *drv = bss->drv;
10873         int ret = -1;
10874         u8 *buf;
10875         struct ieee80211_hdr *hdr;
10876
10877         wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d, "
10878                    "freq=%u MHz wait=%d ms no_cck=%d)",
10879                    drv->ifindex, freq, wait_time, no_cck);
10880
10881         buf = os_zalloc(24 + data_len);
10882         if (buf == NULL)
10883                 return ret;
10884         os_memcpy(buf + 24, data, data_len);
10885         hdr = (struct ieee80211_hdr *) buf;
10886         hdr->frame_control =
10887                 IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
10888         os_memcpy(hdr->addr1, dst, ETH_ALEN);
10889         os_memcpy(hdr->addr2, src, ETH_ALEN);
10890         os_memcpy(hdr->addr3, bssid, ETH_ALEN);
10891
10892         if (is_ap_interface(drv->nlmode) &&
10893             (!(drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX) ||
10894              (int) freq == bss->freq || drv->device_ap_sme ||
10895              !drv->use_monitor))
10896                 ret = wpa_driver_nl80211_send_mlme(bss, buf, 24 + data_len,
10897                                                    0, freq, no_cck, 1,
10898                                                    wait_time);
10899         else
10900                 ret = nl80211_send_frame_cmd(bss, freq, wait_time, buf,
10901                                              24 + data_len,
10902                                              &drv->send_action_cookie,
10903                                              no_cck, 0, 1);
10904
10905         os_free(buf);
10906         return ret;
10907 }
10908
10909
10910 static void wpa_driver_nl80211_send_action_cancel_wait(void *priv)
10911 {
10912         struct i802_bss *bss = priv;
10913         struct wpa_driver_nl80211_data *drv = bss->drv;
10914         struct nl_msg *msg;
10915         int ret;
10916
10917         msg = nlmsg_alloc();
10918         if (!msg)
10919                 return;
10920
10921         wpa_printf(MSG_DEBUG, "nl80211: Cancel TX frame wait: cookie=0x%llx",
10922                    (long long unsigned int) drv->send_action_cookie);
10923         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME_WAIT_CANCEL);
10924
10925         if (nl80211_set_iface_id(msg, bss) < 0)
10926                 goto nla_put_failure;
10927         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->send_action_cookie);
10928
10929         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
10930         msg = NULL;
10931         if (ret)
10932                 wpa_printf(MSG_DEBUG, "nl80211: wait cancel failed: ret=%d "
10933                            "(%s)", ret, strerror(-ret));
10934
10935  nla_put_failure:
10936         nlmsg_free(msg);
10937 }
10938
10939
10940 static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
10941                                                 unsigned int duration)
10942 {
10943         struct i802_bss *bss = priv;
10944         struct wpa_driver_nl80211_data *drv = bss->drv;
10945         struct nl_msg *msg;
10946         int ret;
10947         u64 cookie;
10948
10949         msg = nlmsg_alloc();
10950         if (!msg)
10951                 return -1;
10952
10953         nl80211_cmd(drv, msg, 0, NL80211_CMD_REMAIN_ON_CHANNEL);
10954
10955         if (nl80211_set_iface_id(msg, bss) < 0)
10956                 goto nla_put_failure;
10957
10958         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
10959         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
10960
10961         cookie = 0;
10962         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
10963         msg = NULL;
10964         if (ret == 0) {
10965                 wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
10966                            "0x%llx for freq=%u MHz duration=%u",
10967                            (long long unsigned int) cookie, freq, duration);
10968                 drv->remain_on_chan_cookie = cookie;
10969                 drv->pending_remain_on_chan = 1;
10970                 return 0;
10971         }
10972         wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
10973                    "(freq=%d duration=%u): %d (%s)",
10974                    freq, duration, ret, strerror(-ret));
10975 nla_put_failure:
10976         nlmsg_free(msg);
10977         return -1;
10978 }
10979
10980
10981 static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
10982 {
10983         struct i802_bss *bss = priv;
10984         struct wpa_driver_nl80211_data *drv = bss->drv;
10985         struct nl_msg *msg;
10986         int ret;
10987
10988         if (!drv->pending_remain_on_chan) {
10989                 wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
10990                            "to cancel");
10991                 return -1;
10992         }
10993
10994         wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
10995                    "0x%llx",
10996                    (long long unsigned int) drv->remain_on_chan_cookie);
10997
10998         msg = nlmsg_alloc();
10999         if (!msg)
11000                 return -1;
11001
11002         nl80211_cmd(drv, msg, 0, NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL);
11003
11004         if (nl80211_set_iface_id(msg, bss) < 0)
11005                 goto nla_put_failure;
11006
11007         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
11008
11009         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
11010         msg = NULL;
11011         if (ret == 0)
11012                 return 0;
11013         wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
11014                    "%d (%s)", ret, strerror(-ret));
11015 nla_put_failure:
11016         nlmsg_free(msg);
11017         return -1;
11018 }
11019
11020
11021 static int wpa_driver_nl80211_probe_req_report(struct i802_bss *bss, int report)
11022 {
11023         struct wpa_driver_nl80211_data *drv = bss->drv;
11024
11025         if (!report) {
11026                 if (bss->nl_preq && drv->device_ap_sme &&
11027                     is_ap_interface(drv->nlmode) && !bss->in_deinit &&
11028                     !bss->static_ap) {
11029                         /*
11030                          * Do not disable Probe Request reporting that was
11031                          * enabled in nl80211_setup_ap().
11032                          */
11033                         wpa_printf(MSG_DEBUG, "nl80211: Skip disabling of "
11034                                    "Probe Request reporting nl_preq=%p while "
11035                                    "in AP mode", bss->nl_preq);
11036                 } else if (bss->nl_preq) {
11037                         wpa_printf(MSG_DEBUG, "nl80211: Disable Probe Request "
11038                                    "reporting nl_preq=%p", bss->nl_preq);
11039                         nl80211_destroy_eloop_handle(&bss->nl_preq);
11040                 }
11041                 return 0;
11042         }
11043
11044         if (bss->nl_preq) {
11045                 wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
11046                            "already on! nl_preq=%p", bss->nl_preq);
11047                 return 0;
11048         }
11049
11050         bss->nl_preq = nl_create_handle(drv->global->nl_cb, "preq");
11051         if (bss->nl_preq == NULL)
11052                 return -1;
11053         wpa_printf(MSG_DEBUG, "nl80211: Enable Probe Request "
11054                    "reporting nl_preq=%p", bss->nl_preq);
11055
11056         if (nl80211_register_frame(bss, bss->nl_preq,
11057                                    (WLAN_FC_TYPE_MGMT << 2) |
11058                                    (WLAN_FC_STYPE_PROBE_REQ << 4),
11059                                    NULL, 0) < 0)
11060                 goto out_err;
11061
11062         nl80211_register_eloop_read(&bss->nl_preq,
11063                                     wpa_driver_nl80211_event_receive,
11064                                     bss->nl_cb);
11065
11066         return 0;
11067
11068  out_err:
11069         nl_destroy_handles(&bss->nl_preq);
11070         return -1;
11071 }
11072
11073
11074 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
11075                                      int ifindex, int disabled)
11076 {
11077         struct nl_msg *msg;
11078         struct nlattr *bands, *band;
11079         int ret;
11080
11081         msg = nlmsg_alloc();
11082         if (!msg)
11083                 return -1;
11084
11085         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_TX_BITRATE_MASK);
11086         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
11087
11088         bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
11089         if (!bands)
11090                 goto nla_put_failure;
11091
11092         /*
11093          * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
11094          * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
11095          * rates. All 5 GHz rates are left enabled.
11096          */
11097         band = nla_nest_start(msg, NL80211_BAND_2GHZ);
11098         if (!band)
11099                 goto nla_put_failure;
11100         if (disabled) {
11101                 NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
11102                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
11103         }
11104         nla_nest_end(msg, band);
11105
11106         nla_nest_end(msg, bands);
11107
11108         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
11109         msg = NULL;
11110         if (ret) {
11111                 wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
11112                            "(%s)", ret, strerror(-ret));
11113         } else
11114                 drv->disabled_11b_rates = disabled;
11115
11116         return ret;
11117
11118 nla_put_failure:
11119         nlmsg_free(msg);
11120         return -1;
11121 }
11122
11123
11124 static int wpa_driver_nl80211_deinit_ap(void *priv)
11125 {
11126         struct i802_bss *bss = priv;
11127         struct wpa_driver_nl80211_data *drv = bss->drv;
11128         if (!is_ap_interface(drv->nlmode))
11129                 return -1;
11130         wpa_driver_nl80211_del_beacon(drv);
11131
11132         /*
11133          * If the P2P GO interface was dynamically added, then it is
11134          * possible that the interface change to station is not possible.
11135          */
11136         if (drv->nlmode == NL80211_IFTYPE_P2P_GO && bss->if_dynamic)
11137                 return 0;
11138
11139         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
11140 }
11141
11142
11143 static int wpa_driver_nl80211_stop_ap(void *priv)
11144 {
11145         struct i802_bss *bss = priv;
11146         struct wpa_driver_nl80211_data *drv = bss->drv;
11147         if (!is_ap_interface(drv->nlmode))
11148                 return -1;
11149         wpa_driver_nl80211_del_beacon(drv);
11150         bss->beacon_set = 0;
11151         return 0;
11152 }
11153
11154
11155 static int wpa_driver_nl80211_deinit_p2p_cli(void *priv)
11156 {
11157         struct i802_bss *bss = priv;
11158         struct wpa_driver_nl80211_data *drv = bss->drv;
11159         if (drv->nlmode != NL80211_IFTYPE_P2P_CLIENT)
11160                 return -1;
11161
11162         /*
11163          * If the P2P Client interface was dynamically added, then it is
11164          * possible that the interface change to station is not possible.
11165          */
11166         if (bss->if_dynamic)
11167                 return 0;
11168
11169         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
11170 }
11171
11172
11173 static void wpa_driver_nl80211_resume(void *priv)
11174 {
11175         struct i802_bss *bss = priv;
11176
11177         if (i802_set_iface_flags(bss, 1))
11178                 wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on resume event");
11179 }
11180
11181
11182 static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
11183                                   const u8 *ies, size_t ies_len)
11184 {
11185         struct i802_bss *bss = priv;
11186         struct wpa_driver_nl80211_data *drv = bss->drv;
11187         int ret;
11188         u8 *data, *pos;
11189         size_t data_len;
11190         const u8 *own_addr = bss->addr;
11191
11192         if (action != 1) {
11193                 wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
11194                            "action %d", action);
11195                 return -1;
11196         }
11197
11198         /*
11199          * Action frame payload:
11200          * Category[1] = 6 (Fast BSS Transition)
11201          * Action[1] = 1 (Fast BSS Transition Request)
11202          * STA Address
11203          * Target AP Address
11204          * FT IEs
11205          */
11206
11207         data_len = 2 + 2 * ETH_ALEN + ies_len;
11208         data = os_malloc(data_len);
11209         if (data == NULL)
11210                 return -1;
11211         pos = data;
11212         *pos++ = 0x06; /* FT Action category */
11213         *pos++ = action;
11214         os_memcpy(pos, own_addr, ETH_ALEN);
11215         pos += ETH_ALEN;
11216         os_memcpy(pos, target_ap, ETH_ALEN);
11217         pos += ETH_ALEN;
11218         os_memcpy(pos, ies, ies_len);
11219
11220         ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, 0,
11221                                              drv->bssid, own_addr, drv->bssid,
11222                                              data, data_len, 0);
11223         os_free(data);
11224
11225         return ret;
11226 }
11227
11228
11229 static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
11230 {
11231         struct i802_bss *bss = priv;
11232         struct wpa_driver_nl80211_data *drv = bss->drv;
11233         struct nl_msg *msg;
11234         struct nlattr *cqm;
11235         int ret = -1;
11236
11237         wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
11238                    "hysteresis=%d", threshold, hysteresis);
11239
11240         msg = nlmsg_alloc();
11241         if (!msg)
11242                 return -1;
11243
11244         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_CQM);
11245
11246         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
11247
11248         cqm = nla_nest_start(msg, NL80211_ATTR_CQM);
11249         if (cqm == NULL)
11250                 goto nla_put_failure;
11251
11252         NLA_PUT_U32(msg, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
11253         NLA_PUT_U32(msg, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
11254         nla_nest_end(msg, cqm);
11255
11256         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
11257         msg = NULL;
11258
11259 nla_put_failure:
11260         nlmsg_free(msg);
11261         return ret;
11262 }
11263
11264
11265 static int get_channel_width(struct nl_msg *msg, void *arg)
11266 {
11267         struct nlattr *tb[NL80211_ATTR_MAX + 1];
11268         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
11269         struct wpa_signal_info *sig_change = arg;
11270
11271         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
11272                   genlmsg_attrlen(gnlh, 0), NULL);
11273
11274         sig_change->center_frq1 = -1;
11275         sig_change->center_frq2 = -1;
11276         sig_change->chanwidth = CHAN_WIDTH_UNKNOWN;
11277
11278         if (tb[NL80211_ATTR_CHANNEL_WIDTH]) {
11279                 sig_change->chanwidth = convert2width(
11280                         nla_get_u32(tb[NL80211_ATTR_CHANNEL_WIDTH]));
11281                 if (tb[NL80211_ATTR_CENTER_FREQ1])
11282                         sig_change->center_frq1 =
11283                                 nla_get_u32(tb[NL80211_ATTR_CENTER_FREQ1]);
11284                 if (tb[NL80211_ATTR_CENTER_FREQ2])
11285                         sig_change->center_frq2 =
11286                                 nla_get_u32(tb[NL80211_ATTR_CENTER_FREQ2]);
11287         }
11288
11289         return NL_SKIP;
11290 }
11291
11292
11293 static int nl80211_get_channel_width(struct wpa_driver_nl80211_data *drv,
11294                                      struct wpa_signal_info *sig)
11295 {
11296         struct nl_msg *msg;
11297
11298         msg = nlmsg_alloc();
11299         if (!msg)
11300                 return -ENOMEM;
11301
11302         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_INTERFACE);
11303         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
11304
11305         return send_and_recv_msgs(drv, msg, get_channel_width, sig);
11306
11307 nla_put_failure:
11308         nlmsg_free(msg);
11309         return -ENOBUFS;
11310 }
11311
11312
11313 static int nl80211_signal_poll(void *priv, struct wpa_signal_info *si)
11314 {
11315         struct i802_bss *bss = priv;
11316         struct wpa_driver_nl80211_data *drv = bss->drv;
11317         int res;
11318
11319         os_memset(si, 0, sizeof(*si));
11320         res = nl80211_get_link_signal(drv, si);
11321         if (res != 0)
11322                 return res;
11323
11324         res = nl80211_get_channel_width(drv, si);
11325         if (res != 0)
11326                 return res;
11327
11328         return nl80211_get_link_noise(drv, si);
11329 }
11330
11331
11332 static int wpa_driver_nl80211_shared_freq(void *priv)
11333 {
11334         struct i802_bss *bss = priv;
11335         struct wpa_driver_nl80211_data *drv = bss->drv;
11336         struct wpa_driver_nl80211_data *driver;
11337         int freq = 0;
11338
11339         /*
11340          * If the same PHY is in connected state with some other interface,
11341          * then retrieve the assoc freq.
11342          */
11343         wpa_printf(MSG_DEBUG, "nl80211: Get shared freq for PHY %s",
11344                    drv->phyname);
11345
11346         dl_list_for_each(driver, &drv->global->interfaces,
11347                          struct wpa_driver_nl80211_data, list) {
11348                 if (drv == driver ||
11349                     os_strcmp(drv->phyname, driver->phyname) != 0 ||
11350                     !driver->associated)
11351                         continue;
11352
11353                 wpa_printf(MSG_DEBUG, "nl80211: Found a match for PHY %s - %s "
11354                            MACSTR,
11355                            driver->phyname, driver->first_bss->ifname,
11356                            MAC2STR(driver->first_bss->addr));
11357                 if (is_ap_interface(driver->nlmode))
11358                         freq = driver->first_bss->freq;
11359                 else
11360                         freq = nl80211_get_assoc_freq(driver);
11361                 wpa_printf(MSG_DEBUG, "nl80211: Shared freq for PHY %s: %d",
11362                            drv->phyname, freq);
11363         }
11364
11365         if (!freq)
11366                 wpa_printf(MSG_DEBUG, "nl80211: No shared interface for "
11367                            "PHY (%s) in associated state", drv->phyname);
11368
11369         return freq;
11370 }
11371
11372
11373 static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
11374                               int encrypt)
11375 {
11376         struct i802_bss *bss = priv;
11377         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt, 0,
11378                                              0, 0, 0, 0);
11379 }
11380
11381
11382 static int nl80211_set_param(void *priv, const char *param)
11383 {
11384         wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
11385         if (param == NULL)
11386                 return 0;
11387
11388 #ifdef CONFIG_P2P
11389         if (os_strstr(param, "use_p2p_group_interface=1")) {
11390                 struct i802_bss *bss = priv;
11391                 struct wpa_driver_nl80211_data *drv = bss->drv;
11392
11393                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
11394                            "interface");
11395                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
11396                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
11397         }
11398 #endif /* CONFIG_P2P */
11399
11400         if (os_strstr(param, "use_monitor=1")) {
11401                 struct i802_bss *bss = priv;
11402                 struct wpa_driver_nl80211_data *drv = bss->drv;
11403                 drv->use_monitor = 1;
11404         }
11405
11406         if (os_strstr(param, "force_connect_cmd=1")) {
11407                 struct i802_bss *bss = priv;
11408                 struct wpa_driver_nl80211_data *drv = bss->drv;
11409                 drv->capa.flags &= ~WPA_DRIVER_FLAGS_SME;
11410                 drv->force_connect_cmd = 1;
11411         }
11412
11413         if (os_strstr(param, "no_offchannel_tx=1")) {
11414                 struct i802_bss *bss = priv;
11415                 struct wpa_driver_nl80211_data *drv = bss->drv;
11416                 drv->capa.flags &= ~WPA_DRIVER_FLAGS_OFFCHANNEL_TX;
11417                 drv->test_use_roc_tx = 1;
11418         }
11419
11420         return 0;
11421 }
11422
11423
11424 static void * nl80211_global_init(void)
11425 {
11426         struct nl80211_global *global;
11427         struct netlink_config *cfg;
11428
11429         global = os_zalloc(sizeof(*global));
11430         if (global == NULL)
11431                 return NULL;
11432         global->ioctl_sock = -1;
11433         dl_list_init(&global->interfaces);
11434         global->if_add_ifindex = -1;
11435
11436         cfg = os_zalloc(sizeof(*cfg));
11437         if (cfg == NULL)
11438                 goto err;
11439
11440         cfg->ctx = global;
11441         cfg->newlink_cb = wpa_driver_nl80211_event_rtm_newlink;
11442         cfg->dellink_cb = wpa_driver_nl80211_event_rtm_dellink;
11443         global->netlink = netlink_init(cfg);
11444         if (global->netlink == NULL) {
11445                 os_free(cfg);
11446                 goto err;
11447         }
11448
11449         if (wpa_driver_nl80211_init_nl_global(global) < 0)
11450                 goto err;
11451
11452         global->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
11453         if (global->ioctl_sock < 0) {
11454                 wpa_printf(MSG_ERROR, "nl80211: socket(PF_INET,SOCK_DGRAM) failed: %s",
11455                            strerror(errno));
11456                 goto err;
11457         }
11458
11459         return global;
11460
11461 err:
11462         nl80211_global_deinit(global);
11463         return NULL;
11464 }
11465
11466
11467 static void nl80211_global_deinit(void *priv)
11468 {
11469         struct nl80211_global *global = priv;
11470         if (global == NULL)
11471                 return;
11472         if (!dl_list_empty(&global->interfaces)) {
11473                 wpa_printf(MSG_ERROR, "nl80211: %u interface(s) remain at "
11474                            "nl80211_global_deinit",
11475                            dl_list_len(&global->interfaces));
11476         }
11477
11478         if (global->netlink)
11479                 netlink_deinit(global->netlink);
11480
11481         nl_destroy_handles(&global->nl);
11482
11483         if (global->nl_event)
11484                 nl80211_destroy_eloop_handle(&global->nl_event);
11485
11486         nl_cb_put(global->nl_cb);
11487
11488         if (global->ioctl_sock >= 0)
11489                 close(global->ioctl_sock);
11490
11491         os_free(global);
11492 }
11493
11494
11495 static const char * nl80211_get_radio_name(void *priv)
11496 {
11497         struct i802_bss *bss = priv;
11498         struct wpa_driver_nl80211_data *drv = bss->drv;
11499         return drv->phyname;
11500 }
11501
11502
11503 static int nl80211_pmkid(struct i802_bss *bss, int cmd, const u8 *bssid,
11504                          const u8 *pmkid)
11505 {
11506         struct nl_msg *msg;
11507
11508         msg = nlmsg_alloc();
11509         if (!msg)
11510                 return -ENOMEM;
11511
11512         nl80211_cmd(bss->drv, msg, 0, cmd);
11513
11514         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
11515         if (pmkid)
11516                 NLA_PUT(msg, NL80211_ATTR_PMKID, 16, pmkid);
11517         if (bssid)
11518                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
11519
11520         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
11521  nla_put_failure:
11522         nlmsg_free(msg);
11523         return -ENOBUFS;
11524 }
11525
11526
11527 static int nl80211_add_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
11528 {
11529         struct i802_bss *bss = priv;
11530         wpa_printf(MSG_DEBUG, "nl80211: Add PMKID for " MACSTR, MAC2STR(bssid));
11531         return nl80211_pmkid(bss, NL80211_CMD_SET_PMKSA, bssid, pmkid);
11532 }
11533
11534
11535 static int nl80211_remove_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
11536 {
11537         struct i802_bss *bss = priv;
11538         wpa_printf(MSG_DEBUG, "nl80211: Delete PMKID for " MACSTR,
11539                    MAC2STR(bssid));
11540         return nl80211_pmkid(bss, NL80211_CMD_DEL_PMKSA, bssid, pmkid);
11541 }
11542
11543
11544 static int nl80211_flush_pmkid(void *priv)
11545 {
11546         struct i802_bss *bss = priv;
11547         wpa_printf(MSG_DEBUG, "nl80211: Flush PMKIDs");
11548         return nl80211_pmkid(bss, NL80211_CMD_FLUSH_PMKSA, NULL, NULL);
11549 }
11550
11551
11552 static void clean_survey_results(struct survey_results *survey_results)
11553 {
11554         struct freq_survey *survey, *tmp;
11555
11556         if (dl_list_empty(&survey_results->survey_list))
11557                 return;
11558
11559         dl_list_for_each_safe(survey, tmp, &survey_results->survey_list,
11560                               struct freq_survey, list) {
11561                 dl_list_del(&survey->list);
11562                 os_free(survey);
11563         }
11564 }
11565
11566
11567 static void add_survey(struct nlattr **sinfo, u32 ifidx,
11568                        struct dl_list *survey_list)
11569 {
11570         struct freq_survey *survey;
11571
11572         survey = os_zalloc(sizeof(struct freq_survey));
11573         if  (!survey)
11574                 return;
11575
11576         survey->ifidx = ifidx;
11577         survey->freq = nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]);
11578         survey->filled = 0;
11579
11580         if (sinfo[NL80211_SURVEY_INFO_NOISE]) {
11581                 survey->nf = (int8_t)
11582                         nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
11583                 survey->filled |= SURVEY_HAS_NF;
11584         }
11585
11586         if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME]) {
11587                 survey->channel_time =
11588                         nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME]);
11589                 survey->filled |= SURVEY_HAS_CHAN_TIME;
11590         }
11591
11592         if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_BUSY]) {
11593                 survey->channel_time_busy =
11594                         nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_BUSY]);
11595                 survey->filled |= SURVEY_HAS_CHAN_TIME_BUSY;
11596         }
11597
11598         if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_RX]) {
11599                 survey->channel_time_rx =
11600                         nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_RX]);
11601                 survey->filled |= SURVEY_HAS_CHAN_TIME_RX;
11602         }
11603
11604         if (sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_TX]) {
11605                 survey->channel_time_tx =
11606                         nla_get_u64(sinfo[NL80211_SURVEY_INFO_CHANNEL_TIME_TX]);
11607                 survey->filled |= SURVEY_HAS_CHAN_TIME_TX;
11608         }
11609
11610         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)",
11611                    survey->freq,
11612                    survey->nf,
11613                    (unsigned long int) survey->channel_time,
11614                    (unsigned long int) survey->channel_time_busy,
11615                    (unsigned long int) survey->channel_time_tx,
11616                    (unsigned long int) survey->channel_time_rx,
11617                    survey->filled);
11618
11619         dl_list_add_tail(survey_list, &survey->list);
11620 }
11621
11622
11623 static int check_survey_ok(struct nlattr **sinfo, u32 surveyed_freq,
11624                            unsigned int freq_filter)
11625 {
11626         if (!freq_filter)
11627                 return 1;
11628
11629         return freq_filter == surveyed_freq;
11630 }
11631
11632
11633 static int survey_handler(struct nl_msg *msg, void *arg)
11634 {
11635         struct nlattr *tb[NL80211_ATTR_MAX + 1];
11636         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
11637         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
11638         struct survey_results *survey_results;
11639         u32 surveyed_freq = 0;
11640         u32 ifidx;
11641
11642         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
11643                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
11644                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
11645         };
11646
11647         survey_results = (struct survey_results *) arg;
11648
11649         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
11650                   genlmsg_attrlen(gnlh, 0), NULL);
11651
11652         if (!tb[NL80211_ATTR_IFINDEX])
11653                 return NL_SKIP;
11654
11655         ifidx = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
11656
11657         if (!tb[NL80211_ATTR_SURVEY_INFO])
11658                 return NL_SKIP;
11659
11660         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
11661                              tb[NL80211_ATTR_SURVEY_INFO],
11662                              survey_policy))
11663                 return NL_SKIP;
11664
11665         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY]) {
11666                 wpa_printf(MSG_ERROR, "nl80211: Invalid survey data");
11667                 return NL_SKIP;
11668         }
11669
11670         surveyed_freq = nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]);
11671
11672         if (!check_survey_ok(sinfo, surveyed_freq,
11673                              survey_results->freq_filter))
11674                 return NL_SKIP;
11675
11676         if (survey_results->freq_filter &&
11677             survey_results->freq_filter != surveyed_freq) {
11678                 wpa_printf(MSG_EXCESSIVE, "nl80211: Ignoring survey data for freq %d MHz",
11679                            surveyed_freq);
11680                 return NL_SKIP;
11681         }
11682
11683         add_survey(sinfo, ifidx, &survey_results->survey_list);
11684
11685         return NL_SKIP;
11686 }
11687
11688
11689 static int wpa_driver_nl80211_get_survey(void *priv, unsigned int freq)
11690 {
11691         struct i802_bss *bss = priv;
11692         struct wpa_driver_nl80211_data *drv = bss->drv;
11693         struct nl_msg *msg;
11694         int err = -ENOBUFS;
11695         union wpa_event_data data;
11696         struct survey_results *survey_results;
11697
11698         os_memset(&data, 0, sizeof(data));
11699         survey_results = &data.survey_results;
11700
11701         dl_list_init(&survey_results->survey_list);
11702
11703         msg = nlmsg_alloc();
11704         if (!msg)
11705                 goto nla_put_failure;
11706
11707         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
11708
11709         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
11710
11711         if (freq)
11712                 data.survey_results.freq_filter = freq;
11713
11714         do {
11715                 wpa_printf(MSG_DEBUG, "nl80211: Fetch survey data");
11716                 err = send_and_recv_msgs(drv, msg, survey_handler,
11717                                          survey_results);
11718         } while (err > 0);
11719
11720         if (err) {
11721                 wpa_printf(MSG_ERROR, "nl80211: Failed to process survey data");
11722                 goto out_clean;
11723         }
11724
11725         wpa_supplicant_event(drv->ctx, EVENT_SURVEY, &data);
11726
11727 out_clean:
11728         clean_survey_results(survey_results);
11729 nla_put_failure:
11730         return err;
11731 }
11732
11733
11734 static void nl80211_set_rekey_info(void *priv, const u8 *kek, const u8 *kck,
11735                                    const u8 *replay_ctr)
11736 {
11737         struct i802_bss *bss = priv;
11738         struct wpa_driver_nl80211_data *drv = bss->drv;
11739         struct nlattr *replay_nested;
11740         struct nl_msg *msg;
11741
11742         msg = nlmsg_alloc();
11743         if (!msg)
11744                 return;
11745
11746         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_REKEY_OFFLOAD);
11747
11748         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
11749
11750         replay_nested = nla_nest_start(msg, NL80211_ATTR_REKEY_DATA);
11751         if (!replay_nested)
11752                 goto nla_put_failure;
11753
11754         NLA_PUT(msg, NL80211_REKEY_DATA_KEK, NL80211_KEK_LEN, kek);
11755         NLA_PUT(msg, NL80211_REKEY_DATA_KCK, NL80211_KCK_LEN, kck);
11756         NLA_PUT(msg, NL80211_REKEY_DATA_REPLAY_CTR, NL80211_REPLAY_CTR_LEN,
11757                 replay_ctr);
11758
11759         nla_nest_end(msg, replay_nested);
11760
11761         send_and_recv_msgs(drv, msg, NULL, NULL);
11762         return;
11763  nla_put_failure:
11764         nlmsg_free(msg);
11765 }
11766
11767
11768 static void nl80211_send_null_frame(struct i802_bss *bss, const u8 *own_addr,
11769                                     const u8 *addr, int qos)
11770 {
11771         /* send data frame to poll STA and check whether
11772          * this frame is ACKed */
11773         struct {
11774                 struct ieee80211_hdr hdr;
11775                 u16 qos_ctl;
11776         } STRUCT_PACKED nulldata;
11777         size_t size;
11778
11779         /* Send data frame to poll STA and check whether this frame is ACKed */
11780
11781         os_memset(&nulldata, 0, sizeof(nulldata));
11782
11783         if (qos) {
11784                 nulldata.hdr.frame_control =
11785                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
11786                                      WLAN_FC_STYPE_QOS_NULL);
11787                 size = sizeof(nulldata);
11788         } else {
11789                 nulldata.hdr.frame_control =
11790                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
11791                                      WLAN_FC_STYPE_NULLFUNC);
11792                 size = sizeof(struct ieee80211_hdr);
11793         }
11794
11795         nulldata.hdr.frame_control |= host_to_le16(WLAN_FC_FROMDS);
11796         os_memcpy(nulldata.hdr.IEEE80211_DA_FROMDS, addr, ETH_ALEN);
11797         os_memcpy(nulldata.hdr.IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
11798         os_memcpy(nulldata.hdr.IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
11799
11800         if (wpa_driver_nl80211_send_mlme(bss, (u8 *) &nulldata, size, 0, 0, 0,
11801                                          0, 0) < 0)
11802                 wpa_printf(MSG_DEBUG, "nl80211_send_null_frame: Failed to "
11803                            "send poll frame");
11804 }
11805
11806 static void nl80211_poll_client(void *priv, const u8 *own_addr, const u8 *addr,
11807                                 int qos)
11808 {
11809         struct i802_bss *bss = priv;
11810         struct wpa_driver_nl80211_data *drv = bss->drv;
11811         struct nl_msg *msg;
11812
11813         if (!drv->poll_command_supported) {
11814                 nl80211_send_null_frame(bss, own_addr, addr, qos);
11815                 return;
11816         }
11817
11818         msg = nlmsg_alloc();
11819         if (!msg)
11820                 return;
11821
11822         nl80211_cmd(drv, msg, 0, NL80211_CMD_PROBE_CLIENT);
11823
11824         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
11825         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
11826
11827         send_and_recv_msgs(drv, msg, NULL, NULL);
11828         return;
11829  nla_put_failure:
11830         nlmsg_free(msg);
11831 }
11832
11833
11834 static int nl80211_set_power_save(struct i802_bss *bss, int enabled)
11835 {
11836         struct nl_msg *msg;
11837
11838         msg = nlmsg_alloc();
11839         if (!msg)
11840                 return -ENOMEM;
11841
11842         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_SET_POWER_SAVE);
11843         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
11844         NLA_PUT_U32(msg, NL80211_ATTR_PS_STATE,
11845                     enabled ? NL80211_PS_ENABLED : NL80211_PS_DISABLED);
11846         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
11847 nla_put_failure:
11848         nlmsg_free(msg);
11849         return -ENOBUFS;
11850 }
11851
11852
11853 static int nl80211_set_p2p_powersave(void *priv, int legacy_ps, int opp_ps,
11854                                      int ctwindow)
11855 {
11856         struct i802_bss *bss = priv;
11857
11858         wpa_printf(MSG_DEBUG, "nl80211: set_p2p_powersave (legacy_ps=%d "
11859                    "opp_ps=%d ctwindow=%d)", legacy_ps, opp_ps, ctwindow);
11860
11861         if (opp_ps != -1 || ctwindow != -1) {
11862 #ifdef ANDROID_P2P
11863                 wpa_driver_set_p2p_ps(priv, legacy_ps, opp_ps, ctwindow);
11864 #else /* ANDROID_P2P */
11865                 return -1; /* Not yet supported */
11866 #endif /* ANDROID_P2P */
11867         }
11868
11869         if (legacy_ps == -1)
11870                 return 0;
11871         if (legacy_ps != 0 && legacy_ps != 1)
11872                 return -1; /* Not yet supported */
11873
11874         return nl80211_set_power_save(bss, legacy_ps);
11875 }
11876
11877
11878 static int nl80211_start_radar_detection(void *priv,
11879                                          struct hostapd_freq_params *freq)
11880 {
11881         struct i802_bss *bss = priv;
11882         struct wpa_driver_nl80211_data *drv = bss->drv;
11883         struct nl_msg *msg;
11884         int ret;
11885
11886         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)",
11887                    freq->freq, freq->ht_enabled, freq->vht_enabled,
11888                    freq->bandwidth, freq->center_freq1, freq->center_freq2);
11889
11890         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_RADAR)) {
11891                 wpa_printf(MSG_DEBUG, "nl80211: Driver does not support radar "
11892                            "detection");
11893                 return -1;
11894         }
11895
11896         msg = nlmsg_alloc();
11897         if (!msg)
11898                 return -1;
11899
11900         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_RADAR_DETECT);
11901         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
11902
11903         if (nl80211_put_freq_params(msg, freq) < 0)
11904                 goto nla_put_failure;
11905
11906         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
11907         msg = NULL;
11908         if (ret == 0)
11909                 return 0;
11910         wpa_printf(MSG_DEBUG, "nl80211: Failed to start radar detection: "
11911                    "%d (%s)", ret, strerror(-ret));
11912 nla_put_failure:
11913         nlmsg_free(msg);
11914         return -1;
11915 }
11916
11917 #ifdef CONFIG_TDLS
11918
11919 static int nl80211_send_tdls_mgmt(void *priv, const u8 *dst, u8 action_code,
11920                                   u8 dialog_token, u16 status_code,
11921                                   u32 peer_capab, int initiator, const u8 *buf,
11922                                   size_t len)
11923 {
11924         struct i802_bss *bss = priv;
11925         struct wpa_driver_nl80211_data *drv = bss->drv;
11926         struct nl_msg *msg;
11927
11928         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
11929                 return -EOPNOTSUPP;
11930
11931         if (!dst)
11932                 return -EINVAL;
11933
11934         msg = nlmsg_alloc();
11935         if (!msg)
11936                 return -ENOMEM;
11937
11938         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_MGMT);
11939         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
11940         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, dst);
11941         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_ACTION, action_code);
11942         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_DIALOG_TOKEN, dialog_token);
11943         NLA_PUT_U16(msg, NL80211_ATTR_STATUS_CODE, status_code);
11944         if (peer_capab) {
11945                 /*
11946                  * The internal enum tdls_peer_capability definition is
11947                  * currently identical with the nl80211 enum
11948                  * nl80211_tdls_peer_capability, so no conversion is needed
11949                  * here.
11950                  */
11951                 NLA_PUT_U32(msg, NL80211_ATTR_TDLS_PEER_CAPABILITY, peer_capab);
11952         }
11953         if (initiator)
11954                 NLA_PUT_FLAG(msg, NL80211_ATTR_TDLS_INITIATOR);
11955         NLA_PUT(msg, NL80211_ATTR_IE, len, buf);
11956
11957         return send_and_recv_msgs(drv, msg, NULL, NULL);
11958
11959 nla_put_failure:
11960         nlmsg_free(msg);
11961         return -ENOBUFS;
11962 }
11963
11964
11965 static int nl80211_tdls_oper(void *priv, enum tdls_oper oper, const u8 *peer)
11966 {
11967         struct i802_bss *bss = priv;
11968         struct wpa_driver_nl80211_data *drv = bss->drv;
11969         struct nl_msg *msg;
11970         enum nl80211_tdls_operation nl80211_oper;
11971
11972         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
11973                 return -EOPNOTSUPP;
11974
11975         switch (oper) {
11976         case TDLS_DISCOVERY_REQ:
11977                 nl80211_oper = NL80211_TDLS_DISCOVERY_REQ;
11978                 break;
11979         case TDLS_SETUP:
11980                 nl80211_oper = NL80211_TDLS_SETUP;
11981                 break;
11982         case TDLS_TEARDOWN:
11983                 nl80211_oper = NL80211_TDLS_TEARDOWN;
11984                 break;
11985         case TDLS_ENABLE_LINK:
11986                 nl80211_oper = NL80211_TDLS_ENABLE_LINK;
11987                 break;
11988         case TDLS_DISABLE_LINK:
11989                 nl80211_oper = NL80211_TDLS_DISABLE_LINK;
11990                 break;
11991         case TDLS_ENABLE:
11992                 return 0;
11993         case TDLS_DISABLE:
11994                 return 0;
11995         default:
11996                 return -EINVAL;
11997         }
11998
11999         msg = nlmsg_alloc();
12000         if (!msg)
12001                 return -ENOMEM;
12002
12003         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_OPER);
12004         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_OPERATION, nl80211_oper);
12005         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
12006         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, peer);
12007
12008         return send_and_recv_msgs(drv, msg, NULL, NULL);
12009
12010 nla_put_failure:
12011         nlmsg_free(msg);
12012         return -ENOBUFS;
12013 }
12014
12015 #endif /* CONFIG TDLS */
12016
12017
12018 #ifdef ANDROID
12019
12020 typedef struct android_wifi_priv_cmd {
12021         char *buf;
12022         int used_len;
12023         int total_len;
12024 } android_wifi_priv_cmd;
12025
12026 static int drv_errors = 0;
12027
12028 static void wpa_driver_send_hang_msg(struct wpa_driver_nl80211_data *drv)
12029 {
12030         drv_errors++;
12031         if (drv_errors > DRV_NUMBER_SEQUENTIAL_ERRORS) {
12032                 drv_errors = 0;
12033                 wpa_msg(drv->ctx, MSG_INFO, WPA_EVENT_DRIVER_STATE "HANGED");
12034         }
12035 }
12036
12037
12038 static int android_priv_cmd(struct i802_bss *bss, const char *cmd)
12039 {
12040         struct wpa_driver_nl80211_data *drv = bss->drv;
12041         struct ifreq ifr;
12042         android_wifi_priv_cmd priv_cmd;
12043         char buf[MAX_DRV_CMD_SIZE];
12044         int ret;
12045
12046         os_memset(&ifr, 0, sizeof(ifr));
12047         os_memset(&priv_cmd, 0, sizeof(priv_cmd));
12048         os_strlcpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
12049
12050         os_memset(buf, 0, sizeof(buf));
12051         os_strlcpy(buf, cmd, sizeof(buf));
12052
12053         priv_cmd.buf = buf;
12054         priv_cmd.used_len = sizeof(buf);
12055         priv_cmd.total_len = sizeof(buf);
12056         ifr.ifr_data = &priv_cmd;
12057
12058         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
12059         if (ret < 0) {
12060                 wpa_printf(MSG_ERROR, "%s: failed to issue private commands",
12061                            __func__);
12062                 wpa_driver_send_hang_msg(drv);
12063                 return ret;
12064         }
12065
12066         drv_errors = 0;
12067         return 0;
12068 }
12069
12070
12071 static int android_pno_start(struct i802_bss *bss,
12072                              struct wpa_driver_scan_params *params)
12073 {
12074         struct wpa_driver_nl80211_data *drv = bss->drv;
12075         struct ifreq ifr;
12076         android_wifi_priv_cmd priv_cmd;
12077         int ret = 0, i = 0, bp;
12078         char buf[WEXT_PNO_MAX_COMMAND_SIZE];
12079
12080         bp = WEXT_PNOSETUP_HEADER_SIZE;
12081         os_memcpy(buf, WEXT_PNOSETUP_HEADER, bp);
12082         buf[bp++] = WEXT_PNO_TLV_PREFIX;
12083         buf[bp++] = WEXT_PNO_TLV_VERSION;
12084         buf[bp++] = WEXT_PNO_TLV_SUBVERSION;
12085         buf[bp++] = WEXT_PNO_TLV_RESERVED;
12086
12087         while (i < WEXT_PNO_AMOUNT && (size_t) i < params->num_ssids) {
12088                 /* Check that there is enough space needed for 1 more SSID, the
12089                  * other sections and null termination */
12090                 if ((bp + WEXT_PNO_SSID_HEADER_SIZE + MAX_SSID_LEN +
12091                      WEXT_PNO_NONSSID_SECTIONS_SIZE + 1) >= (int) sizeof(buf))
12092                         break;
12093                 wpa_hexdump_ascii(MSG_DEBUG, "For PNO Scan",
12094                                   params->ssids[i].ssid,
12095                                   params->ssids[i].ssid_len);
12096                 buf[bp++] = WEXT_PNO_SSID_SECTION;
12097                 buf[bp++] = params->ssids[i].ssid_len;
12098                 os_memcpy(&buf[bp], params->ssids[i].ssid,
12099                           params->ssids[i].ssid_len);
12100                 bp += params->ssids[i].ssid_len;
12101                 i++;
12102         }
12103
12104         buf[bp++] = WEXT_PNO_SCAN_INTERVAL_SECTION;
12105         os_snprintf(&buf[bp], WEXT_PNO_SCAN_INTERVAL_LENGTH + 1, "%x",
12106                     WEXT_PNO_SCAN_INTERVAL);
12107         bp += WEXT_PNO_SCAN_INTERVAL_LENGTH;
12108
12109         buf[bp++] = WEXT_PNO_REPEAT_SECTION;
12110         os_snprintf(&buf[bp], WEXT_PNO_REPEAT_LENGTH + 1, "%x",
12111                     WEXT_PNO_REPEAT);
12112         bp += WEXT_PNO_REPEAT_LENGTH;
12113
12114         buf[bp++] = WEXT_PNO_MAX_REPEAT_SECTION;
12115         os_snprintf(&buf[bp], WEXT_PNO_MAX_REPEAT_LENGTH + 1, "%x",
12116                     WEXT_PNO_MAX_REPEAT);
12117         bp += WEXT_PNO_MAX_REPEAT_LENGTH + 1;
12118
12119         memset(&ifr, 0, sizeof(ifr));
12120         memset(&priv_cmd, 0, sizeof(priv_cmd));
12121         os_strlcpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
12122
12123         priv_cmd.buf = buf;
12124         priv_cmd.used_len = bp;
12125         priv_cmd.total_len = bp;
12126         ifr.ifr_data = &priv_cmd;
12127
12128         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
12129
12130         if (ret < 0) {
12131                 wpa_printf(MSG_ERROR, "ioctl[SIOCSIWPRIV] (pnosetup): %d",
12132                            ret);
12133                 wpa_driver_send_hang_msg(drv);
12134                 return ret;
12135         }
12136
12137         drv_errors = 0;
12138
12139         return android_priv_cmd(bss, "PNOFORCE 1");
12140 }
12141
12142
12143 static int android_pno_stop(struct i802_bss *bss)
12144 {
12145         return android_priv_cmd(bss, "PNOFORCE 0");
12146 }
12147
12148 #endif /* ANDROID */
12149
12150
12151 static int driver_nl80211_set_key(const char *ifname, void *priv,
12152                                   enum wpa_alg alg, const u8 *addr,
12153                                   int key_idx, int set_tx,
12154                                   const u8 *seq, size_t seq_len,
12155                                   const u8 *key, size_t key_len)
12156 {
12157         struct i802_bss *bss = priv;
12158         return wpa_driver_nl80211_set_key(ifname, bss, alg, addr, key_idx,
12159                                           set_tx, seq, seq_len, key, key_len);
12160 }
12161
12162
12163 static int driver_nl80211_scan2(void *priv,
12164                                 struct wpa_driver_scan_params *params)
12165 {
12166         struct i802_bss *bss = priv;
12167         return wpa_driver_nl80211_scan(bss, params);
12168 }
12169
12170
12171 static int driver_nl80211_deauthenticate(void *priv, const u8 *addr,
12172                                          int reason_code)
12173 {
12174         struct i802_bss *bss = priv;
12175         return wpa_driver_nl80211_deauthenticate(bss, addr, reason_code);
12176 }
12177
12178
12179 static int driver_nl80211_authenticate(void *priv,
12180                                        struct wpa_driver_auth_params *params)
12181 {
12182         struct i802_bss *bss = priv;
12183         return wpa_driver_nl80211_authenticate(bss, params);
12184 }
12185
12186
12187 static void driver_nl80211_deinit(void *priv)
12188 {
12189         struct i802_bss *bss = priv;
12190         wpa_driver_nl80211_deinit(bss);
12191 }
12192
12193
12194 static int driver_nl80211_if_remove(void *priv, enum wpa_driver_if_type type,
12195                                     const char *ifname)
12196 {
12197         struct i802_bss *bss = priv;
12198         return wpa_driver_nl80211_if_remove(bss, type, ifname);
12199 }
12200
12201
12202 static int driver_nl80211_send_mlme(void *priv, const u8 *data,
12203                                     size_t data_len, int noack)
12204 {
12205         struct i802_bss *bss = priv;
12206         return wpa_driver_nl80211_send_mlme(bss, data, data_len, noack,
12207                                             0, 0, 0, 0);
12208 }
12209
12210
12211 static int driver_nl80211_sta_remove(void *priv, const u8 *addr)
12212 {
12213         struct i802_bss *bss = priv;
12214         return wpa_driver_nl80211_sta_remove(bss, addr, -1, 0);
12215 }
12216
12217
12218 static int driver_nl80211_set_sta_vlan(void *priv, const u8 *addr,
12219                                        const char *ifname, int vlan_id)
12220 {
12221         struct i802_bss *bss = priv;
12222         return i802_set_sta_vlan(bss, addr, ifname, vlan_id);
12223 }
12224
12225
12226 static int driver_nl80211_read_sta_data(void *priv,
12227                                         struct hostap_sta_driver_data *data,
12228                                         const u8 *addr)
12229 {
12230         struct i802_bss *bss = priv;
12231         return i802_read_sta_data(bss, data, addr);
12232 }
12233
12234
12235 static int driver_nl80211_send_action(void *priv, unsigned int freq,
12236                                       unsigned int wait_time,
12237                                       const u8 *dst, const u8 *src,
12238                                       const u8 *bssid,
12239                                       const u8 *data, size_t data_len,
12240                                       int no_cck)
12241 {
12242         struct i802_bss *bss = priv;
12243         return wpa_driver_nl80211_send_action(bss, freq, wait_time, dst, src,
12244                                               bssid, data, data_len, no_cck);
12245 }
12246
12247
12248 static int driver_nl80211_probe_req_report(void *priv, int report)
12249 {
12250         struct i802_bss *bss = priv;
12251         return wpa_driver_nl80211_probe_req_report(bss, report);
12252 }
12253
12254
12255 static int wpa_driver_nl80211_update_ft_ies(void *priv, const u8 *md,
12256                                             const u8 *ies, size_t ies_len)
12257 {
12258         int ret;
12259         struct nl_msg *msg;
12260         struct i802_bss *bss = priv;
12261         struct wpa_driver_nl80211_data *drv = bss->drv;
12262         u16 mdid = WPA_GET_LE16(md);
12263
12264         msg = nlmsg_alloc();
12265         if (!msg)
12266                 return -ENOMEM;
12267
12268         wpa_printf(MSG_DEBUG, "nl80211: Updating FT IEs");
12269         nl80211_cmd(drv, msg, 0, NL80211_CMD_UPDATE_FT_IES);
12270         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
12271         NLA_PUT(msg, NL80211_ATTR_IE, ies_len, ies);
12272         NLA_PUT_U16(msg, NL80211_ATTR_MDID, mdid);
12273
12274         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
12275         if (ret) {
12276                 wpa_printf(MSG_DEBUG, "nl80211: update_ft_ies failed "
12277                            "err=%d (%s)", ret, strerror(-ret));
12278         }
12279
12280         return ret;
12281
12282 nla_put_failure:
12283         nlmsg_free(msg);
12284         return -ENOBUFS;
12285 }
12286
12287
12288 const u8 * wpa_driver_nl80211_get_macaddr(void *priv)
12289 {
12290         struct i802_bss *bss = priv;
12291         struct wpa_driver_nl80211_data *drv = bss->drv;
12292
12293         if (drv->nlmode != NL80211_IFTYPE_P2P_DEVICE)
12294                 return NULL;
12295
12296         return bss->addr;
12297 }
12298
12299
12300 static const char * scan_state_str(enum scan_states scan_state)
12301 {
12302         switch (scan_state) {
12303         case NO_SCAN:
12304                 return "NO_SCAN";
12305         case SCAN_REQUESTED:
12306                 return "SCAN_REQUESTED";
12307         case SCAN_STARTED:
12308                 return "SCAN_STARTED";
12309         case SCAN_COMPLETED:
12310                 return "SCAN_COMPLETED";
12311         case SCAN_ABORTED:
12312                 return "SCAN_ABORTED";
12313         case SCHED_SCAN_STARTED:
12314                 return "SCHED_SCAN_STARTED";
12315         case SCHED_SCAN_STOPPED:
12316                 return "SCHED_SCAN_STOPPED";
12317         case SCHED_SCAN_RESULTS:
12318                 return "SCHED_SCAN_RESULTS";
12319         }
12320
12321         return "??";
12322 }
12323
12324
12325 static int wpa_driver_nl80211_status(void *priv, char *buf, size_t buflen)
12326 {
12327         struct i802_bss *bss = priv;
12328         struct wpa_driver_nl80211_data *drv = bss->drv;
12329         int res;
12330         char *pos, *end;
12331
12332         pos = buf;
12333         end = buf + buflen;
12334
12335         res = os_snprintf(pos, end - pos,
12336                           "ifindex=%d\n"
12337                           "ifname=%s\n"
12338                           "brname=%s\n"
12339                           "addr=" MACSTR "\n"
12340                           "freq=%d\n"
12341                           "%s%s%s%s%s",
12342                           bss->ifindex,
12343                           bss->ifname,
12344                           bss->brname,
12345                           MAC2STR(bss->addr),
12346                           bss->freq,
12347                           bss->beacon_set ? "beacon_set=1\n" : "",
12348                           bss->added_if_into_bridge ?
12349                           "added_if_into_bridge=1\n" : "",
12350                           bss->added_bridge ? "added_bridge=1\n" : "",
12351                           bss->in_deinit ? "in_deinit=1\n" : "",
12352                           bss->if_dynamic ? "if_dynamic=1\n" : "");
12353         if (res < 0 || res >= end - pos)
12354                 return pos - buf;
12355         pos += res;
12356
12357         if (bss->wdev_id_set) {
12358                 res = os_snprintf(pos, end - pos, "wdev_id=%llu\n",
12359                                   (unsigned long long) bss->wdev_id);
12360                 if (res < 0 || res >= end - pos)
12361                         return pos - buf;
12362                 pos += res;
12363         }
12364
12365         res = os_snprintf(pos, end - pos,
12366                           "phyname=%s\n"
12367                           "perm_addr=" MACSTR "\n"
12368                           "drv_ifindex=%d\n"
12369                           "operstate=%d\n"
12370                           "scan_state=%s\n"
12371                           "auth_bssid=" MACSTR "\n"
12372                           "auth_attempt_bssid=" MACSTR "\n"
12373                           "bssid=" MACSTR "\n"
12374                           "prev_bssid=" MACSTR "\n"
12375                           "associated=%d\n"
12376                           "assoc_freq=%u\n"
12377                           "monitor_sock=%d\n"
12378                           "monitor_ifidx=%d\n"
12379                           "monitor_refcount=%d\n"
12380                           "last_mgmt_freq=%u\n"
12381                           "eapol_tx_sock=%d\n"
12382                           "%s%s%s%s%s%s%s%s%s%s%s%s%s",
12383                           drv->phyname,
12384                           MAC2STR(drv->perm_addr),
12385                           drv->ifindex,
12386                           drv->operstate,
12387                           scan_state_str(drv->scan_state),
12388                           MAC2STR(drv->auth_bssid),
12389                           MAC2STR(drv->auth_attempt_bssid),
12390                           MAC2STR(drv->bssid),
12391                           MAC2STR(drv->prev_bssid),
12392                           drv->associated,
12393                           drv->assoc_freq,
12394                           drv->monitor_sock,
12395                           drv->monitor_ifidx,
12396                           drv->monitor_refcount,
12397                           drv->last_mgmt_freq,
12398                           drv->eapol_tx_sock,
12399                           drv->ignore_if_down_event ?
12400                           "ignore_if_down_event=1\n" : "",
12401                           drv->scan_complete_events ?
12402                           "scan_complete_events=1\n" : "",
12403                           drv->disabled_11b_rates ?
12404                           "disabled_11b_rates=1\n" : "",
12405                           drv->pending_remain_on_chan ?
12406                           "pending_remain_on_chan=1\n" : "",
12407                           drv->in_interface_list ? "in_interface_list=1\n" : "",
12408                           drv->device_ap_sme ? "device_ap_sme=1\n" : "",
12409                           drv->poll_command_supported ?
12410                           "poll_command_supported=1\n" : "",
12411                           drv->data_tx_status ? "data_tx_status=1\n" : "",
12412                           drv->scan_for_auth ? "scan_for_auth=1\n" : "",
12413                           drv->retry_auth ? "retry_auth=1\n" : "",
12414                           drv->use_monitor ? "use_monitor=1\n" : "",
12415                           drv->ignore_next_local_disconnect ?
12416                           "ignore_next_local_disconnect=1\n" : "",
12417                           drv->ignore_next_local_deauth ?
12418                           "ignore_next_local_deauth=1\n" : "");
12419         if (res < 0 || res >= end - pos)
12420                 return pos - buf;
12421         pos += res;
12422
12423         if (drv->has_capability) {
12424                 res = os_snprintf(pos, end - pos,
12425                                   "capa.key_mgmt=0x%x\n"
12426                                   "capa.enc=0x%x\n"
12427                                   "capa.auth=0x%x\n"
12428                                   "capa.flags=0x%llx\n"
12429                                   "capa.max_scan_ssids=%d\n"
12430                                   "capa.max_sched_scan_ssids=%d\n"
12431                                   "capa.sched_scan_supported=%d\n"
12432                                   "capa.max_match_sets=%d\n"
12433                                   "capa.max_remain_on_chan=%u\n"
12434                                   "capa.max_stations=%u\n"
12435                                   "capa.probe_resp_offloads=0x%x\n"
12436                                   "capa.max_acl_mac_addrs=%u\n"
12437                                   "capa.num_multichan_concurrent=%u\n",
12438                                   drv->capa.key_mgmt,
12439                                   drv->capa.enc,
12440                                   drv->capa.auth,
12441                                   (unsigned long long) drv->capa.flags,
12442                                   drv->capa.max_scan_ssids,
12443                                   drv->capa.max_sched_scan_ssids,
12444                                   drv->capa.sched_scan_supported,
12445                                   drv->capa.max_match_sets,
12446                                   drv->capa.max_remain_on_chan,
12447                                   drv->capa.max_stations,
12448                                   drv->capa.probe_resp_offloads,
12449                                   drv->capa.max_acl_mac_addrs,
12450                                   drv->capa.num_multichan_concurrent);
12451                 if (res < 0 || res >= end - pos)
12452                         return pos - buf;
12453                 pos += res;
12454         }
12455
12456         return pos - buf;
12457 }
12458
12459
12460 static int set_beacon_data(struct nl_msg *msg, struct beacon_data *settings)
12461 {
12462         if (settings->head)
12463                 NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD,
12464                         settings->head_len, settings->head);
12465
12466         if (settings->tail)
12467                 NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL,
12468                         settings->tail_len, settings->tail);
12469
12470         if (settings->beacon_ies)
12471                 NLA_PUT(msg, NL80211_ATTR_IE,
12472                         settings->beacon_ies_len, settings->beacon_ies);
12473
12474         if (settings->proberesp_ies)
12475                 NLA_PUT(msg, NL80211_ATTR_IE_PROBE_RESP,
12476                         settings->proberesp_ies_len, settings->proberesp_ies);
12477
12478         if (settings->assocresp_ies)
12479                 NLA_PUT(msg,
12480                         NL80211_ATTR_IE_ASSOC_RESP,
12481                         settings->assocresp_ies_len, settings->assocresp_ies);
12482
12483         if (settings->probe_resp)
12484                 NLA_PUT(msg, NL80211_ATTR_PROBE_RESP,
12485                         settings->probe_resp_len, settings->probe_resp);
12486
12487         return 0;
12488
12489 nla_put_failure:
12490         return -ENOBUFS;
12491 }
12492
12493
12494 static int nl80211_switch_channel(void *priv, struct csa_settings *settings)
12495 {
12496         struct nl_msg *msg;
12497         struct i802_bss *bss = priv;
12498         struct wpa_driver_nl80211_data *drv = bss->drv;
12499         struct nlattr *beacon_csa;
12500         int ret = -ENOBUFS;
12501
12502         wpa_printf(MSG_DEBUG, "nl80211: Channel switch request (cs_count=%u block_tx=%u freq=%d width=%d cf1=%d cf2=%d)",
12503                    settings->cs_count, settings->block_tx,
12504                    settings->freq_params.freq, settings->freq_params.bandwidth,
12505                    settings->freq_params.center_freq1,
12506                    settings->freq_params.center_freq2);
12507
12508         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_AP_CSA)) {
12509                 wpa_printf(MSG_DEBUG, "nl80211: Driver does not support channel switch command");
12510                 return -EOPNOTSUPP;
12511         }
12512
12513         if ((drv->nlmode != NL80211_IFTYPE_AP) &&
12514             (drv->nlmode != NL80211_IFTYPE_P2P_GO))
12515                 return -EOPNOTSUPP;
12516
12517         /* check settings validity */
12518         if (!settings->beacon_csa.tail ||
12519             ((settings->beacon_csa.tail_len <=
12520               settings->counter_offset_beacon) ||
12521              (settings->beacon_csa.tail[settings->counter_offset_beacon] !=
12522               settings->cs_count)))
12523                 return -EINVAL;
12524
12525         if (settings->beacon_csa.probe_resp &&
12526             ((settings->beacon_csa.probe_resp_len <=
12527               settings->counter_offset_presp) ||
12528              (settings->beacon_csa.probe_resp[settings->counter_offset_presp] !=
12529               settings->cs_count)))
12530                 return -EINVAL;
12531
12532         msg = nlmsg_alloc();
12533         if (!msg)
12534                 return -ENOMEM;
12535
12536         nl80211_cmd(drv, msg, 0, NL80211_CMD_CHANNEL_SWITCH);
12537         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
12538         NLA_PUT_U32(msg, NL80211_ATTR_CH_SWITCH_COUNT, settings->cs_count);
12539         ret = nl80211_put_freq_params(msg, &settings->freq_params);
12540         if (ret)
12541                 goto error;
12542
12543         if (settings->block_tx)
12544                 NLA_PUT_FLAG(msg, NL80211_ATTR_CH_SWITCH_BLOCK_TX);
12545
12546         /* beacon_after params */
12547         ret = set_beacon_data(msg, &settings->beacon_after);
12548         if (ret)
12549                 goto error;
12550
12551         /* beacon_csa params */
12552         beacon_csa = nla_nest_start(msg, NL80211_ATTR_CSA_IES);
12553         if (!beacon_csa)
12554                 goto nla_put_failure;
12555
12556         ret = set_beacon_data(msg, &settings->beacon_csa);
12557         if (ret)
12558                 goto error;
12559
12560         NLA_PUT_U16(msg, NL80211_ATTR_CSA_C_OFF_BEACON,
12561                     settings->counter_offset_beacon);
12562
12563         if (settings->beacon_csa.probe_resp)
12564                 NLA_PUT_U16(msg, NL80211_ATTR_CSA_C_OFF_PRESP,
12565                             settings->counter_offset_presp);
12566
12567         nla_nest_end(msg, beacon_csa);
12568         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
12569         if (ret) {
12570                 wpa_printf(MSG_DEBUG, "nl80211: switch_channel failed err=%d (%s)",
12571                            ret, strerror(-ret));
12572         }
12573         return ret;
12574
12575 nla_put_failure:
12576         ret = -ENOBUFS;
12577 error:
12578         nlmsg_free(msg);
12579         wpa_printf(MSG_DEBUG, "nl80211: Could not build channel switch request");
12580         return ret;
12581 }
12582
12583
12584 #ifdef CONFIG_TESTING_OPTIONS
12585 static int cmd_reply_handler(struct nl_msg *msg, void *arg)
12586 {
12587         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
12588         struct wpabuf *buf = arg;
12589
12590         if (!buf)
12591                 return NL_SKIP;
12592
12593         if ((size_t) genlmsg_attrlen(gnlh, 0) > wpabuf_tailroom(buf)) {
12594                 wpa_printf(MSG_INFO, "nl80211: insufficient buffer space for reply");
12595                 return NL_SKIP;
12596         }
12597
12598         wpabuf_put_data(buf, genlmsg_attrdata(gnlh, 0),
12599                         genlmsg_attrlen(gnlh, 0));
12600
12601         return NL_SKIP;
12602 }
12603 #endif /* CONFIG_TESTING_OPTIONS */
12604
12605
12606 static int vendor_reply_handler(struct nl_msg *msg, void *arg)
12607 {
12608         struct nlattr *tb[NL80211_ATTR_MAX + 1];
12609         struct nlattr *nl_vendor_reply, *nl;
12610         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
12611         struct wpabuf *buf = arg;
12612         int rem;
12613
12614         if (!buf)
12615                 return NL_SKIP;
12616
12617         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
12618                   genlmsg_attrlen(gnlh, 0), NULL);
12619         nl_vendor_reply = tb[NL80211_ATTR_VENDOR_DATA];
12620
12621         if (!nl_vendor_reply)
12622                 return NL_SKIP;
12623
12624         if ((size_t) nla_len(nl_vendor_reply) > wpabuf_tailroom(buf)) {
12625                 wpa_printf(MSG_INFO, "nl80211: Vendor command: insufficient buffer space for reply");
12626                 return NL_SKIP;
12627         }
12628
12629         nla_for_each_nested(nl, nl_vendor_reply, rem) {
12630                 wpabuf_put_data(buf, nla_data(nl), nla_len(nl));
12631         }
12632
12633         return NL_SKIP;
12634 }
12635
12636
12637 static int nl80211_vendor_cmd(void *priv, unsigned int vendor_id,
12638                               unsigned int subcmd, const u8 *data,
12639                               size_t data_len, struct wpabuf *buf)
12640 {
12641         struct i802_bss *bss = priv;
12642         struct wpa_driver_nl80211_data *drv = bss->drv;
12643         struct nl_msg *msg;
12644         int ret;
12645
12646         msg = nlmsg_alloc();
12647         if (!msg)
12648                 return -ENOMEM;
12649
12650 #ifdef CONFIG_TESTING_OPTIONS
12651         if (vendor_id == 0xffffffff) {
12652                 nl80211_cmd(drv, msg, 0, subcmd);
12653                 if (nlmsg_append(msg, (void *) data, data_len, NLMSG_ALIGNTO) <
12654                     0)
12655                         goto nla_put_failure;
12656                 ret = send_and_recv_msgs(drv, msg, cmd_reply_handler, buf);
12657                 if (ret)
12658                         wpa_printf(MSG_DEBUG, "nl80211: command failed err=%d",
12659                                    ret);
12660                 return ret;
12661         }
12662 #endif /* CONFIG_TESTING_OPTIONS */
12663
12664         nl80211_cmd(drv, msg, 0, NL80211_CMD_VENDOR);
12665         if (nl80211_set_iface_id(msg, bss) < 0)
12666                 goto nla_put_failure;
12667         NLA_PUT_U32(msg, NL80211_ATTR_VENDOR_ID, vendor_id);
12668         NLA_PUT_U32(msg, NL80211_ATTR_VENDOR_SUBCMD, subcmd);
12669         if (data)
12670                 NLA_PUT(msg, NL80211_ATTR_VENDOR_DATA, data_len, data);
12671
12672         ret = send_and_recv_msgs(drv, msg, vendor_reply_handler, buf);
12673         if (ret)
12674                 wpa_printf(MSG_DEBUG, "nl80211: vendor command failed err=%d",
12675                            ret);
12676         return ret;
12677
12678 nla_put_failure:
12679         nlmsg_free(msg);
12680         return -ENOBUFS;
12681 }
12682
12683
12684 static int nl80211_set_qos_map(void *priv, const u8 *qos_map_set,
12685                                u8 qos_map_set_len)
12686 {
12687         struct i802_bss *bss = priv;
12688         struct wpa_driver_nl80211_data *drv = bss->drv;
12689         struct nl_msg *msg;
12690         int ret;
12691
12692         msg = nlmsg_alloc();
12693         if (!msg)
12694                 return -ENOMEM;
12695
12696         wpa_hexdump(MSG_DEBUG, "nl80211: Setting QoS Map",
12697                     qos_map_set, qos_map_set_len);
12698
12699         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_QOS_MAP);
12700         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
12701         NLA_PUT(msg, NL80211_ATTR_QOS_MAP, qos_map_set_len, qos_map_set);
12702
12703         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
12704         if (ret)
12705                 wpa_printf(MSG_DEBUG, "nl80211: Setting QoS Map failed");
12706
12707         return ret;
12708
12709 nla_put_failure:
12710         nlmsg_free(msg);
12711         return -ENOBUFS;
12712 }
12713
12714
12715 static int nl80211_set_wowlan(void *priv,
12716                               const struct wowlan_triggers *triggers)
12717 {
12718         struct i802_bss *bss = priv;
12719         struct wpa_driver_nl80211_data *drv = bss->drv;
12720         struct nl_msg *msg;
12721         struct nlattr *wowlan_triggers;
12722         int ret;
12723
12724         msg = nlmsg_alloc();
12725         if (!msg)
12726                 return -ENOMEM;
12727
12728         wpa_printf(MSG_DEBUG, "nl80211: Setting wowlan");
12729
12730         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WOWLAN);
12731         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
12732
12733         wowlan_triggers = nla_nest_start(msg, NL80211_ATTR_WOWLAN_TRIGGERS);
12734         if (!wowlan_triggers)
12735                 goto nla_put_failure;
12736
12737         if (triggers->any)
12738                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_ANY);
12739         if (triggers->disconnect)
12740                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_DISCONNECT);
12741         if (triggers->magic_pkt)
12742                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_MAGIC_PKT);
12743         if (triggers->gtk_rekey_failure)
12744                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_GTK_REKEY_FAILURE);
12745         if (triggers->eap_identity_req)
12746                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_EAP_IDENT_REQUEST);
12747         if (triggers->four_way_handshake)
12748                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_4WAY_HANDSHAKE);
12749         if (triggers->rfkill_release)
12750                 NLA_PUT_FLAG(msg, NL80211_WOWLAN_TRIG_RFKILL_RELEASE);
12751
12752         nla_nest_end(msg, wowlan_triggers);
12753
12754         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
12755         if (ret)
12756                 wpa_printf(MSG_DEBUG, "nl80211: Setting wowlan failed");
12757
12758         return ret;
12759
12760 nla_put_failure:
12761         nlmsg_free(msg);
12762         return -ENOBUFS;
12763 }
12764
12765
12766 static int nl80211_roaming(void *priv, int allowed, const u8 *bssid)
12767 {
12768         struct i802_bss *bss = priv;
12769         struct wpa_driver_nl80211_data *drv = bss->drv;
12770         struct nl_msg *msg;
12771         struct nlattr *params;
12772
12773         wpa_printf(MSG_DEBUG, "nl80211: Roaming policy: allowed=%d", allowed);
12774
12775         if (!drv->roaming_vendor_cmd_avail) {
12776                 wpa_printf(MSG_DEBUG,
12777                            "nl80211: Ignore roaming policy change since driver does not provide command for setting it");
12778                 return -1;
12779         }
12780
12781         msg = nlmsg_alloc();
12782         if (!msg)
12783                 return -ENOMEM;
12784
12785         nl80211_cmd(drv, msg, 0, NL80211_CMD_VENDOR);
12786
12787         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
12788         NLA_PUT_U32(msg, NL80211_ATTR_VENDOR_ID, OUI_QCA);
12789         NLA_PUT_U32(msg, NL80211_ATTR_VENDOR_SUBCMD,
12790                     QCA_NL80211_VENDOR_SUBCMD_ROAMING);
12791
12792         params = nla_nest_start(msg, NL80211_ATTR_VENDOR_DATA);
12793         if (!params)
12794                 goto nla_put_failure;
12795         NLA_PUT_U32(msg, QCA_WLAN_VENDOR_ATTR_ROAMING_POLICY,
12796                     allowed ? QCA_ROAMING_ALLOWED_WITHIN_ESS :
12797                     QCA_ROAMING_NOT_ALLOWED);
12798         if (bssid)
12799                 NLA_PUT(msg, QCA_WLAN_VENDOR_ATTR_MAC_ADDR, ETH_ALEN, bssid);
12800         nla_nest_end(msg, params);
12801
12802         return send_and_recv_msgs(drv, msg, NULL, NULL);
12803
12804  nla_put_failure:
12805         nlmsg_free(msg);
12806         return -1;
12807 }
12808
12809
12810 static int nl80211_set_mac_addr(void *priv, const u8 *addr)
12811 {
12812         struct i802_bss *bss = priv;
12813         struct wpa_driver_nl80211_data *drv = bss->drv;
12814         int new_addr = addr != NULL;
12815
12816         if (!addr)
12817                 addr = drv->perm_addr;
12818
12819         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0) < 0)
12820                 return -1;
12821
12822         if (linux_set_ifhwaddr(drv->global->ioctl_sock, bss->ifname, addr) < 0)
12823         {
12824                 wpa_printf(MSG_DEBUG,
12825                            "nl80211: failed to set_mac_addr for %s to " MACSTR,
12826                            bss->ifname, MAC2STR(addr));
12827                 if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname,
12828                                           1) < 0) {
12829                         wpa_printf(MSG_DEBUG,
12830                                    "nl80211: Could not restore interface UP after failed set_mac_addr");
12831                 }
12832                 return -1;
12833         }
12834
12835         wpa_printf(MSG_DEBUG, "nl80211: set_mac_addr for %s to " MACSTR,
12836                    bss->ifname, MAC2STR(addr));
12837         drv->addr_changed = new_addr;
12838         os_memcpy(bss->addr, addr, ETH_ALEN);
12839
12840         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1) < 0)
12841         {
12842                 wpa_printf(MSG_DEBUG,
12843                            "nl80211: Could not restore interface UP after set_mac_addr");
12844         }
12845
12846         return 0;
12847 }
12848
12849
12850 #ifdef CONFIG_MESH
12851
12852 static int wpa_driver_nl80211_init_mesh(void *priv)
12853 {
12854         if (wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_MESH_POINT)) {
12855                 wpa_printf(MSG_INFO,
12856                            "nl80211: Failed to set interface into mesh mode");
12857                 return -1;
12858         }
12859         return 0;
12860 }
12861
12862
12863 static int
12864 wpa_driver_nl80211_join_mesh(void *priv,
12865                              struct wpa_driver_mesh_join_params *params)
12866 {
12867         struct i802_bss *bss = priv;
12868         struct wpa_driver_nl80211_data *drv = bss->drv;
12869         struct nl_msg *msg;
12870         struct nlattr *container;
12871         int ret = 0;
12872
12873         msg = nlmsg_alloc();
12874         if (!msg)
12875                 return -1;
12876
12877         wpa_printf(MSG_DEBUG, "nl80211: mesh join (ifindex=%d)", drv->ifindex);
12878         nl80211_cmd(drv, msg, 0, NL80211_CMD_JOIN_MESH);
12879
12880         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
12881         /* XXX: need chtype too in case we want HT */
12882         if (params->freq) {
12883                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
12884                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
12885         }
12886
12887         if (params->basic_rates) {
12888                 u8 rates[NL80211_MAX_SUPP_RATES];
12889                 u8 rates_len = 0;
12890                 int i;
12891
12892                 for (i = 0; i < NL80211_MAX_SUPP_RATES; i++) {
12893                         if (params->basic_rates[i] < 0)
12894                                 break;
12895                         rates[rates_len++] = params->basic_rates[i] / 5;
12896                 }
12897
12898                 NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
12899         }
12900
12901         if (params->meshid) {
12902                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
12903                                   params->meshid, params->meshid_len);
12904                 NLA_PUT(msg, NL80211_ATTR_MESH_ID, params->meshid_len,
12905                         params->meshid);
12906         }
12907
12908         wpa_printf(MSG_DEBUG, "  * flags=%08X", params->flags);
12909
12910         container = nla_nest_start(msg, NL80211_ATTR_MESH_SETUP);
12911         if (!container)
12912                 goto nla_put_failure;
12913
12914         if (params->ies) {
12915                 wpa_hexdump(MSG_DEBUG, "  * IEs", params->ies, params->ie_len);
12916                 NLA_PUT(msg, NL80211_MESH_SETUP_IE, params->ie_len,
12917                         params->ies);
12918         }
12919         /* WPA_DRIVER_MESH_FLAG_OPEN_AUTH is treated as default by nl80211 */
12920         if (params->flags & WPA_DRIVER_MESH_FLAG_SAE_AUTH) {
12921                 NLA_PUT_U8(msg, NL80211_MESH_SETUP_AUTH_PROTOCOL, 0x1);
12922                 NLA_PUT_FLAG(msg, NL80211_MESH_SETUP_USERSPACE_AUTH);
12923         }
12924         if (params->flags & WPA_DRIVER_MESH_FLAG_AMPE)
12925                 NLA_PUT_FLAG(msg, NL80211_MESH_SETUP_USERSPACE_AMPE);
12926         if (params->flags & WPA_DRIVER_MESH_FLAG_USER_MPM)
12927                 NLA_PUT_FLAG(msg, NL80211_MESH_SETUP_USERSPACE_MPM);
12928         nla_nest_end(msg, container);
12929
12930         container = nla_nest_start(msg, NL80211_ATTR_MESH_CONFIG);
12931         if (!container)
12932                 goto nla_put_failure;
12933
12934         if (!(params->conf.flags & WPA_DRIVER_MESH_CONF_FLAG_AUTO_PLINKS))
12935                 NLA_PUT_U32(msg, NL80211_MESHCONF_AUTO_OPEN_PLINKS, 0);
12936         nla_nest_end(msg, container);
12937
12938         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
12939         msg = NULL;
12940         if (ret) {
12941                 wpa_printf(MSG_DEBUG, "nl80211: mesh join failed: ret=%d (%s)",
12942                            ret, strerror(-ret));
12943                 goto nla_put_failure;
12944         }
12945         ret = 0;
12946         bss->freq = params->freq;
12947         wpa_printf(MSG_DEBUG, "nl80211: mesh join request send successfully");
12948
12949
12950 nla_put_failure:
12951         nlmsg_free(msg);
12952         return ret;
12953 }
12954
12955
12956 static int wpa_driver_nl80211_leave_mesh(void *priv)
12957 {
12958         struct i802_bss *bss = priv;
12959         struct wpa_driver_nl80211_data *drv = bss->drv;
12960         struct nl_msg *msg;
12961         int ret = 0;
12962
12963         msg = nlmsg_alloc();
12964         if (!msg)
12965                 return -1;
12966
12967         wpa_printf(MSG_DEBUG, "nl80211: mesh leave (ifindex=%d)", drv->ifindex);
12968         nl80211_cmd(drv, msg, 0, NL80211_CMD_LEAVE_MESH);
12969         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
12970
12971         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
12972         msg = NULL;
12973         if (ret) {
12974                 wpa_printf(MSG_DEBUG, "nl80211: mesh leave failed: ret=%d (%s)",
12975                            ret, strerror(-ret));
12976                 goto nla_put_failure;
12977         }
12978         ret = 0;
12979         wpa_printf(MSG_DEBUG, "nl80211: mesh leave request send successfully");
12980
12981 nla_put_failure:
12982         nlmsg_free(msg);
12983         return ret;
12984 }
12985
12986 #endif /* CONFIG_MESH */
12987
12988
12989 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
12990         .name = "nl80211",
12991         .desc = "Linux nl80211/cfg80211",
12992         .get_bssid = wpa_driver_nl80211_get_bssid,
12993         .get_ssid = wpa_driver_nl80211_get_ssid,
12994         .set_key = driver_nl80211_set_key,
12995         .scan2 = driver_nl80211_scan2,
12996         .sched_scan = wpa_driver_nl80211_sched_scan,
12997         .stop_sched_scan = wpa_driver_nl80211_stop_sched_scan,
12998         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
12999         .deauthenticate = driver_nl80211_deauthenticate,
13000         .authenticate = driver_nl80211_authenticate,
13001         .associate = wpa_driver_nl80211_associate,
13002         .global_init = nl80211_global_init,
13003         .global_deinit = nl80211_global_deinit,
13004         .init2 = wpa_driver_nl80211_init,
13005         .deinit = driver_nl80211_deinit,
13006         .get_capa = wpa_driver_nl80211_get_capa,
13007         .set_operstate = wpa_driver_nl80211_set_operstate,
13008         .set_supp_port = wpa_driver_nl80211_set_supp_port,
13009         .set_country = wpa_driver_nl80211_set_country,
13010         .get_country = wpa_driver_nl80211_get_country,
13011         .set_ap = wpa_driver_nl80211_set_ap,
13012         .set_acl = wpa_driver_nl80211_set_acl,
13013         .if_add = wpa_driver_nl80211_if_add,
13014         .if_remove = driver_nl80211_if_remove,
13015         .send_mlme = driver_nl80211_send_mlme,
13016         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
13017         .sta_add = wpa_driver_nl80211_sta_add,
13018         .sta_remove = driver_nl80211_sta_remove,
13019         .hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
13020         .sta_set_flags = wpa_driver_nl80211_sta_set_flags,
13021         .hapd_init = i802_init,
13022         .hapd_deinit = i802_deinit,
13023         .set_wds_sta = i802_set_wds_sta,
13024         .get_seqnum = i802_get_seqnum,
13025         .flush = i802_flush,
13026         .get_inact_sec = i802_get_inact_sec,
13027         .sta_clear_stats = i802_sta_clear_stats,
13028         .set_rts = i802_set_rts,
13029         .set_frag = i802_set_frag,
13030         .set_tx_queue_params = i802_set_tx_queue_params,
13031         .set_sta_vlan = driver_nl80211_set_sta_vlan,
13032         .sta_deauth = i802_sta_deauth,
13033         .sta_disassoc = i802_sta_disassoc,
13034         .read_sta_data = driver_nl80211_read_sta_data,
13035         .set_freq = i802_set_freq,
13036         .send_action = driver_nl80211_send_action,
13037         .send_action_cancel_wait = wpa_driver_nl80211_send_action_cancel_wait,
13038         .remain_on_channel = wpa_driver_nl80211_remain_on_channel,
13039         .cancel_remain_on_channel =
13040         wpa_driver_nl80211_cancel_remain_on_channel,
13041         .probe_req_report = driver_nl80211_probe_req_report,
13042         .deinit_ap = wpa_driver_nl80211_deinit_ap,
13043         .deinit_p2p_cli = wpa_driver_nl80211_deinit_p2p_cli,
13044         .resume = wpa_driver_nl80211_resume,
13045         .send_ft_action = nl80211_send_ft_action,
13046         .signal_monitor = nl80211_signal_monitor,
13047         .signal_poll = nl80211_signal_poll,
13048         .send_frame = nl80211_send_frame,
13049         .shared_freq = wpa_driver_nl80211_shared_freq,
13050         .set_param = nl80211_set_param,
13051         .get_radio_name = nl80211_get_radio_name,
13052         .add_pmkid = nl80211_add_pmkid,
13053         .remove_pmkid = nl80211_remove_pmkid,
13054         .flush_pmkid = nl80211_flush_pmkid,
13055         .set_rekey_info = nl80211_set_rekey_info,
13056         .poll_client = nl80211_poll_client,
13057         .set_p2p_powersave = nl80211_set_p2p_powersave,
13058         .start_dfs_cac = nl80211_start_radar_detection,
13059         .stop_ap = wpa_driver_nl80211_stop_ap,
13060 #ifdef CONFIG_TDLS
13061         .send_tdls_mgmt = nl80211_send_tdls_mgmt,
13062         .tdls_oper = nl80211_tdls_oper,
13063 #endif /* CONFIG_TDLS */
13064         .update_ft_ies = wpa_driver_nl80211_update_ft_ies,
13065         .get_mac_addr = wpa_driver_nl80211_get_macaddr,
13066         .get_survey = wpa_driver_nl80211_get_survey,
13067         .status = wpa_driver_nl80211_status,
13068         .switch_channel = nl80211_switch_channel,
13069 #ifdef ANDROID_P2P
13070         .set_noa = wpa_driver_set_p2p_noa,
13071         .get_noa = wpa_driver_get_p2p_noa,
13072         .set_ap_wps_ie = wpa_driver_set_ap_wps_p2p_ie,
13073 #endif /* ANDROID_P2P */
13074 #ifdef ANDROID
13075         .driver_cmd = wpa_driver_nl80211_driver_cmd,
13076 #endif /* ANDROID */
13077         .vendor_cmd = nl80211_vendor_cmd,
13078         .set_qos_map = nl80211_set_qos_map,
13079         .set_wowlan = nl80211_set_wowlan,
13080         .roaming = nl80211_roaming,
13081         .set_mac_addr = nl80211_set_mac_addr,
13082 #ifdef CONFIG_MESH
13083         .init_mesh = wpa_driver_nl80211_init_mesh,
13084         .join_mesh = wpa_driver_nl80211_join_mesh,
13085         .leave_mesh = wpa_driver_nl80211_leave_mesh,
13086 #endif /* CONFIG_MESH */
13087 };