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