1/*
2 * Driver interaction with Linux nl80211/cfg80211
3 * Copyright (c) 2002-2012, Jouni Malinen <j@w1.fi>
4 * Copyright (c) 2003-2004, Instant802 Networks, Inc.
5 * Copyright (c) 2005-2006, Devicescape Software, Inc.
6 * Copyright (c) 2007, Johannes Berg <johannes@sipsolutions.net>
7 * Copyright (c) 2009-2010, Atheros Communications
8 *
9 * This software may be distributed under the terms of the BSD license.
10 * See README for more details.
11 */
12
13#include "includes.h"
14#include <sys/ioctl.h>
15#include <sys/types.h>
16#include <sys/stat.h>
17#include <fcntl.h>
18#include <net/if.h>
19#include <netlink/genl/genl.h>
20#include <netlink/genl/family.h>
21#include <netlink/genl/ctrl.h>
22#include <linux/rtnetlink.h>
23#include <netpacket/packet.h>
24#include <linux/filter.h>
25#include <linux/errqueue.h>
26#include "nl80211_copy.h"
27
28#include "common.h"
29#include "eloop.h"
30#include "utils/list.h"
31#include "common/ieee802_11_defs.h"
32#include "common/ieee802_11_common.h"
33#include "l2_packet/l2_packet.h"
34#include "netlink.h"
35#include "linux_ioctl.h"
36#include "radiotap.h"
37#include "radiotap_iter.h"
38#include "rfkill.h"
39#include "driver.h"
40
41#ifndef SO_WIFI_STATUS
42# if defined(__sparc__)
43#  define SO_WIFI_STATUS	0x0025
44# elif defined(__parisc__)
45#  define SO_WIFI_STATUS	0x4022
46# else
47#  define SO_WIFI_STATUS	41
48# endif
49
50# define SCM_WIFI_STATUS	SO_WIFI_STATUS
51#endif
52
53#ifndef SO_EE_ORIGIN_TXSTATUS
54#define SO_EE_ORIGIN_TXSTATUS	4
55#endif
56
57#ifndef PACKET_TX_TIMESTAMP
58#define PACKET_TX_TIMESTAMP	16
59#endif
60
61#ifdef ANDROID
62#include "android_drv.h"
63#endif /* ANDROID */
64#ifdef CONFIG_LIBNL20
65/* libnl 2.0 compatibility code */
66#define nl_handle nl_sock
67#define nl80211_handle_alloc nl_socket_alloc_cb
68#define nl80211_handle_destroy nl_socket_free
69#else
70/*
71 * libnl 1.1 has a bug, it tries to allocate socket numbers densely
72 * but when you free a socket again it will mess up its bitmap and
73 * and use the wrong number the next time it needs a socket ID.
74 * Therefore, we wrap the handle alloc/destroy and add our own pid
75 * accounting.
76 */
77static uint32_t port_bitmap[32] = { 0 };
78
79static struct nl_handle *nl80211_handle_alloc(void *cb)
80{
81	struct nl_handle *handle;
82	uint32_t pid = getpid() & 0x3FFFFF;
83	int i;
84
85	handle = nl_handle_alloc_cb(cb);
86
87	for (i = 0; i < 1024; i++) {
88		if (port_bitmap[i / 32] & (1 << (i % 32)))
89			continue;
90		port_bitmap[i / 32] |= 1 << (i % 32);
91		pid += i << 22;
92		break;
93	}
94
95	nl_socket_set_local_port(handle, pid);
96
97	return handle;
98}
99
100static void nl80211_handle_destroy(struct nl_handle *handle)
101{
102	uint32_t port = nl_socket_get_local_port(handle);
103
104	port >>= 22;
105	port_bitmap[port / 32] &= ~(1 << (port % 32));
106
107	nl_handle_destroy(handle);
108}
109#endif /* CONFIG_LIBNL20 */
110
111
112static struct nl_handle * nl_create_handle(struct nl_cb *cb, const char *dbg)
113{
114	struct nl_handle *handle;
115
116	handle = nl80211_handle_alloc(cb);
117	if (handle == NULL) {
118		wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
119			   "callbacks (%s)", dbg);
120		return NULL;
121	}
122
123	if (genl_connect(handle)) {
124		wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
125			   "netlink (%s)", dbg);
126		nl80211_handle_destroy(handle);
127		return NULL;
128	}
129
130	return handle;
131}
132
133
134static void nl_destroy_handles(struct nl_handle **handle)
135{
136	if (*handle == NULL)
137		return;
138	nl80211_handle_destroy(*handle);
139	*handle = NULL;
140}
141
142
143#ifndef IFF_LOWER_UP
144#define IFF_LOWER_UP   0x10000         /* driver signals L1 up         */
145#endif
146#ifndef IFF_DORMANT
147#define IFF_DORMANT    0x20000         /* driver signals dormant       */
148#endif
149
150#ifndef IF_OPER_DORMANT
151#define IF_OPER_DORMANT 5
152#endif
153#ifndef IF_OPER_UP
154#define IF_OPER_UP 6
155#endif
156
157struct nl80211_global {
158	struct dl_list interfaces;
159	int if_add_ifindex;
160	struct netlink_data *netlink;
161	struct nl_cb *nl_cb;
162	struct nl_handle *nl;
163	int nl80211_id;
164	int ioctl_sock; /* socket for ioctl() use */
165
166	struct nl_handle *nl_event;
167};
168
169struct nl80211_wiphy_data {
170	struct dl_list list;
171	struct dl_list bsss;
172	struct dl_list drvs;
173
174	struct nl_handle *nl_beacons;
175	struct nl_cb *nl_cb;
176
177	int wiphy_idx;
178};
179
180static void nl80211_global_deinit(void *priv);
181static void wpa_driver_nl80211_deinit(void *priv);
182
183struct i802_bss {
184	struct wpa_driver_nl80211_data *drv;
185	struct i802_bss *next;
186	int ifindex;
187	char ifname[IFNAMSIZ + 1];
188	char brname[IFNAMSIZ];
189	unsigned int beacon_set:1;
190	unsigned int added_if_into_bridge:1;
191	unsigned int added_bridge:1;
192	unsigned int in_deinit:1;
193
194	u8 addr[ETH_ALEN];
195
196	int freq;
197
198	struct nl_handle *nl_preq, *nl_mgmt;
199	struct nl_cb *nl_cb;
200
201	struct nl80211_wiphy_data *wiphy_data;
202	struct dl_list wiphy_list;
203};
204
205struct wpa_driver_nl80211_data {
206	struct nl80211_global *global;
207	struct dl_list list;
208	struct dl_list wiphy_list;
209	char phyname[32];
210	void *ctx;
211	int ifindex;
212	int if_removed;
213	int if_disabled;
214	int ignore_if_down_event;
215	struct rfkill_data *rfkill;
216	struct wpa_driver_capa capa;
217	int has_capability;
218
219	int operstate;
220
221	int scan_complete_events;
222
223	struct nl_cb *nl_cb;
224
225	u8 auth_bssid[ETH_ALEN];
226	u8 bssid[ETH_ALEN];
227	int associated;
228	u8 ssid[32];
229	size_t ssid_len;
230	enum nl80211_iftype nlmode;
231	enum nl80211_iftype ap_scan_as_station;
232	unsigned int assoc_freq;
233
234	int monitor_sock;
235	int monitor_ifidx;
236	int monitor_refcount;
237
238	unsigned int disabled_11b_rates:1;
239	unsigned int pending_remain_on_chan:1;
240	unsigned int in_interface_list:1;
241	unsigned int device_ap_sme:1;
242	unsigned int poll_command_supported:1;
243	unsigned int data_tx_status:1;
244	unsigned int scan_for_auth:1;
245	unsigned int retry_auth:1;
246	unsigned int use_monitor:1;
247
248	u64 remain_on_chan_cookie;
249	u64 send_action_cookie;
250
251	unsigned int last_mgmt_freq;
252
253	struct wpa_driver_scan_filter *filter_ssids;
254	size_t num_filter_ssids;
255
256	struct i802_bss first_bss;
257
258	int eapol_tx_sock;
259
260#ifdef HOSTAPD
261	int eapol_sock; /* socket for EAPOL frames */
262
263	int default_if_indices[16];
264	int *if_indices;
265	int num_if_indices;
266
267	int last_freq;
268	int last_freq_ht;
269#endif /* HOSTAPD */
270
271	/* From failed authentication command */
272	int auth_freq;
273	u8 auth_bssid_[ETH_ALEN];
274	u8 auth_ssid[32];
275	size_t auth_ssid_len;
276	int auth_alg;
277	u8 *auth_ie;
278	size_t auth_ie_len;
279	u8 auth_wep_key[4][16];
280	size_t auth_wep_key_len[4];
281	int auth_wep_tx_keyidx;
282	int auth_local_state_change;
283	int auth_p2p;
284};
285
286
287static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx,
288					    void *timeout_ctx);
289static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
290				       enum nl80211_iftype nlmode);
291static int
292wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv);
293static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
294				   const u8 *addr, int cmd, u16 reason_code,
295				   int local_state_change);
296static void nl80211_remove_monitor_interface(
297	struct wpa_driver_nl80211_data *drv);
298static int nl80211_send_frame_cmd(struct i802_bss *bss,
299				  unsigned int freq, unsigned int wait,
300				  const u8 *buf, size_t buf_len, u64 *cookie,
301				  int no_cck, int no_ack, int offchanok);
302static int wpa_driver_nl80211_probe_req_report(void *priv, int report);
303#ifdef ANDROID
304static int android_pno_start(struct i802_bss *bss,
305			     struct wpa_driver_scan_params *params);
306static int android_pno_stop(struct i802_bss *bss);
307#endif /* ANDROID */
308#ifdef ANDROID_P2P
309int wpa_driver_set_p2p_noa(void *priv, u8 count, int start, int duration);
310int wpa_driver_get_p2p_noa(void *priv, u8 *buf, size_t len);
311int wpa_driver_set_p2p_ps(void *priv, int legacy_ps, int opp_ps, int ctwindow);
312int wpa_driver_set_ap_wps_p2p_ie(void *priv, const struct wpabuf *beacon,
313				  const struct wpabuf *proberesp,
314				  const struct wpabuf *assocresp);
315
316#endif
317#ifdef HOSTAPD
318static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
319static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
320static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
321static int wpa_driver_nl80211_if_remove(void *priv,
322					enum wpa_driver_if_type type,
323					const char *ifname);
324#else /* HOSTAPD */
325static inline void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
326{
327}
328
329static inline void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
330{
331}
332
333static inline int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
334{
335	return 0;
336}
337#endif /* HOSTAPD */
338#ifdef ANDROID
339extern int wpa_driver_nl80211_driver_cmd(void *priv, char *cmd, char *buf,
340					 size_t buf_len);
341#endif
342
343static int i802_set_freq(void *priv, struct hostapd_freq_params *freq);
344static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
345				     int ifindex, int disabled);
346
347static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv);
348static int wpa_driver_nl80211_authenticate_retry(
349	struct wpa_driver_nl80211_data *drv);
350
351
352static int is_ap_interface(enum nl80211_iftype nlmode)
353{
354	return (nlmode == NL80211_IFTYPE_AP ||
355		nlmode == NL80211_IFTYPE_P2P_GO);
356}
357
358
359static int is_sta_interface(enum nl80211_iftype nlmode)
360{
361	return (nlmode == NL80211_IFTYPE_STATION ||
362		nlmode == NL80211_IFTYPE_P2P_CLIENT);
363}
364
365
366static int is_p2p_interface(enum nl80211_iftype nlmode)
367{
368	return (nlmode == NL80211_IFTYPE_P2P_CLIENT ||
369		nlmode == NL80211_IFTYPE_P2P_GO);
370}
371
372
373struct nl80211_bss_info_arg {
374	struct wpa_driver_nl80211_data *drv;
375	struct wpa_scan_results *res;
376	unsigned int assoc_freq;
377	u8 assoc_bssid[ETH_ALEN];
378};
379
380static int bss_info_handler(struct nl_msg *msg, void *arg);
381
382
383/* nl80211 code */
384static int ack_handler(struct nl_msg *msg, void *arg)
385{
386	int *err = arg;
387	*err = 0;
388	return NL_STOP;
389}
390
391static int finish_handler(struct nl_msg *msg, void *arg)
392{
393	int *ret = arg;
394	*ret = 0;
395	return NL_SKIP;
396}
397
398static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err,
399			 void *arg)
400{
401	int *ret = arg;
402	*ret = err->error;
403	return NL_SKIP;
404}
405
406
407static int no_seq_check(struct nl_msg *msg, void *arg)
408{
409	return NL_OK;
410}
411
412
413static int send_and_recv(struct nl80211_global *global,
414			 struct nl_handle *nl_handle, struct nl_msg *msg,
415			 int (*valid_handler)(struct nl_msg *, void *),
416			 void *valid_data)
417{
418	struct nl_cb *cb;
419	int err = -ENOMEM;
420
421	cb = nl_cb_clone(global->nl_cb);
422	if (!cb)
423		goto out;
424
425	err = nl_send_auto_complete(nl_handle, msg);
426	if (err < 0)
427		goto out;
428
429	err = 1;
430
431	nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
432	nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
433	nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
434
435	if (valid_handler)
436		nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM,
437			  valid_handler, valid_data);
438
439	while (err > 0)
440		nl_recvmsgs(nl_handle, cb);
441 out:
442	nl_cb_put(cb);
443	nlmsg_free(msg);
444	return err;
445}
446
447
448static int send_and_recv_msgs_global(struct nl80211_global *global,
449				     struct nl_msg *msg,
450				     int (*valid_handler)(struct nl_msg *, void *),
451				     void *valid_data)
452{
453	return send_and_recv(global, global->nl, msg, valid_handler,
454			     valid_data);
455}
456
457
458#ifndef ANDROID
459static
460#endif
461int send_and_recv_msgs(struct wpa_driver_nl80211_data *drv,
462			      struct nl_msg *msg,
463			      int (*valid_handler)(struct nl_msg *, void *),
464			      void *valid_data)
465{
466	return send_and_recv(drv->global, drv->global->nl, msg,
467			     valid_handler, valid_data);
468}
469
470
471struct family_data {
472	const char *group;
473	int id;
474};
475
476
477static int family_handler(struct nl_msg *msg, void *arg)
478{
479	struct family_data *res = arg;
480	struct nlattr *tb[CTRL_ATTR_MAX + 1];
481	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
482	struct nlattr *mcgrp;
483	int i;
484
485	nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
486		  genlmsg_attrlen(gnlh, 0), NULL);
487	if (!tb[CTRL_ATTR_MCAST_GROUPS])
488		return NL_SKIP;
489
490	nla_for_each_nested(mcgrp, tb[CTRL_ATTR_MCAST_GROUPS], i) {
491		struct nlattr *tb2[CTRL_ATTR_MCAST_GRP_MAX + 1];
492		nla_parse(tb2, CTRL_ATTR_MCAST_GRP_MAX, nla_data(mcgrp),
493			  nla_len(mcgrp), NULL);
494		if (!tb2[CTRL_ATTR_MCAST_GRP_NAME] ||
495		    !tb2[CTRL_ATTR_MCAST_GRP_ID] ||
496		    os_strncmp(nla_data(tb2[CTRL_ATTR_MCAST_GRP_NAME]),
497			       res->group,
498			       nla_len(tb2[CTRL_ATTR_MCAST_GRP_NAME])) != 0)
499			continue;
500		res->id = nla_get_u32(tb2[CTRL_ATTR_MCAST_GRP_ID]);
501		break;
502	};
503
504	return NL_SKIP;
505}
506
507
508static int nl_get_multicast_id(struct nl80211_global *global,
509			       const char *family, const char *group)
510{
511	struct nl_msg *msg;
512	int ret = -1;
513	struct family_data res = { group, -ENOENT };
514
515	msg = nlmsg_alloc();
516	if (!msg)
517		return -ENOMEM;
518	genlmsg_put(msg, 0, 0, genl_ctrl_resolve(global->nl, "nlctrl"),
519		    0, 0, CTRL_CMD_GETFAMILY, 0);
520	NLA_PUT_STRING(msg, CTRL_ATTR_FAMILY_NAME, family);
521
522	ret = send_and_recv_msgs_global(global, msg, family_handler, &res);
523	msg = NULL;
524	if (ret == 0)
525		ret = res.id;
526
527nla_put_failure:
528	nlmsg_free(msg);
529	return ret;
530}
531
532
533static void * nl80211_cmd(struct wpa_driver_nl80211_data *drv,
534			  struct nl_msg *msg, int flags, uint8_t cmd)
535{
536	return genlmsg_put(msg, 0, 0, drv->global->nl80211_id,
537			   0, flags, cmd, 0);
538}
539
540
541struct wiphy_idx_data {
542	int wiphy_idx;
543};
544
545
546static int netdev_info_handler(struct nl_msg *msg, void *arg)
547{
548	struct nlattr *tb[NL80211_ATTR_MAX + 1];
549	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
550	struct wiphy_idx_data *info = arg;
551
552	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
553		  genlmsg_attrlen(gnlh, 0), NULL);
554
555	if (tb[NL80211_ATTR_WIPHY])
556		info->wiphy_idx = nla_get_u32(tb[NL80211_ATTR_WIPHY]);
557
558	return NL_SKIP;
559}
560
561
562static int nl80211_get_wiphy_index(struct i802_bss *bss)
563{
564	struct nl_msg *msg;
565	struct wiphy_idx_data data = {
566		.wiphy_idx = -1,
567	};
568
569	msg = nlmsg_alloc();
570	if (!msg)
571		return -1;
572
573	nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_GET_INTERFACE);
574
575	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
576
577	if (send_and_recv_msgs(bss->drv, msg, netdev_info_handler, &data) == 0)
578		return data.wiphy_idx;
579	msg = NULL;
580nla_put_failure:
581	nlmsg_free(msg);
582	return -1;
583}
584
585
586static int nl80211_register_beacons(struct wpa_driver_nl80211_data *drv,
587				    struct nl80211_wiphy_data *w)
588{
589	struct nl_msg *msg;
590	int ret = -1;
591
592	msg = nlmsg_alloc();
593	if (!msg)
594		return -1;
595
596	nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_BEACONS);
597
598	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, w->wiphy_idx);
599
600	ret = send_and_recv(drv->global, w->nl_beacons, msg, NULL, NULL);
601	msg = NULL;
602	if (ret) {
603		wpa_printf(MSG_DEBUG, "nl80211: Register beacons command "
604			   "failed: ret=%d (%s)",
605			   ret, strerror(-ret));
606		goto nla_put_failure;
607	}
608	ret = 0;
609nla_put_failure:
610	nlmsg_free(msg);
611	return ret;
612}
613
614
615static void nl80211_recv_beacons(int sock, void *eloop_ctx, void *handle)
616{
617	struct nl80211_wiphy_data *w = eloop_ctx;
618
619	wpa_printf(MSG_EXCESSIVE, "nl80211: Beacon event message available");
620
621	nl_recvmsgs(handle, w->nl_cb);
622}
623
624
625static int process_beacon_event(struct nl_msg *msg, void *arg)
626{
627	struct nl80211_wiphy_data *w = arg;
628	struct wpa_driver_nl80211_data *drv;
629	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
630	struct nlattr *tb[NL80211_ATTR_MAX + 1];
631	union wpa_event_data event;
632
633	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
634		  genlmsg_attrlen(gnlh, 0), NULL);
635
636	if (gnlh->cmd != NL80211_CMD_FRAME) {
637		wpa_printf(MSG_DEBUG, "nl80211: Unexpected beacon event? (%d)",
638			   gnlh->cmd);
639		return NL_SKIP;
640	}
641
642	if (!tb[NL80211_ATTR_FRAME])
643		return NL_SKIP;
644
645	dl_list_for_each(drv, &w->drvs, struct wpa_driver_nl80211_data,
646			 wiphy_list) {
647		os_memset(&event, 0, sizeof(event));
648		event.rx_mgmt.frame = nla_data(tb[NL80211_ATTR_FRAME]);
649		event.rx_mgmt.frame_len = nla_len(tb[NL80211_ATTR_FRAME]);
650		wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
651	}
652
653	return NL_SKIP;
654}
655
656
657static struct nl80211_wiphy_data *
658nl80211_get_wiphy_data_ap(struct i802_bss *bss)
659{
660	static DEFINE_DL_LIST(nl80211_wiphys);
661	struct nl80211_wiphy_data *w;
662	int wiphy_idx, found = 0;
663	struct i802_bss *tmp_bss;
664
665	if (bss->wiphy_data != NULL)
666		return bss->wiphy_data;
667
668	wiphy_idx = nl80211_get_wiphy_index(bss);
669
670	dl_list_for_each(w, &nl80211_wiphys, struct nl80211_wiphy_data, list) {
671		if (w->wiphy_idx == wiphy_idx)
672			goto add;
673	}
674
675	/* alloc new one */
676	w = os_zalloc(sizeof(*w));
677	if (w == NULL)
678		return NULL;
679	w->wiphy_idx = wiphy_idx;
680	dl_list_init(&w->bsss);
681	dl_list_init(&w->drvs);
682
683	w->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
684	if (!w->nl_cb) {
685		os_free(w);
686		return NULL;
687	}
688	nl_cb_set(w->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, no_seq_check, NULL);
689	nl_cb_set(w->nl_cb, NL_CB_VALID, NL_CB_CUSTOM, process_beacon_event,
690		  w);
691
692	w->nl_beacons = nl_create_handle(bss->drv->global->nl_cb,
693					 "wiphy beacons");
694	if (w->nl_beacons == NULL) {
695		os_free(w);
696		return NULL;
697	}
698
699	if (nl80211_register_beacons(bss->drv, w)) {
700		nl_destroy_handles(&w->nl_beacons);
701		os_free(w);
702		return NULL;
703	}
704
705	eloop_register_read_sock(nl_socket_get_fd(w->nl_beacons),
706				 nl80211_recv_beacons, w, w->nl_beacons);
707
708	dl_list_add(&nl80211_wiphys, &w->list);
709
710add:
711	/* drv entry for this bss already there? */
712	dl_list_for_each(tmp_bss, &w->bsss, struct i802_bss, wiphy_list) {
713		if (tmp_bss->drv == bss->drv) {
714			found = 1;
715			break;
716		}
717	}
718	/* if not add it */
719	if (!found)
720		dl_list_add(&w->drvs, &bss->drv->wiphy_list);
721
722	dl_list_add(&w->bsss, &bss->wiphy_list);
723	bss->wiphy_data = w;
724	return w;
725}
726
727
728static void nl80211_put_wiphy_data_ap(struct i802_bss *bss)
729{
730	struct nl80211_wiphy_data *w = bss->wiphy_data;
731	struct i802_bss *tmp_bss;
732	int found = 0;
733
734	if (w == NULL)
735		return;
736	bss->wiphy_data = NULL;
737	dl_list_del(&bss->wiphy_list);
738
739	/* still any for this drv present? */
740	dl_list_for_each(tmp_bss, &w->bsss, struct i802_bss, wiphy_list) {
741		if (tmp_bss->drv == bss->drv) {
742			found = 1;
743			break;
744		}
745	}
746	/* if not remove it */
747	if (!found)
748		dl_list_del(&bss->drv->wiphy_list);
749
750	if (!dl_list_empty(&w->bsss))
751		return;
752
753	eloop_unregister_read_sock(nl_socket_get_fd(w->nl_beacons));
754
755	nl_cb_put(w->nl_cb);
756	nl_destroy_handles(&w->nl_beacons);
757	dl_list_del(&w->list);
758	os_free(w);
759}
760
761
762static int wpa_driver_nl80211_get_bssid(void *priv, u8 *bssid)
763{
764	struct i802_bss *bss = priv;
765	struct wpa_driver_nl80211_data *drv = bss->drv;
766	if (!drv->associated)
767		return -1;
768	os_memcpy(bssid, drv->bssid, ETH_ALEN);
769	return 0;
770}
771
772
773static int wpa_driver_nl80211_get_ssid(void *priv, u8 *ssid)
774{
775	struct i802_bss *bss = priv;
776	struct wpa_driver_nl80211_data *drv = bss->drv;
777	if (!drv->associated)
778		return -1;
779	os_memcpy(ssid, drv->ssid, drv->ssid_len);
780	return drv->ssid_len;
781}
782
783
784static void wpa_driver_nl80211_event_link(struct wpa_driver_nl80211_data *drv,
785					  char *buf, size_t len, int del)
786{
787	union wpa_event_data event;
788
789	os_memset(&event, 0, sizeof(event));
790	if (len > sizeof(event.interface_status.ifname))
791		len = sizeof(event.interface_status.ifname) - 1;
792	os_memcpy(event.interface_status.ifname, buf, len);
793	event.interface_status.ievent = del ? EVENT_INTERFACE_REMOVED :
794		EVENT_INTERFACE_ADDED;
795
796	wpa_printf(MSG_DEBUG, "RTM_%sLINK, IFLA_IFNAME: Interface '%s' %s",
797		   del ? "DEL" : "NEW",
798		   event.interface_status.ifname,
799		   del ? "removed" : "added");
800
801	if (os_strcmp(drv->first_bss.ifname, event.interface_status.ifname) == 0) {
802		if (del) {
803			if (drv->if_removed) {
804				wpa_printf(MSG_DEBUG, "nl80211: if_removed "
805					   "already set - ignore event");
806				return;
807			}
808			drv->if_removed = 1;
809		} else {
810			if (if_nametoindex(drv->first_bss.ifname) == 0) {
811				wpa_printf(MSG_DEBUG, "nl80211: Interface %s "
812					   "does not exist - ignore "
813					   "RTM_NEWLINK",
814					   drv->first_bss.ifname);
815				return;
816			}
817			if (!drv->if_removed) {
818				wpa_printf(MSG_DEBUG, "nl80211: if_removed "
819					   "already cleared - ignore event");
820				return;
821			}
822			drv->if_removed = 0;
823		}
824	}
825
826	wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_STATUS, &event);
827}
828
829
830static int wpa_driver_nl80211_own_ifname(struct wpa_driver_nl80211_data *drv,
831					 u8 *buf, size_t len)
832{
833	int attrlen, rta_len;
834	struct rtattr *attr;
835
836	attrlen = len;
837	attr = (struct rtattr *) buf;
838
839	rta_len = RTA_ALIGN(sizeof(struct rtattr));
840	while (RTA_OK(attr, attrlen)) {
841		if (attr->rta_type == IFLA_IFNAME) {
842			if (os_strcmp(((char *) attr) + rta_len, drv->first_bss.ifname)
843			    == 0)
844				return 1;
845			else
846				break;
847		}
848		attr = RTA_NEXT(attr, attrlen);
849	}
850
851	return 0;
852}
853
854
855static int wpa_driver_nl80211_own_ifindex(struct wpa_driver_nl80211_data *drv,
856					  int ifindex, u8 *buf, size_t len)
857{
858	if (drv->ifindex == ifindex)
859		return 1;
860
861	if (drv->if_removed && wpa_driver_nl80211_own_ifname(drv, buf, len)) {
862		drv->first_bss.ifindex = if_nametoindex(drv->first_bss.ifname);
863		wpa_printf(MSG_DEBUG, "nl80211: Update ifindex for a removed "
864			   "interface");
865		wpa_driver_nl80211_finish_drv_init(drv);
866		return 1;
867	}
868
869	return 0;
870}
871
872
873static struct wpa_driver_nl80211_data *
874nl80211_find_drv(struct nl80211_global *global, int idx, u8 *buf, size_t len)
875{
876	struct wpa_driver_nl80211_data *drv;
877	dl_list_for_each(drv, &global->interfaces,
878			 struct wpa_driver_nl80211_data, list) {
879		if (wpa_driver_nl80211_own_ifindex(drv, idx, buf, len) ||
880		    have_ifidx(drv, idx))
881			return drv;
882	}
883	return NULL;
884}
885
886
887static void wpa_driver_nl80211_event_rtm_newlink(void *ctx,
888						 struct ifinfomsg *ifi,
889						 u8 *buf, size_t len)
890{
891	struct nl80211_global *global = ctx;
892	struct wpa_driver_nl80211_data *drv;
893	int attrlen, rta_len;
894	struct rtattr *attr;
895	u32 brid = 0;
896	char namebuf[IFNAMSIZ];
897
898	drv = nl80211_find_drv(global, ifi->ifi_index, buf, len);
899	if (!drv) {
900		wpa_printf(MSG_DEBUG, "nl80211: Ignore event for foreign "
901			   "ifindex %d", ifi->ifi_index);
902		return;
903	}
904
905	wpa_printf(MSG_DEBUG, "RTM_NEWLINK: operstate=%d ifi_flags=0x%x "
906		   "(%s%s%s%s)",
907		   drv->operstate, ifi->ifi_flags,
908		   (ifi->ifi_flags & IFF_UP) ? "[UP]" : "",
909		   (ifi->ifi_flags & IFF_RUNNING) ? "[RUNNING]" : "",
910		   (ifi->ifi_flags & IFF_LOWER_UP) ? "[LOWER_UP]" : "",
911		   (ifi->ifi_flags & IFF_DORMANT) ? "[DORMANT]" : "");
912
913	if (!drv->if_disabled && !(ifi->ifi_flags & IFF_UP)) {
914		if (if_indextoname(ifi->ifi_index, namebuf) &&
915		    linux_iface_up(drv->global->ioctl_sock,
916				   drv->first_bss.ifname) > 0) {
917			wpa_printf(MSG_DEBUG, "nl80211: Ignore interface down "
918				   "event since interface %s is up", namebuf);
919			return;
920		}
921		wpa_printf(MSG_DEBUG, "nl80211: Interface down");
922		if (drv->ignore_if_down_event) {
923			wpa_printf(MSG_DEBUG, "nl80211: Ignore interface down "
924				   "event generated by mode change");
925			drv->ignore_if_down_event = 0;
926		} else {
927			drv->if_disabled = 1;
928			wpa_supplicant_event(drv->ctx,
929					     EVENT_INTERFACE_DISABLED, NULL);
930		}
931	}
932
933	if (drv->if_disabled && (ifi->ifi_flags & IFF_UP)) {
934		if (if_indextoname(ifi->ifi_index, namebuf) &&
935		    linux_iface_up(drv->global->ioctl_sock,
936				   drv->first_bss.ifname) == 0) {
937			wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
938				   "event since interface %s is down",
939				   namebuf);
940		} else if (if_nametoindex(drv->first_bss.ifname) == 0) {
941			wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
942				   "event since interface %s does not exist",
943				   drv->first_bss.ifname);
944		} else if (drv->if_removed) {
945			wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
946				   "event since interface %s is marked "
947				   "removed", drv->first_bss.ifname);
948		} else {
949			wpa_printf(MSG_DEBUG, "nl80211: Interface up");
950			drv->if_disabled = 0;
951			wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_ENABLED,
952					     NULL);
953		}
954	}
955
956	/*
957	 * Some drivers send the association event before the operup event--in
958	 * this case, lifting operstate in wpa_driver_nl80211_set_operstate()
959	 * fails. This will hit us when wpa_supplicant does not need to do
960	 * IEEE 802.1X authentication
961	 */
962	if (drv->operstate == 1 &&
963	    (ifi->ifi_flags & (IFF_LOWER_UP | IFF_DORMANT)) == IFF_LOWER_UP &&
964	    !(ifi->ifi_flags & IFF_RUNNING))
965		netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
966				       -1, IF_OPER_UP);
967
968	attrlen = len;
969	attr = (struct rtattr *) buf;
970	rta_len = RTA_ALIGN(sizeof(struct rtattr));
971	while (RTA_OK(attr, attrlen)) {
972		if (attr->rta_type == IFLA_IFNAME) {
973			wpa_driver_nl80211_event_link(
974				drv,
975				((char *) attr) + rta_len,
976				attr->rta_len - rta_len, 0);
977		} else if (attr->rta_type == IFLA_MASTER)
978			brid = nla_get_u32((struct nlattr *) attr);
979		attr = RTA_NEXT(attr, attrlen);
980	}
981
982	if (ifi->ifi_family == AF_BRIDGE && brid) {
983		/* device has been added to bridge */
984		if_indextoname(brid, namebuf);
985		wpa_printf(MSG_DEBUG, "nl80211: Add ifindex %u for bridge %s",
986			   brid, namebuf);
987		add_ifidx(drv, brid);
988	}
989}
990
991
992static void wpa_driver_nl80211_event_rtm_dellink(void *ctx,
993						 struct ifinfomsg *ifi,
994						 u8 *buf, size_t len)
995{
996	struct nl80211_global *global = ctx;
997	struct wpa_driver_nl80211_data *drv;
998	int attrlen, rta_len;
999	struct rtattr *attr;
1000	u32 brid = 0;
1001
1002	drv = nl80211_find_drv(global, ifi->ifi_index, buf, len);
1003	if (!drv) {
1004		wpa_printf(MSG_DEBUG, "nl80211: Ignore dellink event for "
1005			   "foreign ifindex %d", ifi->ifi_index);
1006		return;
1007	}
1008
1009	attrlen = len;
1010	attr = (struct rtattr *) buf;
1011
1012	rta_len = RTA_ALIGN(sizeof(struct rtattr));
1013	while (RTA_OK(attr, attrlen)) {
1014		if (attr->rta_type == IFLA_IFNAME) {
1015			wpa_driver_nl80211_event_link(
1016				drv,
1017				((char *) attr) + rta_len,
1018				attr->rta_len - rta_len, 1);
1019		} else if (attr->rta_type == IFLA_MASTER)
1020			brid = nla_get_u32((struct nlattr *) attr);
1021		attr = RTA_NEXT(attr, attrlen);
1022	}
1023
1024	if (ifi->ifi_family == AF_BRIDGE && brid) {
1025		/* device has been removed from bridge */
1026		char namebuf[IFNAMSIZ];
1027		if_indextoname(brid, namebuf);
1028		wpa_printf(MSG_DEBUG, "nl80211: Remove ifindex %u for bridge "
1029			   "%s", brid, namebuf);
1030		del_ifidx(drv, brid);
1031	}
1032}
1033
1034
1035static void mlme_event_auth(struct wpa_driver_nl80211_data *drv,
1036			    const u8 *frame, size_t len)
1037{
1038	const struct ieee80211_mgmt *mgmt;
1039	union wpa_event_data event;
1040
1041	mgmt = (const struct ieee80211_mgmt *) frame;
1042	if (len < 24 + sizeof(mgmt->u.auth)) {
1043		wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1044			   "frame");
1045		return;
1046	}
1047
1048	os_memcpy(drv->auth_bssid, mgmt->sa, ETH_ALEN);
1049	os_memset(&event, 0, sizeof(event));
1050	os_memcpy(event.auth.peer, mgmt->sa, ETH_ALEN);
1051	event.auth.auth_type = le_to_host16(mgmt->u.auth.auth_alg);
1052	event.auth.status_code = le_to_host16(mgmt->u.auth.status_code);
1053	if (len > 24 + sizeof(mgmt->u.auth)) {
1054		event.auth.ies = mgmt->u.auth.variable;
1055		event.auth.ies_len = len - 24 - sizeof(mgmt->u.auth);
1056	}
1057
1058	wpa_supplicant_event(drv->ctx, EVENT_AUTH, &event);
1059}
1060
1061
1062static unsigned int nl80211_get_assoc_freq(struct wpa_driver_nl80211_data *drv)
1063{
1064	struct nl_msg *msg;
1065	int ret;
1066	struct nl80211_bss_info_arg arg;
1067
1068	os_memset(&arg, 0, sizeof(arg));
1069	msg = nlmsg_alloc();
1070	if (!msg)
1071		goto nla_put_failure;
1072
1073	nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
1074	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1075
1076	arg.drv = drv;
1077	ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
1078	msg = NULL;
1079	if (ret == 0) {
1080		wpa_printf(MSG_DEBUG, "nl80211: Operating frequency for the "
1081			   "associated BSS from scan results: %u MHz",
1082			   arg.assoc_freq);
1083		return arg.assoc_freq ? arg.assoc_freq : drv->assoc_freq;
1084	}
1085	wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
1086		   "(%s)", ret, strerror(-ret));
1087nla_put_failure:
1088	nlmsg_free(msg);
1089	return drv->assoc_freq;
1090}
1091
1092
1093static void mlme_event_assoc(struct wpa_driver_nl80211_data *drv,
1094			    const u8 *frame, size_t len)
1095{
1096	const struct ieee80211_mgmt *mgmt;
1097	union wpa_event_data event;
1098	u16 status;
1099
1100	mgmt = (const struct ieee80211_mgmt *) frame;
1101	if (len < 24 + sizeof(mgmt->u.assoc_resp)) {
1102		wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1103			   "frame");
1104		return;
1105	}
1106
1107	status = le_to_host16(mgmt->u.assoc_resp.status_code);
1108	if (status != WLAN_STATUS_SUCCESS) {
1109		os_memset(&event, 0, sizeof(event));
1110		event.assoc_reject.bssid = mgmt->bssid;
1111		if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
1112			event.assoc_reject.resp_ies =
1113				(u8 *) mgmt->u.assoc_resp.variable;
1114			event.assoc_reject.resp_ies_len =
1115				len - 24 - sizeof(mgmt->u.assoc_resp);
1116		}
1117		event.assoc_reject.status_code = status;
1118
1119		wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
1120		return;
1121	}
1122
1123	drv->associated = 1;
1124	os_memcpy(drv->bssid, mgmt->sa, ETH_ALEN);
1125
1126	os_memset(&event, 0, sizeof(event));
1127	if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
1128		event.assoc_info.resp_ies = (u8 *) mgmt->u.assoc_resp.variable;
1129		event.assoc_info.resp_ies_len =
1130			len - 24 - sizeof(mgmt->u.assoc_resp);
1131	}
1132
1133	event.assoc_info.freq = drv->assoc_freq;
1134
1135	wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
1136}
1137
1138
1139static void mlme_event_connect(struct wpa_driver_nl80211_data *drv,
1140			       enum nl80211_commands cmd, struct nlattr *status,
1141			       struct nlattr *addr, struct nlattr *req_ie,
1142			       struct nlattr *resp_ie)
1143{
1144	union wpa_event_data event;
1145
1146	if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1147		/*
1148		 * Avoid reporting two association events that would confuse
1149		 * the core code.
1150		 */
1151		wpa_printf(MSG_DEBUG, "nl80211: Ignore connect event (cmd=%d) "
1152			   "when using userspace SME", cmd);
1153		return;
1154	}
1155
1156	os_memset(&event, 0, sizeof(event));
1157	if (cmd == NL80211_CMD_CONNECT &&
1158	    nla_get_u16(status) != WLAN_STATUS_SUCCESS) {
1159		if (addr)
1160			event.assoc_reject.bssid = nla_data(addr);
1161		if (resp_ie) {
1162			event.assoc_reject.resp_ies = nla_data(resp_ie);
1163			event.assoc_reject.resp_ies_len = nla_len(resp_ie);
1164		}
1165		event.assoc_reject.status_code = nla_get_u16(status);
1166		wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
1167		return;
1168	}
1169
1170	drv->associated = 1;
1171	if (addr)
1172		os_memcpy(drv->bssid, nla_data(addr), ETH_ALEN);
1173
1174	if (req_ie) {
1175		event.assoc_info.req_ies = nla_data(req_ie);
1176		event.assoc_info.req_ies_len = nla_len(req_ie);
1177	}
1178	if (resp_ie) {
1179		event.assoc_info.resp_ies = nla_data(resp_ie);
1180		event.assoc_info.resp_ies_len = nla_len(resp_ie);
1181	}
1182
1183	event.assoc_info.freq = nl80211_get_assoc_freq(drv);
1184
1185	wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
1186}
1187
1188
1189static void mlme_event_disconnect(struct wpa_driver_nl80211_data *drv,
1190				  struct nlattr *reason, struct nlattr *addr,
1191				  struct nlattr *by_ap)
1192{
1193	union wpa_event_data data;
1194
1195	if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1196		/*
1197		 * Avoid reporting two disassociation events that could
1198		 * confuse the core code.
1199		 */
1200		wpa_printf(MSG_DEBUG, "nl80211: Ignore disconnect "
1201			   "event when using userspace SME");
1202		return;
1203	}
1204
1205	drv->associated = 0;
1206	os_memset(&data, 0, sizeof(data));
1207	if (reason)
1208		data.deauth_info.reason_code = nla_get_u16(reason);
1209	data.deauth_info.locally_generated = by_ap == NULL;
1210	wpa_supplicant_event(drv->ctx, EVENT_DEAUTH, &data);
1211}
1212
1213
1214static void mlme_event_ch_switch(struct wpa_driver_nl80211_data *drv,
1215				 struct nlattr *freq, struct nlattr *type)
1216{
1217	union wpa_event_data data;
1218	int ht_enabled = 1;
1219	int chan_offset = 0;
1220
1221	wpa_printf(MSG_DEBUG, "nl80211: Channel switch event");
1222
1223	if (!freq || !type)
1224		return;
1225
1226	switch (nla_get_u32(type)) {
1227	case NL80211_CHAN_NO_HT:
1228		ht_enabled = 0;
1229		break;
1230	case NL80211_CHAN_HT20:
1231		break;
1232	case NL80211_CHAN_HT40PLUS:
1233		chan_offset = 1;
1234		break;
1235	case NL80211_CHAN_HT40MINUS:
1236		chan_offset = -1;
1237		break;
1238	}
1239
1240	data.ch_switch.freq = nla_get_u32(freq);
1241	data.ch_switch.ht_enabled = ht_enabled;
1242	data.ch_switch.ch_offset = chan_offset;
1243
1244	wpa_supplicant_event(drv->ctx, EVENT_CH_SWITCH, &data);
1245}
1246
1247
1248static void mlme_timeout_event(struct wpa_driver_nl80211_data *drv,
1249			       enum nl80211_commands cmd, struct nlattr *addr)
1250{
1251	union wpa_event_data event;
1252	enum wpa_event_type ev;
1253
1254	if (nla_len(addr) != ETH_ALEN)
1255		return;
1256
1257	wpa_printf(MSG_DEBUG, "nl80211: MLME event %d; timeout with " MACSTR,
1258		   cmd, MAC2STR((u8 *) nla_data(addr)));
1259
1260	if (cmd == NL80211_CMD_AUTHENTICATE)
1261		ev = EVENT_AUTH_TIMED_OUT;
1262	else if (cmd == NL80211_CMD_ASSOCIATE)
1263		ev = EVENT_ASSOC_TIMED_OUT;
1264	else
1265		return;
1266
1267	os_memset(&event, 0, sizeof(event));
1268	os_memcpy(event.timeout_event.addr, nla_data(addr), ETH_ALEN);
1269	wpa_supplicant_event(drv->ctx, ev, &event);
1270}
1271
1272
1273static void mlme_event_mgmt(struct wpa_driver_nl80211_data *drv,
1274			    struct nlattr *freq, struct nlattr *sig,
1275			    const u8 *frame, size_t len)
1276{
1277	const struct ieee80211_mgmt *mgmt;
1278	union wpa_event_data event;
1279	u16 fc, stype;
1280	int ssi_signal = 0;
1281
1282	mgmt = (const struct ieee80211_mgmt *) frame;
1283	if (len < 24) {
1284		wpa_printf(MSG_DEBUG, "nl80211: Too short action frame");
1285		return;
1286	}
1287
1288	fc = le_to_host16(mgmt->frame_control);
1289	stype = WLAN_FC_GET_STYPE(fc);
1290
1291	if (sig)
1292		ssi_signal = (s32) nla_get_u32(sig);
1293
1294	os_memset(&event, 0, sizeof(event));
1295	if (freq) {
1296		event.rx_action.freq = nla_get_u32(freq);
1297		drv->last_mgmt_freq = event.rx_action.freq;
1298	}
1299	if (stype == WLAN_FC_STYPE_ACTION) {
1300		event.rx_action.da = mgmt->da;
1301		event.rx_action.sa = mgmt->sa;
1302		event.rx_action.bssid = mgmt->bssid;
1303		event.rx_action.category = mgmt->u.action.category;
1304		event.rx_action.data = &mgmt->u.action.category + 1;
1305		event.rx_action.len = frame + len - event.rx_action.data;
1306		wpa_supplicant_event(drv->ctx, EVENT_RX_ACTION, &event);
1307	} else {
1308		event.rx_mgmt.frame = frame;
1309		event.rx_mgmt.frame_len = len;
1310		event.rx_mgmt.ssi_signal = ssi_signal;
1311		wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
1312	}
1313}
1314
1315
1316static void mlme_event_mgmt_tx_status(struct wpa_driver_nl80211_data *drv,
1317				      struct nlattr *cookie, const u8 *frame,
1318				      size_t len, struct nlattr *ack)
1319{
1320	union wpa_event_data event;
1321	const struct ieee80211_hdr *hdr;
1322	u16 fc;
1323
1324	if (!is_ap_interface(drv->nlmode)) {
1325		u64 cookie_val;
1326
1327		if (!cookie)
1328			return;
1329
1330		cookie_val = nla_get_u64(cookie);
1331		wpa_printf(MSG_DEBUG, "nl80211: Action TX status:"
1332			   " cookie=0%llx%s (ack=%d)",
1333			   (long long unsigned int) cookie_val,
1334			   cookie_val == drv->send_action_cookie ?
1335			   " (match)" : " (unknown)", ack != NULL);
1336		if (cookie_val != drv->send_action_cookie)
1337			return;
1338	}
1339
1340	hdr = (const struct ieee80211_hdr *) frame;
1341	fc = le_to_host16(hdr->frame_control);
1342
1343	os_memset(&event, 0, sizeof(event));
1344	event.tx_status.type = WLAN_FC_GET_TYPE(fc);
1345	event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
1346	event.tx_status.dst = hdr->addr1;
1347	event.tx_status.data = frame;
1348	event.tx_status.data_len = len;
1349	event.tx_status.ack = ack != NULL;
1350	wpa_supplicant_event(drv->ctx, EVENT_TX_STATUS, &event);
1351}
1352
1353
1354static void mlme_event_deauth_disassoc(struct wpa_driver_nl80211_data *drv,
1355				       enum wpa_event_type type,
1356				       const u8 *frame, size_t len)
1357{
1358	const struct ieee80211_mgmt *mgmt;
1359	union wpa_event_data event;
1360	const u8 *bssid = NULL;
1361	u16 reason_code = 0;
1362
1363	mgmt = (const struct ieee80211_mgmt *) frame;
1364	if (len >= 24) {
1365		bssid = mgmt->bssid;
1366
1367		if (drv->associated != 0 &&
1368		    os_memcmp(bssid, drv->bssid, ETH_ALEN) != 0 &&
1369		    os_memcmp(bssid, drv->auth_bssid, ETH_ALEN) != 0) {
1370			/*
1371			 * We have presumably received this deauth as a
1372			 * response to a clear_state_mismatch() outgoing
1373			 * deauth.  Don't let it take us offline!
1374			 */
1375			wpa_printf(MSG_DEBUG, "nl80211: Deauth received "
1376				   "from Unknown BSSID " MACSTR " -- ignoring",
1377				   MAC2STR(bssid));
1378			return;
1379		}
1380	}
1381
1382	drv->associated = 0;
1383	os_memset(&event, 0, sizeof(event));
1384
1385	/* Note: Same offset for Reason Code in both frame subtypes */
1386	if (len >= 24 + sizeof(mgmt->u.deauth))
1387		reason_code = le_to_host16(mgmt->u.deauth.reason_code);
1388
1389	if (type == EVENT_DISASSOC) {
1390		event.disassoc_info.locally_generated =
1391			!os_memcmp(mgmt->sa, drv->first_bss.addr, ETH_ALEN);
1392		event.disassoc_info.addr = bssid;
1393		event.disassoc_info.reason_code = reason_code;
1394		if (frame + len > mgmt->u.disassoc.variable) {
1395			event.disassoc_info.ie = mgmt->u.disassoc.variable;
1396			event.disassoc_info.ie_len = frame + len -
1397				mgmt->u.disassoc.variable;
1398		}
1399	} else {
1400		event.deauth_info.locally_generated =
1401			!os_memcmp(mgmt->sa, drv->first_bss.addr, ETH_ALEN);
1402		event.deauth_info.addr = bssid;
1403		event.deauth_info.reason_code = reason_code;
1404		if (frame + len > mgmt->u.deauth.variable) {
1405			event.deauth_info.ie = mgmt->u.deauth.variable;
1406			event.deauth_info.ie_len = frame + len -
1407				mgmt->u.deauth.variable;
1408		}
1409	}
1410
1411	wpa_supplicant_event(drv->ctx, type, &event);
1412}
1413
1414
1415static void mlme_event_unprot_disconnect(struct wpa_driver_nl80211_data *drv,
1416					 enum wpa_event_type type,
1417					 const u8 *frame, size_t len)
1418{
1419	const struct ieee80211_mgmt *mgmt;
1420	union wpa_event_data event;
1421	u16 reason_code = 0;
1422
1423	if (len < 24)
1424		return;
1425
1426	mgmt = (const struct ieee80211_mgmt *) frame;
1427
1428	os_memset(&event, 0, sizeof(event));
1429	/* Note: Same offset for Reason Code in both frame subtypes */
1430	if (len >= 24 + sizeof(mgmt->u.deauth))
1431		reason_code = le_to_host16(mgmt->u.deauth.reason_code);
1432
1433	if (type == EVENT_UNPROT_DISASSOC) {
1434		event.unprot_disassoc.sa = mgmt->sa;
1435		event.unprot_disassoc.da = mgmt->da;
1436		event.unprot_disassoc.reason_code = reason_code;
1437	} else {
1438		event.unprot_deauth.sa = mgmt->sa;
1439		event.unprot_deauth.da = mgmt->da;
1440		event.unprot_deauth.reason_code = reason_code;
1441	}
1442
1443	wpa_supplicant_event(drv->ctx, type, &event);
1444}
1445
1446
1447static void mlme_event(struct wpa_driver_nl80211_data *drv,
1448		       enum nl80211_commands cmd, struct nlattr *frame,
1449		       struct nlattr *addr, struct nlattr *timed_out,
1450		       struct nlattr *freq, struct nlattr *ack,
1451		       struct nlattr *cookie, struct nlattr *sig)
1452{
1453	if (timed_out && addr) {
1454		mlme_timeout_event(drv, cmd, addr);
1455		return;
1456	}
1457
1458	if (frame == NULL) {
1459		wpa_printf(MSG_DEBUG, "nl80211: MLME event %d without frame "
1460			   "data", cmd);
1461		return;
1462	}
1463
1464	wpa_printf(MSG_DEBUG, "nl80211: MLME event %d", cmd);
1465	wpa_hexdump(MSG_MSGDUMP, "nl80211: MLME event frame",
1466		    nla_data(frame), nla_len(frame));
1467
1468	switch (cmd) {
1469	case NL80211_CMD_AUTHENTICATE:
1470		mlme_event_auth(drv, nla_data(frame), nla_len(frame));
1471		break;
1472	case NL80211_CMD_ASSOCIATE:
1473		mlme_event_assoc(drv, nla_data(frame), nla_len(frame));
1474		break;
1475	case NL80211_CMD_DEAUTHENTICATE:
1476		mlme_event_deauth_disassoc(drv, EVENT_DEAUTH,
1477					   nla_data(frame), nla_len(frame));
1478		break;
1479	case NL80211_CMD_DISASSOCIATE:
1480		mlme_event_deauth_disassoc(drv, EVENT_DISASSOC,
1481					   nla_data(frame), nla_len(frame));
1482		break;
1483	case NL80211_CMD_FRAME:
1484		mlme_event_mgmt(drv, freq, sig, nla_data(frame),
1485				nla_len(frame));
1486		break;
1487	case NL80211_CMD_FRAME_TX_STATUS:
1488		mlme_event_mgmt_tx_status(drv, cookie, nla_data(frame),
1489					  nla_len(frame), ack);
1490		break;
1491	case NL80211_CMD_UNPROT_DEAUTHENTICATE:
1492		mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DEAUTH,
1493					     nla_data(frame), nla_len(frame));
1494		break;
1495	case NL80211_CMD_UNPROT_DISASSOCIATE:
1496		mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DISASSOC,
1497					     nla_data(frame), nla_len(frame));
1498		break;
1499	default:
1500		break;
1501	}
1502}
1503
1504
1505static void mlme_event_michael_mic_failure(struct wpa_driver_nl80211_data *drv,
1506					   struct nlattr *tb[])
1507{
1508	union wpa_event_data data;
1509
1510	wpa_printf(MSG_DEBUG, "nl80211: MLME event Michael MIC failure");
1511	os_memset(&data, 0, sizeof(data));
1512	if (tb[NL80211_ATTR_MAC]) {
1513		wpa_hexdump(MSG_DEBUG, "nl80211: Source MAC address",
1514			    nla_data(tb[NL80211_ATTR_MAC]),
1515			    nla_len(tb[NL80211_ATTR_MAC]));
1516		data.michael_mic_failure.src = nla_data(tb[NL80211_ATTR_MAC]);
1517	}
1518	if (tb[NL80211_ATTR_KEY_SEQ]) {
1519		wpa_hexdump(MSG_DEBUG, "nl80211: TSC",
1520			    nla_data(tb[NL80211_ATTR_KEY_SEQ]),
1521			    nla_len(tb[NL80211_ATTR_KEY_SEQ]));
1522	}
1523	if (tb[NL80211_ATTR_KEY_TYPE]) {
1524		enum nl80211_key_type key_type =
1525			nla_get_u32(tb[NL80211_ATTR_KEY_TYPE]);
1526		wpa_printf(MSG_DEBUG, "nl80211: Key Type %d", key_type);
1527		if (key_type == NL80211_KEYTYPE_PAIRWISE)
1528			data.michael_mic_failure.unicast = 1;
1529	} else
1530		data.michael_mic_failure.unicast = 1;
1531
1532	if (tb[NL80211_ATTR_KEY_IDX]) {
1533		u8 key_id = nla_get_u8(tb[NL80211_ATTR_KEY_IDX]);
1534		wpa_printf(MSG_DEBUG, "nl80211: Key Id %d", key_id);
1535	}
1536
1537	wpa_supplicant_event(drv->ctx, EVENT_MICHAEL_MIC_FAILURE, &data);
1538}
1539
1540
1541static void mlme_event_join_ibss(struct wpa_driver_nl80211_data *drv,
1542				 struct nlattr *tb[])
1543{
1544	if (tb[NL80211_ATTR_MAC] == NULL) {
1545		wpa_printf(MSG_DEBUG, "nl80211: No address in IBSS joined "
1546			   "event");
1547		return;
1548	}
1549	os_memcpy(drv->bssid, nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
1550	drv->associated = 1;
1551	wpa_printf(MSG_DEBUG, "nl80211: IBSS " MACSTR " joined",
1552		   MAC2STR(drv->bssid));
1553
1554	wpa_supplicant_event(drv->ctx, EVENT_ASSOC, NULL);
1555}
1556
1557
1558static void mlme_event_remain_on_channel(struct wpa_driver_nl80211_data *drv,
1559					 int cancel_event, struct nlattr *tb[])
1560{
1561	unsigned int freq, chan_type, duration;
1562	union wpa_event_data data;
1563	u64 cookie;
1564
1565	if (tb[NL80211_ATTR_WIPHY_FREQ])
1566		freq = nla_get_u32(tb[NL80211_ATTR_WIPHY_FREQ]);
1567	else
1568		freq = 0;
1569
1570	if (tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE])
1571		chan_type = nla_get_u32(tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
1572	else
1573		chan_type = 0;
1574
1575	if (tb[NL80211_ATTR_DURATION])
1576		duration = nla_get_u32(tb[NL80211_ATTR_DURATION]);
1577	else
1578		duration = 0;
1579
1580	if (tb[NL80211_ATTR_COOKIE])
1581		cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
1582	else
1583		cookie = 0;
1584
1585	wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel event (cancel=%d "
1586		   "freq=%u channel_type=%u duration=%u cookie=0x%llx (%s))",
1587		   cancel_event, freq, chan_type, duration,
1588		   (long long unsigned int) cookie,
1589		   cookie == drv->remain_on_chan_cookie ? "match" : "unknown");
1590
1591	if (cookie != drv->remain_on_chan_cookie)
1592		return; /* not for us */
1593
1594	if (cancel_event)
1595		drv->pending_remain_on_chan = 0;
1596
1597	os_memset(&data, 0, sizeof(data));
1598	data.remain_on_channel.freq = freq;
1599	data.remain_on_channel.duration = duration;
1600	wpa_supplicant_event(drv->ctx, cancel_event ?
1601			     EVENT_CANCEL_REMAIN_ON_CHANNEL :
1602			     EVENT_REMAIN_ON_CHANNEL, &data);
1603}
1604
1605
1606static void send_scan_event(struct wpa_driver_nl80211_data *drv, int aborted,
1607			    struct nlattr *tb[])
1608{
1609	union wpa_event_data event;
1610	struct nlattr *nl;
1611	int rem;
1612	struct scan_info *info;
1613#define MAX_REPORT_FREQS 50
1614	int freqs[MAX_REPORT_FREQS];
1615	int num_freqs = 0;
1616
1617	if (drv->scan_for_auth) {
1618		drv->scan_for_auth = 0;
1619		wpa_printf(MSG_DEBUG, "nl80211: Scan results for missing "
1620			   "cfg80211 BSS entry");
1621		wpa_driver_nl80211_authenticate_retry(drv);
1622		return;
1623	}
1624
1625	os_memset(&event, 0, sizeof(event));
1626	info = &event.scan_info;
1627	info->aborted = aborted;
1628
1629	if (tb[NL80211_ATTR_SCAN_SSIDS]) {
1630		nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_SSIDS], rem) {
1631			struct wpa_driver_scan_ssid *s =
1632				&info->ssids[info->num_ssids];
1633			s->ssid = nla_data(nl);
1634			s->ssid_len = nla_len(nl);
1635			info->num_ssids++;
1636			if (info->num_ssids == WPAS_MAX_SCAN_SSIDS)
1637				break;
1638		}
1639	}
1640	if (tb[NL80211_ATTR_SCAN_FREQUENCIES]) {
1641		nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_FREQUENCIES], rem)
1642		{
1643			freqs[num_freqs] = nla_get_u32(nl);
1644			num_freqs++;
1645			if (num_freqs == MAX_REPORT_FREQS - 1)
1646				break;
1647		}
1648		info->freqs = freqs;
1649		info->num_freqs = num_freqs;
1650	}
1651	wpa_supplicant_event(drv->ctx, EVENT_SCAN_RESULTS, &event);
1652}
1653
1654
1655static int get_link_signal(struct nl_msg *msg, void *arg)
1656{
1657	struct nlattr *tb[NL80211_ATTR_MAX + 1];
1658	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1659	struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
1660	static struct nla_policy policy[NL80211_STA_INFO_MAX + 1] = {
1661		[NL80211_STA_INFO_SIGNAL] = { .type = NLA_U8 },
1662	};
1663	struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
1664	static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
1665		[NL80211_RATE_INFO_BITRATE] = { .type = NLA_U16 },
1666		[NL80211_RATE_INFO_MCS] = { .type = NLA_U8 },
1667		[NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG },
1668		[NL80211_RATE_INFO_SHORT_GI] = { .type = NLA_FLAG },
1669	};
1670	struct wpa_signal_info *sig_change = arg;
1671
1672	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1673		  genlmsg_attrlen(gnlh, 0), NULL);
1674	if (!tb[NL80211_ATTR_STA_INFO] ||
1675	    nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
1676			     tb[NL80211_ATTR_STA_INFO], policy))
1677		return NL_SKIP;
1678	if (!sinfo[NL80211_STA_INFO_SIGNAL])
1679		return NL_SKIP;
1680
1681	sig_change->current_signal =
1682		(s8) nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
1683
1684	if (sinfo[NL80211_STA_INFO_TX_BITRATE]) {
1685		if (nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1686				     sinfo[NL80211_STA_INFO_TX_BITRATE],
1687				     rate_policy)) {
1688			sig_change->current_txrate = 0;
1689		} else {
1690			if (rinfo[NL80211_RATE_INFO_BITRATE]) {
1691				sig_change->current_txrate =
1692					nla_get_u16(rinfo[
1693					     NL80211_RATE_INFO_BITRATE]) * 100;
1694			}
1695		}
1696	}
1697
1698	return NL_SKIP;
1699}
1700
1701
1702static int nl80211_get_link_signal(struct wpa_driver_nl80211_data *drv,
1703				   struct wpa_signal_info *sig)
1704{
1705	struct nl_msg *msg;
1706
1707	sig->current_signal = -9999;
1708	sig->current_txrate = 0;
1709
1710	msg = nlmsg_alloc();
1711	if (!msg)
1712		return -ENOMEM;
1713
1714	nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
1715
1716	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1717	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
1718
1719	return send_and_recv_msgs(drv, msg, get_link_signal, sig);
1720 nla_put_failure:
1721	nlmsg_free(msg);
1722	return -ENOBUFS;
1723}
1724
1725
1726static int get_link_noise(struct nl_msg *msg, void *arg)
1727{
1728	struct nlattr *tb[NL80211_ATTR_MAX + 1];
1729	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1730	struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1731	static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1732		[NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1733		[NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
1734	};
1735	struct wpa_signal_info *sig_change = arg;
1736
1737	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1738		  genlmsg_attrlen(gnlh, 0), NULL);
1739
1740	if (!tb[NL80211_ATTR_SURVEY_INFO]) {
1741		wpa_printf(MSG_DEBUG, "nl80211: survey data missing!");
1742		return NL_SKIP;
1743	}
1744
1745	if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1746			     tb[NL80211_ATTR_SURVEY_INFO],
1747			     survey_policy)) {
1748		wpa_printf(MSG_DEBUG, "nl80211: failed to parse nested "
1749			   "attributes!");
1750		return NL_SKIP;
1751	}
1752
1753	if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1754		return NL_SKIP;
1755
1756	if (nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
1757	    sig_change->frequency)
1758		return NL_SKIP;
1759
1760	if (!sinfo[NL80211_SURVEY_INFO_NOISE])
1761		return NL_SKIP;
1762
1763	sig_change->current_noise =
1764		(s8) nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1765
1766	return NL_SKIP;
1767}
1768
1769
1770static int nl80211_get_link_noise(struct wpa_driver_nl80211_data *drv,
1771				  struct wpa_signal_info *sig_change)
1772{
1773	struct nl_msg *msg;
1774
1775	sig_change->current_noise = 9999;
1776	sig_change->frequency = drv->assoc_freq;
1777
1778	msg = nlmsg_alloc();
1779	if (!msg)
1780		return -ENOMEM;
1781
1782	nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
1783
1784	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1785
1786	return send_and_recv_msgs(drv, msg, get_link_noise, sig_change);
1787 nla_put_failure:
1788	nlmsg_free(msg);
1789	return -ENOBUFS;
1790}
1791
1792
1793static int get_noise_for_scan_results(struct nl_msg *msg, void *arg)
1794{
1795	struct nlattr *tb[NL80211_ATTR_MAX + 1];
1796	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1797	struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1798	static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1799		[NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1800		[NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
1801	};
1802	struct wpa_scan_results *scan_results = arg;
1803	struct wpa_scan_res *scan_res;
1804	size_t i;
1805
1806	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1807		  genlmsg_attrlen(gnlh, 0), NULL);
1808
1809	if (!tb[NL80211_ATTR_SURVEY_INFO]) {
1810		wpa_printf(MSG_DEBUG, "nl80211: Survey data missing");
1811		return NL_SKIP;
1812	}
1813
1814	if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1815			     tb[NL80211_ATTR_SURVEY_INFO],
1816			     survey_policy)) {
1817		wpa_printf(MSG_DEBUG, "nl80211: Failed to parse nested "
1818			   "attributes");
1819		return NL_SKIP;
1820	}
1821
1822	if (!sinfo[NL80211_SURVEY_INFO_NOISE])
1823		return NL_SKIP;
1824
1825	if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1826		return NL_SKIP;
1827
1828	for (i = 0; i < scan_results->num; ++i) {
1829		scan_res = scan_results->res[i];
1830		if (!scan_res)
1831			continue;
1832		if ((int) nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
1833		    scan_res->freq)
1834			continue;
1835		if (!(scan_res->flags & WPA_SCAN_NOISE_INVALID))
1836			continue;
1837		scan_res->noise = (s8)
1838			nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1839		scan_res->flags &= ~WPA_SCAN_NOISE_INVALID;
1840	}
1841
1842	return NL_SKIP;
1843}
1844
1845
1846static int nl80211_get_noise_for_scan_results(
1847	struct wpa_driver_nl80211_data *drv,
1848	struct wpa_scan_results *scan_res)
1849{
1850	struct nl_msg *msg;
1851
1852	msg = nlmsg_alloc();
1853	if (!msg)
1854		return -ENOMEM;
1855
1856	nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
1857
1858	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1859
1860	return send_and_recv_msgs(drv, msg, get_noise_for_scan_results,
1861				  scan_res);
1862 nla_put_failure:
1863	nlmsg_free(msg);
1864	return -ENOBUFS;
1865}
1866
1867
1868static void nl80211_cqm_event(struct wpa_driver_nl80211_data *drv,
1869			      struct nlattr *tb[])
1870{
1871	static struct nla_policy cqm_policy[NL80211_ATTR_CQM_MAX + 1] = {
1872		[NL80211_ATTR_CQM_RSSI_THOLD] = { .type = NLA_U32 },
1873		[NL80211_ATTR_CQM_RSSI_HYST] = { .type = NLA_U8 },
1874		[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] = { .type = NLA_U32 },
1875		[NL80211_ATTR_CQM_PKT_LOSS_EVENT] = { .type = NLA_U32 },
1876	};
1877	struct nlattr *cqm[NL80211_ATTR_CQM_MAX + 1];
1878	enum nl80211_cqm_rssi_threshold_event event;
1879	union wpa_event_data ed;
1880	struct wpa_signal_info sig;
1881	int res;
1882
1883	if (tb[NL80211_ATTR_CQM] == NULL ||
1884	    nla_parse_nested(cqm, NL80211_ATTR_CQM_MAX, tb[NL80211_ATTR_CQM],
1885			     cqm_policy)) {
1886		wpa_printf(MSG_DEBUG, "nl80211: Ignore invalid CQM event");
1887		return;
1888	}
1889
1890	os_memset(&ed, 0, sizeof(ed));
1891
1892	if (cqm[NL80211_ATTR_CQM_PKT_LOSS_EVENT]) {
1893		if (!tb[NL80211_ATTR_MAC])
1894			return;
1895		os_memcpy(ed.low_ack.addr, nla_data(tb[NL80211_ATTR_MAC]),
1896			  ETH_ALEN);
1897		wpa_supplicant_event(drv->ctx, EVENT_STATION_LOW_ACK, &ed);
1898		return;
1899	}
1900
1901	if (cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] == NULL)
1902		return;
1903	event = nla_get_u32(cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]);
1904
1905	if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH) {
1906		wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1907			   "event: RSSI high");
1908		ed.signal_change.above_threshold = 1;
1909	} else if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW) {
1910		wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1911			   "event: RSSI low");
1912		ed.signal_change.above_threshold = 0;
1913	} else
1914		return;
1915
1916	res = nl80211_get_link_signal(drv, &sig);
1917	if (res == 0) {
1918		ed.signal_change.current_signal = sig.current_signal;
1919		ed.signal_change.current_txrate = sig.current_txrate;
1920		wpa_printf(MSG_DEBUG, "nl80211: Signal: %d dBm  txrate: %d",
1921			   sig.current_signal, sig.current_txrate);
1922	}
1923
1924	res = nl80211_get_link_noise(drv, &sig);
1925	if (res == 0) {
1926		ed.signal_change.current_noise = sig.current_noise;
1927		wpa_printf(MSG_DEBUG, "nl80211: Noise: %d dBm",
1928			   sig.current_noise);
1929	}
1930
1931	wpa_supplicant_event(drv->ctx, EVENT_SIGNAL_CHANGE, &ed);
1932}
1933
1934
1935static void nl80211_new_station_event(struct wpa_driver_nl80211_data *drv,
1936				      struct nlattr **tb)
1937{
1938	u8 *addr;
1939	union wpa_event_data data;
1940
1941	if (tb[NL80211_ATTR_MAC] == NULL)
1942		return;
1943	addr = nla_data(tb[NL80211_ATTR_MAC]);
1944	wpa_printf(MSG_DEBUG, "nl80211: New station " MACSTR, MAC2STR(addr));
1945
1946	if (is_ap_interface(drv->nlmode) && drv->device_ap_sme) {
1947		u8 *ies = NULL;
1948		size_t ies_len = 0;
1949		if (tb[NL80211_ATTR_IE]) {
1950			ies = nla_data(tb[NL80211_ATTR_IE]);
1951			ies_len = nla_len(tb[NL80211_ATTR_IE]);
1952		}
1953		wpa_hexdump(MSG_DEBUG, "nl80211: Assoc Req IEs", ies, ies_len);
1954		drv_event_assoc(drv->ctx, addr, ies, ies_len, 0);
1955		return;
1956	}
1957
1958	if (drv->nlmode != NL80211_IFTYPE_ADHOC)
1959		return;
1960
1961	os_memset(&data, 0, sizeof(data));
1962	os_memcpy(data.ibss_rsn_start.peer, addr, ETH_ALEN);
1963	wpa_supplicant_event(drv->ctx, EVENT_IBSS_RSN_START, &data);
1964}
1965
1966
1967static void nl80211_del_station_event(struct wpa_driver_nl80211_data *drv,
1968				      struct nlattr **tb)
1969{
1970	u8 *addr;
1971	union wpa_event_data data;
1972
1973	if (tb[NL80211_ATTR_MAC] == NULL)
1974		return;
1975	addr = nla_data(tb[NL80211_ATTR_MAC]);
1976	wpa_printf(MSG_DEBUG, "nl80211: Delete station " MACSTR,
1977		   MAC2STR(addr));
1978
1979	if (is_ap_interface(drv->nlmode) && drv->device_ap_sme) {
1980		drv_event_disassoc(drv->ctx, addr);
1981		return;
1982	}
1983
1984	if (drv->nlmode != NL80211_IFTYPE_ADHOC)
1985		return;
1986
1987	os_memset(&data, 0, sizeof(data));
1988	os_memcpy(data.ibss_peer_lost.peer, addr, ETH_ALEN);
1989	wpa_supplicant_event(drv->ctx, EVENT_IBSS_PEER_LOST, &data);
1990}
1991
1992
1993static void nl80211_rekey_offload_event(struct wpa_driver_nl80211_data *drv,
1994					struct nlattr **tb)
1995{
1996	struct nlattr *rekey_info[NUM_NL80211_REKEY_DATA];
1997	static struct nla_policy rekey_policy[NUM_NL80211_REKEY_DATA] = {
1998		[NL80211_REKEY_DATA_KEK] = {
1999			.minlen = NL80211_KEK_LEN,
2000			.maxlen = NL80211_KEK_LEN,
2001		},
2002		[NL80211_REKEY_DATA_KCK] = {
2003			.minlen = NL80211_KCK_LEN,
2004			.maxlen = NL80211_KCK_LEN,
2005		},
2006		[NL80211_REKEY_DATA_REPLAY_CTR] = {
2007			.minlen = NL80211_REPLAY_CTR_LEN,
2008			.maxlen = NL80211_REPLAY_CTR_LEN,
2009		},
2010	};
2011	union wpa_event_data data;
2012
2013	if (!tb[NL80211_ATTR_MAC])
2014		return;
2015	if (!tb[NL80211_ATTR_REKEY_DATA])
2016		return;
2017	if (nla_parse_nested(rekey_info, MAX_NL80211_REKEY_DATA,
2018			     tb[NL80211_ATTR_REKEY_DATA], rekey_policy))
2019		return;
2020	if (!rekey_info[NL80211_REKEY_DATA_REPLAY_CTR])
2021		return;
2022
2023	os_memset(&data, 0, sizeof(data));
2024	data.driver_gtk_rekey.bssid = nla_data(tb[NL80211_ATTR_MAC]);
2025	wpa_printf(MSG_DEBUG, "nl80211: Rekey offload event for BSSID " MACSTR,
2026		   MAC2STR(data.driver_gtk_rekey.bssid));
2027	data.driver_gtk_rekey.replay_ctr =
2028		nla_data(rekey_info[NL80211_REKEY_DATA_REPLAY_CTR]);
2029	wpa_hexdump(MSG_DEBUG, "nl80211: Rekey offload - Replay Counter",
2030		    data.driver_gtk_rekey.replay_ctr, NL80211_REPLAY_CTR_LEN);
2031	wpa_supplicant_event(drv->ctx, EVENT_DRIVER_GTK_REKEY, &data);
2032}
2033
2034
2035static void nl80211_pmksa_candidate_event(struct wpa_driver_nl80211_data *drv,
2036					  struct nlattr **tb)
2037{
2038	struct nlattr *cand[NUM_NL80211_PMKSA_CANDIDATE];
2039	static struct nla_policy cand_policy[NUM_NL80211_PMKSA_CANDIDATE] = {
2040		[NL80211_PMKSA_CANDIDATE_INDEX] = { .type = NLA_U32 },
2041		[NL80211_PMKSA_CANDIDATE_BSSID] = {
2042			.minlen = ETH_ALEN,
2043			.maxlen = ETH_ALEN,
2044		},
2045		[NL80211_PMKSA_CANDIDATE_PREAUTH] = { .type = NLA_FLAG },
2046	};
2047	union wpa_event_data data;
2048
2049	if (!tb[NL80211_ATTR_PMKSA_CANDIDATE])
2050		return;
2051	if (nla_parse_nested(cand, MAX_NL80211_PMKSA_CANDIDATE,
2052			     tb[NL80211_ATTR_PMKSA_CANDIDATE], cand_policy))
2053		return;
2054	if (!cand[NL80211_PMKSA_CANDIDATE_INDEX] ||
2055	    !cand[NL80211_PMKSA_CANDIDATE_BSSID])
2056		return;
2057
2058	os_memset(&data, 0, sizeof(data));
2059	os_memcpy(data.pmkid_candidate.bssid,
2060		  nla_data(cand[NL80211_PMKSA_CANDIDATE_BSSID]), ETH_ALEN);
2061	data.pmkid_candidate.index =
2062		nla_get_u32(cand[NL80211_PMKSA_CANDIDATE_INDEX]);
2063	data.pmkid_candidate.preauth =
2064		cand[NL80211_PMKSA_CANDIDATE_PREAUTH] != NULL;
2065	wpa_supplicant_event(drv->ctx, EVENT_PMKID_CANDIDATE, &data);
2066}
2067
2068
2069static void nl80211_client_probe_event(struct wpa_driver_nl80211_data *drv,
2070				       struct nlattr **tb)
2071{
2072	union wpa_event_data data;
2073
2074	if (!tb[NL80211_ATTR_MAC] || !tb[NL80211_ATTR_ACK])
2075		return;
2076
2077	os_memset(&data, 0, sizeof(data));
2078	os_memcpy(data.client_poll.addr,
2079		  nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2080
2081	wpa_supplicant_event(drv->ctx, EVENT_DRIVER_CLIENT_POLL_OK, &data);
2082}
2083
2084
2085static void nl80211_spurious_frame(struct i802_bss *bss, struct nlattr **tb,
2086				   int wds)
2087{
2088	struct wpa_driver_nl80211_data *drv = bss->drv;
2089	union wpa_event_data event;
2090
2091	if (!tb[NL80211_ATTR_MAC])
2092		return;
2093
2094	os_memset(&event, 0, sizeof(event));
2095	event.rx_from_unknown.bssid = bss->addr;
2096	event.rx_from_unknown.addr = nla_data(tb[NL80211_ATTR_MAC]);
2097	event.rx_from_unknown.wds = wds;
2098
2099	wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
2100}
2101
2102
2103static void do_process_drv_event(struct wpa_driver_nl80211_data *drv,
2104				 int cmd, struct nlattr **tb)
2105{
2106	if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED &&
2107	    (cmd == NL80211_CMD_NEW_SCAN_RESULTS ||
2108	     cmd == NL80211_CMD_SCAN_ABORTED)) {
2109		wpa_driver_nl80211_set_mode(&drv->first_bss,
2110					    drv->ap_scan_as_station);
2111		drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
2112	}
2113
2114	switch (cmd) {
2115	case NL80211_CMD_TRIGGER_SCAN:
2116		wpa_printf(MSG_DEBUG, "nl80211: Scan trigger");
2117		break;
2118	case NL80211_CMD_START_SCHED_SCAN:
2119		wpa_printf(MSG_DEBUG, "nl80211: Sched scan started");
2120		break;
2121	case NL80211_CMD_SCHED_SCAN_STOPPED:
2122		wpa_printf(MSG_DEBUG, "nl80211: Sched scan stopped");
2123		wpa_supplicant_event(drv->ctx, EVENT_SCHED_SCAN_STOPPED, NULL);
2124		break;
2125	case NL80211_CMD_NEW_SCAN_RESULTS:
2126		wpa_printf(MSG_DEBUG, "nl80211: New scan results available");
2127		drv->scan_complete_events = 1;
2128		eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
2129				     drv->ctx);
2130		send_scan_event(drv, 0, tb);
2131		break;
2132	case NL80211_CMD_SCHED_SCAN_RESULTS:
2133		wpa_printf(MSG_DEBUG,
2134			   "nl80211: New sched scan results available");
2135		send_scan_event(drv, 0, tb);
2136		break;
2137	case NL80211_CMD_SCAN_ABORTED:
2138		wpa_printf(MSG_DEBUG, "nl80211: Scan aborted");
2139		/*
2140		 * Need to indicate that scan results are available in order
2141		 * not to make wpa_supplicant stop its scanning.
2142		 */
2143		eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
2144				     drv->ctx);
2145		send_scan_event(drv, 1, tb);
2146		break;
2147	case NL80211_CMD_AUTHENTICATE:
2148	case NL80211_CMD_ASSOCIATE:
2149	case NL80211_CMD_DEAUTHENTICATE:
2150	case NL80211_CMD_DISASSOCIATE:
2151	case NL80211_CMD_FRAME_TX_STATUS:
2152	case NL80211_CMD_UNPROT_DEAUTHENTICATE:
2153	case NL80211_CMD_UNPROT_DISASSOCIATE:
2154		mlme_event(drv, cmd, tb[NL80211_ATTR_FRAME],
2155			   tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
2156			   tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
2157			   tb[NL80211_ATTR_COOKIE],
2158			   tb[NL80211_ATTR_RX_SIGNAL_DBM]);
2159		break;
2160	case NL80211_CMD_CONNECT:
2161	case NL80211_CMD_ROAM:
2162		mlme_event_connect(drv, cmd,
2163				   tb[NL80211_ATTR_STATUS_CODE],
2164				   tb[NL80211_ATTR_MAC],
2165				   tb[NL80211_ATTR_REQ_IE],
2166				   tb[NL80211_ATTR_RESP_IE]);
2167		break;
2168	case NL80211_CMD_CH_SWITCH_NOTIFY:
2169		mlme_event_ch_switch(drv, tb[NL80211_ATTR_WIPHY_FREQ],
2170				     tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
2171		break;
2172	case NL80211_CMD_DISCONNECT:
2173		mlme_event_disconnect(drv, tb[NL80211_ATTR_REASON_CODE],
2174				      tb[NL80211_ATTR_MAC],
2175				      tb[NL80211_ATTR_DISCONNECTED_BY_AP]);
2176		break;
2177	case NL80211_CMD_MICHAEL_MIC_FAILURE:
2178		mlme_event_michael_mic_failure(drv, tb);
2179		break;
2180	case NL80211_CMD_JOIN_IBSS:
2181		mlme_event_join_ibss(drv, tb);
2182		break;
2183	case NL80211_CMD_REMAIN_ON_CHANNEL:
2184		mlme_event_remain_on_channel(drv, 0, tb);
2185		break;
2186	case NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL:
2187		mlme_event_remain_on_channel(drv, 1, tb);
2188		break;
2189	case NL80211_CMD_NOTIFY_CQM:
2190		nl80211_cqm_event(drv, tb);
2191		break;
2192	case NL80211_CMD_REG_CHANGE:
2193		wpa_printf(MSG_DEBUG, "nl80211: Regulatory domain change");
2194		wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
2195				     NULL);
2196		break;
2197	case NL80211_CMD_REG_BEACON_HINT:
2198		wpa_printf(MSG_DEBUG, "nl80211: Regulatory beacon hint");
2199		wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
2200				     NULL);
2201		break;
2202	case NL80211_CMD_NEW_STATION:
2203		nl80211_new_station_event(drv, tb);
2204		break;
2205	case NL80211_CMD_DEL_STATION:
2206		nl80211_del_station_event(drv, tb);
2207		break;
2208	case NL80211_CMD_SET_REKEY_OFFLOAD:
2209		nl80211_rekey_offload_event(drv, tb);
2210		break;
2211	case NL80211_CMD_PMKSA_CANDIDATE:
2212		nl80211_pmksa_candidate_event(drv, tb);
2213		break;
2214	case NL80211_CMD_PROBE_CLIENT:
2215		nl80211_client_probe_event(drv, tb);
2216		break;
2217	default:
2218		wpa_printf(MSG_DEBUG, "nl80211: Ignored unknown event "
2219			   "(cmd=%d)", cmd);
2220		break;
2221	}
2222}
2223
2224
2225static int process_drv_event(struct nl_msg *msg, void *arg)
2226{
2227	struct wpa_driver_nl80211_data *drv = arg;
2228	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2229	struct nlattr *tb[NL80211_ATTR_MAX + 1];
2230
2231	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2232		  genlmsg_attrlen(gnlh, 0), NULL);
2233
2234	if (tb[NL80211_ATTR_IFINDEX]) {
2235		int ifindex = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
2236		if (ifindex != drv->ifindex && !have_ifidx(drv, ifindex)) {
2237			wpa_printf(MSG_DEBUG, "nl80211: Ignored event (cmd=%d)"
2238				   " for foreign interface (ifindex %d)",
2239				   gnlh->cmd, ifindex);
2240			return NL_SKIP;
2241		}
2242	}
2243
2244	do_process_drv_event(drv, gnlh->cmd, tb);
2245	return NL_SKIP;
2246}
2247
2248
2249static int process_global_event(struct nl_msg *msg, void *arg)
2250{
2251	struct nl80211_global *global = arg;
2252	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2253	struct nlattr *tb[NL80211_ATTR_MAX + 1];
2254	struct wpa_driver_nl80211_data *drv, *tmp;
2255	int ifidx = -1;
2256
2257	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2258		  genlmsg_attrlen(gnlh, 0), NULL);
2259
2260	if (tb[NL80211_ATTR_IFINDEX])
2261		ifidx = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
2262
2263	dl_list_for_each_safe(drv, tmp, &global->interfaces,
2264			      struct wpa_driver_nl80211_data, list) {
2265		if (ifidx == -1 || ifidx == drv->ifindex ||
2266		    have_ifidx(drv, ifidx))
2267			do_process_drv_event(drv, gnlh->cmd, tb);
2268	}
2269
2270	return NL_SKIP;
2271}
2272
2273
2274static int process_bss_event(struct nl_msg *msg, void *arg)
2275{
2276	struct i802_bss *bss = arg;
2277	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2278	struct nlattr *tb[NL80211_ATTR_MAX + 1];
2279
2280	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2281		  genlmsg_attrlen(gnlh, 0), NULL);
2282
2283	switch (gnlh->cmd) {
2284	case NL80211_CMD_FRAME:
2285	case NL80211_CMD_FRAME_TX_STATUS:
2286		mlme_event(bss->drv, gnlh->cmd, tb[NL80211_ATTR_FRAME],
2287			   tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
2288			   tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
2289			   tb[NL80211_ATTR_COOKIE],
2290			   tb[NL80211_ATTR_RX_SIGNAL_DBM]);
2291		break;
2292	case NL80211_CMD_UNEXPECTED_FRAME:
2293		nl80211_spurious_frame(bss, tb, 0);
2294		break;
2295	case NL80211_CMD_UNEXPECTED_4ADDR_FRAME:
2296		nl80211_spurious_frame(bss, tb, 1);
2297		break;
2298	default:
2299		wpa_printf(MSG_DEBUG, "nl80211: Ignored unknown event "
2300			   "(cmd=%d)", gnlh->cmd);
2301		break;
2302	}
2303
2304	return NL_SKIP;
2305}
2306
2307
2308static void wpa_driver_nl80211_event_receive(int sock, void *eloop_ctx,
2309					     void *handle)
2310{
2311	struct nl_cb *cb = eloop_ctx;
2312
2313	wpa_printf(MSG_DEBUG, "nl80211: Event message available");
2314
2315	nl_recvmsgs(handle, cb);
2316}
2317
2318
2319/**
2320 * wpa_driver_nl80211_set_country - ask nl80211 to set the regulatory domain
2321 * @priv: driver_nl80211 private data
2322 * @alpha2_arg: country to which to switch to
2323 * Returns: 0 on success, -1 on failure
2324 *
2325 * This asks nl80211 to set the regulatory domain for given
2326 * country ISO / IEC alpha2.
2327 */
2328static int wpa_driver_nl80211_set_country(void *priv, const char *alpha2_arg)
2329{
2330	struct i802_bss *bss = priv;
2331	struct wpa_driver_nl80211_data *drv = bss->drv;
2332	char alpha2[3];
2333	struct nl_msg *msg;
2334
2335	msg = nlmsg_alloc();
2336	if (!msg)
2337		return -ENOMEM;
2338
2339	alpha2[0] = alpha2_arg[0];
2340	alpha2[1] = alpha2_arg[1];
2341	alpha2[2] = '\0';
2342
2343	nl80211_cmd(drv, msg, 0, NL80211_CMD_REQ_SET_REG);
2344
2345	NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
2346	if (send_and_recv_msgs(drv, msg, NULL, NULL))
2347		return -EINVAL;
2348	return 0;
2349nla_put_failure:
2350	nlmsg_free(msg);
2351	return -EINVAL;
2352}
2353
2354
2355struct wiphy_info_data {
2356	struct wpa_driver_capa *capa;
2357
2358	unsigned int error:1;
2359	unsigned int device_ap_sme:1;
2360	unsigned int poll_command_supported:1;
2361	unsigned int data_tx_status:1;
2362	unsigned int monitor_supported:1;
2363};
2364
2365
2366static unsigned int probe_resp_offload_support(int supp_protocols)
2367{
2368	unsigned int prot = 0;
2369
2370	if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS)
2371		prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS;
2372	if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2)
2373		prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS2;
2374	if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P)
2375		prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_P2P;
2376	if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_80211U)
2377		prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_INTERWORKING;
2378
2379	return prot;
2380}
2381
2382
2383static int wiphy_info_handler(struct nl_msg *msg, void *arg)
2384{
2385	struct nlattr *tb[NL80211_ATTR_MAX + 1];
2386	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2387	struct wiphy_info_data *info = arg;
2388	int p2p_go_supported = 0, p2p_client_supported = 0;
2389	int p2p_concurrent = 0, p2p_multichan_concurrent = 0;
2390	int auth_supported = 0, connect_supported = 0;
2391	struct wpa_driver_capa *capa = info->capa;
2392	static struct nla_policy
2393	iface_combination_policy[NUM_NL80211_IFACE_COMB] = {
2394		[NL80211_IFACE_COMB_LIMITS] = { .type = NLA_NESTED },
2395		[NL80211_IFACE_COMB_MAXNUM] = { .type = NLA_U32 },
2396		[NL80211_IFACE_COMB_STA_AP_BI_MATCH] = { .type = NLA_FLAG },
2397		[NL80211_IFACE_COMB_NUM_CHANNELS] = { .type = NLA_U32 },
2398	},
2399	iface_limit_policy[NUM_NL80211_IFACE_LIMIT] = {
2400		[NL80211_IFACE_LIMIT_TYPES] = { .type = NLA_NESTED },
2401		[NL80211_IFACE_LIMIT_MAX] = { .type = NLA_U32 },
2402	};
2403
2404	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2405		  genlmsg_attrlen(gnlh, 0), NULL);
2406
2407	if (tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS])
2408		capa->max_scan_ssids =
2409			nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS]);
2410
2411	if (tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS])
2412		capa->max_sched_scan_ssids =
2413			nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS]);
2414
2415	if (tb[NL80211_ATTR_MAX_MATCH_SETS])
2416		capa->max_match_sets =
2417			nla_get_u8(tb[NL80211_ATTR_MAX_MATCH_SETS]);
2418
2419	if (tb[NL80211_ATTR_SUPPORTED_IFTYPES]) {
2420		struct nlattr *nl_mode;
2421		int i;
2422		nla_for_each_nested(nl_mode,
2423				    tb[NL80211_ATTR_SUPPORTED_IFTYPES], i) {
2424			switch (nla_type(nl_mode)) {
2425			case NL80211_IFTYPE_AP:
2426				capa->flags |= WPA_DRIVER_FLAGS_AP;
2427				break;
2428			case NL80211_IFTYPE_P2P_GO:
2429				p2p_go_supported = 1;
2430				break;
2431			case NL80211_IFTYPE_P2P_CLIENT:
2432				p2p_client_supported = 1;
2433				break;
2434			case NL80211_IFTYPE_MONITOR:
2435				info->monitor_supported = 1;
2436				break;
2437			}
2438		}
2439	}
2440
2441	if (tb[NL80211_ATTR_INTERFACE_COMBINATIONS]) {
2442		struct nlattr *nl_combi;
2443		int rem_combi;
2444
2445		nla_for_each_nested(nl_combi,
2446				    tb[NL80211_ATTR_INTERFACE_COMBINATIONS],
2447				    rem_combi) {
2448			struct nlattr *tb_comb[NUM_NL80211_IFACE_COMB];
2449			struct nlattr *tb_limit[NUM_NL80211_IFACE_LIMIT];
2450			struct nlattr *nl_limit, *nl_mode;
2451			int err, rem_limit, rem_mode;
2452			int combination_has_p2p = 0, combination_has_mgd = 0;
2453
2454			err = nla_parse_nested(tb_comb, MAX_NL80211_IFACE_COMB,
2455					       nl_combi,
2456					       iface_combination_policy);
2457			if (err || !tb_comb[NL80211_IFACE_COMB_LIMITS] ||
2458			    !tb_comb[NL80211_IFACE_COMB_MAXNUM] ||
2459			    !tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS])
2460				goto broken_combination;
2461
2462			nla_for_each_nested(nl_limit,
2463					    tb_comb[NL80211_IFACE_COMB_LIMITS],
2464					    rem_limit) {
2465				err = nla_parse_nested(tb_limit,
2466						       MAX_NL80211_IFACE_LIMIT,
2467						       nl_limit,
2468						       iface_limit_policy);
2469				if (err ||
2470				    !tb_limit[NL80211_IFACE_LIMIT_TYPES])
2471					goto broken_combination;
2472
2473				nla_for_each_nested(
2474					nl_mode,
2475					tb_limit[NL80211_IFACE_LIMIT_TYPES],
2476					rem_mode) {
2477					int ift = nla_type(nl_mode);
2478					if (ift == NL80211_IFTYPE_P2P_GO ||
2479					    ift == NL80211_IFTYPE_P2P_CLIENT)
2480						combination_has_p2p = 1;
2481					if (ift == NL80211_IFTYPE_STATION)
2482						combination_has_mgd = 1;
2483				}
2484				if (combination_has_p2p && combination_has_mgd)
2485					break;
2486			}
2487
2488			if (combination_has_p2p && combination_has_mgd) {
2489				p2p_concurrent = 1;
2490				if (nla_get_u32(tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS]) > 1)
2491					p2p_multichan_concurrent = 1;
2492				break;
2493			}
2494
2495broken_combination:
2496			;
2497		}
2498	}
2499
2500	if (tb[NL80211_ATTR_SUPPORTED_COMMANDS]) {
2501		struct nlattr *nl_cmd;
2502		int i;
2503
2504		nla_for_each_nested(nl_cmd,
2505				    tb[NL80211_ATTR_SUPPORTED_COMMANDS], i) {
2506			switch (nla_get_u32(nl_cmd)) {
2507			case NL80211_CMD_AUTHENTICATE:
2508				auth_supported = 1;
2509				break;
2510			case NL80211_CMD_CONNECT:
2511				connect_supported = 1;
2512				break;
2513			case NL80211_CMD_START_SCHED_SCAN:
2514				capa->sched_scan_supported = 1;
2515				break;
2516			case NL80211_CMD_PROBE_CLIENT:
2517				info->poll_command_supported = 1;
2518				break;
2519			}
2520		}
2521	}
2522
2523	if (tb[NL80211_ATTR_OFFCHANNEL_TX_OK]) {
2524		wpa_printf(MSG_DEBUG, "nl80211: Using driver-based "
2525			   "off-channel TX");
2526		capa->flags |= WPA_DRIVER_FLAGS_OFFCHANNEL_TX;
2527	}
2528
2529	if (tb[NL80211_ATTR_ROAM_SUPPORT]) {
2530		wpa_printf(MSG_DEBUG, "nl80211: Using driver-based roaming");
2531		capa->flags |= WPA_DRIVER_FLAGS_BSS_SELECTION;
2532	}
2533
2534	/* default to 5000 since early versions of mac80211 don't set it */
2535	capa->max_remain_on_chan = 5000;
2536
2537	if (tb[NL80211_ATTR_SUPPORT_AP_UAPSD])
2538		capa->flags |= WPA_DRIVER_FLAGS_AP_UAPSD;
2539
2540	if (tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION])
2541		capa->max_remain_on_chan =
2542			nla_get_u32(tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION]);
2543
2544	if (auth_supported)
2545		capa->flags |= WPA_DRIVER_FLAGS_SME;
2546	else if (!connect_supported) {
2547		wpa_printf(MSG_INFO, "nl80211: Driver does not support "
2548			   "authentication/association or connect commands");
2549		info->error = 1;
2550	}
2551
2552	if (p2p_go_supported && p2p_client_supported)
2553		capa->flags |= WPA_DRIVER_FLAGS_P2P_CAPABLE;
2554	if (p2p_concurrent) {
2555		wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
2556			   "interface (driver advertised support)");
2557		capa->flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
2558		capa->flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
2559
2560		if (p2p_multichan_concurrent) {
2561			wpa_printf(MSG_DEBUG, "nl80211: Enable multi-channel "
2562				   "concurrent (driver advertised support)");
2563			capa->flags |=
2564				WPA_DRIVER_FLAGS_MULTI_CHANNEL_CONCURRENT;
2565		}
2566	}
2567
2568	if (tb[NL80211_ATTR_TDLS_SUPPORT]) {
2569		wpa_printf(MSG_DEBUG, "nl80211: TDLS supported");
2570		capa->flags |= WPA_DRIVER_FLAGS_TDLS_SUPPORT;
2571
2572		if (tb[NL80211_ATTR_TDLS_EXTERNAL_SETUP]) {
2573			wpa_printf(MSG_DEBUG, "nl80211: TDLS external setup");
2574			capa->flags |=
2575				WPA_DRIVER_FLAGS_TDLS_EXTERNAL_SETUP;
2576		}
2577	}
2578
2579	if (tb[NL80211_ATTR_DEVICE_AP_SME])
2580		info->device_ap_sme = 1;
2581
2582	if (tb[NL80211_ATTR_FEATURE_FLAGS]) {
2583		u32 flags = nla_get_u32(tb[NL80211_ATTR_FEATURE_FLAGS]);
2584
2585		if (flags & NL80211_FEATURE_SK_TX_STATUS)
2586			info->data_tx_status = 1;
2587
2588		if (flags & NL80211_FEATURE_INACTIVITY_TIMER)
2589			capa->flags |= WPA_DRIVER_FLAGS_INACTIVITY_TIMER;
2590	}
2591
2592	if (tb[NL80211_ATTR_PROBE_RESP_OFFLOAD]) {
2593		int protocols =
2594			nla_get_u32(tb[NL80211_ATTR_PROBE_RESP_OFFLOAD]);
2595		wpa_printf(MSG_DEBUG, "nl80211: Supports Probe Response "
2596			   "offload in AP mode");
2597		capa->flags |= WPA_DRIVER_FLAGS_PROBE_RESP_OFFLOAD;
2598		capa->probe_resp_offloads =
2599			probe_resp_offload_support(protocols);
2600	}
2601
2602	return NL_SKIP;
2603}
2604
2605
2606static int wpa_driver_nl80211_get_info(struct wpa_driver_nl80211_data *drv,
2607				       struct wiphy_info_data *info)
2608{
2609	struct nl_msg *msg;
2610
2611	os_memset(info, 0, sizeof(*info));
2612	info->capa = &drv->capa;
2613
2614	msg = nlmsg_alloc();
2615	if (!msg)
2616		return -1;
2617
2618	nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
2619
2620	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->first_bss.ifindex);
2621
2622	if (send_and_recv_msgs(drv, msg, wiphy_info_handler, info) == 0)
2623		return 0;
2624	msg = NULL;
2625nla_put_failure:
2626	nlmsg_free(msg);
2627	return -1;
2628}
2629
2630
2631static int wpa_driver_nl80211_capa(struct wpa_driver_nl80211_data *drv)
2632{
2633	struct wiphy_info_data info;
2634	if (wpa_driver_nl80211_get_info(drv, &info))
2635		return -1;
2636
2637	if (info.error)
2638		return -1;
2639
2640	drv->has_capability = 1;
2641	/* For now, assume TKIP, CCMP, WPA, WPA2 are supported */
2642	drv->capa.key_mgmt = WPA_DRIVER_CAPA_KEY_MGMT_WPA |
2643		WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK |
2644		WPA_DRIVER_CAPA_KEY_MGMT_WPA2 |
2645		WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK;
2646	drv->capa.enc = WPA_DRIVER_CAPA_ENC_WEP40 |
2647		WPA_DRIVER_CAPA_ENC_WEP104 |
2648		WPA_DRIVER_CAPA_ENC_TKIP |
2649		WPA_DRIVER_CAPA_ENC_CCMP;
2650	drv->capa.auth = WPA_DRIVER_AUTH_OPEN |
2651		WPA_DRIVER_AUTH_SHARED |
2652		WPA_DRIVER_AUTH_LEAP;
2653
2654	drv->capa.flags |= WPA_DRIVER_FLAGS_SANE_ERROR_CODES;
2655	drv->capa.flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE;
2656	drv->capa.flags |= WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2657
2658	if (!info.device_ap_sme) {
2659		drv->capa.flags |= WPA_DRIVER_FLAGS_DEAUTH_TX_STATUS;
2660
2661		/*
2662		 * No AP SME is currently assumed to also indicate no AP MLME
2663		 * in the driver/firmware.
2664		 */
2665		drv->capa.flags |= WPA_DRIVER_FLAGS_AP_MLME;
2666	}
2667
2668	drv->device_ap_sme = info.device_ap_sme;
2669	drv->poll_command_supported = info.poll_command_supported;
2670	drv->data_tx_status = info.data_tx_status;
2671
2672#ifdef ANDROID_P2P
2673	if(drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX) {
2674		/* Driver is new enough to support monitorless mode*/
2675		wpa_printf(MSG_DEBUG, "nl80211: Driver is new "
2676			  "enough to support monitor-less mode");
2677		drv->use_monitor = 0;
2678	}
2679#else
2680	/*
2681	 * If poll command and tx status are supported, mac80211 is new enough
2682	 * to have everything we need to not need monitor interfaces.
2683	 */
2684	drv->use_monitor = !info.poll_command_supported || !info.data_tx_status;
2685#endif
2686
2687	if (drv->device_ap_sme && drv->use_monitor) {
2688		/*
2689		 * Non-mac80211 drivers may not support monitor interface.
2690		 * Make sure we do not get stuck with incorrect capability here
2691		 * by explicitly testing this.
2692		 */
2693		if (!info.monitor_supported) {
2694			wpa_printf(MSG_DEBUG, "nl80211: Disable use_monitor "
2695				   "with device_ap_sme since no monitor mode "
2696				   "support detected");
2697			drv->use_monitor = 0;
2698		}
2699	}
2700
2701	/*
2702	 * If we aren't going to use monitor interfaces, but the
2703	 * driver doesn't support data TX status, we won't get TX
2704	 * status for EAPOL frames.
2705	 */
2706	if (!drv->use_monitor && !info.data_tx_status)
2707		drv->capa.flags &= ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2708
2709	return 0;
2710}
2711
2712
2713#ifdef ANDROID
2714static int android_genl_ctrl_resolve(struct nl_handle *handle,
2715				     const char *name)
2716{
2717	/*
2718	 * Android ICS has very minimal genl_ctrl_resolve() implementation, so
2719	 * need to work around that.
2720	 */
2721	struct nl_cache *cache = NULL;
2722	struct genl_family *nl80211 = NULL;
2723	int id = -1;
2724
2725	if (genl_ctrl_alloc_cache(handle, &cache) < 0) {
2726		wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
2727			   "netlink cache");
2728		goto fail;
2729	}
2730
2731	nl80211 = genl_ctrl_search_by_name(cache, name);
2732	if (nl80211 == NULL)
2733		goto fail;
2734
2735	id = genl_family_get_id(nl80211);
2736
2737fail:
2738	if (nl80211)
2739		genl_family_put(nl80211);
2740	if (cache)
2741		nl_cache_free(cache);
2742
2743	return id;
2744}
2745#define genl_ctrl_resolve android_genl_ctrl_resolve
2746#endif /* ANDROID */
2747
2748
2749static int wpa_driver_nl80211_init_nl_global(struct nl80211_global *global)
2750{
2751	int ret;
2752
2753	global->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2754	if (global->nl_cb == NULL) {
2755		wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
2756			   "callbacks");
2757		return -1;
2758	}
2759
2760	global->nl = nl_create_handle(global->nl_cb, "nl");
2761	if (global->nl == NULL)
2762		goto err;
2763
2764	global->nl80211_id = genl_ctrl_resolve(global->nl, "nl80211");
2765	if (global->nl80211_id < 0) {
2766		wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
2767			   "found");
2768		goto err;
2769	}
2770
2771	global->nl_event = nl_create_handle(global->nl_cb, "event");
2772	if (global->nl_event == NULL)
2773		goto err;
2774
2775	ret = nl_get_multicast_id(global, "nl80211", "scan");
2776	if (ret >= 0)
2777		ret = nl_socket_add_membership(global->nl_event, ret);
2778	if (ret < 0) {
2779		wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
2780			   "membership for scan events: %d (%s)",
2781			   ret, strerror(-ret));
2782		goto err;
2783	}
2784
2785	ret = nl_get_multicast_id(global, "nl80211", "mlme");
2786	if (ret >= 0)
2787		ret = nl_socket_add_membership(global->nl_event, ret);
2788	if (ret < 0) {
2789		wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
2790			   "membership for mlme events: %d (%s)",
2791			   ret, strerror(-ret));
2792		goto err;
2793	}
2794
2795	ret = nl_get_multicast_id(global, "nl80211", "regulatory");
2796	if (ret >= 0)
2797		ret = nl_socket_add_membership(global->nl_event, ret);
2798	if (ret < 0) {
2799		wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
2800			   "membership for regulatory events: %d (%s)",
2801			   ret, strerror(-ret));
2802		/* Continue without regulatory events */
2803	}
2804
2805	nl_cb_set(global->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2806		  no_seq_check, NULL);
2807	nl_cb_set(global->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2808		  process_global_event, global);
2809
2810	eloop_register_read_sock(nl_socket_get_fd(global->nl_event),
2811				 wpa_driver_nl80211_event_receive,
2812				 global->nl_cb, global->nl_event);
2813
2814	return 0;
2815
2816err:
2817	nl_destroy_handles(&global->nl_event);
2818	nl_destroy_handles(&global->nl);
2819	nl_cb_put(global->nl_cb);
2820	global->nl_cb = NULL;
2821	return -1;
2822}
2823
2824
2825static int wpa_driver_nl80211_init_nl(struct wpa_driver_nl80211_data *drv)
2826{
2827	drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2828	if (!drv->nl_cb) {
2829		wpa_printf(MSG_ERROR, "nl80211: Failed to alloc cb struct");
2830		return -1;
2831	}
2832
2833	nl_cb_set(drv->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2834		  no_seq_check, NULL);
2835	nl_cb_set(drv->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2836		  process_drv_event, drv);
2837
2838	return 0;
2839}
2840
2841
2842static void wpa_driver_nl80211_rfkill_blocked(void *ctx)
2843{
2844	wpa_printf(MSG_DEBUG, "nl80211: RFKILL blocked");
2845	/*
2846	 * This may be for any interface; use ifdown event to disable
2847	 * interface.
2848	 */
2849}
2850
2851
2852static void wpa_driver_nl80211_rfkill_unblocked(void *ctx)
2853{
2854	struct wpa_driver_nl80211_data *drv = ctx;
2855	wpa_printf(MSG_DEBUG, "nl80211: RFKILL unblocked");
2856	if (linux_set_iface_flags(drv->global->ioctl_sock,
2857				  drv->first_bss.ifname, 1)) {
2858		wpa_printf(MSG_DEBUG, "nl80211: Could not set interface UP "
2859			   "after rfkill unblock");
2860		return;
2861	}
2862	/* rtnetlink ifup handler will report interface as enabled */
2863}
2864
2865
2866static void nl80211_get_phy_name(struct wpa_driver_nl80211_data *drv)
2867{
2868	/* Find phy (radio) to which this interface belongs */
2869	char buf[90], *pos;
2870	int f, rv;
2871
2872	drv->phyname[0] = '\0';
2873	snprintf(buf, sizeof(buf) - 1, "/sys/class/net/%s/phy80211/name",
2874		 drv->first_bss.ifname);
2875	f = open(buf, O_RDONLY);
2876	if (f < 0) {
2877		wpa_printf(MSG_DEBUG, "Could not open file %s: %s",
2878			   buf, strerror(errno));
2879		return;
2880	}
2881
2882	rv = read(f, drv->phyname, sizeof(drv->phyname) - 1);
2883	close(f);
2884	if (rv < 0) {
2885		wpa_printf(MSG_DEBUG, "Could not read file %s: %s",
2886			   buf, strerror(errno));
2887		return;
2888	}
2889
2890	drv->phyname[rv] = '\0';
2891	pos = os_strchr(drv->phyname, '\n');
2892	if (pos)
2893		*pos = '\0';
2894	wpa_printf(MSG_DEBUG, "nl80211: interface %s in phy %s",
2895		   drv->first_bss.ifname, drv->phyname);
2896}
2897
2898
2899static void wpa_driver_nl80211_handle_eapol_tx_status(int sock,
2900						      void *eloop_ctx,
2901						      void *handle)
2902{
2903	struct wpa_driver_nl80211_data *drv = eloop_ctx;
2904	u8 data[2048];
2905	struct msghdr msg;
2906	struct iovec entry;
2907	u8 control[512];
2908	struct cmsghdr *cmsg;
2909	int res, found_ee = 0, found_wifi = 0, acked = 0;
2910	union wpa_event_data event;
2911
2912	memset(&msg, 0, sizeof(msg));
2913	msg.msg_iov = &entry;
2914	msg.msg_iovlen = 1;
2915	entry.iov_base = data;
2916	entry.iov_len = sizeof(data);
2917	msg.msg_control = &control;
2918	msg.msg_controllen = sizeof(control);
2919
2920	res = recvmsg(sock, &msg, MSG_ERRQUEUE);
2921	/* if error or not fitting 802.3 header, return */
2922	if (res < 14)
2923		return;
2924
2925	for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg))
2926	{
2927		if (cmsg->cmsg_level == SOL_SOCKET &&
2928		    cmsg->cmsg_type == SCM_WIFI_STATUS) {
2929			int *ack;
2930
2931			found_wifi = 1;
2932			ack = (void *)CMSG_DATA(cmsg);
2933			acked = *ack;
2934		}
2935
2936		if (cmsg->cmsg_level == SOL_PACKET &&
2937		    cmsg->cmsg_type == PACKET_TX_TIMESTAMP) {
2938			struct sock_extended_err *err =
2939				(struct sock_extended_err *)CMSG_DATA(cmsg);
2940
2941			if (err->ee_origin == SO_EE_ORIGIN_TXSTATUS)
2942				found_ee = 1;
2943		}
2944	}
2945
2946	if (!found_ee || !found_wifi)
2947		return;
2948
2949	memset(&event, 0, sizeof(event));
2950	event.eapol_tx_status.dst = data;
2951	event.eapol_tx_status.data = data + 14;
2952	event.eapol_tx_status.data_len = res - 14;
2953	event.eapol_tx_status.ack = acked;
2954	wpa_supplicant_event(drv->ctx, EVENT_EAPOL_TX_STATUS, &event);
2955}
2956
2957
2958static int nl80211_init_bss(struct i802_bss *bss)
2959{
2960	bss->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2961	if (!bss->nl_cb)
2962		return -1;
2963
2964	nl_cb_set(bss->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2965		  no_seq_check, NULL);
2966	nl_cb_set(bss->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2967		  process_bss_event, bss);
2968
2969	return 0;
2970}
2971
2972
2973static void nl80211_destroy_bss(struct i802_bss *bss)
2974{
2975	nl_cb_put(bss->nl_cb);
2976	bss->nl_cb = NULL;
2977}
2978
2979
2980/**
2981 * wpa_driver_nl80211_init - Initialize nl80211 driver interface
2982 * @ctx: context to be used when calling wpa_supplicant functions,
2983 * e.g., wpa_supplicant_event()
2984 * @ifname: interface name, e.g., wlan0
2985 * @global_priv: private driver global data from global_init()
2986 * Returns: Pointer to private data, %NULL on failure
2987 */
2988static void * wpa_driver_nl80211_init(void *ctx, const char *ifname,
2989				      void *global_priv)
2990{
2991	struct wpa_driver_nl80211_data *drv;
2992	struct rfkill_config *rcfg;
2993	struct i802_bss *bss;
2994
2995	if (global_priv == NULL)
2996		return NULL;
2997	drv = os_zalloc(sizeof(*drv));
2998	if (drv == NULL)
2999		return NULL;
3000	drv->global = global_priv;
3001	drv->ctx = ctx;
3002	bss = &drv->first_bss;
3003	bss->drv = drv;
3004	os_strlcpy(bss->ifname, ifname, sizeof(bss->ifname));
3005	drv->monitor_ifidx = -1;
3006	drv->monitor_sock = -1;
3007	drv->eapol_tx_sock = -1;
3008	drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
3009
3010	if (wpa_driver_nl80211_init_nl(drv)) {
3011		os_free(drv);
3012		return NULL;
3013	}
3014
3015	if (nl80211_init_bss(bss))
3016		goto failed;
3017
3018	nl80211_get_phy_name(drv);
3019
3020	rcfg = os_zalloc(sizeof(*rcfg));
3021	if (rcfg == NULL)
3022		goto failed;
3023	rcfg->ctx = drv;
3024	os_strlcpy(rcfg->ifname, ifname, sizeof(rcfg->ifname));
3025	rcfg->blocked_cb = wpa_driver_nl80211_rfkill_blocked;
3026	rcfg->unblocked_cb = wpa_driver_nl80211_rfkill_unblocked;
3027	drv->rfkill = rfkill_init(rcfg);
3028	if (drv->rfkill == NULL) {
3029		wpa_printf(MSG_DEBUG, "nl80211: RFKILL status not available");
3030		os_free(rcfg);
3031	}
3032
3033	if (wpa_driver_nl80211_finish_drv_init(drv))
3034		goto failed;
3035
3036	drv->eapol_tx_sock = socket(PF_PACKET, SOCK_DGRAM, 0);
3037	if (drv->eapol_tx_sock < 0)
3038		goto failed;
3039
3040	if (drv->data_tx_status) {
3041		int enabled = 1;
3042
3043		if (setsockopt(drv->eapol_tx_sock, SOL_SOCKET, SO_WIFI_STATUS,
3044			       &enabled, sizeof(enabled)) < 0) {
3045			wpa_printf(MSG_DEBUG,
3046				"nl80211: wifi status sockopt failed\n");
3047			drv->data_tx_status = 0;
3048			if (!drv->use_monitor)
3049				drv->capa.flags &=
3050					~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
3051		} else {
3052			eloop_register_read_sock(drv->eapol_tx_sock,
3053				wpa_driver_nl80211_handle_eapol_tx_status,
3054				drv, NULL);
3055		}
3056	}
3057
3058	if (drv->global) {
3059		dl_list_add(&drv->global->interfaces, &drv->list);
3060		drv->in_interface_list = 1;
3061	}
3062
3063	return bss;
3064
3065failed:
3066	wpa_driver_nl80211_deinit(bss);
3067	return NULL;
3068}
3069
3070
3071static int nl80211_register_frame(struct i802_bss *bss,
3072				  struct nl_handle *nl_handle,
3073				  u16 type, const u8 *match, size_t match_len)
3074{
3075	struct wpa_driver_nl80211_data *drv = bss->drv;
3076	struct nl_msg *msg;
3077	int ret = -1;
3078
3079	msg = nlmsg_alloc();
3080	if (!msg)
3081		return -1;
3082
3083	wpa_printf(MSG_DEBUG, "nl80211: Register frame type=0x%x nl_handle=%p",
3084		   type, nl_handle);
3085	wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
3086		    match, match_len);
3087
3088	nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_ACTION);
3089
3090	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3091	NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE, type);
3092	NLA_PUT(msg, NL80211_ATTR_FRAME_MATCH, match_len, match);
3093
3094	ret = send_and_recv(drv->global, nl_handle, msg, NULL, NULL);
3095	msg = NULL;
3096	if (ret) {
3097		wpa_printf(MSG_DEBUG, "nl80211: Register frame command "
3098			   "failed (type=%u): ret=%d (%s)",
3099			   type, ret, strerror(-ret));
3100		wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
3101			    match, match_len);
3102		goto nla_put_failure;
3103	}
3104	ret = 0;
3105nla_put_failure:
3106	nlmsg_free(msg);
3107	return ret;
3108}
3109
3110
3111static int nl80211_alloc_mgmt_handle(struct i802_bss *bss)
3112{
3113	struct wpa_driver_nl80211_data *drv = bss->drv;
3114
3115	if (bss->nl_mgmt) {
3116		wpa_printf(MSG_DEBUG, "nl80211: Mgmt reporting "
3117			   "already on! (nl_mgmt=%p)", bss->nl_mgmt);
3118		return -1;
3119	}
3120
3121	bss->nl_mgmt = nl_create_handle(drv->nl_cb, "mgmt");
3122	if (bss->nl_mgmt == NULL)
3123		return -1;
3124
3125	eloop_register_read_sock(nl_socket_get_fd(bss->nl_mgmt),
3126				 wpa_driver_nl80211_event_receive, bss->nl_cb,
3127				 bss->nl_mgmt);
3128
3129	return 0;
3130}
3131
3132
3133static int nl80211_register_action_frame(struct i802_bss *bss,
3134					 const u8 *match, size_t match_len)
3135{
3136	u16 type = (WLAN_FC_TYPE_MGMT << 2) | (WLAN_FC_STYPE_ACTION << 4);
3137	return nl80211_register_frame(bss, bss->nl_mgmt,
3138				      type, match, match_len);
3139}
3140
3141
3142static int nl80211_mgmt_subscribe_non_ap(struct i802_bss *bss)
3143{
3144	struct wpa_driver_nl80211_data *drv = bss->drv;
3145
3146	if (nl80211_alloc_mgmt_handle(bss))
3147		return -1;
3148	wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with non-AP "
3149		   "handle %p", bss->nl_mgmt);
3150
3151#if defined(CONFIG_P2P) || defined(CONFIG_INTERWORKING)
3152	/* GAS Initial Request */
3153	if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0a", 2) < 0)
3154		return -1;
3155	/* GAS Initial Response */
3156	if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0b", 2) < 0)
3157		return -1;
3158	/* GAS Comeback Request */
3159	if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0c", 2) < 0)
3160		return -1;
3161	/* GAS Comeback Response */
3162	if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0d", 2) < 0)
3163		return -1;
3164#endif /* CONFIG_P2P || CONFIG_INTERWORKING */
3165#ifdef CONFIG_P2P
3166	/* P2P Public Action */
3167	if (nl80211_register_action_frame(bss,
3168					  (u8 *) "\x04\x09\x50\x6f\x9a\x09",
3169					  6) < 0)
3170		return -1;
3171	/* P2P Action */
3172	if (nl80211_register_action_frame(bss,
3173					  (u8 *) "\x7f\x50\x6f\x9a\x09",
3174					  5) < 0)
3175		return -1;
3176#endif /* CONFIG_P2P */
3177#ifdef CONFIG_IEEE80211W
3178	/* SA Query Response */
3179	if (nl80211_register_action_frame(bss, (u8 *) "\x08\x01", 2) < 0)
3180		return -1;
3181#endif /* CONFIG_IEEE80211W */
3182#ifdef CONFIG_TDLS
3183	if ((drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT)) {
3184		/* TDLS Discovery Response */
3185		if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0e", 2) <
3186		    0)
3187			return -1;
3188	}
3189#endif /* CONFIG_TDLS */
3190
3191	/* FT Action frames */
3192	if (nl80211_register_action_frame(bss, (u8 *) "\x06", 1) < 0)
3193		return -1;
3194	else
3195		drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_FT |
3196			WPA_DRIVER_CAPA_KEY_MGMT_FT_PSK;
3197
3198	/* WNM - BSS Transition Management Request */
3199	if (nl80211_register_action_frame(bss, (u8 *) "\x0a\x07", 2) < 0)
3200		return -1;
3201
3202	return 0;
3203}
3204
3205
3206static int nl80211_register_spurious_class3(struct i802_bss *bss)
3207{
3208	struct wpa_driver_nl80211_data *drv = bss->drv;
3209	struct nl_msg *msg;
3210	int ret = -1;
3211
3212	msg = nlmsg_alloc();
3213	if (!msg)
3214		return -1;
3215
3216	nl80211_cmd(drv, msg, 0, NL80211_CMD_UNEXPECTED_FRAME);
3217
3218	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3219
3220	ret = send_and_recv(drv->global, bss->nl_mgmt, msg, NULL, NULL);
3221	msg = NULL;
3222	if (ret) {
3223		wpa_printf(MSG_DEBUG, "nl80211: Register spurious class3 "
3224			   "failed: ret=%d (%s)",
3225			   ret, strerror(-ret));
3226		goto nla_put_failure;
3227	}
3228	ret = 0;
3229nla_put_failure:
3230	nlmsg_free(msg);
3231	return ret;
3232}
3233
3234
3235static int nl80211_mgmt_subscribe_ap(struct i802_bss *bss)
3236{
3237	static const int stypes[] = {
3238		WLAN_FC_STYPE_AUTH,
3239		WLAN_FC_STYPE_ASSOC_REQ,
3240		WLAN_FC_STYPE_REASSOC_REQ,
3241		WLAN_FC_STYPE_DISASSOC,
3242		WLAN_FC_STYPE_DEAUTH,
3243		WLAN_FC_STYPE_ACTION,
3244		WLAN_FC_STYPE_PROBE_REQ,
3245/* Beacon doesn't work as mac80211 doesn't currently allow
3246 * it, but it wouldn't really be the right thing anyway as
3247 * it isn't per interface ... maybe just dump the scan
3248 * results periodically for OLBC?
3249 */
3250//		WLAN_FC_STYPE_BEACON,
3251	};
3252	unsigned int i;
3253
3254	if (nl80211_alloc_mgmt_handle(bss))
3255		return -1;
3256	wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3257		   "handle %p", bss->nl_mgmt);
3258
3259	for (i = 0; i < sizeof(stypes) / sizeof(stypes[0]); i++) {
3260		if (nl80211_register_frame(bss, bss->nl_mgmt,
3261					   (WLAN_FC_TYPE_MGMT << 2) |
3262					   (stypes[i] << 4),
3263					   NULL, 0) < 0) {
3264			goto out_err;
3265		}
3266	}
3267
3268	if (nl80211_register_spurious_class3(bss))
3269		goto out_err;
3270
3271	if (nl80211_get_wiphy_data_ap(bss) == NULL)
3272		goto out_err;
3273
3274	return 0;
3275
3276out_err:
3277	eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3278	nl_destroy_handles(&bss->nl_mgmt);
3279	return -1;
3280}
3281
3282
3283static int nl80211_mgmt_subscribe_ap_dev_sme(struct i802_bss *bss)
3284{
3285	if (nl80211_alloc_mgmt_handle(bss))
3286		return -1;
3287	wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3288		   "handle %p (device SME)", bss->nl_mgmt);
3289
3290	if (nl80211_register_frame(bss, bss->nl_mgmt,
3291				   (WLAN_FC_TYPE_MGMT << 2) |
3292				   (WLAN_FC_STYPE_ACTION << 4),
3293				   NULL, 0) < 0)
3294		goto out_err;
3295
3296	return 0;
3297
3298out_err:
3299	eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3300	nl_destroy_handles(&bss->nl_mgmt);
3301	return -1;
3302}
3303
3304
3305static void nl80211_mgmt_unsubscribe(struct i802_bss *bss, const char *reason)
3306{
3307	if (bss->nl_mgmt == NULL)
3308		return;
3309	wpa_printf(MSG_DEBUG, "nl80211: Unsubscribe mgmt frames handle %p "
3310		   "(%s)", bss->nl_mgmt, reason);
3311	eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3312	nl_destroy_handles(&bss->nl_mgmt);
3313
3314	nl80211_put_wiphy_data_ap(bss);
3315}
3316
3317
3318static void wpa_driver_nl80211_send_rfkill(void *eloop_ctx, void *timeout_ctx)
3319{
3320	wpa_supplicant_event(timeout_ctx, EVENT_INTERFACE_DISABLED, NULL);
3321}
3322
3323
3324static int
3325wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv)
3326{
3327	struct i802_bss *bss = &drv->first_bss;
3328	int send_rfkill_event = 0;
3329
3330	drv->ifindex = if_nametoindex(bss->ifname);
3331	drv->first_bss.ifindex = drv->ifindex;
3332
3333#ifndef HOSTAPD
3334	/*
3335	 * Make sure the interface starts up in station mode unless this is a
3336	 * dynamically added interface (e.g., P2P) that was already configured
3337	 * with proper iftype.
3338	 */
3339	if (drv->ifindex != drv->global->if_add_ifindex &&
3340	    wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION) < 0) {
3341		wpa_printf(MSG_ERROR, "nl80211: Could not configure driver to "
3342			   "use managed mode");
3343		return -1;
3344	}
3345
3346	if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
3347		if (rfkill_is_blocked(drv->rfkill)) {
3348			wpa_printf(MSG_DEBUG, "nl80211: Could not yet enable "
3349				   "interface '%s' due to rfkill",
3350				   bss->ifname);
3351			drv->if_disabled = 1;
3352			send_rfkill_event = 1;
3353		} else {
3354			wpa_printf(MSG_ERROR, "nl80211: Could not set "
3355				   "interface '%s' UP", bss->ifname);
3356			return -1;
3357		}
3358	}
3359
3360	netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
3361			       1, IF_OPER_DORMANT);
3362#endif /* HOSTAPD */
3363
3364	if (wpa_driver_nl80211_capa(drv))
3365		return -1;
3366
3367	if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
3368			       bss->addr))
3369		return -1;
3370
3371	if (send_rfkill_event) {
3372		eloop_register_timeout(0, 0, wpa_driver_nl80211_send_rfkill,
3373				       drv, drv->ctx);
3374	}
3375
3376	return 0;
3377}
3378
3379
3380static int wpa_driver_nl80211_del_beacon(struct wpa_driver_nl80211_data *drv)
3381{
3382	struct nl_msg *msg;
3383
3384	msg = nlmsg_alloc();
3385	if (!msg)
3386		return -ENOMEM;
3387
3388	nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_BEACON);
3389	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3390
3391	return send_and_recv_msgs(drv, msg, NULL, NULL);
3392 nla_put_failure:
3393	nlmsg_free(msg);
3394	return -ENOBUFS;
3395}
3396
3397
3398/**
3399 * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
3400 * @priv: Pointer to private nl80211 data from wpa_driver_nl80211_init()
3401 *
3402 * Shut down driver interface and processing of driver events. Free
3403 * private data buffer if one was allocated in wpa_driver_nl80211_init().
3404 */
3405static void wpa_driver_nl80211_deinit(void *priv)
3406{
3407	struct i802_bss *bss = priv;
3408	struct wpa_driver_nl80211_data *drv = bss->drv;
3409
3410	bss->in_deinit = 1;
3411	if (drv->data_tx_status)
3412		eloop_unregister_read_sock(drv->eapol_tx_sock);
3413	if (drv->eapol_tx_sock >= 0)
3414		close(drv->eapol_tx_sock);
3415
3416	if (bss->nl_preq)
3417		wpa_driver_nl80211_probe_req_report(bss, 0);
3418	if (bss->added_if_into_bridge) {
3419		if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
3420				    bss->ifname) < 0)
3421			wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3422				   "interface %s from bridge %s: %s",
3423				   bss->ifname, bss->brname, strerror(errno));
3424	}
3425	if (bss->added_bridge) {
3426		if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
3427			wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3428				   "bridge %s: %s",
3429				   bss->brname, strerror(errno));
3430	}
3431
3432	nl80211_remove_monitor_interface(drv);
3433
3434	if (is_ap_interface(drv->nlmode))
3435		wpa_driver_nl80211_del_beacon(drv);
3436
3437#ifdef HOSTAPD
3438	if (drv->last_freq_ht) {
3439		/* Clear HT flags from the driver */
3440		struct hostapd_freq_params freq;
3441		os_memset(&freq, 0, sizeof(freq));
3442		freq.freq = drv->last_freq;
3443		i802_set_freq(priv, &freq);
3444	}
3445
3446	if (drv->eapol_sock >= 0) {
3447		eloop_unregister_read_sock(drv->eapol_sock);
3448		close(drv->eapol_sock);
3449	}
3450
3451	if (drv->if_indices != drv->default_if_indices)
3452		os_free(drv->if_indices);
3453#endif /* HOSTAPD */
3454
3455	if (drv->disabled_11b_rates)
3456		nl80211_disable_11b_rates(drv, drv->ifindex, 0);
3457
3458	netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, 0,
3459			       IF_OPER_UP);
3460	rfkill_deinit(drv->rfkill);
3461
3462	eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3463
3464	(void) linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0);
3465	wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION);
3466	nl80211_mgmt_unsubscribe(bss, "deinit");
3467
3468	nl_cb_put(drv->nl_cb);
3469
3470	nl80211_destroy_bss(&drv->first_bss);
3471
3472	os_free(drv->filter_ssids);
3473
3474	os_free(drv->auth_ie);
3475
3476	if (drv->in_interface_list)
3477		dl_list_del(&drv->list);
3478
3479	os_free(drv);
3480}
3481
3482
3483/**
3484 * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
3485 * @eloop_ctx: Driver private data
3486 * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
3487 *
3488 * This function can be used as registered timeout when starting a scan to
3489 * generate a scan completed event if the driver does not report this.
3490 */
3491static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
3492{
3493	struct wpa_driver_nl80211_data *drv = eloop_ctx;
3494	if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED) {
3495		wpa_driver_nl80211_set_mode(&drv->first_bss,
3496					    drv->ap_scan_as_station);
3497		drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
3498	}
3499	wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
3500	wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
3501}
3502
3503
3504static struct nl_msg *
3505nl80211_scan_common(struct wpa_driver_nl80211_data *drv, u8 cmd,
3506		    struct wpa_driver_scan_params *params)
3507{
3508	struct nl_msg *msg;
3509	int err;
3510	size_t i;
3511
3512	msg = nlmsg_alloc();
3513	if (!msg)
3514		return NULL;
3515
3516	nl80211_cmd(drv, msg, 0, cmd);
3517
3518	if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, drv->ifindex) < 0)
3519		goto fail;
3520
3521	if (params->num_ssids) {
3522		struct nl_msg *ssids = nlmsg_alloc();
3523		if (ssids == NULL)
3524			goto fail;
3525		for (i = 0; i < params->num_ssids; i++) {
3526			wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan SSID",
3527					  params->ssids[i].ssid,
3528					  params->ssids[i].ssid_len);
3529			if (nla_put(ssids, i + 1, params->ssids[i].ssid_len,
3530				    params->ssids[i].ssid) < 0) {
3531				nlmsg_free(ssids);
3532				goto fail;
3533			}
3534		}
3535		err = nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
3536		nlmsg_free(ssids);
3537		if (err < 0)
3538			goto fail;
3539	}
3540
3541	if (params->extra_ies) {
3542		wpa_hexdump(MSG_MSGDUMP, "nl80211: Scan extra IEs",
3543			    params->extra_ies, params->extra_ies_len);
3544		if (nla_put(msg, NL80211_ATTR_IE, params->extra_ies_len,
3545			    params->extra_ies) < 0)
3546			goto fail;
3547	}
3548
3549	if (params->freqs) {
3550		struct nl_msg *freqs = nlmsg_alloc();
3551		if (freqs == NULL)
3552			goto fail;
3553		for (i = 0; params->freqs[i]; i++) {
3554			wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
3555				   "MHz", params->freqs[i]);
3556			if (nla_put_u32(freqs, i + 1, params->freqs[i]) < 0) {
3557				nlmsg_free(freqs);
3558				goto fail;
3559			}
3560		}
3561		err = nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES,
3562				     freqs);
3563		nlmsg_free(freqs);
3564		if (err < 0)
3565			goto fail;
3566	}
3567
3568	os_free(drv->filter_ssids);
3569	drv->filter_ssids = params->filter_ssids;
3570	params->filter_ssids = NULL;
3571	drv->num_filter_ssids = params->num_filter_ssids;
3572
3573	return msg;
3574
3575fail:
3576	nlmsg_free(msg);
3577	return NULL;
3578}
3579
3580
3581/**
3582 * wpa_driver_nl80211_scan - Request the driver to initiate scan
3583 * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3584 * @params: Scan parameters
3585 * Returns: 0 on success, -1 on failure
3586 */
3587static int wpa_driver_nl80211_scan(void *priv,
3588				   struct wpa_driver_scan_params *params)
3589{
3590	struct i802_bss *bss = priv;
3591	struct wpa_driver_nl80211_data *drv = bss->drv;
3592	int ret = -1, timeout;
3593	struct nl_msg *msg, *rates = NULL;
3594
3595	drv->scan_for_auth = 0;
3596
3597	msg = nl80211_scan_common(drv, NL80211_CMD_TRIGGER_SCAN, params);
3598	if (!msg)
3599		return -1;
3600
3601	if (params->p2p_probe) {
3602		wpa_printf(MSG_DEBUG, "nl80211: P2P probe - mask SuppRates");
3603
3604		rates = nlmsg_alloc();
3605		if (rates == NULL)
3606			goto nla_put_failure;
3607
3608		/*
3609		 * Remove 2.4 GHz rates 1, 2, 5.5, 11 Mbps from supported rates
3610		 * by masking out everything else apart from the OFDM rates 6,
3611		 * 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS rates. All 5 GHz
3612		 * rates are left enabled.
3613		 */
3614		NLA_PUT(rates, NL80211_BAND_2GHZ, 8,
3615			"\x0c\x12\x18\x24\x30\x48\x60\x6c");
3616		if (nla_put_nested(msg, NL80211_ATTR_SCAN_SUPP_RATES, rates) <
3617		    0)
3618			goto nla_put_failure;
3619
3620		NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
3621	}
3622
3623	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3624	msg = NULL;
3625	if (ret) {
3626		wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
3627			   "(%s)", ret, strerror(-ret));
3628#ifdef HOSTAPD
3629		if (is_ap_interface(drv->nlmode)) {
3630			/*
3631			 * mac80211 does not allow scan requests in AP mode, so
3632			 * try to do this in station mode.
3633			 */
3634			if (wpa_driver_nl80211_set_mode(
3635				    bss, NL80211_IFTYPE_STATION))
3636				goto nla_put_failure;
3637
3638			if (wpa_driver_nl80211_scan(drv, params)) {
3639				wpa_driver_nl80211_set_mode(bss, drv->nlmode);
3640				goto nla_put_failure;
3641			}
3642
3643			/* Restore AP mode when processing scan results */
3644			drv->ap_scan_as_station = drv->nlmode;
3645			ret = 0;
3646		} else
3647			goto nla_put_failure;
3648#else /* HOSTAPD */
3649		goto nla_put_failure;
3650#endif /* HOSTAPD */
3651	}
3652
3653	/* Not all drivers generate "scan completed" wireless event, so try to
3654	 * read results after a timeout. */
3655	timeout = 10;
3656	if (drv->scan_complete_events) {
3657		/*
3658		 * The driver seems to deliver events to notify when scan is
3659		 * complete, so use longer timeout to avoid race conditions
3660		 * with scanning and following association request.
3661		 */
3662		timeout = 30;
3663	}
3664	wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
3665		   "seconds", ret, timeout);
3666	eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3667	eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
3668			       drv, drv->ctx);
3669
3670nla_put_failure:
3671	nlmsg_free(msg);
3672	nlmsg_free(rates);
3673	return ret;
3674}
3675
3676
3677/**
3678 * wpa_driver_nl80211_sched_scan - Initiate a scheduled scan
3679 * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3680 * @params: Scan parameters
3681 * @interval: Interval between scan cycles in milliseconds
3682 * Returns: 0 on success, -1 on failure or if not supported
3683 */
3684static int wpa_driver_nl80211_sched_scan(void *priv,
3685					 struct wpa_driver_scan_params *params,
3686					 u32 interval)
3687{
3688	struct i802_bss *bss = priv;
3689	struct wpa_driver_nl80211_data *drv = bss->drv;
3690	int ret = -1;
3691	struct nl_msg *msg;
3692	struct nl_msg *match_set_ssid = NULL, *match_sets = NULL;
3693	struct nl_msg *match_set_rssi = NULL;
3694	size_t i;
3695
3696#ifdef ANDROID
3697	if (!drv->capa.sched_scan_supported)
3698		return android_pno_start(bss, params);
3699#endif /* ANDROID */
3700
3701	msg = nl80211_scan_common(drv, NL80211_CMD_START_SCHED_SCAN, params);
3702	if (!msg)
3703		goto nla_put_failure;
3704
3705	NLA_PUT_U32(msg, NL80211_ATTR_SCHED_SCAN_INTERVAL, interval);
3706
3707	if ((drv->num_filter_ssids &&
3708	    (int) drv->num_filter_ssids <= drv->capa.max_match_sets) ||
3709	    params->filter_rssi) {
3710		match_sets = nlmsg_alloc();
3711		if (match_sets == NULL)
3712			goto nla_put_failure;
3713
3714		for (i = 0; i < drv->num_filter_ssids; i++) {
3715			wpa_hexdump_ascii(MSG_MSGDUMP,
3716					  "nl80211: Sched scan filter SSID",
3717					  drv->filter_ssids[i].ssid,
3718					  drv->filter_ssids[i].ssid_len);
3719
3720			match_set_ssid = nlmsg_alloc();
3721			if (match_set_ssid == NULL)
3722				goto nla_put_failure;
3723			NLA_PUT(match_set_ssid,
3724				NL80211_ATTR_SCHED_SCAN_MATCH_SSID,
3725				drv->filter_ssids[i].ssid_len,
3726				drv->filter_ssids[i].ssid);
3727
3728			if (nla_put_nested(match_sets, i + 1, match_set_ssid) <
3729			    0)
3730				goto nla_put_failure;
3731		}
3732
3733		if (params->filter_rssi) {
3734			match_set_rssi = nlmsg_alloc();
3735			if (match_set_rssi == NULL)
3736				goto nla_put_failure;
3737			NLA_PUT_U32(match_set_rssi,
3738				    NL80211_SCHED_SCAN_MATCH_ATTR_RSSI,
3739				    params->filter_rssi);
3740			wpa_printf(MSG_MSGDUMP,
3741				   "nl80211: Sched scan RSSI filter %d dBm",
3742				   params->filter_rssi);
3743			if (nla_put_nested(match_sets, 0, match_set_rssi) < 0)
3744				goto nla_put_failure;
3745		}
3746
3747		if (nla_put_nested(msg, NL80211_ATTR_SCHED_SCAN_MATCH,
3748				   match_sets) < 0)
3749			goto nla_put_failure;
3750	}
3751
3752	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3753
3754	/* TODO: if we get an error here, we should fall back to normal scan */
3755
3756	msg = NULL;
3757	if (ret) {
3758		wpa_printf(MSG_DEBUG, "nl80211: Sched scan start failed: "
3759			   "ret=%d (%s)", ret, strerror(-ret));
3760		goto nla_put_failure;
3761	}
3762
3763	wpa_printf(MSG_DEBUG, "nl80211: Sched scan requested (ret=%d) - "
3764		   "scan interval %d msec", ret, interval);
3765
3766nla_put_failure:
3767	nlmsg_free(match_set_ssid);
3768	nlmsg_free(match_sets);
3769	nlmsg_free(match_set_rssi);
3770	nlmsg_free(msg);
3771	return ret;
3772}
3773
3774
3775/**
3776 * wpa_driver_nl80211_stop_sched_scan - Stop a scheduled scan
3777 * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3778 * Returns: 0 on success, -1 on failure or if not supported
3779 */
3780static int wpa_driver_nl80211_stop_sched_scan(void *priv)
3781{
3782	struct i802_bss *bss = priv;
3783	struct wpa_driver_nl80211_data *drv = bss->drv;
3784	int ret = 0;
3785	struct nl_msg *msg;
3786
3787#ifdef ANDROID
3788	if (!drv->capa.sched_scan_supported)
3789		return android_pno_stop(bss);
3790#endif /* ANDROID */
3791
3792	msg = nlmsg_alloc();
3793	if (!msg)
3794		return -1;
3795
3796	nl80211_cmd(drv, msg, 0, NL80211_CMD_STOP_SCHED_SCAN);
3797
3798	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3799
3800	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3801	msg = NULL;
3802	if (ret) {
3803		wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop failed: "
3804			   "ret=%d (%s)", ret, strerror(-ret));
3805		goto nla_put_failure;
3806	}
3807
3808	wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop sent (ret=%d)", ret);
3809
3810nla_put_failure:
3811	nlmsg_free(msg);
3812	return ret;
3813}
3814
3815
3816static const u8 * nl80211_get_ie(const u8 *ies, size_t ies_len, u8 ie)
3817{
3818	const u8 *end, *pos;
3819
3820	if (ies == NULL)
3821		return NULL;
3822
3823	pos = ies;
3824	end = ies + ies_len;
3825
3826	while (pos + 1 < end) {
3827		if (pos + 2 + pos[1] > end)
3828			break;
3829		if (pos[0] == ie)
3830			return pos;
3831		pos += 2 + pos[1];
3832	}
3833
3834	return NULL;
3835}
3836
3837
3838static int nl80211_scan_filtered(struct wpa_driver_nl80211_data *drv,
3839				 const u8 *ie, size_t ie_len)
3840{
3841	const u8 *ssid;
3842	size_t i;
3843
3844	if (drv->filter_ssids == NULL)
3845		return 0;
3846
3847	ssid = nl80211_get_ie(ie, ie_len, WLAN_EID_SSID);
3848	if (ssid == NULL)
3849		return 1;
3850
3851	for (i = 0; i < drv->num_filter_ssids; i++) {
3852		if (ssid[1] == drv->filter_ssids[i].ssid_len &&
3853		    os_memcmp(ssid + 2, drv->filter_ssids[i].ssid, ssid[1]) ==
3854		    0)
3855			return 0;
3856	}
3857
3858	return 1;
3859}
3860
3861
3862static int bss_info_handler(struct nl_msg *msg, void *arg)
3863{
3864	struct nlattr *tb[NL80211_ATTR_MAX + 1];
3865	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3866	struct nlattr *bss[NL80211_BSS_MAX + 1];
3867	static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
3868		[NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
3869		[NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
3870		[NL80211_BSS_TSF] = { .type = NLA_U64 },
3871		[NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
3872		[NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
3873		[NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
3874		[NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
3875		[NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
3876		[NL80211_BSS_STATUS] = { .type = NLA_U32 },
3877		[NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
3878		[NL80211_BSS_BEACON_IES] = { .type = NLA_UNSPEC },
3879	};
3880	struct nl80211_bss_info_arg *_arg = arg;
3881	struct wpa_scan_results *res = _arg->res;
3882	struct wpa_scan_res **tmp;
3883	struct wpa_scan_res *r;
3884	const u8 *ie, *beacon_ie;
3885	size_t ie_len, beacon_ie_len;
3886	u8 *pos;
3887	size_t i;
3888
3889	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3890		  genlmsg_attrlen(gnlh, 0), NULL);
3891	if (!tb[NL80211_ATTR_BSS])
3892		return NL_SKIP;
3893	if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
3894			     bss_policy))
3895		return NL_SKIP;
3896	if (bss[NL80211_BSS_STATUS]) {
3897		enum nl80211_bss_status status;
3898		status = nla_get_u32(bss[NL80211_BSS_STATUS]);
3899		if (status == NL80211_BSS_STATUS_ASSOCIATED &&
3900		    bss[NL80211_BSS_FREQUENCY]) {
3901			_arg->assoc_freq =
3902				nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
3903			wpa_printf(MSG_DEBUG, "nl80211: Associated on %u MHz",
3904				   _arg->assoc_freq);
3905		}
3906		if (status == NL80211_BSS_STATUS_ASSOCIATED &&
3907		    bss[NL80211_BSS_BSSID]) {
3908			os_memcpy(_arg->assoc_bssid,
3909				  nla_data(bss[NL80211_BSS_BSSID]), ETH_ALEN);
3910			wpa_printf(MSG_DEBUG, "nl80211: Associated with "
3911				   MACSTR, MAC2STR(_arg->assoc_bssid));
3912		}
3913	}
3914	if (!res)
3915		return NL_SKIP;
3916	if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
3917		ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
3918		ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
3919	} else {
3920		ie = NULL;
3921		ie_len = 0;
3922	}
3923	if (bss[NL80211_BSS_BEACON_IES]) {
3924		beacon_ie = nla_data(bss[NL80211_BSS_BEACON_IES]);
3925		beacon_ie_len = nla_len(bss[NL80211_BSS_BEACON_IES]);
3926	} else {
3927		beacon_ie = NULL;
3928		beacon_ie_len = 0;
3929	}
3930
3931	if (nl80211_scan_filtered(_arg->drv, ie ? ie : beacon_ie,
3932				  ie ? ie_len : beacon_ie_len))
3933		return NL_SKIP;
3934
3935	r = os_zalloc(sizeof(*r) + ie_len + beacon_ie_len);
3936	if (r == NULL)
3937		return NL_SKIP;
3938	if (bss[NL80211_BSS_BSSID])
3939		os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
3940			  ETH_ALEN);
3941	if (bss[NL80211_BSS_FREQUENCY])
3942		r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
3943	if (bss[NL80211_BSS_BEACON_INTERVAL])
3944		r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
3945	if (bss[NL80211_BSS_CAPABILITY])
3946		r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
3947	r->flags |= WPA_SCAN_NOISE_INVALID;
3948	if (bss[NL80211_BSS_SIGNAL_MBM]) {
3949		r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
3950		r->level /= 100; /* mBm to dBm */
3951		r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
3952	} else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
3953		r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
3954		r->flags |= WPA_SCAN_QUAL_INVALID;
3955	} else
3956		r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
3957	if (bss[NL80211_BSS_TSF])
3958		r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
3959	if (bss[NL80211_BSS_SEEN_MS_AGO])
3960		r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
3961	r->ie_len = ie_len;
3962	pos = (u8 *) (r + 1);
3963	if (ie) {
3964		os_memcpy(pos, ie, ie_len);
3965		pos += ie_len;
3966	}
3967	r->beacon_ie_len = beacon_ie_len;
3968	if (beacon_ie)
3969		os_memcpy(pos, beacon_ie, beacon_ie_len);
3970
3971	if (bss[NL80211_BSS_STATUS]) {
3972		enum nl80211_bss_status status;
3973		status = nla_get_u32(bss[NL80211_BSS_STATUS]);
3974		switch (status) {
3975		case NL80211_BSS_STATUS_AUTHENTICATED:
3976			r->flags |= WPA_SCAN_AUTHENTICATED;
3977			break;
3978		case NL80211_BSS_STATUS_ASSOCIATED:
3979			r->flags |= WPA_SCAN_ASSOCIATED;
3980			break;
3981		default:
3982			break;
3983		}
3984	}
3985
3986	/*
3987	 * cfg80211 maintains separate BSS table entries for APs if the same
3988	 * BSSID,SSID pair is seen on multiple channels. wpa_supplicant does
3989	 * not use frequency as a separate key in the BSS table, so filter out
3990	 * duplicated entries. Prefer associated BSS entry in such a case in
3991	 * order to get the correct frequency into the BSS table.
3992	 */
3993	for (i = 0; i < res->num; i++) {
3994		const u8 *s1, *s2;
3995		if (os_memcmp(res->res[i]->bssid, r->bssid, ETH_ALEN) != 0)
3996			continue;
3997
3998		s1 = nl80211_get_ie((u8 *) (res->res[i] + 1),
3999				    res->res[i]->ie_len, WLAN_EID_SSID);
4000		s2 = nl80211_get_ie((u8 *) (r + 1), r->ie_len, WLAN_EID_SSID);
4001		if (s1 == NULL || s2 == NULL || s1[1] != s2[1] ||
4002		    os_memcmp(s1, s2, 2 + s1[1]) != 0)
4003			continue;
4004
4005		/* Same BSSID,SSID was already included in scan results */
4006		wpa_printf(MSG_DEBUG, "nl80211: Remove duplicated scan result "
4007			   "for " MACSTR, MAC2STR(r->bssid));
4008
4009		if ((r->flags & WPA_SCAN_ASSOCIATED) &&
4010		    !(res->res[i]->flags & WPA_SCAN_ASSOCIATED)) {
4011			os_free(res->res[i]);
4012			res->res[i] = r;
4013		} else
4014			os_free(r);
4015		return NL_SKIP;
4016	}
4017
4018	tmp = os_realloc_array(res->res, res->num + 1,
4019			       sizeof(struct wpa_scan_res *));
4020	if (tmp == NULL) {
4021		os_free(r);
4022		return NL_SKIP;
4023	}
4024	tmp[res->num++] = r;
4025	res->res = tmp;
4026
4027	return NL_SKIP;
4028}
4029
4030
4031static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
4032				 const u8 *addr)
4033{
4034	if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
4035		wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
4036			   "mismatch (" MACSTR ")", MAC2STR(addr));
4037		wpa_driver_nl80211_mlme(drv, addr,
4038					NL80211_CMD_DEAUTHENTICATE,
4039					WLAN_REASON_PREV_AUTH_NOT_VALID, 1);
4040	}
4041}
4042
4043
4044static void wpa_driver_nl80211_check_bss_status(
4045	struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
4046{
4047	size_t i;
4048
4049	for (i = 0; i < res->num; i++) {
4050		struct wpa_scan_res *r = res->res[i];
4051		if (r->flags & WPA_SCAN_AUTHENTICATED) {
4052			wpa_printf(MSG_DEBUG, "nl80211: Scan results "
4053				   "indicates BSS status with " MACSTR
4054				   " as authenticated",
4055				   MAC2STR(r->bssid));
4056			if (is_sta_interface(drv->nlmode) &&
4057			    os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
4058			    os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
4059			    0) {
4060				wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
4061					   " in local state (auth=" MACSTR
4062					   " assoc=" MACSTR ")",
4063					   MAC2STR(drv->auth_bssid),
4064					   MAC2STR(drv->bssid));
4065				clear_state_mismatch(drv, r->bssid);
4066			}
4067		}
4068
4069		if (r->flags & WPA_SCAN_ASSOCIATED) {
4070			wpa_printf(MSG_DEBUG, "nl80211: Scan results "
4071				   "indicate BSS status with " MACSTR
4072				   " as associated",
4073				   MAC2STR(r->bssid));
4074			if (is_sta_interface(drv->nlmode) &&
4075			    !drv->associated) {
4076				wpa_printf(MSG_DEBUG, "nl80211: Local state "
4077					   "(not associated) does not match "
4078					   "with BSS state");
4079				clear_state_mismatch(drv, r->bssid);
4080			} else if (is_sta_interface(drv->nlmode) &&
4081				   os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
4082				   0) {
4083				wpa_printf(MSG_DEBUG, "nl80211: Local state "
4084					   "(associated with " MACSTR ") does "
4085					   "not match with BSS state",
4086					   MAC2STR(drv->bssid));
4087				clear_state_mismatch(drv, r->bssid);
4088				clear_state_mismatch(drv, drv->bssid);
4089			}
4090		}
4091	}
4092}
4093
4094
4095static struct wpa_scan_results *
4096nl80211_get_scan_results(struct wpa_driver_nl80211_data *drv)
4097{
4098	struct nl_msg *msg;
4099	struct wpa_scan_results *res;
4100	int ret;
4101	struct nl80211_bss_info_arg arg;
4102
4103	res = os_zalloc(sizeof(*res));
4104	if (res == NULL)
4105		return NULL;
4106	msg = nlmsg_alloc();
4107	if (!msg)
4108		goto nla_put_failure;
4109
4110	nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
4111	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4112
4113	arg.drv = drv;
4114	arg.res = res;
4115	ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
4116	msg = NULL;
4117	if (ret == 0) {
4118		wpa_printf(MSG_DEBUG, "nl80211: Received scan results (%lu "
4119			   "BSSes)", (unsigned long) res->num);
4120		nl80211_get_noise_for_scan_results(drv, res);
4121		return res;
4122	}
4123	wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
4124		   "(%s)", ret, strerror(-ret));
4125nla_put_failure:
4126	nlmsg_free(msg);
4127	wpa_scan_results_free(res);
4128	return NULL;
4129}
4130
4131
4132/**
4133 * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
4134 * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
4135 * Returns: Scan results on success, -1 on failure
4136 */
4137static struct wpa_scan_results *
4138wpa_driver_nl80211_get_scan_results(void *priv)
4139{
4140	struct i802_bss *bss = priv;
4141	struct wpa_driver_nl80211_data *drv = bss->drv;
4142	struct wpa_scan_results *res;
4143
4144	res = nl80211_get_scan_results(drv);
4145	if (res)
4146		wpa_driver_nl80211_check_bss_status(drv, res);
4147	return res;
4148}
4149
4150
4151static void nl80211_dump_scan(struct wpa_driver_nl80211_data *drv)
4152{
4153	struct wpa_scan_results *res;
4154	size_t i;
4155
4156	res = nl80211_get_scan_results(drv);
4157	if (res == NULL) {
4158		wpa_printf(MSG_DEBUG, "nl80211: Failed to get scan results");
4159		return;
4160	}
4161
4162	wpa_printf(MSG_DEBUG, "nl80211: Scan result dump");
4163	for (i = 0; i < res->num; i++) {
4164		struct wpa_scan_res *r = res->res[i];
4165		wpa_printf(MSG_DEBUG, "nl80211: %d/%d " MACSTR "%s%s",
4166			   (int) i, (int) res->num, MAC2STR(r->bssid),
4167			   r->flags & WPA_SCAN_AUTHENTICATED ? " [auth]" : "",
4168			   r->flags & WPA_SCAN_ASSOCIATED ? " [assoc]" : "");
4169	}
4170
4171	wpa_scan_results_free(res);
4172}
4173
4174
4175static int wpa_driver_nl80211_set_key(const char *ifname, void *priv,
4176				      enum wpa_alg alg, const u8 *addr,
4177				      int key_idx, int set_tx,
4178				      const u8 *seq, size_t seq_len,
4179				      const u8 *key, size_t key_len)
4180{
4181	struct i802_bss *bss = priv;
4182	struct wpa_driver_nl80211_data *drv = bss->drv;
4183	int ifindex = if_nametoindex(ifname);
4184	struct nl_msg *msg;
4185	int ret;
4186
4187	wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
4188		   "set_tx=%d seq_len=%lu key_len=%lu",
4189		   __func__, ifindex, alg, addr, key_idx, set_tx,
4190		   (unsigned long) seq_len, (unsigned long) key_len);
4191#ifdef CONFIG_TDLS
4192	if (key_idx == -1)
4193		key_idx = 0;
4194#endif /* CONFIG_TDLS */
4195
4196	msg = nlmsg_alloc();
4197	if (!msg)
4198		return -ENOMEM;
4199
4200	if (alg == WPA_ALG_NONE) {
4201		nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_KEY);
4202	} else {
4203		nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_KEY);
4204		NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
4205		switch (alg) {
4206		case WPA_ALG_WEP:
4207			if (key_len == 5)
4208				NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4209					    WLAN_CIPHER_SUITE_WEP40);
4210			else
4211				NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4212					    WLAN_CIPHER_SUITE_WEP104);
4213			break;
4214		case WPA_ALG_TKIP:
4215			NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4216				    WLAN_CIPHER_SUITE_TKIP);
4217			break;
4218		case WPA_ALG_CCMP:
4219			NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4220				    WLAN_CIPHER_SUITE_CCMP);
4221			break;
4222		case WPA_ALG_GCMP:
4223			NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4224				    WLAN_CIPHER_SUITE_GCMP);
4225			break;
4226		case WPA_ALG_IGTK:
4227			NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4228				    WLAN_CIPHER_SUITE_AES_CMAC);
4229			break;
4230		default:
4231			wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4232				   "algorithm %d", __func__, alg);
4233			nlmsg_free(msg);
4234			return -1;
4235		}
4236	}
4237
4238	if (seq && seq_len)
4239		NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
4240
4241	if (addr && !is_broadcast_ether_addr(addr)) {
4242		wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
4243		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4244
4245		if (alg != WPA_ALG_WEP && key_idx && !set_tx) {
4246			wpa_printf(MSG_DEBUG, "   RSN IBSS RX GTK");
4247			NLA_PUT_U32(msg, NL80211_ATTR_KEY_TYPE,
4248				    NL80211_KEYTYPE_GROUP);
4249		}
4250	} else if (addr && is_broadcast_ether_addr(addr)) {
4251		struct nl_msg *types;
4252		int err;
4253		wpa_printf(MSG_DEBUG, "   broadcast key");
4254		types = nlmsg_alloc();
4255		if (!types)
4256			goto nla_put_failure;
4257		NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4258		err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4259				     types);
4260		nlmsg_free(types);
4261		if (err)
4262			goto nla_put_failure;
4263	}
4264	NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4265	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4266
4267	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4268	if ((ret == -ENOENT || ret == -ENOLINK) && alg == WPA_ALG_NONE)
4269		ret = 0;
4270	if (ret)
4271		wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
4272			   ret, strerror(-ret));
4273
4274	/*
4275	 * If we failed or don't need to set the default TX key (below),
4276	 * we're done here.
4277	 */
4278	if (ret || !set_tx || alg == WPA_ALG_NONE)
4279		return ret;
4280	if (is_ap_interface(drv->nlmode) && addr &&
4281	    !is_broadcast_ether_addr(addr))
4282		return ret;
4283
4284	msg = nlmsg_alloc();
4285	if (!msg)
4286		return -ENOMEM;
4287
4288	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_KEY);
4289	NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4290	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4291	if (alg == WPA_ALG_IGTK)
4292		NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
4293	else
4294		NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
4295	if (addr && is_broadcast_ether_addr(addr)) {
4296		struct nl_msg *types;
4297		int err;
4298		types = nlmsg_alloc();
4299		if (!types)
4300			goto nla_put_failure;
4301		NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4302		err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4303				     types);
4304		nlmsg_free(types);
4305		if (err)
4306			goto nla_put_failure;
4307	} else if (addr) {
4308		struct nl_msg *types;
4309		int err;
4310		types = nlmsg_alloc();
4311		if (!types)
4312			goto nla_put_failure;
4313		NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_UNICAST);
4314		err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4315				     types);
4316		nlmsg_free(types);
4317		if (err)
4318			goto nla_put_failure;
4319	}
4320
4321	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4322	if (ret == -ENOENT)
4323		ret = 0;
4324	if (ret)
4325		wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
4326			   "err=%d %s)", ret, strerror(-ret));
4327	return ret;
4328
4329nla_put_failure:
4330	nlmsg_free(msg);
4331	return -ENOBUFS;
4332}
4333
4334
4335static int nl_add_key(struct nl_msg *msg, enum wpa_alg alg,
4336		      int key_idx, int defkey,
4337		      const u8 *seq, size_t seq_len,
4338		      const u8 *key, size_t key_len)
4339{
4340	struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
4341	if (!key_attr)
4342		return -1;
4343
4344	if (defkey && alg == WPA_ALG_IGTK)
4345		NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
4346	else if (defkey)
4347		NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4348
4349	NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
4350
4351	switch (alg) {
4352	case WPA_ALG_WEP:
4353		if (key_len == 5)
4354			NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4355				    WLAN_CIPHER_SUITE_WEP40);
4356		else
4357			NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4358				    WLAN_CIPHER_SUITE_WEP104);
4359		break;
4360	case WPA_ALG_TKIP:
4361		NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_TKIP);
4362		break;
4363	case WPA_ALG_CCMP:
4364		NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_CCMP);
4365		break;
4366	case WPA_ALG_GCMP:
4367		NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_GCMP);
4368		break;
4369	case WPA_ALG_IGTK:
4370		NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4371			    WLAN_CIPHER_SUITE_AES_CMAC);
4372		break;
4373	default:
4374		wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4375			   "algorithm %d", __func__, alg);
4376		return -1;
4377	}
4378
4379	if (seq && seq_len)
4380		NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
4381
4382	NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
4383
4384	nla_nest_end(msg, key_attr);
4385
4386	return 0;
4387 nla_put_failure:
4388	return -1;
4389}
4390
4391
4392static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
4393				 struct nl_msg *msg)
4394{
4395	int i, privacy = 0;
4396	struct nlattr *nl_keys, *nl_key;
4397
4398	for (i = 0; i < 4; i++) {
4399		if (!params->wep_key[i])
4400			continue;
4401		privacy = 1;
4402		break;
4403	}
4404	if (params->wps == WPS_MODE_PRIVACY)
4405		privacy = 1;
4406	if (params->pairwise_suite &&
4407	    params->pairwise_suite != WPA_CIPHER_NONE)
4408		privacy = 1;
4409
4410	if (!privacy)
4411		return 0;
4412
4413	NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
4414
4415	nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
4416	if (!nl_keys)
4417		goto nla_put_failure;
4418
4419	for (i = 0; i < 4; i++) {
4420		if (!params->wep_key[i])
4421			continue;
4422
4423		nl_key = nla_nest_start(msg, i);
4424		if (!nl_key)
4425			goto nla_put_failure;
4426
4427		NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
4428			params->wep_key[i]);
4429		if (params->wep_key_len[i] == 5)
4430			NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4431				    WLAN_CIPHER_SUITE_WEP40);
4432		else
4433			NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4434				    WLAN_CIPHER_SUITE_WEP104);
4435
4436		NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
4437
4438		if (i == params->wep_tx_keyidx)
4439			NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4440
4441		nla_nest_end(msg, nl_key);
4442	}
4443	nla_nest_end(msg, nl_keys);
4444
4445	return 0;
4446
4447nla_put_failure:
4448	return -ENOBUFS;
4449}
4450
4451
4452static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
4453				   const u8 *addr, int cmd, u16 reason_code,
4454				   int local_state_change)
4455{
4456	int ret = -1;
4457	struct nl_msg *msg;
4458
4459	msg = nlmsg_alloc();
4460	if (!msg)
4461		return -1;
4462
4463	nl80211_cmd(drv, msg, 0, cmd);
4464
4465	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4466	NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
4467	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4468	if (local_state_change)
4469		NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4470
4471	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4472	msg = NULL;
4473	if (ret) {
4474		wpa_dbg(drv->ctx, MSG_DEBUG,
4475			"nl80211: MLME command failed: reason=%u ret=%d (%s)",
4476			reason_code, ret, strerror(-ret));
4477		goto nla_put_failure;
4478	}
4479	ret = 0;
4480
4481nla_put_failure:
4482	nlmsg_free(msg);
4483	return ret;
4484}
4485
4486
4487static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
4488					 const u8 *addr, int reason_code)
4489{
4490	wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
4491		   __func__, MAC2STR(addr), reason_code);
4492	drv->associated = 0;
4493	return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISCONNECT,
4494				       reason_code, 0);
4495}
4496
4497
4498static int wpa_driver_nl80211_deauthenticate(void *priv, const u8 *addr,
4499					     int reason_code)
4500{
4501	struct i802_bss *bss = priv;
4502	struct wpa_driver_nl80211_data *drv = bss->drv;
4503	if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
4504		return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
4505	wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
4506		   __func__, MAC2STR(addr), reason_code);
4507	drv->associated = 0;
4508	if (drv->nlmode == NL80211_IFTYPE_ADHOC)
4509		return nl80211_leave_ibss(drv);
4510	return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
4511				       reason_code, 0);
4512}
4513
4514
4515static int wpa_driver_nl80211_disassociate(void *priv, const u8 *addr,
4516					   int reason_code)
4517{
4518	struct i802_bss *bss = priv;
4519	struct wpa_driver_nl80211_data *drv = bss->drv;
4520	if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
4521		return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
4522	wpa_printf(MSG_DEBUG, "%s", __func__);
4523	drv->associated = 0;
4524	return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISASSOCIATE,
4525				       reason_code, 0);
4526}
4527
4528
4529static void nl80211_copy_auth_params(struct wpa_driver_nl80211_data *drv,
4530				     struct wpa_driver_auth_params *params)
4531{
4532	int i;
4533
4534	drv->auth_freq = params->freq;
4535	drv->auth_alg = params->auth_alg;
4536	drv->auth_wep_tx_keyidx = params->wep_tx_keyidx;
4537	drv->auth_local_state_change = params->local_state_change;
4538	drv->auth_p2p = params->p2p;
4539
4540	if (params->bssid)
4541		os_memcpy(drv->auth_bssid_, params->bssid, ETH_ALEN);
4542	else
4543		os_memset(drv->auth_bssid_, 0, ETH_ALEN);
4544
4545	if (params->ssid) {
4546		os_memcpy(drv->auth_ssid, params->ssid, params->ssid_len);
4547		drv->auth_ssid_len = params->ssid_len;
4548	} else
4549		drv->auth_ssid_len = 0;
4550
4551
4552	os_free(drv->auth_ie);
4553	drv->auth_ie = NULL;
4554	drv->auth_ie_len = 0;
4555	if (params->ie) {
4556		drv->auth_ie = os_malloc(params->ie_len);
4557		if (drv->auth_ie) {
4558			os_memcpy(drv->auth_ie, params->ie, params->ie_len);
4559			drv->auth_ie_len = params->ie_len;
4560		}
4561	}
4562
4563	for (i = 0; i < 4; i++) {
4564		if (params->wep_key[i] && params->wep_key_len[i] &&
4565		    params->wep_key_len[i] <= 16) {
4566			os_memcpy(drv->auth_wep_key[i], params->wep_key[i],
4567				  params->wep_key_len[i]);
4568			drv->auth_wep_key_len[i] = params->wep_key_len[i];
4569		} else
4570			drv->auth_wep_key_len[i] = 0;
4571	}
4572}
4573
4574
4575static int wpa_driver_nl80211_authenticate(
4576	void *priv, struct wpa_driver_auth_params *params)
4577{
4578	struct i802_bss *bss = priv;
4579	struct wpa_driver_nl80211_data *drv = bss->drv;
4580	int ret = -1, i;
4581	struct nl_msg *msg;
4582	enum nl80211_auth_type type;
4583	enum nl80211_iftype nlmode;
4584	int count = 0;
4585	int is_retry;
4586
4587	is_retry = drv->retry_auth;
4588	drv->retry_auth = 0;
4589
4590	drv->associated = 0;
4591	os_memset(drv->auth_bssid, 0, ETH_ALEN);
4592	/* FIX: IBSS mode */
4593	nlmode = params->p2p ?
4594		NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
4595	if (drv->nlmode != nlmode &&
4596	    wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
4597		return -1;
4598
4599retry:
4600	msg = nlmsg_alloc();
4601	if (!msg)
4602		return -1;
4603
4604	wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
4605		   drv->ifindex);
4606
4607	nl80211_cmd(drv, msg, 0, NL80211_CMD_AUTHENTICATE);
4608
4609	for (i = 0; i < 4; i++) {
4610		if (!params->wep_key[i])
4611			continue;
4612		wpa_driver_nl80211_set_key(bss->ifname, priv, WPA_ALG_WEP,
4613					   NULL, i,
4614					   i == params->wep_tx_keyidx, NULL, 0,
4615					   params->wep_key[i],
4616					   params->wep_key_len[i]);
4617		if (params->wep_tx_keyidx != i)
4618			continue;
4619		if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
4620			       params->wep_key[i], params->wep_key_len[i])) {
4621			nlmsg_free(msg);
4622			return -1;
4623		}
4624	}
4625
4626	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4627	if (params->bssid) {
4628		wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4629			   MAC2STR(params->bssid));
4630		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4631	}
4632	if (params->freq) {
4633		wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4634		NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4635	}
4636	if (params->ssid) {
4637		wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4638				  params->ssid, params->ssid_len);
4639		NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4640			params->ssid);
4641	}
4642	wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
4643	if (params->ie)
4644		NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
4645	if (params->auth_alg & WPA_AUTH_ALG_OPEN)
4646		type = NL80211_AUTHTYPE_OPEN_SYSTEM;
4647	else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
4648		type = NL80211_AUTHTYPE_SHARED_KEY;
4649	else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
4650		type = NL80211_AUTHTYPE_NETWORK_EAP;
4651	else if (params->auth_alg & WPA_AUTH_ALG_FT)
4652		type = NL80211_AUTHTYPE_FT;
4653	else
4654		goto nla_put_failure;
4655	wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
4656	NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
4657	if (params->local_state_change) {
4658		wpa_printf(MSG_DEBUG, "  * Local state change only");
4659		NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4660	}
4661
4662	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4663	msg = NULL;
4664	if (ret) {
4665		wpa_dbg(drv->ctx, MSG_DEBUG,
4666			"nl80211: MLME command failed (auth): ret=%d (%s)",
4667			ret, strerror(-ret));
4668		count++;
4669		if (ret == -EALREADY && count == 1 && params->bssid &&
4670		    !params->local_state_change) {
4671			/*
4672			 * mac80211 does not currently accept new
4673			 * authentication if we are already authenticated. As a
4674			 * workaround, force deauthentication and try again.
4675			 */
4676			wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
4677				   "after forced deauthentication");
4678			wpa_driver_nl80211_deauthenticate(
4679				bss, params->bssid,
4680				WLAN_REASON_PREV_AUTH_NOT_VALID);
4681			nlmsg_free(msg);
4682			goto retry;
4683		}
4684
4685		if (ret == -ENOENT && params->freq && !is_retry) {
4686			/*
4687			 * cfg80211 has likely expired the BSS entry even
4688			 * though it was previously available in our internal
4689			 * BSS table. To recover quickly, start a single
4690			 * channel scan on the specified channel.
4691			 */
4692			struct wpa_driver_scan_params scan;
4693			int freqs[2];
4694
4695			os_memset(&scan, 0, sizeof(scan));
4696			scan.num_ssids = 1;
4697			if (params->ssid) {
4698				scan.ssids[0].ssid = params->ssid;
4699				scan.ssids[0].ssid_len = params->ssid_len;
4700			}
4701			freqs[0] = params->freq;
4702			freqs[1] = 0;
4703			scan.freqs = freqs;
4704			wpa_printf(MSG_DEBUG, "nl80211: Trigger single "
4705				   "channel scan to refresh cfg80211 BSS "
4706				   "entry");
4707			ret = wpa_driver_nl80211_scan(bss, &scan);
4708			if (ret == 0) {
4709				nl80211_copy_auth_params(drv, params);
4710				drv->scan_for_auth = 1;
4711			}
4712		} else if (is_retry) {
4713			/*
4714			 * Need to indicate this with an event since the return
4715			 * value from the retry is not delivered to core code.
4716			 */
4717			union wpa_event_data event;
4718			wpa_printf(MSG_DEBUG, "nl80211: Authentication retry "
4719				   "failed");
4720			os_memset(&event, 0, sizeof(event));
4721			os_memcpy(event.timeout_event.addr, drv->auth_bssid_,
4722				  ETH_ALEN);
4723			wpa_supplicant_event(drv->ctx, EVENT_AUTH_TIMED_OUT,
4724					     &event);
4725		}
4726
4727		goto nla_put_failure;
4728	}
4729	ret = 0;
4730	wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
4731		   "successfully");
4732
4733nla_put_failure:
4734	nlmsg_free(msg);
4735	return ret;
4736}
4737
4738
4739static int wpa_driver_nl80211_authenticate_retry(
4740	struct wpa_driver_nl80211_data *drv)
4741{
4742	struct wpa_driver_auth_params params;
4743	struct i802_bss *bss = &drv->first_bss;
4744	int i;
4745
4746	wpa_printf(MSG_DEBUG, "nl80211: Try to authenticate again");
4747
4748	os_memset(&params, 0, sizeof(params));
4749	params.freq = drv->auth_freq;
4750	params.auth_alg = drv->auth_alg;
4751	params.wep_tx_keyidx = drv->auth_wep_tx_keyidx;
4752	params.local_state_change = drv->auth_local_state_change;
4753	params.p2p = drv->auth_p2p;
4754
4755	if (!is_zero_ether_addr(drv->auth_bssid_))
4756		params.bssid = drv->auth_bssid_;
4757
4758	if (drv->auth_ssid_len) {
4759		params.ssid = drv->auth_ssid;
4760		params.ssid_len = drv->auth_ssid_len;
4761	}
4762
4763	params.ie = drv->auth_ie;
4764	params.ie_len = drv->auth_ie_len;
4765
4766	for (i = 0; i < 4; i++) {
4767		if (drv->auth_wep_key_len[i]) {
4768			params.wep_key[i] = drv->auth_wep_key[i];
4769			params.wep_key_len[i] = drv->auth_wep_key_len[i];
4770		}
4771	}
4772
4773	drv->retry_auth = 1;
4774	return wpa_driver_nl80211_authenticate(bss, &params);
4775}
4776
4777
4778struct phy_info_arg {
4779	u16 *num_modes;
4780	struct hostapd_hw_modes *modes;
4781};
4782
4783static int phy_info_handler(struct nl_msg *msg, void *arg)
4784{
4785	struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
4786	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
4787	struct phy_info_arg *phy_info = arg;
4788
4789	struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
4790
4791	struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
4792	static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
4793		[NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
4794		[NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
4795		[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
4796		[NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
4797		[NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
4798		[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
4799	};
4800
4801	struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
4802	static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
4803		[NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
4804		[NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
4805	};
4806
4807	struct nlattr *nl_band;
4808	struct nlattr *nl_freq;
4809	struct nlattr *nl_rate;
4810	int rem_band, rem_freq, rem_rate;
4811	struct hostapd_hw_modes *mode;
4812	int idx, mode_is_set;
4813
4814	nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
4815		  genlmsg_attrlen(gnlh, 0), NULL);
4816
4817	if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
4818		return NL_SKIP;
4819
4820	nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
4821		mode = os_realloc_array(phy_info->modes,
4822					*phy_info->num_modes + 1,
4823					sizeof(*mode));
4824		if (!mode)
4825			return NL_SKIP;
4826		phy_info->modes = mode;
4827
4828		mode_is_set = 0;
4829
4830		mode = &phy_info->modes[*(phy_info->num_modes)];
4831		memset(mode, 0, sizeof(*mode));
4832		mode->flags = HOSTAPD_MODE_FLAG_HT_INFO_KNOWN;
4833		*(phy_info->num_modes) += 1;
4834
4835		nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
4836			  nla_len(nl_band), NULL);
4837
4838		if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
4839			mode->ht_capab = nla_get_u16(
4840				tb_band[NL80211_BAND_ATTR_HT_CAPA]);
4841		}
4842
4843		if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) {
4844			mode->a_mpdu_params |= nla_get_u8(
4845				tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) &
4846				0x03;
4847		}
4848
4849		if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) {
4850			mode->a_mpdu_params |= nla_get_u8(
4851				tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) <<
4852				2;
4853		}
4854
4855		if (tb_band[NL80211_BAND_ATTR_HT_MCS_SET] &&
4856		    nla_len(tb_band[NL80211_BAND_ATTR_HT_MCS_SET])) {
4857			u8 *mcs;
4858			mcs = nla_data(tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
4859			os_memcpy(mode->mcs_set, mcs, 16);
4860		}
4861
4862		if (tb_band[NL80211_BAND_ATTR_VHT_CAPA]) {
4863			mode->vht_capab = nla_get_u32(
4864				tb_band[NL80211_BAND_ATTR_VHT_CAPA]);
4865		}
4866
4867		if (tb_band[NL80211_BAND_ATTR_VHT_MCS_SET] &&
4868		    nla_len(tb_band[NL80211_BAND_ATTR_VHT_MCS_SET])) {
4869			u8 *mcs;
4870			mcs = nla_data(tb_band[NL80211_BAND_ATTR_VHT_MCS_SET]);
4871			os_memcpy(mode->vht_mcs_set, mcs, 8);
4872		}
4873
4874		nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
4875			nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
4876				  nla_len(nl_freq), freq_policy);
4877			if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
4878				continue;
4879			mode->num_channels++;
4880		}
4881
4882		mode->channels = os_calloc(mode->num_channels,
4883					   sizeof(struct hostapd_channel_data));
4884		if (!mode->channels)
4885			return NL_SKIP;
4886
4887		idx = 0;
4888
4889		nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
4890			nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
4891				  nla_len(nl_freq), freq_policy);
4892			if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
4893				continue;
4894
4895			mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
4896			mode->channels[idx].flag = 0;
4897
4898			if (!mode_is_set) {
4899				/* crude heuristic */
4900				if (mode->channels[idx].freq < 4000)
4901					mode->mode = HOSTAPD_MODE_IEEE80211B;
4902				else
4903					mode->mode = HOSTAPD_MODE_IEEE80211A;
4904				mode_is_set = 1;
4905			}
4906
4907			/* crude heuristic */
4908			if (mode->channels[idx].freq < 4000)
4909				if (mode->channels[idx].freq == 2484)
4910					mode->channels[idx].chan = 14;
4911				else
4912					mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
4913			else
4914				mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
4915
4916			if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
4917				mode->channels[idx].flag |=
4918					HOSTAPD_CHAN_DISABLED;
4919			if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
4920				mode->channels[idx].flag |=
4921					HOSTAPD_CHAN_PASSIVE_SCAN;
4922			if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
4923				mode->channels[idx].flag |=
4924					HOSTAPD_CHAN_NO_IBSS;
4925			if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
4926				mode->channels[idx].flag |=
4927					HOSTAPD_CHAN_RADAR;
4928
4929			if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
4930			    !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
4931				mode->channels[idx].max_tx_power =
4932					nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
4933
4934			idx++;
4935		}
4936
4937		nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
4938			nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
4939				  nla_len(nl_rate), rate_policy);
4940			if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
4941				continue;
4942			mode->num_rates++;
4943		}
4944
4945		mode->rates = os_calloc(mode->num_rates, sizeof(int));
4946		if (!mode->rates)
4947			return NL_SKIP;
4948
4949		idx = 0;
4950
4951		nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
4952			nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
4953				  nla_len(nl_rate), rate_policy);
4954			if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
4955				continue;
4956			mode->rates[idx] = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
4957
4958			/* crude heuristic */
4959			if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
4960			    mode->rates[idx] > 200)
4961				mode->mode = HOSTAPD_MODE_IEEE80211G;
4962
4963			idx++;
4964		}
4965	}
4966
4967	return NL_SKIP;
4968}
4969
4970static struct hostapd_hw_modes *
4971wpa_driver_nl80211_add_11b(struct hostapd_hw_modes *modes, u16 *num_modes)
4972{
4973	u16 m;
4974	struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
4975	int i, mode11g_idx = -1;
4976
4977	/* If only 802.11g mode is included, use it to construct matching
4978	 * 802.11b mode data. */
4979
4980	for (m = 0; m < *num_modes; m++) {
4981		if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
4982			return modes; /* 802.11b already included */
4983		if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
4984			mode11g_idx = m;
4985	}
4986
4987	if (mode11g_idx < 0)
4988		return modes; /* 2.4 GHz band not supported at all */
4989
4990	nmodes = os_realloc_array(modes, *num_modes + 1, sizeof(*nmodes));
4991	if (nmodes == NULL)
4992		return modes; /* Could not add 802.11b mode */
4993
4994	mode = &nmodes[*num_modes];
4995	os_memset(mode, 0, sizeof(*mode));
4996	(*num_modes)++;
4997	modes = nmodes;
4998
4999	mode->mode = HOSTAPD_MODE_IEEE80211B;
5000
5001	mode11g = &modes[mode11g_idx];
5002	mode->num_channels = mode11g->num_channels;
5003	mode->channels = os_malloc(mode11g->num_channels *
5004				   sizeof(struct hostapd_channel_data));
5005	if (mode->channels == NULL) {
5006		(*num_modes)--;
5007		return modes; /* Could not add 802.11b mode */
5008	}
5009	os_memcpy(mode->channels, mode11g->channels,
5010		  mode11g->num_channels * sizeof(struct hostapd_channel_data));
5011
5012	mode->num_rates = 0;
5013	mode->rates = os_malloc(4 * sizeof(int));
5014	if (mode->rates == NULL) {
5015		os_free(mode->channels);
5016		(*num_modes)--;
5017		return modes; /* Could not add 802.11b mode */
5018	}
5019
5020	for (i = 0; i < mode11g->num_rates; i++) {
5021		if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 &&
5022		    mode11g->rates[i] != 55 && mode11g->rates[i] != 110)
5023			continue;
5024		mode->rates[mode->num_rates] = mode11g->rates[i];
5025		mode->num_rates++;
5026		if (mode->num_rates == 4)
5027			break;
5028	}
5029
5030	if (mode->num_rates == 0) {
5031		os_free(mode->channels);
5032		os_free(mode->rates);
5033		(*num_modes)--;
5034		return modes; /* No 802.11b rates */
5035	}
5036
5037	wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
5038		   "information");
5039
5040	return modes;
5041}
5042
5043
5044static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start,
5045				  int end)
5046{
5047	int c;
5048
5049	for (c = 0; c < mode->num_channels; c++) {
5050		struct hostapd_channel_data *chan = &mode->channels[c];
5051		if (chan->freq - 10 >= start && chan->freq + 10 <= end)
5052			chan->flag |= HOSTAPD_CHAN_HT40;
5053	}
5054}
5055
5056
5057static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start,
5058				      int end)
5059{
5060	int c;
5061
5062	for (c = 0; c < mode->num_channels; c++) {
5063		struct hostapd_channel_data *chan = &mode->channels[c];
5064		if (!(chan->flag & HOSTAPD_CHAN_HT40))
5065			continue;
5066		if (chan->freq - 30 >= start && chan->freq - 10 <= end)
5067			chan->flag |= HOSTAPD_CHAN_HT40MINUS;
5068		if (chan->freq + 10 >= start && chan->freq + 30 <= end)
5069			chan->flag |= HOSTAPD_CHAN_HT40PLUS;
5070	}
5071}
5072
5073
5074static void nl80211_reg_rule_ht40(struct nlattr *tb[],
5075				  struct phy_info_arg *results)
5076{
5077	u32 start, end, max_bw;
5078	u16 m;
5079
5080	if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
5081	    tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
5082	    tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
5083		return;
5084
5085	start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
5086	end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
5087	max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
5088
5089	wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz",
5090		   start, end, max_bw);
5091	if (max_bw < 40)
5092		return;
5093
5094	for (m = 0; m < *results->num_modes; m++) {
5095		if (!(results->modes[m].ht_capab &
5096		      HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
5097			continue;
5098		nl80211_set_ht40_mode(&results->modes[m], start, end);
5099	}
5100}
5101
5102
5103static void nl80211_reg_rule_sec(struct nlattr *tb[],
5104				 struct phy_info_arg *results)
5105{
5106	u32 start, end, max_bw;
5107	u16 m;
5108
5109	if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
5110	    tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
5111	    tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
5112		return;
5113
5114	start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
5115	end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
5116	max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
5117
5118	if (max_bw < 20)
5119		return;
5120
5121	for (m = 0; m < *results->num_modes; m++) {
5122		if (!(results->modes[m].ht_capab &
5123		      HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
5124			continue;
5125		nl80211_set_ht40_mode_sec(&results->modes[m], start, end);
5126	}
5127}
5128
5129
5130static int nl80211_get_reg(struct nl_msg *msg, void *arg)
5131{
5132	struct phy_info_arg *results = arg;
5133	struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
5134	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5135	struct nlattr *nl_rule;
5136	struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1];
5137	int rem_rule;
5138	static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
5139		[NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
5140		[NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
5141		[NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
5142		[NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
5143		[NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
5144		[NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
5145	};
5146
5147	nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5148		  genlmsg_attrlen(gnlh, 0), NULL);
5149	if (!tb_msg[NL80211_ATTR_REG_ALPHA2] ||
5150	    !tb_msg[NL80211_ATTR_REG_RULES]) {
5151		wpa_printf(MSG_DEBUG, "nl80211: No regulatory information "
5152			   "available");
5153		return NL_SKIP;
5154	}
5155
5156	wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s",
5157		   (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]));
5158
5159	nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5160	{
5161		nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5162			  nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5163		nl80211_reg_rule_ht40(tb_rule, results);
5164	}
5165
5166	nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5167	{
5168		nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5169			  nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5170		nl80211_reg_rule_sec(tb_rule, results);
5171	}
5172
5173	return NL_SKIP;
5174}
5175
5176
5177static int nl80211_set_ht40_flags(struct wpa_driver_nl80211_data *drv,
5178				  struct phy_info_arg *results)
5179{
5180	struct nl_msg *msg;
5181
5182	msg = nlmsg_alloc();
5183	if (!msg)
5184		return -ENOMEM;
5185
5186	nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_REG);
5187	return send_and_recv_msgs(drv, msg, nl80211_get_reg, results);
5188}
5189
5190
5191static struct hostapd_hw_modes *
5192wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
5193{
5194	struct i802_bss *bss = priv;
5195	struct wpa_driver_nl80211_data *drv = bss->drv;
5196	struct nl_msg *msg;
5197	struct phy_info_arg result = {
5198		.num_modes = num_modes,
5199		.modes = NULL,
5200	};
5201
5202	*num_modes = 0;
5203	*flags = 0;
5204
5205	msg = nlmsg_alloc();
5206	if (!msg)
5207		return NULL;
5208
5209	nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
5210
5211	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5212
5213	if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) {
5214		nl80211_set_ht40_flags(drv, &result);
5215		return wpa_driver_nl80211_add_11b(result.modes, num_modes);
5216	}
5217	msg = NULL;
5218 nla_put_failure:
5219	nlmsg_free(msg);
5220	return NULL;
5221}
5222
5223
5224static int wpa_driver_nl80211_send_mntr(struct wpa_driver_nl80211_data *drv,
5225					const void *data, size_t len,
5226					int encrypt, int noack)
5227{
5228	__u8 rtap_hdr[] = {
5229		0x00, 0x00, /* radiotap version */
5230		0x0e, 0x00, /* radiotap length */
5231		0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
5232		IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
5233		0x00,       /* padding */
5234		0x00, 0x00, /* RX and TX flags to indicate that */
5235		0x00, 0x00, /* this is the injected frame directly */
5236	};
5237	struct iovec iov[2] = {
5238		{
5239			.iov_base = &rtap_hdr,
5240			.iov_len = sizeof(rtap_hdr),
5241		},
5242		{
5243			.iov_base = (void *) data,
5244			.iov_len = len,
5245		}
5246	};
5247	struct msghdr msg = {
5248		.msg_name = NULL,
5249		.msg_namelen = 0,
5250		.msg_iov = iov,
5251		.msg_iovlen = 2,
5252		.msg_control = NULL,
5253		.msg_controllen = 0,
5254		.msg_flags = 0,
5255	};
5256	int res;
5257	u16 txflags = 0;
5258
5259	if (encrypt)
5260		rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
5261
5262	if (drv->monitor_sock < 0) {
5263		wpa_printf(MSG_DEBUG, "nl80211: No monitor socket available "
5264			   "for %s", __func__);
5265		return -1;
5266	}
5267
5268	if (noack)
5269		txflags |= IEEE80211_RADIOTAP_F_TX_NOACK;
5270	*(le16 *) &rtap_hdr[12] = host_to_le16(txflags);
5271
5272	res = sendmsg(drv->monitor_sock, &msg, 0);
5273	if (res < 0) {
5274		wpa_printf(MSG_INFO, "nl80211: sendmsg: %s", strerror(errno));
5275		return -1;
5276	}
5277	return 0;
5278}
5279
5280
5281static int wpa_driver_nl80211_send_frame(struct i802_bss *bss,
5282					 const void *data, size_t len,
5283					 int encrypt, int noack,
5284					 unsigned int freq, int no_cck,
5285					 int offchanok, unsigned int wait_time)
5286{
5287	struct wpa_driver_nl80211_data *drv = bss->drv;
5288	u64 cookie;
5289
5290	if (freq == 0)
5291		freq = bss->freq;
5292
5293	if (drv->use_monitor)
5294		return wpa_driver_nl80211_send_mntr(drv, data, len,
5295						    encrypt, noack);
5296
5297	return nl80211_send_frame_cmd(bss, freq, wait_time, data, len,
5298				      &cookie, no_cck, noack, offchanok);
5299}
5300
5301
5302static int wpa_driver_nl80211_send_mlme_freq(struct i802_bss *bss,
5303					     const u8 *data,
5304					     size_t data_len, int noack,
5305					     unsigned int freq, int no_cck,
5306					     int offchanok,
5307					     unsigned int wait_time)
5308{
5309	struct wpa_driver_nl80211_data *drv = bss->drv;
5310	struct ieee80211_mgmt *mgmt;
5311	int encrypt = 1;
5312	u16 fc;
5313
5314	mgmt = (struct ieee80211_mgmt *) data;
5315	fc = le_to_host16(mgmt->frame_control);
5316
5317	if (is_sta_interface(drv->nlmode) &&
5318	    WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5319	    WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_PROBE_RESP) {
5320		/*
5321		 * The use of last_mgmt_freq is a bit of a hack,
5322		 * but it works due to the single-threaded nature
5323		 * of wpa_supplicant.
5324		 */
5325		if (freq == 0)
5326			freq = drv->last_mgmt_freq;
5327		return nl80211_send_frame_cmd(bss, freq, 0,
5328					      data, data_len, NULL, 1, noack,
5329					      1);
5330	}
5331
5332	if (drv->device_ap_sme && is_ap_interface(drv->nlmode)) {
5333		if (freq == 0)
5334			freq = bss->freq;
5335		return nl80211_send_frame_cmd(bss, freq,
5336					      (int) freq == bss->freq ? 0 :
5337					      wait_time,
5338					      data, data_len,
5339					      &drv->send_action_cookie,
5340					      no_cck, noack, offchanok);
5341	}
5342
5343	if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5344	    WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
5345		/*
5346		 * Only one of the authentication frame types is encrypted.
5347		 * In order for static WEP encryption to work properly (i.e.,
5348		 * to not encrypt the frame), we need to tell mac80211 about
5349		 * the frames that must not be encrypted.
5350		 */
5351		u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
5352		u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
5353		if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
5354			encrypt = 0;
5355	}
5356
5357	return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt,
5358					     noack, freq, no_cck, offchanok,
5359					     wait_time);
5360}
5361
5362
5363static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
5364					size_t data_len, int noack)
5365{
5366	struct i802_bss *bss = priv;
5367	return wpa_driver_nl80211_send_mlme_freq(bss, data, data_len, noack,
5368						 0, 0, 0, 0);
5369}
5370
5371
5372static int nl80211_set_bss(struct i802_bss *bss, int cts, int preamble,
5373			   int slot, int ht_opmode, int ap_isolate,
5374			   int *basic_rates)
5375{
5376	struct wpa_driver_nl80211_data *drv = bss->drv;
5377	struct nl_msg *msg;
5378
5379	msg = nlmsg_alloc();
5380	if (!msg)
5381		return -ENOMEM;
5382
5383	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_BSS);
5384
5385	if (cts >= 0)
5386		NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
5387	if (preamble >= 0)
5388		NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
5389	if (slot >= 0)
5390		NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
5391	if (ht_opmode >= 0)
5392		NLA_PUT_U16(msg, NL80211_ATTR_BSS_HT_OPMODE, ht_opmode);
5393	if (ap_isolate >= 0)
5394		NLA_PUT_U8(msg, NL80211_ATTR_AP_ISOLATE, ap_isolate);
5395
5396	if (basic_rates) {
5397		u8 rates[NL80211_MAX_SUPP_RATES];
5398		u8 rates_len = 0;
5399		int i;
5400
5401		for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0;
5402		     i++)
5403			rates[rates_len++] = basic_rates[i] / 5;
5404
5405		NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
5406	}
5407
5408	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5409
5410	return send_and_recv_msgs(drv, msg, NULL, NULL);
5411 nla_put_failure:
5412	nlmsg_free(msg);
5413	return -ENOBUFS;
5414}
5415
5416
5417static int wpa_driver_nl80211_set_ap(void *priv,
5418				     struct wpa_driver_ap_params *params)
5419{
5420	struct i802_bss *bss = priv;
5421	struct wpa_driver_nl80211_data *drv = bss->drv;
5422	struct nl_msg *msg;
5423	u8 cmd = NL80211_CMD_NEW_BEACON;
5424	int ret;
5425	int beacon_set;
5426	int ifindex = if_nametoindex(bss->ifname);
5427	int num_suites;
5428	u32 suites[10];
5429	u32 ver;
5430
5431	beacon_set = bss->beacon_set;
5432
5433	msg = nlmsg_alloc();
5434	if (!msg)
5435		return -ENOMEM;
5436
5437	wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
5438		   beacon_set);
5439	if (beacon_set)
5440		cmd = NL80211_CMD_SET_BEACON;
5441
5442	nl80211_cmd(drv, msg, 0, cmd);
5443	NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, params->head_len, params->head);
5444	NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, params->tail_len, params->tail);
5445	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
5446	NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, params->beacon_int);
5447	NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, params->dtim_period);
5448	NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
5449		params->ssid);
5450	if (params->proberesp && params->proberesp_len)
5451		NLA_PUT(msg, NL80211_ATTR_PROBE_RESP, params->proberesp_len,
5452			params->proberesp);
5453	switch (params->hide_ssid) {
5454	case NO_SSID_HIDING:
5455		NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5456			    NL80211_HIDDEN_SSID_NOT_IN_USE);
5457		break;
5458	case HIDDEN_SSID_ZERO_LEN:
5459		NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5460			    NL80211_HIDDEN_SSID_ZERO_LEN);
5461		break;
5462	case HIDDEN_SSID_ZERO_CONTENTS:
5463		NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5464			    NL80211_HIDDEN_SSID_ZERO_CONTENTS);
5465		break;
5466	}
5467	if (params->privacy)
5468		NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
5469	if ((params->auth_algs & (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) ==
5470	    (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) {
5471		/* Leave out the attribute */
5472	} else if (params->auth_algs & WPA_AUTH_ALG_SHARED)
5473		NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5474			    NL80211_AUTHTYPE_SHARED_KEY);
5475	else
5476		NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5477			    NL80211_AUTHTYPE_OPEN_SYSTEM);
5478
5479	ver = 0;
5480	if (params->wpa_version & WPA_PROTO_WPA)
5481		ver |= NL80211_WPA_VERSION_1;
5482	if (params->wpa_version & WPA_PROTO_RSN)
5483		ver |= NL80211_WPA_VERSION_2;
5484	if (ver)
5485		NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
5486
5487	num_suites = 0;
5488	if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X)
5489		suites[num_suites++] = WLAN_AKM_SUITE_8021X;
5490	if (params->key_mgmt_suites & WPA_KEY_MGMT_PSK)
5491		suites[num_suites++] = WLAN_AKM_SUITE_PSK;
5492	if (num_suites) {
5493		NLA_PUT(msg, NL80211_ATTR_AKM_SUITES,
5494			num_suites * sizeof(u32), suites);
5495	}
5496
5497	if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X &&
5498	    params->pairwise_ciphers & (WPA_CIPHER_WEP104 | WPA_CIPHER_WEP40))
5499		NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT);
5500
5501	num_suites = 0;
5502	if (params->pairwise_ciphers & WPA_CIPHER_CCMP)
5503		suites[num_suites++] = WLAN_CIPHER_SUITE_CCMP;
5504	if (params->pairwise_ciphers & WPA_CIPHER_GCMP)
5505		suites[num_suites++] = WLAN_CIPHER_SUITE_GCMP;
5506	if (params->pairwise_ciphers & WPA_CIPHER_TKIP)
5507		suites[num_suites++] = WLAN_CIPHER_SUITE_TKIP;
5508	if (params->pairwise_ciphers & WPA_CIPHER_WEP104)
5509		suites[num_suites++] = WLAN_CIPHER_SUITE_WEP104;
5510	if (params->pairwise_ciphers & WPA_CIPHER_WEP40)
5511		suites[num_suites++] = WLAN_CIPHER_SUITE_WEP40;
5512	if (num_suites) {
5513		NLA_PUT(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE,
5514			num_suites * sizeof(u32), suites);
5515	}
5516
5517	switch (params->group_cipher) {
5518	case WPA_CIPHER_CCMP:
5519		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5520			    WLAN_CIPHER_SUITE_CCMP);
5521		break;
5522	case WPA_CIPHER_GCMP:
5523		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5524			    WLAN_CIPHER_SUITE_GCMP);
5525		break;
5526	case WPA_CIPHER_TKIP:
5527		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5528			    WLAN_CIPHER_SUITE_TKIP);
5529		break;
5530	case WPA_CIPHER_WEP104:
5531		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5532			    WLAN_CIPHER_SUITE_WEP104);
5533		break;
5534	case WPA_CIPHER_WEP40:
5535		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5536			    WLAN_CIPHER_SUITE_WEP40);
5537		break;
5538	}
5539
5540	if (params->beacon_ies) {
5541		NLA_PUT(msg, NL80211_ATTR_IE, wpabuf_len(params->beacon_ies),
5542			wpabuf_head(params->beacon_ies));
5543	}
5544	if (params->proberesp_ies) {
5545		NLA_PUT(msg, NL80211_ATTR_IE_PROBE_RESP,
5546			wpabuf_len(params->proberesp_ies),
5547			wpabuf_head(params->proberesp_ies));
5548	}
5549	if (params->assocresp_ies) {
5550		NLA_PUT(msg, NL80211_ATTR_IE_ASSOC_RESP,
5551			wpabuf_len(params->assocresp_ies),
5552			wpabuf_head(params->assocresp_ies));
5553	}
5554
5555	if (drv->capa.flags & WPA_DRIVER_FLAGS_INACTIVITY_TIMER)  {
5556		NLA_PUT_U16(msg, NL80211_ATTR_INACTIVITY_TIMEOUT,
5557			    params->ap_max_inactivity);
5558	}
5559
5560	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5561	if (ret) {
5562		wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
5563			   ret, strerror(-ret));
5564	} else {
5565		bss->beacon_set = 1;
5566		nl80211_set_bss(bss, params->cts_protect, params->preamble,
5567				params->short_slot_time, params->ht_opmode,
5568				params->isolate, params->basic_rates);
5569	}
5570	return ret;
5571 nla_put_failure:
5572	nlmsg_free(msg);
5573	return -ENOBUFS;
5574}
5575
5576
5577static int wpa_driver_nl80211_set_freq(struct i802_bss *bss,
5578				       int freq, int ht_enabled,
5579				       int sec_channel_offset)
5580{
5581	struct wpa_driver_nl80211_data *drv = bss->drv;
5582	struct nl_msg *msg;
5583	int ret;
5584
5585	wpa_printf(MSG_DEBUG, "nl80211: Set freq %d (ht_enabled=%d "
5586		   "sec_channel_offset=%d)",
5587		   freq, ht_enabled, sec_channel_offset);
5588	msg = nlmsg_alloc();
5589	if (!msg)
5590		return -1;
5591
5592	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
5593
5594	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5595	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
5596	if (ht_enabled) {
5597		switch (sec_channel_offset) {
5598		case -1:
5599			NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5600				    NL80211_CHAN_HT40MINUS);
5601			break;
5602		case 1:
5603			NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5604				    NL80211_CHAN_HT40PLUS);
5605			break;
5606		default:
5607			NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5608				    NL80211_CHAN_HT20);
5609			break;
5610		}
5611	}
5612
5613	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5614	msg = NULL;
5615	if (ret == 0) {
5616		bss->freq = freq;
5617		return 0;
5618	}
5619	wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
5620		   "%d (%s)", freq, ret, strerror(-ret));
5621nla_put_failure:
5622	nlmsg_free(msg);
5623	return -1;
5624}
5625
5626
5627static u32 sta_flags_nl80211(int flags)
5628{
5629	u32 f = 0;
5630
5631	if (flags & WPA_STA_AUTHORIZED)
5632		f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
5633	if (flags & WPA_STA_WMM)
5634		f |= BIT(NL80211_STA_FLAG_WME);
5635	if (flags & WPA_STA_SHORT_PREAMBLE)
5636		f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
5637	if (flags & WPA_STA_MFP)
5638		f |= BIT(NL80211_STA_FLAG_MFP);
5639	if (flags & WPA_STA_TDLS_PEER)
5640		f |= BIT(NL80211_STA_FLAG_TDLS_PEER);
5641
5642	return f;
5643}
5644
5645
5646static int wpa_driver_nl80211_sta_add(void *priv,
5647				      struct hostapd_sta_add_params *params)
5648{
5649	struct i802_bss *bss = priv;
5650	struct wpa_driver_nl80211_data *drv = bss->drv;
5651	struct nl_msg *msg, *wme = NULL;
5652	struct nl80211_sta_flag_update upd;
5653	int ret = -ENOBUFS;
5654
5655	if ((params->flags & WPA_STA_TDLS_PEER) &&
5656	    !(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
5657		return -EOPNOTSUPP;
5658
5659	msg = nlmsg_alloc();
5660	if (!msg)
5661		return -ENOMEM;
5662
5663	nl80211_cmd(drv, msg, 0, params->set ? NL80211_CMD_SET_STATION :
5664		    NL80211_CMD_NEW_STATION);
5665
5666	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5667	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
5668	NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
5669		params->supp_rates);
5670	if (!params->set) {
5671		NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
5672		NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
5673			    params->listen_interval);
5674	}
5675	if (params->ht_capabilities) {
5676		NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
5677			sizeof(*params->ht_capabilities),
5678			params->ht_capabilities);
5679	}
5680
5681	os_memset(&upd, 0, sizeof(upd));
5682	upd.mask = sta_flags_nl80211(params->flags);
5683	upd.set = upd.mask;
5684	NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
5685
5686	if (params->flags & WPA_STA_WMM) {
5687		wme = nlmsg_alloc();
5688		if (!wme)
5689			goto nla_put_failure;
5690
5691		NLA_PUT_U8(wme, NL80211_STA_WME_UAPSD_QUEUES,
5692				params->qosinfo & WMM_QOSINFO_STA_AC_MASK);
5693		NLA_PUT_U8(wme, NL80211_STA_WME_MAX_SP,
5694				(params->qosinfo > WMM_QOSINFO_STA_SP_SHIFT) &
5695				WMM_QOSINFO_STA_SP_MASK);
5696		if (nla_put_nested(msg, NL80211_ATTR_STA_WME, wme) < 0)
5697			goto nla_put_failure;
5698	}
5699
5700	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5701	msg = NULL;
5702	if (ret)
5703		wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_%s_STATION "
5704			   "result: %d (%s)", params->set ? "SET" : "NEW", ret,
5705			   strerror(-ret));
5706	if (ret == -EEXIST)
5707		ret = 0;
5708 nla_put_failure:
5709	nlmsg_free(wme);
5710	nlmsg_free(msg);
5711	return ret;
5712}
5713
5714
5715static int wpa_driver_nl80211_sta_remove(void *priv, const u8 *addr)
5716{
5717	struct i802_bss *bss = priv;
5718	struct wpa_driver_nl80211_data *drv = bss->drv;
5719	struct nl_msg *msg;
5720	int ret;
5721
5722	msg = nlmsg_alloc();
5723	if (!msg)
5724		return -ENOMEM;
5725
5726	nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
5727
5728	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5729		    if_nametoindex(bss->ifname));
5730	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5731
5732	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5733	if (ret == -ENOENT)
5734		return 0;
5735	return ret;
5736 nla_put_failure:
5737	nlmsg_free(msg);
5738	return -ENOBUFS;
5739}
5740
5741
5742static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
5743				 int ifidx)
5744{
5745	struct nl_msg *msg;
5746
5747	wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
5748
5749	/* stop listening for EAPOL on this interface */
5750	del_ifidx(drv, ifidx);
5751
5752	msg = nlmsg_alloc();
5753	if (!msg)
5754		goto nla_put_failure;
5755
5756	nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_INTERFACE);
5757	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
5758
5759	if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
5760		return;
5761	msg = NULL;
5762 nla_put_failure:
5763	nlmsg_free(msg);
5764	wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
5765}
5766
5767
5768static const char * nl80211_iftype_str(enum nl80211_iftype mode)
5769{
5770	switch (mode) {
5771	case NL80211_IFTYPE_ADHOC:
5772		return "ADHOC";
5773	case NL80211_IFTYPE_STATION:
5774		return "STATION";
5775	case NL80211_IFTYPE_AP:
5776		return "AP";
5777	case NL80211_IFTYPE_MONITOR:
5778		return "MONITOR";
5779	case NL80211_IFTYPE_P2P_CLIENT:
5780		return "P2P_CLIENT";
5781	case NL80211_IFTYPE_P2P_GO:
5782		return "P2P_GO";
5783	default:
5784		return "unknown";
5785	}
5786}
5787
5788
5789static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
5790				     const char *ifname,
5791				     enum nl80211_iftype iftype,
5792				     const u8 *addr, int wds)
5793{
5794	struct nl_msg *msg, *flags = NULL;
5795	int ifidx;
5796	int ret = -ENOBUFS;
5797
5798	wpa_printf(MSG_DEBUG, "nl80211: Create interface iftype %d (%s)",
5799		   iftype, nl80211_iftype_str(iftype));
5800
5801	msg = nlmsg_alloc();
5802	if (!msg)
5803		return -1;
5804
5805	nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_INTERFACE);
5806	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5807	NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
5808	NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
5809
5810	if (iftype == NL80211_IFTYPE_MONITOR) {
5811		int err;
5812
5813		flags = nlmsg_alloc();
5814		if (!flags)
5815			goto nla_put_failure;
5816
5817		NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
5818
5819		err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
5820
5821		nlmsg_free(flags);
5822
5823		if (err)
5824			goto nla_put_failure;
5825	} else if (wds) {
5826		NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
5827	}
5828
5829	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5830	msg = NULL;
5831	if (ret) {
5832 nla_put_failure:
5833		nlmsg_free(msg);
5834		wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
5835			   ifname, ret, strerror(-ret));
5836		return ret;
5837	}
5838
5839	ifidx = if_nametoindex(ifname);
5840	wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
5841		   ifname, ifidx);
5842
5843	if (ifidx <= 0)
5844		return -1;
5845
5846	/* start listening for EAPOL on this interface */
5847	add_ifidx(drv, ifidx);
5848
5849	if (addr && iftype != NL80211_IFTYPE_MONITOR &&
5850	    linux_set_ifhwaddr(drv->global->ioctl_sock, ifname, addr)) {
5851		nl80211_remove_iface(drv, ifidx);
5852		return -1;
5853	}
5854
5855	return ifidx;
5856}
5857
5858
5859static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
5860				const char *ifname, enum nl80211_iftype iftype,
5861				const u8 *addr, int wds)
5862{
5863	int ret;
5864
5865	ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds);
5866
5867	/* if error occurred and interface exists already */
5868	if (ret == -ENFILE && if_nametoindex(ifname)) {
5869		wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
5870
5871		/* Try to remove the interface that was already there. */
5872		nl80211_remove_iface(drv, if_nametoindex(ifname));
5873
5874		/* Try to create the interface again */
5875		ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
5876						wds);
5877	}
5878
5879	if (ret >= 0 && is_p2p_interface(iftype))
5880		nl80211_disable_11b_rates(drv, ret, 1);
5881
5882	return ret;
5883}
5884
5885
5886static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
5887{
5888	struct ieee80211_hdr *hdr;
5889	u16 fc;
5890	union wpa_event_data event;
5891
5892	hdr = (struct ieee80211_hdr *) buf;
5893	fc = le_to_host16(hdr->frame_control);
5894
5895	os_memset(&event, 0, sizeof(event));
5896	event.tx_status.type = WLAN_FC_GET_TYPE(fc);
5897	event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
5898	event.tx_status.dst = hdr->addr1;
5899	event.tx_status.data = buf;
5900	event.tx_status.data_len = len;
5901	event.tx_status.ack = ok;
5902	wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
5903}
5904
5905
5906static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
5907			     u8 *buf, size_t len)
5908{
5909	struct ieee80211_hdr *hdr = (void *)buf;
5910	u16 fc;
5911	union wpa_event_data event;
5912
5913	if (len < sizeof(*hdr))
5914		return;
5915
5916	fc = le_to_host16(hdr->frame_control);
5917
5918	os_memset(&event, 0, sizeof(event));
5919	event.rx_from_unknown.bssid = get_hdr_bssid(hdr, len);
5920	event.rx_from_unknown.addr = hdr->addr2;
5921	event.rx_from_unknown.wds = (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) ==
5922		(WLAN_FC_FROMDS | WLAN_FC_TODS);
5923	wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
5924}
5925
5926
5927static void handle_frame(struct wpa_driver_nl80211_data *drv,
5928			 u8 *buf, size_t len, int datarate, int ssi_signal)
5929{
5930	struct ieee80211_hdr *hdr;
5931	u16 fc;
5932	union wpa_event_data event;
5933
5934	hdr = (struct ieee80211_hdr *) buf;
5935	fc = le_to_host16(hdr->frame_control);
5936
5937	switch (WLAN_FC_GET_TYPE(fc)) {
5938	case WLAN_FC_TYPE_MGMT:
5939		os_memset(&event, 0, sizeof(event));
5940		event.rx_mgmt.frame = buf;
5941		event.rx_mgmt.frame_len = len;
5942		event.rx_mgmt.datarate = datarate;
5943		event.rx_mgmt.ssi_signal = ssi_signal;
5944		wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
5945		break;
5946	case WLAN_FC_TYPE_CTRL:
5947		/* can only get here with PS-Poll frames */
5948		wpa_printf(MSG_DEBUG, "CTRL");
5949		from_unknown_sta(drv, buf, len);
5950		break;
5951	case WLAN_FC_TYPE_DATA:
5952		from_unknown_sta(drv, buf, len);
5953		break;
5954	}
5955}
5956
5957
5958static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
5959{
5960	struct wpa_driver_nl80211_data *drv = eloop_ctx;
5961	int len;
5962	unsigned char buf[3000];
5963	struct ieee80211_radiotap_iterator iter;
5964	int ret;
5965	int datarate = 0, ssi_signal = 0;
5966	int injected = 0, failed = 0, rxflags = 0;
5967
5968	len = recv(sock, buf, sizeof(buf), 0);
5969	if (len < 0) {
5970		perror("recv");
5971		return;
5972	}
5973
5974	if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
5975		printf("received invalid radiotap frame\n");
5976		return;
5977	}
5978
5979	while (1) {
5980		ret = ieee80211_radiotap_iterator_next(&iter);
5981		if (ret == -ENOENT)
5982			break;
5983		if (ret) {
5984			printf("received invalid radiotap frame (%d)\n", ret);
5985			return;
5986		}
5987		switch (iter.this_arg_index) {
5988		case IEEE80211_RADIOTAP_FLAGS:
5989			if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
5990				len -= 4;
5991			break;
5992		case IEEE80211_RADIOTAP_RX_FLAGS:
5993			rxflags = 1;
5994			break;
5995		case IEEE80211_RADIOTAP_TX_FLAGS:
5996			injected = 1;
5997			failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
5998					IEEE80211_RADIOTAP_F_TX_FAIL;
5999			break;
6000		case IEEE80211_RADIOTAP_DATA_RETRIES:
6001			break;
6002		case IEEE80211_RADIOTAP_CHANNEL:
6003			/* TODO: convert from freq/flags to channel number */
6004			break;
6005		case IEEE80211_RADIOTAP_RATE:
6006			datarate = *iter.this_arg * 5;
6007			break;
6008		case IEEE80211_RADIOTAP_DBM_ANTSIGNAL:
6009			ssi_signal = (s8) *iter.this_arg;
6010			break;
6011		}
6012	}
6013
6014	if (rxflags && injected)
6015		return;
6016
6017	if (!injected)
6018		handle_frame(drv, buf + iter.max_length,
6019			     len - iter.max_length, datarate, ssi_signal);
6020	else
6021		handle_tx_callback(drv->ctx, buf + iter.max_length,
6022				   len - iter.max_length, !failed);
6023}
6024
6025
6026/*
6027 * we post-process the filter code later and rewrite
6028 * this to the offset to the last instruction
6029 */
6030#define PASS	0xFF
6031#define FAIL	0xFE
6032
6033static struct sock_filter msock_filter_insns[] = {
6034	/*
6035	 * do a little-endian load of the radiotap length field
6036	 */
6037	/* load lower byte into A */
6038	BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
6039	/* put it into X (== index register) */
6040	BPF_STMT(BPF_MISC| BPF_TAX, 0),
6041	/* load upper byte into A */
6042	BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
6043	/* left-shift it by 8 */
6044	BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
6045	/* or with X */
6046	BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
6047	/* put result into X */
6048	BPF_STMT(BPF_MISC| BPF_TAX, 0),
6049
6050	/*
6051	 * Allow management frames through, this also gives us those
6052	 * management frames that we sent ourselves with status
6053	 */
6054	/* load the lower byte of the IEEE 802.11 frame control field */
6055	BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
6056	/* mask off frame type and version */
6057	BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
6058	/* accept frame if it's both 0, fall through otherwise */
6059	BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
6060
6061	/*
6062	 * TODO: add a bit to radiotap RX flags that indicates
6063	 * that the sending station is not associated, then
6064	 * add a filter here that filters on our DA and that flag
6065	 * to allow us to deauth frames to that bad station.
6066	 *
6067	 * For now allow all To DS data frames through.
6068	 */
6069	/* load the IEEE 802.11 frame control field */
6070	BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
6071	/* mask off frame type, version and DS status */
6072	BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
6073	/* accept frame if version 0, type 2 and To DS, fall through otherwise
6074	 */
6075	BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
6076
6077#if 0
6078	/*
6079	 * drop non-data frames
6080	 */
6081	/* load the lower byte of the frame control field */
6082	BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
6083	/* mask off QoS bit */
6084	BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
6085	/* drop non-data frames */
6086	BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
6087#endif
6088	/* load the upper byte of the frame control field */
6089	BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
6090	/* mask off toDS/fromDS */
6091	BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
6092	/* accept WDS frames */
6093	BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
6094
6095	/*
6096	 * add header length to index
6097	 */
6098	/* load the lower byte of the frame control field */
6099	BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
6100	/* mask off QoS bit */
6101	BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
6102	/* right shift it by 6 to give 0 or 2 */
6103	BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
6104	/* add data frame header length */
6105	BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
6106	/* add index, was start of 802.11 header */
6107	BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
6108	/* move to index, now start of LL header */
6109	BPF_STMT(BPF_MISC | BPF_TAX, 0),
6110
6111	/*
6112	 * Accept empty data frames, we use those for
6113	 * polling activity.
6114	 */
6115	BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
6116	BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
6117
6118	/*
6119	 * Accept EAPOL frames
6120	 */
6121	BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
6122	BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
6123	BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
6124	BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
6125
6126	/* keep these last two statements or change the code below */
6127	/* return 0 == "DROP" */
6128	BPF_STMT(BPF_RET | BPF_K, 0),
6129	/* return ~0 == "keep all" */
6130	BPF_STMT(BPF_RET | BPF_K, ~0),
6131};
6132
6133static struct sock_fprog msock_filter = {
6134	.len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
6135	.filter = msock_filter_insns,
6136};
6137
6138
6139static int add_monitor_filter(int s)
6140{
6141	int idx;
6142
6143	/* rewrite all PASS/FAIL jump offsets */
6144	for (idx = 0; idx < msock_filter.len; idx++) {
6145		struct sock_filter *insn = &msock_filter_insns[idx];
6146
6147		if (BPF_CLASS(insn->code) == BPF_JMP) {
6148			if (insn->code == (BPF_JMP|BPF_JA)) {
6149				if (insn->k == PASS)
6150					insn->k = msock_filter.len - idx - 2;
6151				else if (insn->k == FAIL)
6152					insn->k = msock_filter.len - idx - 3;
6153			}
6154
6155			if (insn->jt == PASS)
6156				insn->jt = msock_filter.len - idx - 2;
6157			else if (insn->jt == FAIL)
6158				insn->jt = msock_filter.len - idx - 3;
6159
6160			if (insn->jf == PASS)
6161				insn->jf = msock_filter.len - idx - 2;
6162			else if (insn->jf == FAIL)
6163				insn->jf = msock_filter.len - idx - 3;
6164		}
6165	}
6166
6167	if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
6168		       &msock_filter, sizeof(msock_filter))) {
6169		perror("SO_ATTACH_FILTER");
6170		return -1;
6171	}
6172
6173	return 0;
6174}
6175
6176
6177static void nl80211_remove_monitor_interface(
6178	struct wpa_driver_nl80211_data *drv)
6179{
6180	drv->monitor_refcount--;
6181	if (drv->monitor_refcount > 0)
6182		return;
6183
6184	if (drv->monitor_ifidx >= 0) {
6185		nl80211_remove_iface(drv, drv->monitor_ifidx);
6186		drv->monitor_ifidx = -1;
6187	}
6188	if (drv->monitor_sock >= 0) {
6189		eloop_unregister_read_sock(drv->monitor_sock);
6190		close(drv->monitor_sock);
6191		drv->monitor_sock = -1;
6192	}
6193}
6194
6195
6196static int
6197nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
6198{
6199	char buf[IFNAMSIZ];
6200	struct sockaddr_ll ll;
6201	int optval;
6202	socklen_t optlen;
6203
6204	if (drv->monitor_ifidx >= 0) {
6205		drv->monitor_refcount++;
6206		return 0;
6207	}
6208
6209	if (os_strncmp(drv->first_bss.ifname, "p2p-", 4) == 0) {
6210		/*
6211		 * P2P interface name is of the format p2p-%s-%d. For monitor
6212		 * interface name corresponding to P2P GO, replace "p2p-" with
6213		 * "mon-" to retain the same interface name length and to
6214		 * indicate that it is a monitor interface.
6215		 */
6216		snprintf(buf, IFNAMSIZ, "mon-%s", drv->first_bss.ifname + 4);
6217	} else {
6218		/* Non-P2P interface with AP functionality. */
6219		snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss.ifname);
6220	}
6221
6222	buf[IFNAMSIZ - 1] = '\0';
6223
6224	drv->monitor_ifidx =
6225		nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
6226				     0);
6227
6228	if (drv->monitor_ifidx == -EOPNOTSUPP) {
6229		/*
6230		 * This is backward compatibility for a few versions of
6231		 * the kernel only that didn't advertise the right
6232		 * attributes for the only driver that then supported
6233		 * AP mode w/o monitor -- ath6kl.
6234		 */
6235		wpa_printf(MSG_DEBUG, "nl80211: Driver does not support "
6236			   "monitor interface type - try to run without it");
6237		drv->device_ap_sme = 1;
6238	}
6239
6240	if (drv->monitor_ifidx < 0)
6241		return -1;
6242
6243	if (linux_set_iface_flags(drv->global->ioctl_sock, buf, 1))
6244		goto error;
6245
6246	memset(&ll, 0, sizeof(ll));
6247	ll.sll_family = AF_PACKET;
6248	ll.sll_ifindex = drv->monitor_ifidx;
6249	drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
6250	if (drv->monitor_sock < 0) {
6251		perror("socket[PF_PACKET,SOCK_RAW]");
6252		goto error;
6253	}
6254
6255	if (add_monitor_filter(drv->monitor_sock)) {
6256		wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
6257			   "interface; do filtering in user space");
6258		/* This works, but will cost in performance. */
6259	}
6260
6261	if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
6262		perror("monitor socket bind");
6263		goto error;
6264	}
6265
6266	optlen = sizeof(optval);
6267	optval = 20;
6268	if (setsockopt
6269	    (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
6270		perror("Failed to set socket priority");
6271		goto error;
6272	}
6273
6274	if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
6275				     drv, NULL)) {
6276		printf("Could not register monitor read socket\n");
6277		goto error;
6278	}
6279
6280	return 0;
6281 error:
6282	nl80211_remove_monitor_interface(drv);
6283	return -1;
6284}
6285
6286
6287static int nl80211_setup_ap(struct i802_bss *bss)
6288{
6289	struct wpa_driver_nl80211_data *drv = bss->drv;
6290
6291	wpa_printf(MSG_DEBUG, "nl80211: Setup AP - device_ap_sme=%d "
6292		   "use_monitor=%d", drv->device_ap_sme, drv->use_monitor);
6293
6294	/*
6295	 * Disable Probe Request reporting unless we need it in this way for
6296	 * devices that include the AP SME, in the other case (unless using
6297	 * monitor iface) we'll get it through the nl_mgmt socket instead.
6298	 */
6299	if (!drv->device_ap_sme)
6300		wpa_driver_nl80211_probe_req_report(bss, 0);
6301
6302	if (!drv->device_ap_sme && !drv->use_monitor)
6303		if (nl80211_mgmt_subscribe_ap(bss))
6304			return -1;
6305
6306	if (drv->device_ap_sme && !drv->use_monitor)
6307		if (nl80211_mgmt_subscribe_ap_dev_sme(bss))
6308			return -1;
6309
6310	if (!drv->device_ap_sme && drv->use_monitor &&
6311	    nl80211_create_monitor_interface(drv) &&
6312	    !drv->device_ap_sme)
6313		return -1;
6314
6315#ifdef ANDROID_P2P
6316	if (drv->device_ap_sme && drv->use_monitor)
6317		if (nl80211_mgmt_subscribe_ap_dev_sme(bss))
6318			return -1;
6319
6320	if (drv->use_monitor &&
6321	    nl80211_create_monitor_interface(drv))
6322		return -1;
6323#endif
6324
6325	if (drv->device_ap_sme &&
6326	    wpa_driver_nl80211_probe_req_report(bss, 1) < 0) {
6327		wpa_printf(MSG_DEBUG, "nl80211: Failed to enable "
6328			   "Probe Request frame reporting in AP mode");
6329		/* Try to survive without this */
6330	}
6331
6332	return 0;
6333}
6334
6335
6336static void nl80211_teardown_ap(struct i802_bss *bss)
6337{
6338	struct wpa_driver_nl80211_data *drv = bss->drv;
6339
6340	if (drv->device_ap_sme) {
6341		wpa_driver_nl80211_probe_req_report(bss, 0);
6342		if (!drv->use_monitor)
6343			nl80211_mgmt_unsubscribe(bss, "AP teardown (dev SME)");
6344	} else if (drv->use_monitor)
6345		nl80211_remove_monitor_interface(drv);
6346	else
6347		nl80211_mgmt_unsubscribe(bss, "AP teardown");
6348
6349	bss->beacon_set = 0;
6350}
6351
6352
6353static int nl80211_send_eapol_data(struct i802_bss *bss,
6354				   const u8 *addr, const u8 *data,
6355				   size_t data_len)
6356{
6357	struct sockaddr_ll ll;
6358	int ret;
6359
6360	if (bss->drv->eapol_tx_sock < 0) {
6361		wpa_printf(MSG_DEBUG, "nl80211: No socket to send EAPOL");
6362		return -1;
6363	}
6364
6365	os_memset(&ll, 0, sizeof(ll));
6366	ll.sll_family = AF_PACKET;
6367	ll.sll_ifindex = bss->ifindex;
6368	ll.sll_protocol = htons(ETH_P_PAE);
6369	ll.sll_halen = ETH_ALEN;
6370	os_memcpy(ll.sll_addr, addr, ETH_ALEN);
6371	ret = sendto(bss->drv->eapol_tx_sock, data, data_len, 0,
6372		     (struct sockaddr *) &ll, sizeof(ll));
6373	if (ret < 0)
6374		wpa_printf(MSG_ERROR, "nl80211: EAPOL TX: %s",
6375			   strerror(errno));
6376
6377	return ret;
6378}
6379
6380
6381static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
6382
6383static int wpa_driver_nl80211_hapd_send_eapol(
6384	void *priv, const u8 *addr, const u8 *data,
6385	size_t data_len, int encrypt, const u8 *own_addr, u32 flags)
6386{
6387	struct i802_bss *bss = priv;
6388	struct wpa_driver_nl80211_data *drv = bss->drv;
6389	struct ieee80211_hdr *hdr;
6390	size_t len;
6391	u8 *pos;
6392	int res;
6393	int qos = flags & WPA_STA_WMM;
6394#ifndef ANDROID_P2P
6395	if (drv->device_ap_sme || !drv->use_monitor)
6396#else
6397	if (drv->device_ap_sme && !drv->use_monitor)
6398#endif
6399		return nl80211_send_eapol_data(bss, addr, data, data_len);
6400
6401	len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
6402		data_len;
6403	hdr = os_zalloc(len);
6404	if (hdr == NULL) {
6405		printf("malloc() failed for i802_send_data(len=%lu)\n",
6406		       (unsigned long) len);
6407		return -1;
6408	}
6409
6410	hdr->frame_control =
6411		IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
6412	hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
6413	if (encrypt)
6414		hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
6415	if (qos) {
6416		hdr->frame_control |=
6417			host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
6418	}
6419
6420	memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
6421	memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
6422	memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
6423	pos = (u8 *) (hdr + 1);
6424
6425	if (qos) {
6426		/* Set highest priority in QoS header */
6427		pos[0] = 7;
6428		pos[1] = 0;
6429		pos += 2;
6430	}
6431
6432	memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
6433	pos += sizeof(rfc1042_header);
6434	WPA_PUT_BE16(pos, ETH_P_PAE);
6435	pos += 2;
6436	memcpy(pos, data, data_len);
6437
6438	res = wpa_driver_nl80211_send_frame(bss, (u8 *) hdr, len, encrypt, 0,
6439					    0, 0, 0, 0);
6440	if (res < 0) {
6441		wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
6442			   "failed: %d (%s)",
6443			   (unsigned long) len, errno, strerror(errno));
6444	}
6445	os_free(hdr);
6446
6447	return res;
6448}
6449
6450
6451static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
6452					    int total_flags,
6453					    int flags_or, int flags_and)
6454{
6455	struct i802_bss *bss = priv;
6456	struct wpa_driver_nl80211_data *drv = bss->drv;
6457	struct nl_msg *msg, *flags = NULL;
6458	struct nl80211_sta_flag_update upd;
6459
6460	msg = nlmsg_alloc();
6461	if (!msg)
6462		return -ENOMEM;
6463
6464	flags = nlmsg_alloc();
6465	if (!flags) {
6466		nlmsg_free(msg);
6467		return -ENOMEM;
6468	}
6469
6470	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
6471
6472	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
6473		    if_nametoindex(bss->ifname));
6474	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
6475
6476	/*
6477	 * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
6478	 * can be removed eventually.
6479	 */
6480	if (total_flags & WPA_STA_AUTHORIZED)
6481		NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
6482
6483	if (total_flags & WPA_STA_WMM)
6484		NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
6485
6486	if (total_flags & WPA_STA_SHORT_PREAMBLE)
6487		NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
6488
6489	if (total_flags & WPA_STA_MFP)
6490		NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
6491
6492	if (total_flags & WPA_STA_TDLS_PEER)
6493		NLA_PUT_FLAG(flags, NL80211_STA_FLAG_TDLS_PEER);
6494
6495	if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
6496		goto nla_put_failure;
6497
6498	os_memset(&upd, 0, sizeof(upd));
6499	upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
6500	upd.set = sta_flags_nl80211(flags_or);
6501	NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
6502
6503	nlmsg_free(flags);
6504
6505	return send_and_recv_msgs(drv, msg, NULL, NULL);
6506 nla_put_failure:
6507	nlmsg_free(msg);
6508	nlmsg_free(flags);
6509	return -ENOBUFS;
6510}
6511
6512
6513static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
6514				 struct wpa_driver_associate_params *params)
6515{
6516	enum nl80211_iftype nlmode;
6517
6518	if (params->p2p) {
6519		wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
6520			   "group (GO)");
6521		nlmode = NL80211_IFTYPE_P2P_GO;
6522	} else
6523		nlmode = NL80211_IFTYPE_AP;
6524
6525	if (wpa_driver_nl80211_set_mode(&drv->first_bss, nlmode) ||
6526	    wpa_driver_nl80211_set_freq(&drv->first_bss, params->freq, 0, 0)) {
6527		nl80211_remove_monitor_interface(drv);
6528		return -1;
6529	}
6530
6531	return 0;
6532}
6533
6534
6535static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
6536{
6537	struct nl_msg *msg;
6538	int ret = -1;
6539
6540	msg = nlmsg_alloc();
6541	if (!msg)
6542		return -1;
6543
6544	nl80211_cmd(drv, msg, 0, NL80211_CMD_LEAVE_IBSS);
6545	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6546	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6547	msg = NULL;
6548	if (ret) {
6549		wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
6550			   "(%s)", ret, strerror(-ret));
6551		goto nla_put_failure;
6552	}
6553
6554	ret = 0;
6555	wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
6556
6557nla_put_failure:
6558	nlmsg_free(msg);
6559	return ret;
6560}
6561
6562
6563static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
6564				   struct wpa_driver_associate_params *params)
6565{
6566	struct nl_msg *msg;
6567	int ret = -1;
6568	int count = 0;
6569
6570	wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
6571
6572	if (wpa_driver_nl80211_set_mode(&drv->first_bss,
6573					NL80211_IFTYPE_ADHOC)) {
6574		wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
6575			   "IBSS mode");
6576		return -1;
6577	}
6578
6579retry:
6580	msg = nlmsg_alloc();
6581	if (!msg)
6582		return -1;
6583
6584	nl80211_cmd(drv, msg, 0, NL80211_CMD_JOIN_IBSS);
6585	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6586
6587	if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
6588		goto nla_put_failure;
6589
6590	wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6591			  params->ssid, params->ssid_len);
6592	NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6593		params->ssid);
6594	os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6595	drv->ssid_len = params->ssid_len;
6596
6597	wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6598	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6599
6600	ret = nl80211_set_conn_keys(params, msg);
6601	if (ret)
6602		goto nla_put_failure;
6603
6604	if (params->bssid && params->fixed_bssid) {
6605		wpa_printf(MSG_DEBUG, "  * BSSID=" MACSTR,
6606			   MAC2STR(params->bssid));
6607		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6608	}
6609
6610	if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
6611	    params->key_mgmt_suite == KEY_MGMT_PSK ||
6612	    params->key_mgmt_suite == KEY_MGMT_802_1X_SHA256 ||
6613	    params->key_mgmt_suite == KEY_MGMT_PSK_SHA256) {
6614		wpa_printf(MSG_DEBUG, "  * control port");
6615		NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
6616	}
6617
6618	if (params->wpa_ie) {
6619		wpa_hexdump(MSG_DEBUG,
6620			    "  * Extra IEs for Beacon/Probe Response frames",
6621			    params->wpa_ie, params->wpa_ie_len);
6622		NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6623			params->wpa_ie);
6624	}
6625
6626	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6627	msg = NULL;
6628	if (ret) {
6629		wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
6630			   ret, strerror(-ret));
6631		count++;
6632		if (ret == -EALREADY && count == 1) {
6633			wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
6634				   "forced leave");
6635			nl80211_leave_ibss(drv);
6636			nlmsg_free(msg);
6637			goto retry;
6638		}
6639
6640		goto nla_put_failure;
6641	}
6642	ret = 0;
6643	wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
6644
6645nla_put_failure:
6646	nlmsg_free(msg);
6647	return ret;
6648}
6649
6650
6651static unsigned int nl80211_get_assoc_bssid(struct wpa_driver_nl80211_data *drv,
6652					    u8 *bssid)
6653{
6654	struct nl_msg *msg;
6655	int ret;
6656	struct nl80211_bss_info_arg arg;
6657
6658	os_memset(&arg, 0, sizeof(arg));
6659	msg = nlmsg_alloc();
6660	if (!msg)
6661		goto nla_put_failure;
6662
6663	nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
6664	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6665
6666	arg.drv = drv;
6667	ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
6668	msg = NULL;
6669	if (ret == 0) {
6670		if (is_zero_ether_addr(arg.assoc_bssid))
6671			return -ENOTCONN;
6672		os_memcpy(bssid, arg.assoc_bssid, ETH_ALEN);
6673		return 0;
6674	}
6675	wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
6676		   "(%s)", ret, strerror(-ret));
6677nla_put_failure:
6678	nlmsg_free(msg);
6679	return drv->assoc_freq;
6680}
6681
6682
6683static int nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
6684			      const u8 *bssid)
6685{
6686	u8 addr[ETH_ALEN];
6687
6688	if (bssid == NULL) {
6689		int res = nl80211_get_assoc_bssid(drv, addr);
6690		if (res)
6691			return res;
6692		bssid = addr;
6693	}
6694
6695	return wpa_driver_nl80211_disconnect(drv, bssid,
6696					     WLAN_REASON_PREV_AUTH_NOT_VALID);
6697}
6698
6699
6700static int wpa_driver_nl80211_connect(
6701	struct wpa_driver_nl80211_data *drv,
6702	struct wpa_driver_associate_params *params)
6703{
6704	struct nl_msg *msg;
6705	enum nl80211_auth_type type;
6706	int ret = 0;
6707	int algs;
6708
6709	msg = nlmsg_alloc();
6710	if (!msg)
6711		return -1;
6712
6713	wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
6714	nl80211_cmd(drv, msg, 0, NL80211_CMD_CONNECT);
6715
6716	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6717	if (params->bssid) {
6718		wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
6719			   MAC2STR(params->bssid));
6720		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6721	}
6722	if (params->freq) {
6723		wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6724		NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6725	}
6726	if (params->bg_scan_period >= 0) {
6727		wpa_printf(MSG_DEBUG, "  * bg scan period=%d",
6728			   params->bg_scan_period);
6729		NLA_PUT_U16(msg, NL80211_ATTR_BG_SCAN_PERIOD,
6730			    params->bg_scan_period);
6731	}
6732	if (params->ssid) {
6733		wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6734				  params->ssid, params->ssid_len);
6735		NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6736			params->ssid);
6737		if (params->ssid_len > sizeof(drv->ssid))
6738			goto nla_put_failure;
6739		os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6740		drv->ssid_len = params->ssid_len;
6741	}
6742	wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
6743	if (params->wpa_ie)
6744		NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6745			params->wpa_ie);
6746
6747	algs = 0;
6748	if (params->auth_alg & WPA_AUTH_ALG_OPEN)
6749		algs++;
6750	if (params->auth_alg & WPA_AUTH_ALG_SHARED)
6751		algs++;
6752	if (params->auth_alg & WPA_AUTH_ALG_LEAP)
6753		algs++;
6754	if (algs > 1) {
6755		wpa_printf(MSG_DEBUG, "  * Leave out Auth Type for automatic "
6756			   "selection");
6757		goto skip_auth_type;
6758	}
6759
6760	if (params->auth_alg & WPA_AUTH_ALG_OPEN)
6761		type = NL80211_AUTHTYPE_OPEN_SYSTEM;
6762	else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
6763		type = NL80211_AUTHTYPE_SHARED_KEY;
6764	else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
6765		type = NL80211_AUTHTYPE_NETWORK_EAP;
6766	else if (params->auth_alg & WPA_AUTH_ALG_FT)
6767		type = NL80211_AUTHTYPE_FT;
6768	else
6769		goto nla_put_failure;
6770
6771	wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
6772	NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
6773
6774skip_auth_type:
6775	if (params->wpa_proto) {
6776		enum nl80211_wpa_versions ver = 0;
6777
6778		if (params->wpa_proto & WPA_PROTO_WPA)
6779			ver |= NL80211_WPA_VERSION_1;
6780		if (params->wpa_proto & WPA_PROTO_RSN)
6781			ver |= NL80211_WPA_VERSION_2;
6782
6783		wpa_printf(MSG_DEBUG, "  * WPA Versions 0x%x", ver);
6784		NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
6785	}
6786
6787	if (params->pairwise_suite != CIPHER_NONE) {
6788		int cipher;
6789
6790		switch (params->pairwise_suite) {
6791		case CIPHER_WEP40:
6792			cipher = WLAN_CIPHER_SUITE_WEP40;
6793			break;
6794		case CIPHER_WEP104:
6795			cipher = WLAN_CIPHER_SUITE_WEP104;
6796			break;
6797		case CIPHER_CCMP:
6798			cipher = WLAN_CIPHER_SUITE_CCMP;
6799			break;
6800		case CIPHER_GCMP:
6801			cipher = WLAN_CIPHER_SUITE_GCMP;
6802			break;
6803		case CIPHER_TKIP:
6804		default:
6805			cipher = WLAN_CIPHER_SUITE_TKIP;
6806			break;
6807		}
6808		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
6809	}
6810
6811	if (params->group_suite != CIPHER_NONE) {
6812		int cipher;
6813
6814		switch (params->group_suite) {
6815		case CIPHER_WEP40:
6816			cipher = WLAN_CIPHER_SUITE_WEP40;
6817			break;
6818		case CIPHER_WEP104:
6819			cipher = WLAN_CIPHER_SUITE_WEP104;
6820			break;
6821		case CIPHER_CCMP:
6822			cipher = WLAN_CIPHER_SUITE_CCMP;
6823			break;
6824		case CIPHER_GCMP:
6825			cipher = WLAN_CIPHER_SUITE_GCMP;
6826			break;
6827		case CIPHER_TKIP:
6828		default:
6829			cipher = WLAN_CIPHER_SUITE_TKIP;
6830			break;
6831		}
6832		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
6833	}
6834
6835	if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
6836	    params->key_mgmt_suite == KEY_MGMT_PSK) {
6837		int mgmt = WLAN_AKM_SUITE_PSK;
6838
6839		switch (params->key_mgmt_suite) {
6840		case KEY_MGMT_802_1X:
6841			mgmt = WLAN_AKM_SUITE_8021X;
6842			break;
6843		case KEY_MGMT_PSK:
6844		default:
6845			mgmt = WLAN_AKM_SUITE_PSK;
6846			break;
6847		}
6848		NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
6849	}
6850
6851	if (params->disable_ht)
6852		NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
6853
6854	if (params->htcaps && params->htcaps_mask) {
6855		int sz = sizeof(struct ieee80211_ht_capabilities);
6856		NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
6857		NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
6858			params->htcaps_mask);
6859	}
6860
6861	ret = nl80211_set_conn_keys(params, msg);
6862	if (ret)
6863		goto nla_put_failure;
6864
6865	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6866	msg = NULL;
6867	if (ret) {
6868		wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
6869			   "(%s)", ret, strerror(-ret));
6870		/*
6871		 * cfg80211 does not currently accept new connection if we are
6872		 * already connected. As a workaround, force disconnection and
6873		 * try again once the driver indicates it completed
6874		 * disconnection.
6875		 */
6876		if (ret == -EALREADY)
6877			nl80211_disconnect(drv, params->bssid);
6878		goto nla_put_failure;
6879	}
6880	ret = 0;
6881	wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
6882
6883nla_put_failure:
6884	nlmsg_free(msg);
6885	return ret;
6886
6887}
6888
6889
6890static int wpa_driver_nl80211_associate(
6891	void *priv, struct wpa_driver_associate_params *params)
6892{
6893	struct i802_bss *bss = priv;
6894	struct wpa_driver_nl80211_data *drv = bss->drv;
6895	int ret = -1;
6896	struct nl_msg *msg;
6897
6898	if (params->mode == IEEE80211_MODE_AP)
6899		return wpa_driver_nl80211_ap(drv, params);
6900
6901	if (params->mode == IEEE80211_MODE_IBSS)
6902		return wpa_driver_nl80211_ibss(drv, params);
6903
6904	if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
6905		enum nl80211_iftype nlmode = params->p2p ?
6906			NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
6907
6908		if (wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
6909			return -1;
6910		return wpa_driver_nl80211_connect(drv, params);
6911	}
6912
6913	drv->associated = 0;
6914
6915	msg = nlmsg_alloc();
6916	if (!msg)
6917		return -1;
6918
6919	wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
6920		   drv->ifindex);
6921	nl80211_cmd(drv, msg, 0, NL80211_CMD_ASSOCIATE);
6922
6923	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6924	if (params->bssid) {
6925		wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
6926			   MAC2STR(params->bssid));
6927		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6928	}
6929	if (params->freq) {
6930		wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6931		NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6932		drv->assoc_freq = params->freq;
6933	} else
6934		drv->assoc_freq = 0;
6935	if (params->bg_scan_period >= 0) {
6936		wpa_printf(MSG_DEBUG, "  * bg scan period=%d",
6937			   params->bg_scan_period);
6938		NLA_PUT_U16(msg, NL80211_ATTR_BG_SCAN_PERIOD,
6939			    params->bg_scan_period);
6940	}
6941	if (params->ssid) {
6942		wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6943				  params->ssid, params->ssid_len);
6944		NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6945			params->ssid);
6946		if (params->ssid_len > sizeof(drv->ssid))
6947			goto nla_put_failure;
6948		os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6949		drv->ssid_len = params->ssid_len;
6950	}
6951	wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
6952	if (params->wpa_ie)
6953		NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6954			params->wpa_ie);
6955
6956	if (params->pairwise_suite != CIPHER_NONE) {
6957		int cipher;
6958
6959		switch (params->pairwise_suite) {
6960		case CIPHER_WEP40:
6961			cipher = WLAN_CIPHER_SUITE_WEP40;
6962			break;
6963		case CIPHER_WEP104:
6964			cipher = WLAN_CIPHER_SUITE_WEP104;
6965			break;
6966		case CIPHER_CCMP:
6967			cipher = WLAN_CIPHER_SUITE_CCMP;
6968			break;
6969		case CIPHER_GCMP:
6970			cipher = WLAN_CIPHER_SUITE_GCMP;
6971			break;
6972		case CIPHER_TKIP:
6973		default:
6974			cipher = WLAN_CIPHER_SUITE_TKIP;
6975			break;
6976		}
6977		wpa_printf(MSG_DEBUG, "  * pairwise=0x%x", cipher);
6978		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
6979	}
6980
6981	if (params->group_suite != CIPHER_NONE) {
6982		int cipher;
6983
6984		switch (params->group_suite) {
6985		case CIPHER_WEP40:
6986			cipher = WLAN_CIPHER_SUITE_WEP40;
6987			break;
6988		case CIPHER_WEP104:
6989			cipher = WLAN_CIPHER_SUITE_WEP104;
6990			break;
6991		case CIPHER_CCMP:
6992			cipher = WLAN_CIPHER_SUITE_CCMP;
6993			break;
6994		case CIPHER_GCMP:
6995			cipher = WLAN_CIPHER_SUITE_GCMP;
6996			break;
6997		case CIPHER_TKIP:
6998		default:
6999			cipher = WLAN_CIPHER_SUITE_TKIP;
7000			break;
7001		}
7002		wpa_printf(MSG_DEBUG, "  * group=0x%x", cipher);
7003		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
7004	}
7005
7006#ifdef CONFIG_IEEE80211W
7007	if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
7008		NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
7009#endif /* CONFIG_IEEE80211W */
7010
7011	NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
7012
7013	if (params->prev_bssid) {
7014		wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
7015			   MAC2STR(params->prev_bssid));
7016		NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
7017			params->prev_bssid);
7018	}
7019
7020	if (params->disable_ht)
7021		NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
7022
7023	if (params->htcaps && params->htcaps_mask) {
7024		int sz = sizeof(struct ieee80211_ht_capabilities);
7025		NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
7026		NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
7027			params->htcaps_mask);
7028	}
7029
7030	if (params->p2p)
7031		wpa_printf(MSG_DEBUG, "  * P2P group");
7032
7033	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7034	msg = NULL;
7035	if (ret) {
7036		wpa_dbg(drv->ctx, MSG_DEBUG,
7037			"nl80211: MLME command failed (assoc): ret=%d (%s)",
7038			ret, strerror(-ret));
7039		nl80211_dump_scan(drv);
7040		goto nla_put_failure;
7041	}
7042	ret = 0;
7043	wpa_printf(MSG_DEBUG, "nl80211: Association request send "
7044		   "successfully");
7045
7046nla_put_failure:
7047	nlmsg_free(msg);
7048	return ret;
7049}
7050
7051
7052static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
7053			    int ifindex, enum nl80211_iftype mode)
7054{
7055	struct nl_msg *msg;
7056	int ret = -ENOBUFS;
7057
7058	wpa_printf(MSG_DEBUG, "nl80211: Set mode ifindex %d iftype %d (%s)",
7059		   ifindex, mode, nl80211_iftype_str(mode));
7060
7061	msg = nlmsg_alloc();
7062	if (!msg)
7063		return -ENOMEM;
7064
7065	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_INTERFACE);
7066	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
7067	NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
7068
7069	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7070	msg = NULL;
7071	if (!ret)
7072		return 0;
7073nla_put_failure:
7074	nlmsg_free(msg);
7075	wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
7076		   " %d (%s)", ifindex, mode, ret, strerror(-ret));
7077	return ret;
7078}
7079
7080
7081static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
7082				       enum nl80211_iftype nlmode)
7083{
7084	struct wpa_driver_nl80211_data *drv = bss->drv;
7085	int ret = -1;
7086	int i;
7087	int was_ap = is_ap_interface(drv->nlmode);
7088	int res;
7089
7090	res = nl80211_set_mode(drv, drv->ifindex, nlmode);
7091	if (res == 0) {
7092		drv->nlmode = nlmode;
7093		ret = 0;
7094		goto done;
7095	}
7096
7097	if (res == -ENODEV)
7098		return -1;
7099
7100	if (nlmode == drv->nlmode) {
7101		wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
7102			   "requested mode - ignore error");
7103		ret = 0;
7104		goto done; /* Already in the requested mode */
7105	}
7106
7107	/* mac80211 doesn't allow mode changes while the device is up, so
7108	 * take the device down, try to set the mode again, and bring the
7109	 * device back up.
7110	 */
7111	wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
7112		   "interface down");
7113	for (i = 0; i < 10; i++) {
7114		res = linux_set_iface_flags(drv->global->ioctl_sock,
7115					    bss->ifname, 0);
7116		if (res == -EACCES || res == -ENODEV)
7117			break;
7118		if (res == 0) {
7119			/* Try to set the mode again while the interface is
7120			 * down */
7121			ret = nl80211_set_mode(drv, drv->ifindex, nlmode);
7122			if (ret == -EACCES)
7123				break;
7124			res = linux_set_iface_flags(drv->global->ioctl_sock,
7125						    bss->ifname, 1);
7126			if (res && !ret)
7127				ret = -1;
7128			else if (ret != -EBUSY)
7129				break;
7130		} else
7131			wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
7132				   "interface down");
7133		os_sleep(0, 100000);
7134	}
7135
7136	if (!ret) {
7137		wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
7138			   "interface is down");
7139		drv->nlmode = nlmode;
7140		drv->ignore_if_down_event = 1;
7141	}
7142
7143done:
7144	if (ret) {
7145		wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
7146			   "from %d failed", nlmode, drv->nlmode);
7147		return ret;
7148	}
7149
7150	if (is_p2p_interface(nlmode))
7151		nl80211_disable_11b_rates(drv, drv->ifindex, 1);
7152	else if (drv->disabled_11b_rates)
7153		nl80211_disable_11b_rates(drv, drv->ifindex, 0);
7154
7155	if (is_ap_interface(nlmode)) {
7156		nl80211_mgmt_unsubscribe(bss, "start AP");
7157		/* Setup additional AP mode functionality if needed */
7158		if (nl80211_setup_ap(bss))
7159			return -1;
7160	} else if (was_ap) {
7161		/* Remove additional AP mode functionality */
7162		nl80211_teardown_ap(bss);
7163	} else {
7164		nl80211_mgmt_unsubscribe(bss, "mode change");
7165	}
7166
7167	if (!bss->in_deinit && !is_ap_interface(nlmode) &&
7168	    nl80211_mgmt_subscribe_non_ap(bss) < 0)
7169		wpa_printf(MSG_DEBUG, "nl80211: Failed to register Action "
7170			   "frame processing - ignore for now");
7171
7172	return 0;
7173}
7174
7175
7176static int wpa_driver_nl80211_get_capa(void *priv,
7177				       struct wpa_driver_capa *capa)
7178{
7179	struct i802_bss *bss = priv;
7180	struct wpa_driver_nl80211_data *drv = bss->drv;
7181	if (!drv->has_capability)
7182		return -1;
7183	os_memcpy(capa, &drv->capa, sizeof(*capa));
7184	return 0;
7185}
7186
7187
7188static int wpa_driver_nl80211_set_operstate(void *priv, int state)
7189{
7190	struct i802_bss *bss = priv;
7191	struct wpa_driver_nl80211_data *drv = bss->drv;
7192
7193	wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
7194		   __func__, drv->operstate, state, state ? "UP" : "DORMANT");
7195	drv->operstate = state;
7196	return netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, -1,
7197				      state ? IF_OPER_UP : IF_OPER_DORMANT);
7198}
7199
7200
7201static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
7202{
7203	struct i802_bss *bss = priv;
7204	struct wpa_driver_nl80211_data *drv = bss->drv;
7205	struct nl_msg *msg;
7206	struct nl80211_sta_flag_update upd;
7207
7208	msg = nlmsg_alloc();
7209	if (!msg)
7210		return -ENOMEM;
7211
7212	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
7213
7214	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7215		    if_nametoindex(bss->ifname));
7216	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
7217
7218	os_memset(&upd, 0, sizeof(upd));
7219	upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
7220	if (authorized)
7221		upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
7222	NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
7223
7224	return send_and_recv_msgs(drv, msg, NULL, NULL);
7225 nla_put_failure:
7226	nlmsg_free(msg);
7227	return -ENOBUFS;
7228}
7229
7230
7231/* Set kernel driver on given frequency (MHz) */
7232static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
7233{
7234	struct i802_bss *bss = priv;
7235	return wpa_driver_nl80211_set_freq(bss, freq->freq, freq->ht_enabled,
7236					   freq->sec_channel_offset);
7237}
7238
7239
7240#if defined(HOSTAPD) || defined(CONFIG_AP)
7241
7242static inline int min_int(int a, int b)
7243{
7244	if (a < b)
7245		return a;
7246	return b;
7247}
7248
7249
7250static int get_key_handler(struct nl_msg *msg, void *arg)
7251{
7252	struct nlattr *tb[NL80211_ATTR_MAX + 1];
7253	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7254
7255	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7256		  genlmsg_attrlen(gnlh, 0), NULL);
7257
7258	/*
7259	 * TODO: validate the key index and mac address!
7260	 * Otherwise, there's a race condition as soon as
7261	 * the kernel starts sending key notifications.
7262	 */
7263
7264	if (tb[NL80211_ATTR_KEY_SEQ])
7265		memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
7266		       min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
7267	return NL_SKIP;
7268}
7269
7270
7271static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
7272			   int idx, u8 *seq)
7273{
7274	struct i802_bss *bss = priv;
7275	struct wpa_driver_nl80211_data *drv = bss->drv;
7276	struct nl_msg *msg;
7277
7278	msg = nlmsg_alloc();
7279	if (!msg)
7280		return -ENOMEM;
7281
7282	nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_KEY);
7283
7284	if (addr)
7285		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7286	NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
7287	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
7288
7289	memset(seq, 0, 6);
7290
7291	return send_and_recv_msgs(drv, msg, get_key_handler, seq);
7292 nla_put_failure:
7293	nlmsg_free(msg);
7294	return -ENOBUFS;
7295}
7296
7297
7298static int i802_set_rts(void *priv, int rts)
7299{
7300	struct i802_bss *bss = priv;
7301	struct wpa_driver_nl80211_data *drv = bss->drv;
7302	struct nl_msg *msg;
7303	int ret = -ENOBUFS;
7304	u32 val;
7305
7306	msg = nlmsg_alloc();
7307	if (!msg)
7308		return -ENOMEM;
7309
7310	if (rts >= 2347)
7311		val = (u32) -1;
7312	else
7313		val = rts;
7314
7315	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7316	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7317	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
7318
7319	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7320	msg = NULL;
7321	if (!ret)
7322		return 0;
7323nla_put_failure:
7324	nlmsg_free(msg);
7325	wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
7326		   "%d (%s)", rts, ret, strerror(-ret));
7327	return ret;
7328}
7329
7330
7331static int i802_set_frag(void *priv, int frag)
7332{
7333	struct i802_bss *bss = priv;
7334	struct wpa_driver_nl80211_data *drv = bss->drv;
7335	struct nl_msg *msg;
7336	int ret = -ENOBUFS;
7337	u32 val;
7338
7339	msg = nlmsg_alloc();
7340	if (!msg)
7341		return -ENOMEM;
7342
7343	if (frag >= 2346)
7344		val = (u32) -1;
7345	else
7346		val = frag;
7347
7348	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7349	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7350	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
7351
7352	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7353	msg = NULL;
7354	if (!ret)
7355		return 0;
7356nla_put_failure:
7357	nlmsg_free(msg);
7358	wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
7359		   "%d: %d (%s)", frag, ret, strerror(-ret));
7360	return ret;
7361}
7362
7363
7364static int i802_flush(void *priv)
7365{
7366	struct i802_bss *bss = priv;
7367	struct wpa_driver_nl80211_data *drv = bss->drv;
7368	struct nl_msg *msg;
7369	int res;
7370
7371	msg = nlmsg_alloc();
7372	if (!msg)
7373		return -1;
7374
7375	nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
7376
7377	/*
7378	 * XXX: FIX! this needs to flush all VLANs too
7379	 */
7380	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7381		    if_nametoindex(bss->ifname));
7382
7383	res = send_and_recv_msgs(drv, msg, NULL, NULL);
7384	if (res) {
7385		wpa_printf(MSG_DEBUG, "nl80211: Station flush failed: ret=%d "
7386			   "(%s)", res, strerror(-res));
7387	}
7388	return res;
7389 nla_put_failure:
7390	nlmsg_free(msg);
7391	return -ENOBUFS;
7392}
7393
7394#endif /* HOSTAPD || CONFIG_AP */
7395
7396
7397static int get_sta_handler(struct nl_msg *msg, void *arg)
7398{
7399	struct nlattr *tb[NL80211_ATTR_MAX + 1];
7400	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7401	struct hostap_sta_driver_data *data = arg;
7402	struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
7403	static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
7404		[NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
7405		[NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
7406		[NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
7407		[NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
7408		[NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
7409		[NL80211_STA_INFO_TX_FAILED] = { .type = NLA_U32 },
7410	};
7411
7412	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7413		  genlmsg_attrlen(gnlh, 0), NULL);
7414
7415	/*
7416	 * TODO: validate the interface and mac address!
7417	 * Otherwise, there's a race condition as soon as
7418	 * the kernel starts sending station notifications.
7419	 */
7420
7421	if (!tb[NL80211_ATTR_STA_INFO]) {
7422		wpa_printf(MSG_DEBUG, "sta stats missing!");
7423		return NL_SKIP;
7424	}
7425	if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
7426			     tb[NL80211_ATTR_STA_INFO],
7427			     stats_policy)) {
7428		wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
7429		return NL_SKIP;
7430	}
7431
7432	if (stats[NL80211_STA_INFO_INACTIVE_TIME])
7433		data->inactive_msec =
7434			nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
7435	if (stats[NL80211_STA_INFO_RX_BYTES])
7436		data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
7437	if (stats[NL80211_STA_INFO_TX_BYTES])
7438		data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
7439	if (stats[NL80211_STA_INFO_RX_PACKETS])
7440		data->rx_packets =
7441			nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
7442	if (stats[NL80211_STA_INFO_TX_PACKETS])
7443		data->tx_packets =
7444			nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
7445	if (stats[NL80211_STA_INFO_TX_FAILED])
7446		data->tx_retry_failed =
7447			nla_get_u32(stats[NL80211_STA_INFO_TX_FAILED]);
7448
7449	return NL_SKIP;
7450}
7451
7452static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
7453			      const u8 *addr)
7454{
7455	struct i802_bss *bss = priv;
7456	struct wpa_driver_nl80211_data *drv = bss->drv;
7457	struct nl_msg *msg;
7458
7459	os_memset(data, 0, sizeof(*data));
7460	msg = nlmsg_alloc();
7461	if (!msg)
7462		return -ENOMEM;
7463
7464	nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
7465
7466	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7467	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7468
7469	return send_and_recv_msgs(drv, msg, get_sta_handler, data);
7470 nla_put_failure:
7471	nlmsg_free(msg);
7472	return -ENOBUFS;
7473}
7474
7475
7476#if defined(HOSTAPD) || defined(CONFIG_AP)
7477
7478static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
7479				    int cw_min, int cw_max, int burst_time)
7480{
7481	struct i802_bss *bss = priv;
7482	struct wpa_driver_nl80211_data *drv = bss->drv;
7483	struct nl_msg *msg;
7484	struct nlattr *txq, *params;
7485
7486	msg = nlmsg_alloc();
7487	if (!msg)
7488		return -1;
7489
7490	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7491
7492	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7493
7494	txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
7495	if (!txq)
7496		goto nla_put_failure;
7497
7498	/* We are only sending parameters for a single TXQ at a time */
7499	params = nla_nest_start(msg, 1);
7500	if (!params)
7501		goto nla_put_failure;
7502
7503	switch (queue) {
7504	case 0:
7505		NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
7506		break;
7507	case 1:
7508		NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
7509		break;
7510	case 2:
7511		NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
7512		break;
7513	case 3:
7514		NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
7515		break;
7516	}
7517	/* Burst time is configured in units of 0.1 msec and TXOP parameter in
7518	 * 32 usec, so need to convert the value here. */
7519	NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
7520	NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
7521	NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
7522	NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
7523
7524	nla_nest_end(msg, params);
7525
7526	nla_nest_end(msg, txq);
7527
7528	if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
7529		return 0;
7530	msg = NULL;
7531 nla_put_failure:
7532	nlmsg_free(msg);
7533	return -1;
7534}
7535
7536
7537static int i802_set_sta_vlan(void *priv, const u8 *addr,
7538			     const char *ifname, int vlan_id)
7539{
7540	struct i802_bss *bss = priv;
7541	struct wpa_driver_nl80211_data *drv = bss->drv;
7542	struct nl_msg *msg;
7543	int ret = -ENOBUFS;
7544
7545	msg = nlmsg_alloc();
7546	if (!msg)
7547		return -ENOMEM;
7548
7549	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
7550
7551	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7552		    if_nametoindex(bss->ifname));
7553	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7554	NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
7555		    if_nametoindex(ifname));
7556
7557	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7558	msg = NULL;
7559	if (ret < 0) {
7560		wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
7561			   MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
7562			   MAC2STR(addr), ifname, vlan_id, ret,
7563			   strerror(-ret));
7564	}
7565 nla_put_failure:
7566	nlmsg_free(msg);
7567	return ret;
7568}
7569
7570
7571static int i802_get_inact_sec(void *priv, const u8 *addr)
7572{
7573	struct hostap_sta_driver_data data;
7574	int ret;
7575
7576	data.inactive_msec = (unsigned long) -1;
7577	ret = i802_read_sta_data(priv, &data, addr);
7578	if (ret || data.inactive_msec == (unsigned long) -1)
7579		return -1;
7580	return data.inactive_msec / 1000;
7581}
7582
7583
7584static int i802_sta_clear_stats(void *priv, const u8 *addr)
7585{
7586#if 0
7587	/* TODO */
7588#endif
7589	return 0;
7590}
7591
7592
7593static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
7594			   int reason)
7595{
7596	struct i802_bss *bss = priv;
7597	struct wpa_driver_nl80211_data *drv = bss->drv;
7598	struct ieee80211_mgmt mgmt;
7599
7600	if (drv->device_ap_sme)
7601		return wpa_driver_nl80211_sta_remove(bss, addr);
7602
7603	memset(&mgmt, 0, sizeof(mgmt));
7604	mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
7605					  WLAN_FC_STYPE_DEAUTH);
7606	memcpy(mgmt.da, addr, ETH_ALEN);
7607	memcpy(mgmt.sa, own_addr, ETH_ALEN);
7608	memcpy(mgmt.bssid, own_addr, ETH_ALEN);
7609	mgmt.u.deauth.reason_code = host_to_le16(reason);
7610	return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
7611					    IEEE80211_HDRLEN +
7612					    sizeof(mgmt.u.deauth), 0);
7613}
7614
7615
7616static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
7617			     int reason)
7618{
7619	struct i802_bss *bss = priv;
7620	struct wpa_driver_nl80211_data *drv = bss->drv;
7621	struct ieee80211_mgmt mgmt;
7622
7623	if (drv->device_ap_sme)
7624		return wpa_driver_nl80211_sta_remove(bss, addr);
7625
7626	memset(&mgmt, 0, sizeof(mgmt));
7627	mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
7628					  WLAN_FC_STYPE_DISASSOC);
7629	memcpy(mgmt.da, addr, ETH_ALEN);
7630	memcpy(mgmt.sa, own_addr, ETH_ALEN);
7631	memcpy(mgmt.bssid, own_addr, ETH_ALEN);
7632	mgmt.u.disassoc.reason_code = host_to_le16(reason);
7633	return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
7634					    IEEE80211_HDRLEN +
7635					    sizeof(mgmt.u.disassoc), 0);
7636}
7637
7638#endif /* HOSTAPD || CONFIG_AP */
7639
7640#ifdef HOSTAPD
7641
7642static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7643{
7644	int i;
7645	int *old;
7646
7647	wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
7648		   ifidx);
7649	for (i = 0; i < drv->num_if_indices; i++) {
7650		if (drv->if_indices[i] == 0) {
7651			drv->if_indices[i] = ifidx;
7652			return;
7653		}
7654	}
7655
7656	if (drv->if_indices != drv->default_if_indices)
7657		old = drv->if_indices;
7658	else
7659		old = NULL;
7660
7661	drv->if_indices = os_realloc_array(old, drv->num_if_indices + 1,
7662					   sizeof(int));
7663	if (!drv->if_indices) {
7664		if (!old)
7665			drv->if_indices = drv->default_if_indices;
7666		else
7667			drv->if_indices = old;
7668		wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
7669			   "interfaces");
7670		wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
7671		return;
7672	} else if (!old)
7673		os_memcpy(drv->if_indices, drv->default_if_indices,
7674			  sizeof(drv->default_if_indices));
7675	drv->if_indices[drv->num_if_indices] = ifidx;
7676	drv->num_if_indices++;
7677}
7678
7679
7680static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7681{
7682	int i;
7683
7684	for (i = 0; i < drv->num_if_indices; i++) {
7685		if (drv->if_indices[i] == ifidx) {
7686			drv->if_indices[i] = 0;
7687			break;
7688		}
7689	}
7690}
7691
7692
7693static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7694{
7695	int i;
7696
7697	for (i = 0; i < drv->num_if_indices; i++)
7698		if (drv->if_indices[i] == ifidx)
7699			return 1;
7700
7701	return 0;
7702}
7703
7704
7705static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
7706                            const char *bridge_ifname)
7707{
7708	struct i802_bss *bss = priv;
7709	struct wpa_driver_nl80211_data *drv = bss->drv;
7710	char name[IFNAMSIZ + 1];
7711
7712	os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
7713	wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
7714		   " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
7715	if (val) {
7716		if (!if_nametoindex(name)) {
7717			if (nl80211_create_iface(drv, name,
7718						 NL80211_IFTYPE_AP_VLAN,
7719						 NULL, 1) < 0)
7720				return -1;
7721			if (bridge_ifname &&
7722			    linux_br_add_if(drv->global->ioctl_sock,
7723					    bridge_ifname, name) < 0)
7724				return -1;
7725		}
7726		if (linux_set_iface_flags(drv->global->ioctl_sock, name, 1)) {
7727			wpa_printf(MSG_ERROR, "nl80211: Failed to set WDS STA "
7728				   "interface %s up", name);
7729		}
7730		return i802_set_sta_vlan(priv, addr, name, 0);
7731	} else {
7732		if (bridge_ifname)
7733			linux_br_del_if(drv->global->ioctl_sock, bridge_ifname,
7734					name);
7735
7736		i802_set_sta_vlan(priv, addr, bss->ifname, 0);
7737		return wpa_driver_nl80211_if_remove(priv, WPA_IF_AP_VLAN,
7738						    name);
7739	}
7740}
7741
7742
7743static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
7744{
7745	struct wpa_driver_nl80211_data *drv = eloop_ctx;
7746	struct sockaddr_ll lladdr;
7747	unsigned char buf[3000];
7748	int len;
7749	socklen_t fromlen = sizeof(lladdr);
7750
7751	len = recvfrom(sock, buf, sizeof(buf), 0,
7752		       (struct sockaddr *)&lladdr, &fromlen);
7753	if (len < 0) {
7754		perror("recv");
7755		return;
7756	}
7757
7758	if (have_ifidx(drv, lladdr.sll_ifindex))
7759		drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
7760}
7761
7762
7763static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
7764			     struct i802_bss *bss,
7765			     const char *brname, const char *ifname)
7766{
7767	int ifindex;
7768	char in_br[IFNAMSIZ];
7769
7770	os_strlcpy(bss->brname, brname, IFNAMSIZ);
7771	ifindex = if_nametoindex(brname);
7772	if (ifindex == 0) {
7773		/*
7774		 * Bridge was configured, but the bridge device does
7775		 * not exist. Try to add it now.
7776		 */
7777		if (linux_br_add(drv->global->ioctl_sock, brname) < 0) {
7778			wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
7779				   "bridge interface %s: %s",
7780				   brname, strerror(errno));
7781			return -1;
7782		}
7783		bss->added_bridge = 1;
7784		add_ifidx(drv, if_nametoindex(brname));
7785	}
7786
7787	if (linux_br_get(in_br, ifname) == 0) {
7788		if (os_strcmp(in_br, brname) == 0)
7789			return 0; /* already in the bridge */
7790
7791		wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
7792			   "bridge %s", ifname, in_br);
7793		if (linux_br_del_if(drv->global->ioctl_sock, in_br, ifname) <
7794		    0) {
7795			wpa_printf(MSG_ERROR, "nl80211: Failed to "
7796				   "remove interface %s from bridge "
7797				   "%s: %s",
7798				   ifname, brname, strerror(errno));
7799			return -1;
7800		}
7801	}
7802
7803	wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
7804		   ifname, brname);
7805	if (linux_br_add_if(drv->global->ioctl_sock, brname, ifname) < 0) {
7806		wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
7807			   "into bridge %s: %s",
7808			   ifname, brname, strerror(errno));
7809		return -1;
7810	}
7811	bss->added_if_into_bridge = 1;
7812
7813	return 0;
7814}
7815
7816
7817static void *i802_init(struct hostapd_data *hapd,
7818		       struct wpa_init_params *params)
7819{
7820	struct wpa_driver_nl80211_data *drv;
7821	struct i802_bss *bss;
7822	size_t i;
7823	char brname[IFNAMSIZ];
7824	int ifindex, br_ifindex;
7825	int br_added = 0;
7826
7827	bss = wpa_driver_nl80211_init(hapd, params->ifname,
7828				      params->global_priv);
7829	if (bss == NULL)
7830		return NULL;
7831
7832	drv = bss->drv;
7833	drv->nlmode = NL80211_IFTYPE_AP;
7834	drv->eapol_sock = -1;
7835
7836	if (linux_br_get(brname, params->ifname) == 0) {
7837		wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
7838			   params->ifname, brname);
7839		br_ifindex = if_nametoindex(brname);
7840	} else {
7841		brname[0] = '\0';
7842		br_ifindex = 0;
7843	}
7844
7845	drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
7846	drv->if_indices = drv->default_if_indices;
7847	for (i = 0; i < params->num_bridge; i++) {
7848		if (params->bridge[i]) {
7849			ifindex = if_nametoindex(params->bridge[i]);
7850			if (ifindex)
7851				add_ifidx(drv, ifindex);
7852			if (ifindex == br_ifindex)
7853				br_added = 1;
7854		}
7855	}
7856	if (!br_added && br_ifindex &&
7857	    (params->num_bridge == 0 || !params->bridge[0]))
7858		add_ifidx(drv, br_ifindex);
7859
7860	/* start listening for EAPOL on the default AP interface */
7861	add_ifidx(drv, drv->ifindex);
7862
7863	if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0))
7864		goto failed;
7865
7866	if (params->bssid) {
7867		if (linux_set_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7868				       params->bssid))
7869			goto failed;
7870	}
7871
7872	if (wpa_driver_nl80211_set_mode(bss, drv->nlmode)) {
7873		wpa_printf(MSG_ERROR, "nl80211: Failed to set interface %s "
7874			   "into AP mode", bss->ifname);
7875		goto failed;
7876	}
7877
7878	if (params->num_bridge && params->bridge[0] &&
7879	    i802_check_bridge(drv, bss, params->bridge[0], params->ifname) < 0)
7880		goto failed;
7881
7882	if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1))
7883		goto failed;
7884
7885	drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
7886	if (drv->eapol_sock < 0) {
7887		perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
7888		goto failed;
7889	}
7890
7891	if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
7892	{
7893		printf("Could not register read socket for eapol\n");
7894		goto failed;
7895	}
7896
7897	if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7898			       params->own_addr))
7899		goto failed;
7900
7901	memcpy(bss->addr, params->own_addr, ETH_ALEN);
7902
7903	return bss;
7904
7905failed:
7906	wpa_driver_nl80211_deinit(bss);
7907	return NULL;
7908}
7909
7910
7911static void i802_deinit(void *priv)
7912{
7913	wpa_driver_nl80211_deinit(priv);
7914}
7915
7916#endif /* HOSTAPD */
7917
7918
7919static enum nl80211_iftype wpa_driver_nl80211_if_type(
7920	enum wpa_driver_if_type type)
7921{
7922	switch (type) {
7923	case WPA_IF_STATION:
7924		return NL80211_IFTYPE_STATION;
7925	case WPA_IF_P2P_CLIENT:
7926	case WPA_IF_P2P_GROUP:
7927		return NL80211_IFTYPE_P2P_CLIENT;
7928	case WPA_IF_AP_VLAN:
7929		return NL80211_IFTYPE_AP_VLAN;
7930	case WPA_IF_AP_BSS:
7931		return NL80211_IFTYPE_AP;
7932	case WPA_IF_P2P_GO:
7933		return NL80211_IFTYPE_P2P_GO;
7934	}
7935	return -1;
7936}
7937
7938
7939#ifdef CONFIG_P2P
7940
7941static int nl80211_addr_in_use(struct nl80211_global *global, const u8 *addr)
7942{
7943	struct wpa_driver_nl80211_data *drv;
7944	dl_list_for_each(drv, &global->interfaces,
7945			 struct wpa_driver_nl80211_data, list) {
7946		if (os_memcmp(addr, drv->first_bss.addr, ETH_ALEN) == 0)
7947			return 1;
7948	}
7949	return 0;
7950}
7951
7952
7953static int nl80211_p2p_interface_addr(struct wpa_driver_nl80211_data *drv,
7954				      u8 *new_addr)
7955{
7956	unsigned int idx;
7957
7958	if (!drv->global)
7959		return -1;
7960
7961	os_memcpy(new_addr, drv->first_bss.addr, ETH_ALEN);
7962	for (idx = 0; idx < 64; idx++) {
7963		new_addr[0] = drv->first_bss.addr[0] | 0x02;
7964		new_addr[0] ^= idx << 2;
7965		if (!nl80211_addr_in_use(drv->global, new_addr))
7966			break;
7967	}
7968	if (idx == 64)
7969		return -1;
7970
7971	wpa_printf(MSG_DEBUG, "nl80211: Assigned new P2P Interface Address "
7972		   MACSTR, MAC2STR(new_addr));
7973
7974	return 0;
7975}
7976
7977#endif /* CONFIG_P2P */
7978
7979
7980static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
7981				     const char *ifname, const u8 *addr,
7982				     void *bss_ctx, void **drv_priv,
7983				     char *force_ifname, u8 *if_addr,
7984				     const char *bridge)
7985{
7986	struct i802_bss *bss = priv;
7987	struct wpa_driver_nl80211_data *drv = bss->drv;
7988	int ifidx;
7989#ifdef HOSTAPD
7990	struct i802_bss *new_bss = NULL;
7991
7992	if (type == WPA_IF_AP_BSS) {
7993		new_bss = os_zalloc(sizeof(*new_bss));
7994		if (new_bss == NULL)
7995			return -1;
7996	}
7997#endif /* HOSTAPD */
7998
7999	if (addr)
8000		os_memcpy(if_addr, addr, ETH_ALEN);
8001	ifidx = nl80211_create_iface(drv, ifname,
8002				     wpa_driver_nl80211_if_type(type), addr,
8003				     0);
8004	if (ifidx < 0) {
8005#ifdef HOSTAPD
8006		os_free(new_bss);
8007#endif /* HOSTAPD */
8008		return -1;
8009	}
8010
8011	if (!addr &&
8012	    linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
8013			       if_addr) < 0) {
8014		nl80211_remove_iface(drv, ifidx);
8015		return -1;
8016	}
8017
8018#ifdef CONFIG_P2P
8019	if (!addr &&
8020	    (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
8021	     type == WPA_IF_P2P_GO)) {
8022		/* Enforce unique P2P Interface Address */
8023		u8 new_addr[ETH_ALEN], own_addr[ETH_ALEN];
8024
8025		if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
8026				       own_addr) < 0 ||
8027		    linux_get_ifhwaddr(drv->global->ioctl_sock, ifname,
8028				       new_addr) < 0) {
8029			nl80211_remove_iface(drv, ifidx);
8030			return -1;
8031		}
8032		if (os_memcmp(own_addr, new_addr, ETH_ALEN) == 0) {
8033			wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
8034				   "for P2P group interface");
8035			if (nl80211_p2p_interface_addr(drv, new_addr) < 0) {
8036				nl80211_remove_iface(drv, ifidx);
8037				return -1;
8038			}
8039			if (linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
8040					       new_addr) < 0) {
8041				nl80211_remove_iface(drv, ifidx);
8042				return -1;
8043			}
8044		}
8045		os_memcpy(if_addr, new_addr, ETH_ALEN);
8046	}
8047#endif /* CONFIG_P2P */
8048
8049#ifdef HOSTAPD
8050	if (bridge &&
8051	    i802_check_bridge(drv, new_bss, bridge, ifname) < 0) {
8052		wpa_printf(MSG_ERROR, "nl80211: Failed to add the new "
8053			   "interface %s to a bridge %s", ifname, bridge);
8054		nl80211_remove_iface(drv, ifidx);
8055		os_free(new_bss);
8056		return -1;
8057	}
8058
8059	if (type == WPA_IF_AP_BSS) {
8060		if (linux_set_iface_flags(drv->global->ioctl_sock, ifname, 1))
8061		{
8062			nl80211_remove_iface(drv, ifidx);
8063			os_free(new_bss);
8064			return -1;
8065		}
8066		os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
8067		os_memcpy(new_bss->addr, if_addr, ETH_ALEN);
8068		new_bss->ifindex = ifidx;
8069		new_bss->drv = drv;
8070		new_bss->next = drv->first_bss.next;
8071		new_bss->freq = drv->first_bss.freq;
8072		drv->first_bss.next = new_bss;
8073		if (drv_priv)
8074			*drv_priv = new_bss;
8075		nl80211_init_bss(new_bss);
8076
8077		/* Subscribe management frames for this WPA_IF_AP_BSS */
8078		if (nl80211_setup_ap(new_bss))
8079			return -1;
8080	}
8081#endif /* HOSTAPD */
8082
8083	if (drv->global)
8084		drv->global->if_add_ifindex = ifidx;
8085
8086	return 0;
8087}
8088
8089
8090static int wpa_driver_nl80211_if_remove(void *priv,
8091					enum wpa_driver_if_type type,
8092					const char *ifname)
8093{
8094	struct i802_bss *bss = priv;
8095	struct wpa_driver_nl80211_data *drv = bss->drv;
8096	int ifindex = if_nametoindex(ifname);
8097
8098	wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d",
8099		   __func__, type, ifname, ifindex);
8100	if (ifindex <= 0)
8101		return -1;
8102
8103	nl80211_remove_iface(drv, ifindex);
8104
8105#ifdef HOSTAPD
8106	if (type != WPA_IF_AP_BSS)
8107		return 0;
8108
8109	if (bss->added_if_into_bridge) {
8110		if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
8111				    bss->ifname) < 0)
8112			wpa_printf(MSG_INFO, "nl80211: Failed to remove "
8113				   "interface %s from bridge %s: %s",
8114				   bss->ifname, bss->brname, strerror(errno));
8115	}
8116	if (bss->added_bridge) {
8117		if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
8118			wpa_printf(MSG_INFO, "nl80211: Failed to remove "
8119				   "bridge %s: %s",
8120				   bss->brname, strerror(errno));
8121	}
8122
8123	if (bss != &drv->first_bss) {
8124		struct i802_bss *tbss;
8125
8126		for (tbss = &drv->first_bss; tbss; tbss = tbss->next) {
8127			if (tbss->next == bss) {
8128				tbss->next = bss->next;
8129				/* Unsubscribe management frames */
8130				nl80211_teardown_ap(bss);
8131				nl80211_destroy_bss(bss);
8132				os_free(bss);
8133				bss = NULL;
8134				break;
8135			}
8136		}
8137		if (bss)
8138			wpa_printf(MSG_INFO, "nl80211: %s - could not find "
8139				   "BSS %p in the list", __func__, bss);
8140	}
8141#endif /* HOSTAPD */
8142
8143	return 0;
8144}
8145
8146
8147static int cookie_handler(struct nl_msg *msg, void *arg)
8148{
8149	struct nlattr *tb[NL80211_ATTR_MAX + 1];
8150	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
8151	u64 *cookie = arg;
8152	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
8153		  genlmsg_attrlen(gnlh, 0), NULL);
8154	if (tb[NL80211_ATTR_COOKIE])
8155		*cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
8156	return NL_SKIP;
8157}
8158
8159
8160static int nl80211_send_frame_cmd(struct i802_bss *bss,
8161				  unsigned int freq, unsigned int wait,
8162				  const u8 *buf, size_t buf_len,
8163				  u64 *cookie_out, int no_cck, int no_ack,
8164				  int offchanok)
8165{
8166	struct wpa_driver_nl80211_data *drv = bss->drv;
8167	struct nl_msg *msg;
8168	u64 cookie;
8169	int ret = -1;
8170
8171	msg = nlmsg_alloc();
8172	if (!msg)
8173		return -1;
8174
8175	wpa_printf(MSG_DEBUG, "nl80211: CMD_FRAME freq=%u wait=%u no_cck=%d "
8176		   "no_ack=%d offchanok=%d",
8177		   freq, wait, no_cck, no_ack, offchanok);
8178	nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME);
8179
8180	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8181	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
8182	if (wait)
8183		NLA_PUT_U32(msg, NL80211_ATTR_DURATION, wait);
8184	if (offchanok && (drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX))
8185		NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
8186	if (no_cck)
8187		NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
8188	if (no_ack)
8189		NLA_PUT_FLAG(msg, NL80211_ATTR_DONT_WAIT_FOR_ACK);
8190
8191	NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
8192
8193	cookie = 0;
8194	ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
8195	msg = NULL;
8196	if (ret) {
8197		wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
8198			   "(%s) (freq=%u wait=%u)", ret, strerror(-ret),
8199			   freq, wait);
8200		goto nla_put_failure;
8201	}
8202	wpa_printf(MSG_DEBUG, "nl80211: Frame TX command accepted%s; "
8203		   "cookie 0x%llx", no_ack ? " (no ACK)" : "",
8204		   (long long unsigned int) cookie);
8205
8206	if (cookie_out)
8207		*cookie_out = no_ack ? (u64) -1 : cookie;
8208
8209nla_put_failure:
8210	nlmsg_free(msg);
8211	return ret;
8212}
8213
8214
8215static int wpa_driver_nl80211_send_action(void *priv, unsigned int freq,
8216					  unsigned int wait_time,
8217					  const u8 *dst, const u8 *src,
8218					  const u8 *bssid,
8219					  const u8 *data, size_t data_len,
8220					  int no_cck)
8221{
8222	struct i802_bss *bss = priv;
8223	struct wpa_driver_nl80211_data *drv = bss->drv;
8224	int ret = -1;
8225	u8 *buf;
8226	struct ieee80211_hdr *hdr;
8227
8228	wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d, "
8229		   "freq=%u MHz wait=%d ms no_cck=%d)",
8230		   drv->ifindex, freq, wait_time, no_cck);
8231
8232	buf = os_zalloc(24 + data_len);
8233	if (buf == NULL)
8234		return ret;
8235	os_memcpy(buf + 24, data, data_len);
8236	hdr = (struct ieee80211_hdr *) buf;
8237	hdr->frame_control =
8238		IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
8239	os_memcpy(hdr->addr1, dst, ETH_ALEN);
8240	os_memcpy(hdr->addr2, src, ETH_ALEN);
8241	os_memcpy(hdr->addr3, bssid, ETH_ALEN);
8242
8243	if (is_ap_interface(drv->nlmode))
8244		ret = wpa_driver_nl80211_send_mlme_freq(priv, buf,
8245							24 + data_len,
8246							0, freq, no_cck, 1,
8247							wait_time);
8248	else
8249		ret = nl80211_send_frame_cmd(bss, freq, wait_time, buf,
8250					     24 + data_len,
8251					     &drv->send_action_cookie,
8252					     no_cck, 0, 1);
8253
8254	os_free(buf);
8255	return ret;
8256}
8257
8258
8259static void wpa_driver_nl80211_send_action_cancel_wait(void *priv)
8260{
8261	struct i802_bss *bss = priv;
8262	struct wpa_driver_nl80211_data *drv = bss->drv;
8263	struct nl_msg *msg;
8264	int ret;
8265
8266	msg = nlmsg_alloc();
8267	if (!msg)
8268		return;
8269
8270	nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME_WAIT_CANCEL);
8271
8272	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8273	NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->send_action_cookie);
8274
8275	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8276	msg = NULL;
8277	if (ret)
8278		wpa_printf(MSG_DEBUG, "nl80211: wait cancel failed: ret=%d "
8279			   "(%s)", ret, strerror(-ret));
8280
8281 nla_put_failure:
8282	nlmsg_free(msg);
8283}
8284
8285
8286static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
8287						unsigned int duration)
8288{
8289	struct i802_bss *bss = priv;
8290	struct wpa_driver_nl80211_data *drv = bss->drv;
8291	struct nl_msg *msg;
8292	int ret;
8293	u64 cookie;
8294
8295	msg = nlmsg_alloc();
8296	if (!msg)
8297		return -1;
8298
8299	nl80211_cmd(drv, msg, 0, NL80211_CMD_REMAIN_ON_CHANNEL);
8300
8301	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8302	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
8303	NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
8304
8305	cookie = 0;
8306	ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
8307	msg = NULL;
8308	if (ret == 0) {
8309		wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
8310			   "0x%llx for freq=%u MHz duration=%u",
8311			   (long long unsigned int) cookie, freq, duration);
8312		drv->remain_on_chan_cookie = cookie;
8313		drv->pending_remain_on_chan = 1;
8314		return 0;
8315	}
8316	wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
8317		   "(freq=%d duration=%u): %d (%s)",
8318		   freq, duration, ret, strerror(-ret));
8319nla_put_failure:
8320	nlmsg_free(msg);
8321	return -1;
8322}
8323
8324
8325static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
8326{
8327	struct i802_bss *bss = priv;
8328	struct wpa_driver_nl80211_data *drv = bss->drv;
8329	struct nl_msg *msg;
8330	int ret;
8331
8332	if (!drv->pending_remain_on_chan) {
8333		wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
8334			   "to cancel");
8335		return -1;
8336	}
8337
8338	wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
8339		   "0x%llx",
8340		   (long long unsigned int) drv->remain_on_chan_cookie);
8341
8342	msg = nlmsg_alloc();
8343	if (!msg)
8344		return -1;
8345
8346	nl80211_cmd(drv, msg, 0, NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL);
8347
8348	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8349	NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
8350
8351	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8352	msg = NULL;
8353	if (ret == 0)
8354		return 0;
8355	wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
8356		   "%d (%s)", ret, strerror(-ret));
8357nla_put_failure:
8358	nlmsg_free(msg);
8359	return -1;
8360}
8361
8362
8363static int wpa_driver_nl80211_probe_req_report(void *priv, int report)
8364{
8365	struct i802_bss *bss = priv;
8366	struct wpa_driver_nl80211_data *drv = bss->drv;
8367
8368	if (!report) {
8369		if (bss->nl_preq && drv->device_ap_sme &&
8370		    is_ap_interface(drv->nlmode)) {
8371			/*
8372			 * Do not disable Probe Request reporting that was
8373			 * enabled in nl80211_setup_ap().
8374			 */
8375			wpa_printf(MSG_DEBUG, "nl80211: Skip disabling of "
8376				   "Probe Request reporting nl_preq=%p while "
8377				   "in AP mode", bss->nl_preq);
8378		} else if (bss->nl_preq) {
8379			wpa_printf(MSG_DEBUG, "nl80211: Disable Probe Request "
8380				   "reporting nl_preq=%p", bss->nl_preq);
8381			eloop_unregister_read_sock(
8382				nl_socket_get_fd(bss->nl_preq));
8383			nl_destroy_handles(&bss->nl_preq);
8384		}
8385		return 0;
8386	}
8387
8388	if (bss->nl_preq) {
8389		wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
8390			   "already on! nl_preq=%p", bss->nl_preq);
8391		return 0;
8392	}
8393
8394	bss->nl_preq = nl_create_handle(drv->global->nl_cb, "preq");
8395	if (bss->nl_preq == NULL)
8396		return -1;
8397	wpa_printf(MSG_DEBUG, "nl80211: Enable Probe Request "
8398		   "reporting nl_preq=%p", bss->nl_preq);
8399
8400	if (nl80211_register_frame(bss, bss->nl_preq,
8401				   (WLAN_FC_TYPE_MGMT << 2) |
8402				   (WLAN_FC_STYPE_PROBE_REQ << 4),
8403				   NULL, 0) < 0)
8404		goto out_err;
8405
8406	eloop_register_read_sock(nl_socket_get_fd(bss->nl_preq),
8407				 wpa_driver_nl80211_event_receive, bss->nl_cb,
8408				 bss->nl_preq);
8409
8410	return 0;
8411
8412 out_err:
8413	nl_destroy_handles(&bss->nl_preq);
8414	return -1;
8415}
8416
8417
8418static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
8419				     int ifindex, int disabled)
8420{
8421	struct nl_msg *msg;
8422	struct nlattr *bands, *band;
8423	int ret;
8424
8425	msg = nlmsg_alloc();
8426	if (!msg)
8427		return -1;
8428
8429	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_TX_BITRATE_MASK);
8430	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
8431
8432	bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
8433	if (!bands)
8434		goto nla_put_failure;
8435
8436	/*
8437	 * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
8438	 * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
8439	 * rates. All 5 GHz rates are left enabled.
8440	 */
8441	band = nla_nest_start(msg, NL80211_BAND_2GHZ);
8442	if (!band)
8443		goto nla_put_failure;
8444	if (disabled) {
8445		NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
8446			"\x0c\x12\x18\x24\x30\x48\x60\x6c");
8447	}
8448	nla_nest_end(msg, band);
8449
8450	nla_nest_end(msg, bands);
8451
8452	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8453	msg = NULL;
8454	if (ret) {
8455		wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
8456			   "(%s)", ret, strerror(-ret));
8457	} else
8458		drv->disabled_11b_rates = disabled;
8459
8460	return ret;
8461
8462nla_put_failure:
8463	nlmsg_free(msg);
8464	return -1;
8465}
8466
8467
8468static int wpa_driver_nl80211_deinit_ap(void *priv)
8469{
8470	struct i802_bss *bss = priv;
8471	struct wpa_driver_nl80211_data *drv = bss->drv;
8472	if (!is_ap_interface(drv->nlmode))
8473		return -1;
8474	wpa_driver_nl80211_del_beacon(drv);
8475	return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
8476}
8477
8478
8479static int wpa_driver_nl80211_deinit_p2p_cli(void *priv)
8480{
8481	struct i802_bss *bss = priv;
8482	struct wpa_driver_nl80211_data *drv = bss->drv;
8483	if (drv->nlmode != NL80211_IFTYPE_P2P_CLIENT)
8484		return -1;
8485	return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
8486}
8487
8488
8489static void wpa_driver_nl80211_resume(void *priv)
8490{
8491	struct i802_bss *bss = priv;
8492	struct wpa_driver_nl80211_data *drv = bss->drv;
8493	if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
8494		wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on "
8495			   "resume event");
8496	}
8497}
8498
8499
8500static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
8501				  const u8 *ies, size_t ies_len)
8502{
8503	struct i802_bss *bss = priv;
8504	struct wpa_driver_nl80211_data *drv = bss->drv;
8505	int ret;
8506	u8 *data, *pos;
8507	size_t data_len;
8508	const u8 *own_addr = bss->addr;
8509
8510	if (action != 1) {
8511		wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
8512			   "action %d", action);
8513		return -1;
8514	}
8515
8516	/*
8517	 * Action frame payload:
8518	 * Category[1] = 6 (Fast BSS Transition)
8519	 * Action[1] = 1 (Fast BSS Transition Request)
8520	 * STA Address
8521	 * Target AP Address
8522	 * FT IEs
8523	 */
8524
8525	data_len = 2 + 2 * ETH_ALEN + ies_len;
8526	data = os_malloc(data_len);
8527	if (data == NULL)
8528		return -1;
8529	pos = data;
8530	*pos++ = 0x06; /* FT Action category */
8531	*pos++ = action;
8532	os_memcpy(pos, own_addr, ETH_ALEN);
8533	pos += ETH_ALEN;
8534	os_memcpy(pos, target_ap, ETH_ALEN);
8535	pos += ETH_ALEN;
8536	os_memcpy(pos, ies, ies_len);
8537
8538	ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, 0,
8539					     drv->bssid, own_addr, drv->bssid,
8540					     data, data_len, 0);
8541	os_free(data);
8542
8543	return ret;
8544}
8545
8546
8547static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
8548{
8549	struct i802_bss *bss = priv;
8550	struct wpa_driver_nl80211_data *drv = bss->drv;
8551	struct nl_msg *msg, *cqm = NULL;
8552	int ret = -1;
8553
8554	wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
8555		   "hysteresis=%d", threshold, hysteresis);
8556
8557	msg = nlmsg_alloc();
8558	if (!msg)
8559		return -1;
8560
8561	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_CQM);
8562
8563	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8564
8565	cqm = nlmsg_alloc();
8566	if (cqm == NULL)
8567		goto nla_put_failure;
8568
8569	NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
8570	NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
8571	if (nla_put_nested(msg, NL80211_ATTR_CQM, cqm) < 0)
8572		goto nla_put_failure;
8573
8574	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8575	msg = NULL;
8576
8577nla_put_failure:
8578	nlmsg_free(cqm);
8579	nlmsg_free(msg);
8580	return ret;
8581}
8582
8583
8584static int nl80211_signal_poll(void *priv, struct wpa_signal_info *si)
8585{
8586	struct i802_bss *bss = priv;
8587	struct wpa_driver_nl80211_data *drv = bss->drv;
8588	int res;
8589
8590	os_memset(si, 0, sizeof(*si));
8591	res = nl80211_get_link_signal(drv, si);
8592	if (res != 0)
8593		return res;
8594
8595	return nl80211_get_link_noise(drv, si);
8596}
8597
8598
8599static int wpa_driver_nl80211_shared_freq(void *priv)
8600{
8601	struct i802_bss *bss = priv;
8602	struct wpa_driver_nl80211_data *drv = bss->drv;
8603	struct wpa_driver_nl80211_data *driver;
8604	int freq = 0;
8605
8606	/*
8607	 * If the same PHY is in connected state with some other interface,
8608	 * then retrieve the assoc freq.
8609	 */
8610	wpa_printf(MSG_DEBUG, "nl80211: Get shared freq for PHY %s",
8611		   drv->phyname);
8612
8613	dl_list_for_each(driver, &drv->global->interfaces,
8614			 struct wpa_driver_nl80211_data, list) {
8615		if (drv == driver ||
8616		    os_strcmp(drv->phyname, driver->phyname) != 0 ||
8617#ifdef ANDROID_P2P
8618		    (!driver->associated && !is_ap_interface(driver->nlmode)))
8619#else
8620		    !driver->associated)
8621#endif
8622			continue;
8623
8624		wpa_printf(MSG_DEBUG, "nl80211: Found a match for PHY %s - %s "
8625			   MACSTR,
8626			   driver->phyname, driver->first_bss.ifname,
8627			   MAC2STR(driver->first_bss.addr));
8628		if (is_ap_interface(driver->nlmode))
8629			freq = driver->first_bss.freq;
8630		else
8631			freq = nl80211_get_assoc_freq(driver);
8632		wpa_printf(MSG_DEBUG, "nl80211: Shared freq for PHY %s: %d",
8633			   drv->phyname, freq);
8634	}
8635
8636	if (!freq)
8637		wpa_printf(MSG_DEBUG, "nl80211: No shared interface for "
8638			   "PHY (%s) in associated state", drv->phyname);
8639
8640	return freq;
8641}
8642
8643
8644static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
8645			      int encrypt)
8646{
8647	struct i802_bss *bss = priv;
8648	return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt, 0,
8649					     0, 0, 0, 0);
8650}
8651
8652
8653static int nl80211_set_param(void *priv, const char *param)
8654{
8655	wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
8656	if (param == NULL)
8657		return 0;
8658
8659#ifdef CONFIG_P2P
8660	if (os_strstr(param, "use_p2p_group_interface=1")) {
8661		struct i802_bss *bss = priv;
8662		struct wpa_driver_nl80211_data *drv = bss->drv;
8663
8664		wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
8665			   "interface");
8666		drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
8667		drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
8668	}
8669#ifdef ANDROID_P2P
8670	if(os_strstr(param, "use_multi_chan_concurrent=1")) {
8671		struct i802_bss *bss = priv;
8672		struct wpa_driver_nl80211_data *drv = bss->drv;
8673		wpa_printf(MSG_DEBUG, "nl80211: Use Multi channel "
8674			   "concurrency");
8675		drv->capa.flags |= WPA_DRIVER_FLAGS_MULTI_CHANNEL_CONCURRENT;
8676	}
8677#endif
8678#endif /* CONFIG_P2P */
8679
8680	return 0;
8681}
8682
8683
8684static void * nl80211_global_init(void)
8685{
8686	struct nl80211_global *global;
8687	struct netlink_config *cfg;
8688
8689	global = os_zalloc(sizeof(*global));
8690	if (global == NULL)
8691		return NULL;
8692	global->ioctl_sock = -1;
8693	dl_list_init(&global->interfaces);
8694	global->if_add_ifindex = -1;
8695
8696	cfg = os_zalloc(sizeof(*cfg));
8697	if (cfg == NULL)
8698		goto err;
8699
8700	cfg->ctx = global;
8701	cfg->newlink_cb = wpa_driver_nl80211_event_rtm_newlink;
8702	cfg->dellink_cb = wpa_driver_nl80211_event_rtm_dellink;
8703	global->netlink = netlink_init(cfg);
8704	if (global->netlink == NULL) {
8705		os_free(cfg);
8706		goto err;
8707	}
8708
8709	if (wpa_driver_nl80211_init_nl_global(global) < 0)
8710		goto err;
8711
8712	global->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
8713	if (global->ioctl_sock < 0) {
8714		perror("socket(PF_INET,SOCK_DGRAM)");
8715		goto err;
8716	}
8717
8718	return global;
8719
8720err:
8721	nl80211_global_deinit(global);
8722	return NULL;
8723}
8724
8725
8726static void nl80211_global_deinit(void *priv)
8727{
8728	struct nl80211_global *global = priv;
8729	if (global == NULL)
8730		return;
8731	if (!dl_list_empty(&global->interfaces)) {
8732		wpa_printf(MSG_ERROR, "nl80211: %u interface(s) remain at "
8733			   "nl80211_global_deinit",
8734			   dl_list_len(&global->interfaces));
8735	}
8736
8737	if (global->netlink)
8738		netlink_deinit(global->netlink);
8739
8740	nl_destroy_handles(&global->nl);
8741
8742	if (global->nl_event) {
8743		eloop_unregister_read_sock(
8744			nl_socket_get_fd(global->nl_event));
8745		nl_destroy_handles(&global->nl_event);
8746	}
8747
8748	nl_cb_put(global->nl_cb);
8749
8750	if (global->ioctl_sock >= 0)
8751		close(global->ioctl_sock);
8752
8753	os_free(global);
8754}
8755
8756
8757static const char * nl80211_get_radio_name(void *priv)
8758{
8759	struct i802_bss *bss = priv;
8760	struct wpa_driver_nl80211_data *drv = bss->drv;
8761	return drv->phyname;
8762}
8763
8764
8765static int nl80211_pmkid(struct i802_bss *bss, int cmd, const u8 *bssid,
8766			 const u8 *pmkid)
8767{
8768	struct nl_msg *msg;
8769
8770	msg = nlmsg_alloc();
8771	if (!msg)
8772		return -ENOMEM;
8773
8774	nl80211_cmd(bss->drv, msg, 0, cmd);
8775
8776	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
8777	if (pmkid)
8778		NLA_PUT(msg, NL80211_ATTR_PMKID, 16, pmkid);
8779	if (bssid)
8780		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
8781
8782	return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
8783 nla_put_failure:
8784	nlmsg_free(msg);
8785	return -ENOBUFS;
8786}
8787
8788
8789static int nl80211_add_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
8790{
8791	struct i802_bss *bss = priv;
8792	wpa_printf(MSG_DEBUG, "nl80211: Add PMKID for " MACSTR, MAC2STR(bssid));
8793	return nl80211_pmkid(bss, NL80211_CMD_SET_PMKSA, bssid, pmkid);
8794}
8795
8796
8797static int nl80211_remove_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
8798{
8799	struct i802_bss *bss = priv;
8800	wpa_printf(MSG_DEBUG, "nl80211: Delete PMKID for " MACSTR,
8801		   MAC2STR(bssid));
8802	return nl80211_pmkid(bss, NL80211_CMD_DEL_PMKSA, bssid, pmkid);
8803}
8804
8805
8806static int nl80211_flush_pmkid(void *priv)
8807{
8808	struct i802_bss *bss = priv;
8809	wpa_printf(MSG_DEBUG, "nl80211: Flush PMKIDs");
8810	return nl80211_pmkid(bss, NL80211_CMD_FLUSH_PMKSA, NULL, NULL);
8811}
8812
8813
8814static void nl80211_set_rekey_info(void *priv, const u8 *kek, const u8 *kck,
8815				   const u8 *replay_ctr)
8816{
8817	struct i802_bss *bss = priv;
8818	struct wpa_driver_nl80211_data *drv = bss->drv;
8819	struct nlattr *replay_nested;
8820	struct nl_msg *msg;
8821
8822	msg = nlmsg_alloc();
8823	if (!msg)
8824		return;
8825
8826	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_REKEY_OFFLOAD);
8827
8828	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8829
8830	replay_nested = nla_nest_start(msg, NL80211_ATTR_REKEY_DATA);
8831	if (!replay_nested)
8832		goto nla_put_failure;
8833
8834	NLA_PUT(msg, NL80211_REKEY_DATA_KEK, NL80211_KEK_LEN, kek);
8835	NLA_PUT(msg, NL80211_REKEY_DATA_KCK, NL80211_KCK_LEN, kck);
8836	NLA_PUT(msg, NL80211_REKEY_DATA_REPLAY_CTR, NL80211_REPLAY_CTR_LEN,
8837		replay_ctr);
8838
8839	nla_nest_end(msg, replay_nested);
8840
8841	send_and_recv_msgs(drv, msg, NULL, NULL);
8842	return;
8843 nla_put_failure:
8844	nlmsg_free(msg);
8845}
8846
8847
8848static void nl80211_send_null_frame(struct i802_bss *bss, const u8 *own_addr,
8849				    const u8 *addr, int qos)
8850{
8851	/* send data frame to poll STA and check whether
8852	 * this frame is ACKed */
8853	struct {
8854		struct ieee80211_hdr hdr;
8855		u16 qos_ctl;
8856	} STRUCT_PACKED nulldata;
8857	size_t size;
8858
8859	/* Send data frame to poll STA and check whether this frame is ACKed */
8860
8861	os_memset(&nulldata, 0, sizeof(nulldata));
8862
8863	if (qos) {
8864		nulldata.hdr.frame_control =
8865			IEEE80211_FC(WLAN_FC_TYPE_DATA,
8866				     WLAN_FC_STYPE_QOS_NULL);
8867		size = sizeof(nulldata);
8868	} else {
8869		nulldata.hdr.frame_control =
8870			IEEE80211_FC(WLAN_FC_TYPE_DATA,
8871				     WLAN_FC_STYPE_NULLFUNC);
8872		size = sizeof(struct ieee80211_hdr);
8873	}
8874
8875	nulldata.hdr.frame_control |= host_to_le16(WLAN_FC_FROMDS);
8876	os_memcpy(nulldata.hdr.IEEE80211_DA_FROMDS, addr, ETH_ALEN);
8877	os_memcpy(nulldata.hdr.IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
8878	os_memcpy(nulldata.hdr.IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
8879
8880	if (wpa_driver_nl80211_send_mlme(bss, (u8 *) &nulldata, size, 0) < 0)
8881		wpa_printf(MSG_DEBUG, "nl80211_send_null_frame: Failed to "
8882			   "send poll frame");
8883}
8884
8885static void nl80211_poll_client(void *priv, const u8 *own_addr, const u8 *addr,
8886				int qos)
8887{
8888	struct i802_bss *bss = priv;
8889	struct wpa_driver_nl80211_data *drv = bss->drv;
8890	struct nl_msg *msg;
8891
8892	if (!drv->poll_command_supported) {
8893		nl80211_send_null_frame(bss, own_addr, addr, qos);
8894		return;
8895	}
8896
8897	msg = nlmsg_alloc();
8898	if (!msg)
8899		return;
8900
8901	nl80211_cmd(drv, msg, 0, NL80211_CMD_PROBE_CLIENT);
8902
8903	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8904	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
8905
8906	send_and_recv_msgs(drv, msg, NULL, NULL);
8907	return;
8908 nla_put_failure:
8909	nlmsg_free(msg);
8910}
8911
8912
8913static int nl80211_set_power_save(struct i802_bss *bss, int enabled)
8914{
8915	struct nl_msg *msg;
8916
8917	msg = nlmsg_alloc();
8918	if (!msg)
8919		return -ENOMEM;
8920
8921	nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_SET_POWER_SAVE);
8922	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8923	NLA_PUT_U32(msg, NL80211_ATTR_PS_STATE,
8924		    enabled ? NL80211_PS_ENABLED : NL80211_PS_DISABLED);
8925	return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
8926nla_put_failure:
8927	nlmsg_free(msg);
8928	return -ENOBUFS;
8929}
8930
8931
8932static int nl80211_set_p2p_powersave(void *priv, int legacy_ps, int opp_ps,
8933				     int ctwindow)
8934{
8935	struct i802_bss *bss = priv;
8936
8937	wpa_printf(MSG_DEBUG, "nl80211: set_p2p_powersave (legacy_ps=%d "
8938		   "opp_ps=%d ctwindow=%d)", legacy_ps, opp_ps, ctwindow);
8939
8940	if (opp_ps != -1 || ctwindow != -1)
8941#ifdef ANDROID_P2P
8942		wpa_driver_set_p2p_ps(priv, legacy_ps, opp_ps, ctwindow);
8943#else
8944		return -1; /* Not yet supported */
8945#endif
8946
8947	if (legacy_ps == -1)
8948		return 0;
8949	if (legacy_ps != 0 && legacy_ps != 1)
8950		return -1; /* Not yet supported */
8951
8952	return nl80211_set_power_save(bss, legacy_ps);
8953}
8954
8955
8956#ifdef CONFIG_TDLS
8957
8958static int nl80211_send_tdls_mgmt(void *priv, const u8 *dst, u8 action_code,
8959				  u8 dialog_token, u16 status_code,
8960				  const u8 *buf, size_t len)
8961{
8962	struct i802_bss *bss = priv;
8963	struct wpa_driver_nl80211_data *drv = bss->drv;
8964	struct nl_msg *msg;
8965
8966	if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
8967		return -EOPNOTSUPP;
8968
8969	if (!dst)
8970		return -EINVAL;
8971
8972	msg = nlmsg_alloc();
8973	if (!msg)
8974		return -ENOMEM;
8975
8976	nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_MGMT);
8977	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8978	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, dst);
8979	NLA_PUT_U8(msg, NL80211_ATTR_TDLS_ACTION, action_code);
8980	NLA_PUT_U8(msg, NL80211_ATTR_TDLS_DIALOG_TOKEN, dialog_token);
8981	NLA_PUT_U16(msg, NL80211_ATTR_STATUS_CODE, status_code);
8982	NLA_PUT(msg, NL80211_ATTR_IE, len, buf);
8983
8984	return send_and_recv_msgs(drv, msg, NULL, NULL);
8985
8986nla_put_failure:
8987	nlmsg_free(msg);
8988	return -ENOBUFS;
8989}
8990
8991
8992static int nl80211_tdls_oper(void *priv, enum tdls_oper oper, const u8 *peer)
8993{
8994	struct i802_bss *bss = priv;
8995	struct wpa_driver_nl80211_data *drv = bss->drv;
8996	struct nl_msg *msg;
8997	enum nl80211_tdls_operation nl80211_oper;
8998
8999	if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
9000		return -EOPNOTSUPP;
9001
9002	switch (oper) {
9003	case TDLS_DISCOVERY_REQ:
9004		nl80211_oper = NL80211_TDLS_DISCOVERY_REQ;
9005		break;
9006	case TDLS_SETUP:
9007		nl80211_oper = NL80211_TDLS_SETUP;
9008		break;
9009	case TDLS_TEARDOWN:
9010		nl80211_oper = NL80211_TDLS_TEARDOWN;
9011		break;
9012	case TDLS_ENABLE_LINK:
9013		nl80211_oper = NL80211_TDLS_ENABLE_LINK;
9014		break;
9015	case TDLS_DISABLE_LINK:
9016		nl80211_oper = NL80211_TDLS_DISABLE_LINK;
9017		break;
9018	case TDLS_ENABLE:
9019		return 0;
9020	case TDLS_DISABLE:
9021		return 0;
9022	default:
9023		return -EINVAL;
9024	}
9025
9026	msg = nlmsg_alloc();
9027	if (!msg)
9028		return -ENOMEM;
9029
9030	nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_OPER);
9031	NLA_PUT_U8(msg, NL80211_ATTR_TDLS_OPERATION, nl80211_oper);
9032	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9033	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, peer);
9034
9035	return send_and_recv_msgs(drv, msg, NULL, NULL);
9036
9037nla_put_failure:
9038	nlmsg_free(msg);
9039	return -ENOBUFS;
9040}
9041
9042#endif /* CONFIG TDLS */
9043
9044
9045#ifdef ANDROID
9046
9047typedef struct android_wifi_priv_cmd {
9048	char *buf;
9049	int used_len;
9050	int total_len;
9051} android_wifi_priv_cmd;
9052
9053static int drv_errors = 0;
9054
9055static void wpa_driver_send_hang_msg(struct wpa_driver_nl80211_data *drv)
9056{
9057	drv_errors++;
9058	if (drv_errors > DRV_NUMBER_SEQUENTIAL_ERRORS) {
9059		drv_errors = 0;
9060		wpa_msg(drv->ctx, MSG_INFO, WPA_EVENT_DRIVER_STATE "HANGED");
9061	}
9062}
9063
9064
9065static int android_priv_cmd(struct i802_bss *bss, const char *cmd)
9066{
9067	struct wpa_driver_nl80211_data *drv = bss->drv;
9068	struct ifreq ifr;
9069	android_wifi_priv_cmd priv_cmd;
9070	char buf[MAX_DRV_CMD_SIZE];
9071	int ret;
9072
9073	os_memset(&ifr, 0, sizeof(ifr));
9074	os_memset(&priv_cmd, 0, sizeof(priv_cmd));
9075	os_strlcpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
9076
9077	os_memset(buf, 0, sizeof(buf));
9078	os_strlcpy(buf, cmd, sizeof(buf));
9079
9080	priv_cmd.buf = buf;
9081	priv_cmd.used_len = sizeof(buf);
9082	priv_cmd.total_len = sizeof(buf);
9083	ifr.ifr_data = &priv_cmd;
9084
9085	ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
9086	if (ret < 0) {
9087		wpa_printf(MSG_ERROR, "%s: failed to issue private commands",
9088			   __func__);
9089		wpa_driver_send_hang_msg(drv);
9090		return ret;
9091	}
9092
9093	drv_errors = 0;
9094	return 0;
9095}
9096
9097
9098static int android_pno_start(struct i802_bss *bss,
9099			     struct wpa_driver_scan_params *params)
9100{
9101	struct wpa_driver_nl80211_data *drv = bss->drv;
9102	struct ifreq ifr;
9103	android_wifi_priv_cmd priv_cmd;
9104	int ret = 0, i = 0, bp;
9105	char buf[WEXT_PNO_MAX_COMMAND_SIZE];
9106
9107	bp = WEXT_PNOSETUP_HEADER_SIZE;
9108	os_memcpy(buf, WEXT_PNOSETUP_HEADER, bp);
9109	buf[bp++] = WEXT_PNO_TLV_PREFIX;
9110	buf[bp++] = WEXT_PNO_TLV_VERSION;
9111	buf[bp++] = WEXT_PNO_TLV_SUBVERSION;
9112	buf[bp++] = WEXT_PNO_TLV_RESERVED;
9113
9114	while (i < WEXT_PNO_AMOUNT && (size_t) i < params->num_ssids) {
9115		/* Check that there is enough space needed for 1 more SSID, the
9116		 * other sections and null termination */
9117		if ((bp + WEXT_PNO_SSID_HEADER_SIZE + MAX_SSID_LEN +
9118		     WEXT_PNO_NONSSID_SECTIONS_SIZE + 1) >= (int) sizeof(buf))
9119			break;
9120		wpa_hexdump_ascii(MSG_DEBUG, "For PNO Scan",
9121				  params->ssids[i].ssid,
9122				  params->ssids[i].ssid_len);
9123		buf[bp++] = WEXT_PNO_SSID_SECTION;
9124		buf[bp++] = params->ssids[i].ssid_len;
9125		os_memcpy(&buf[bp], params->ssids[i].ssid,
9126			  params->ssids[i].ssid_len);
9127		bp += params->ssids[i].ssid_len;
9128		i++;
9129	}
9130
9131	buf[bp++] = WEXT_PNO_SCAN_INTERVAL_SECTION;
9132	os_snprintf(&buf[bp], WEXT_PNO_SCAN_INTERVAL_LENGTH + 1, "%x",
9133		    WEXT_PNO_SCAN_INTERVAL);
9134	bp += WEXT_PNO_SCAN_INTERVAL_LENGTH;
9135
9136	buf[bp++] = WEXT_PNO_REPEAT_SECTION;
9137	os_snprintf(&buf[bp], WEXT_PNO_REPEAT_LENGTH + 1, "%x",
9138		    WEXT_PNO_REPEAT);
9139	bp += WEXT_PNO_REPEAT_LENGTH;
9140
9141	buf[bp++] = WEXT_PNO_MAX_REPEAT_SECTION;
9142	os_snprintf(&buf[bp], WEXT_PNO_MAX_REPEAT_LENGTH + 1, "%x",
9143		    WEXT_PNO_MAX_REPEAT);
9144	bp += WEXT_PNO_MAX_REPEAT_LENGTH + 1;
9145
9146	memset(&ifr, 0, sizeof(ifr));
9147	memset(&priv_cmd, 0, sizeof(priv_cmd));
9148	os_strncpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
9149
9150	priv_cmd.buf = buf;
9151	priv_cmd.used_len = bp;
9152	priv_cmd.total_len = bp;
9153	ifr.ifr_data = &priv_cmd;
9154
9155	ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
9156
9157	if (ret < 0) {
9158		wpa_printf(MSG_ERROR, "ioctl[SIOCSIWPRIV] (pnosetup): %d",
9159			   ret);
9160		wpa_driver_send_hang_msg(drv);
9161		return ret;
9162	}
9163
9164	drv_errors = 0;
9165
9166	return android_priv_cmd(bss, "PNOFORCE 1");
9167}
9168
9169
9170static int android_pno_stop(struct i802_bss *bss)
9171{
9172	return android_priv_cmd(bss, "PNOFORCE 0");
9173}
9174
9175#endif /* ANDROID */
9176
9177
9178const struct wpa_driver_ops wpa_driver_nl80211_ops = {
9179	.name = "nl80211",
9180	.desc = "Linux nl80211/cfg80211",
9181	.get_bssid = wpa_driver_nl80211_get_bssid,
9182	.get_ssid = wpa_driver_nl80211_get_ssid,
9183	.set_key = wpa_driver_nl80211_set_key,
9184	.scan2 = wpa_driver_nl80211_scan,
9185	.sched_scan = wpa_driver_nl80211_sched_scan,
9186	.stop_sched_scan = wpa_driver_nl80211_stop_sched_scan,
9187	.get_scan_results2 = wpa_driver_nl80211_get_scan_results,
9188	.deauthenticate = wpa_driver_nl80211_deauthenticate,
9189	.disassociate = wpa_driver_nl80211_disassociate,
9190	.authenticate = wpa_driver_nl80211_authenticate,
9191	.associate = wpa_driver_nl80211_associate,
9192	.global_init = nl80211_global_init,
9193	.global_deinit = nl80211_global_deinit,
9194	.init2 = wpa_driver_nl80211_init,
9195	.deinit = wpa_driver_nl80211_deinit,
9196	.get_capa = wpa_driver_nl80211_get_capa,
9197	.set_operstate = wpa_driver_nl80211_set_operstate,
9198	.set_supp_port = wpa_driver_nl80211_set_supp_port,
9199	.set_country = wpa_driver_nl80211_set_country,
9200	.set_ap = wpa_driver_nl80211_set_ap,
9201	.if_add = wpa_driver_nl80211_if_add,
9202	.if_remove = wpa_driver_nl80211_if_remove,
9203	.send_mlme = wpa_driver_nl80211_send_mlme,
9204	.get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
9205	.sta_add = wpa_driver_nl80211_sta_add,
9206	.sta_remove = wpa_driver_nl80211_sta_remove,
9207	.hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
9208	.sta_set_flags = wpa_driver_nl80211_sta_set_flags,
9209#ifdef HOSTAPD
9210	.hapd_init = i802_init,
9211	.hapd_deinit = i802_deinit,
9212	.set_wds_sta = i802_set_wds_sta,
9213#endif /* HOSTAPD */
9214#if defined(HOSTAPD) || defined(CONFIG_AP)
9215	.get_seqnum = i802_get_seqnum,
9216	.flush = i802_flush,
9217	.get_inact_sec = i802_get_inact_sec,
9218	.sta_clear_stats = i802_sta_clear_stats,
9219	.set_rts = i802_set_rts,
9220	.set_frag = i802_set_frag,
9221	.set_tx_queue_params = i802_set_tx_queue_params,
9222	.set_sta_vlan = i802_set_sta_vlan,
9223	.sta_deauth = i802_sta_deauth,
9224	.sta_disassoc = i802_sta_disassoc,
9225#endif /* HOSTAPD || CONFIG_AP */
9226	.read_sta_data = i802_read_sta_data,
9227	.set_freq = i802_set_freq,
9228	.send_action = wpa_driver_nl80211_send_action,
9229	.send_action_cancel_wait = wpa_driver_nl80211_send_action_cancel_wait,
9230	.remain_on_channel = wpa_driver_nl80211_remain_on_channel,
9231	.cancel_remain_on_channel =
9232	wpa_driver_nl80211_cancel_remain_on_channel,
9233	.probe_req_report = wpa_driver_nl80211_probe_req_report,
9234	.deinit_ap = wpa_driver_nl80211_deinit_ap,
9235	.deinit_p2p_cli = wpa_driver_nl80211_deinit_p2p_cli,
9236	.resume = wpa_driver_nl80211_resume,
9237	.send_ft_action = nl80211_send_ft_action,
9238	.signal_monitor = nl80211_signal_monitor,
9239	.signal_poll = nl80211_signal_poll,
9240	.send_frame = nl80211_send_frame,
9241	.shared_freq = wpa_driver_nl80211_shared_freq,
9242	.set_param = nl80211_set_param,
9243	.get_radio_name = nl80211_get_radio_name,
9244	.add_pmkid = nl80211_add_pmkid,
9245	.remove_pmkid = nl80211_remove_pmkid,
9246	.flush_pmkid = nl80211_flush_pmkid,
9247	.set_rekey_info = nl80211_set_rekey_info,
9248	.poll_client = nl80211_poll_client,
9249	.set_p2p_powersave = nl80211_set_p2p_powersave,
9250#ifdef CONFIG_TDLS
9251	.send_tdls_mgmt = nl80211_send_tdls_mgmt,
9252	.tdls_oper = nl80211_tdls_oper,
9253#endif /* CONFIG_TDLS */
9254#ifdef ANDROID_P2P
9255	.set_noa = wpa_driver_set_p2p_noa,
9256	.get_noa = wpa_driver_get_p2p_noa,
9257	.set_ap_wps_ie = wpa_driver_set_ap_wps_p2p_ie,
9258#endif
9259#ifdef ANDROID
9260	.driver_cmd = wpa_driver_nl80211_driver_cmd,
9261#endif
9262};
9263