driver_nl80211.c revision 80da0428ce21beb670d31bd06d025d8609d658b4
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;
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				break;
2491			}
2492
2493broken_combination:
2494			;
2495		}
2496	}
2497
2498	if (tb[NL80211_ATTR_SUPPORTED_COMMANDS]) {
2499		struct nlattr *nl_cmd;
2500		int i;
2501
2502		nla_for_each_nested(nl_cmd,
2503				    tb[NL80211_ATTR_SUPPORTED_COMMANDS], i) {
2504			switch (nla_get_u32(nl_cmd)) {
2505			case NL80211_CMD_AUTHENTICATE:
2506				auth_supported = 1;
2507				break;
2508			case NL80211_CMD_CONNECT:
2509				connect_supported = 1;
2510				break;
2511			case NL80211_CMD_START_SCHED_SCAN:
2512				capa->sched_scan_supported = 1;
2513				break;
2514			case NL80211_CMD_PROBE_CLIENT:
2515				info->poll_command_supported = 1;
2516				break;
2517			}
2518		}
2519	}
2520
2521	if (tb[NL80211_ATTR_OFFCHANNEL_TX_OK]) {
2522		wpa_printf(MSG_DEBUG, "nl80211: Using driver-based "
2523			   "off-channel TX");
2524		capa->flags |= WPA_DRIVER_FLAGS_OFFCHANNEL_TX;
2525	}
2526
2527	if (tb[NL80211_ATTR_ROAM_SUPPORT]) {
2528		wpa_printf(MSG_DEBUG, "nl80211: Using driver-based roaming");
2529		capa->flags |= WPA_DRIVER_FLAGS_BSS_SELECTION;
2530	}
2531
2532	/* default to 5000 since early versions of mac80211 don't set it */
2533	capa->max_remain_on_chan = 5000;
2534
2535	if (tb[NL80211_ATTR_SUPPORT_AP_UAPSD])
2536		capa->flags |= WPA_DRIVER_FLAGS_AP_UAPSD;
2537
2538	if (tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION])
2539		capa->max_remain_on_chan =
2540			nla_get_u32(tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION]);
2541
2542	if (auth_supported)
2543		capa->flags |= WPA_DRIVER_FLAGS_SME;
2544	else if (!connect_supported) {
2545		wpa_printf(MSG_INFO, "nl80211: Driver does not support "
2546			   "authentication/association or connect commands");
2547		info->error = 1;
2548	}
2549
2550	if (p2p_go_supported && p2p_client_supported)
2551		capa->flags |= WPA_DRIVER_FLAGS_P2P_CAPABLE;
2552	if (p2p_concurrent) {
2553		wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
2554			   "interface (driver advertised support)");
2555		capa->flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
2556		capa->flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
2557	}
2558
2559	if (tb[NL80211_ATTR_TDLS_SUPPORT]) {
2560		wpa_printf(MSG_DEBUG, "nl80211: TDLS supported");
2561		capa->flags |= WPA_DRIVER_FLAGS_TDLS_SUPPORT;
2562
2563		if (tb[NL80211_ATTR_TDLS_EXTERNAL_SETUP]) {
2564			wpa_printf(MSG_DEBUG, "nl80211: TDLS external setup");
2565			capa->flags |=
2566				WPA_DRIVER_FLAGS_TDLS_EXTERNAL_SETUP;
2567		}
2568	}
2569#ifndef ANDROID_P2P
2570	if (tb[NL80211_ATTR_DEVICE_AP_SME])
2571#endif
2572		info->device_ap_sme = 1;
2573
2574	if (tb[NL80211_ATTR_FEATURE_FLAGS]) {
2575		u32 flags = nla_get_u32(tb[NL80211_ATTR_FEATURE_FLAGS]);
2576
2577		if (flags & NL80211_FEATURE_SK_TX_STATUS)
2578			info->data_tx_status = 1;
2579
2580		if (flags & NL80211_FEATURE_INACTIVITY_TIMER)
2581			capa->flags |= WPA_DRIVER_FLAGS_INACTIVITY_TIMER;
2582	}
2583
2584	if (tb[NL80211_ATTR_PROBE_RESP_OFFLOAD]) {
2585		int protocols =
2586			nla_get_u32(tb[NL80211_ATTR_PROBE_RESP_OFFLOAD]);
2587		wpa_printf(MSG_DEBUG, "nl80211: Supports Probe Response "
2588			   "offload in AP mode");
2589		capa->flags |= WPA_DRIVER_FLAGS_PROBE_RESP_OFFLOAD;
2590		capa->probe_resp_offloads =
2591			probe_resp_offload_support(protocols);
2592	}
2593
2594	return NL_SKIP;
2595}
2596
2597
2598static int wpa_driver_nl80211_get_info(struct wpa_driver_nl80211_data *drv,
2599				       struct wiphy_info_data *info)
2600{
2601	struct nl_msg *msg;
2602
2603	os_memset(info, 0, sizeof(*info));
2604	info->capa = &drv->capa;
2605
2606	msg = nlmsg_alloc();
2607	if (!msg)
2608		return -1;
2609
2610	nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
2611
2612	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->first_bss.ifindex);
2613
2614	if (send_and_recv_msgs(drv, msg, wiphy_info_handler, info) == 0)
2615		return 0;
2616	msg = NULL;
2617nla_put_failure:
2618	nlmsg_free(msg);
2619	return -1;
2620}
2621
2622
2623static int wpa_driver_nl80211_capa(struct wpa_driver_nl80211_data *drv)
2624{
2625	struct wiphy_info_data info;
2626	if (wpa_driver_nl80211_get_info(drv, &info))
2627		return -1;
2628
2629	if (info.error)
2630		return -1;
2631
2632	drv->has_capability = 1;
2633	/* For now, assume TKIP, CCMP, WPA, WPA2 are supported */
2634	drv->capa.key_mgmt = WPA_DRIVER_CAPA_KEY_MGMT_WPA |
2635		WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK |
2636		WPA_DRIVER_CAPA_KEY_MGMT_WPA2 |
2637		WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK;
2638	drv->capa.enc = WPA_DRIVER_CAPA_ENC_WEP40 |
2639		WPA_DRIVER_CAPA_ENC_WEP104 |
2640		WPA_DRIVER_CAPA_ENC_TKIP |
2641		WPA_DRIVER_CAPA_ENC_CCMP;
2642	drv->capa.auth = WPA_DRIVER_AUTH_OPEN |
2643		WPA_DRIVER_AUTH_SHARED |
2644		WPA_DRIVER_AUTH_LEAP;
2645
2646	drv->capa.flags |= WPA_DRIVER_FLAGS_SANE_ERROR_CODES;
2647	drv->capa.flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE;
2648	drv->capa.flags |= WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2649#ifndef ANDROID_P2P
2650	if (!info.device_ap_sme)
2651#endif
2652		drv->capa.flags |= WPA_DRIVER_FLAGS_DEAUTH_TX_STATUS;
2653
2654	drv->device_ap_sme = info.device_ap_sme;
2655	drv->poll_command_supported = info.poll_command_supported;
2656	drv->data_tx_status = info.data_tx_status;
2657
2658#ifdef ANDROID_P2P
2659	if(drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX) {
2660		/* Driver is new enough to support monitorless mode*/
2661		wpa_printf(MSG_DEBUG, "nl80211: Driver is new "
2662			  "enough to support monitor-less mode");
2663		drv->use_monitor = 0;
2664	}
2665#else
2666	/*
2667	 * If poll command is supported mac80211 is new enough to
2668	 * have everything we need to not need monitor interfaces.
2669	 */
2670	drv->use_monitor = !info.poll_command_supported;
2671#endif
2672
2673	if (drv->device_ap_sme && drv->use_monitor) {
2674		/*
2675		 * Non-mac80211 drivers may not support monitor interface.
2676		 * Make sure we do not get stuck with incorrect capability here
2677		 * by explicitly testing this.
2678		 */
2679		if (!info.monitor_supported) {
2680			wpa_printf(MSG_DEBUG, "nl80211: Disable use_monitor "
2681				   "with device_ap_sme since no monitor mode "
2682				   "support detected");
2683			drv->use_monitor = 0;
2684		}
2685	}
2686
2687	/*
2688	 * If we aren't going to use monitor interfaces, but the
2689	 * driver doesn't support data TX status, we won't get TX
2690	 * status for EAPOL frames.
2691	 */
2692	if (!drv->use_monitor && !info.data_tx_status)
2693		drv->capa.flags &= ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2694
2695	return 0;
2696}
2697
2698
2699#ifdef ANDROID
2700static int android_genl_ctrl_resolve(struct nl_handle *handle,
2701				     const char *name)
2702{
2703	/*
2704	 * Android ICS has very minimal genl_ctrl_resolve() implementation, so
2705	 * need to work around that.
2706	 */
2707	struct nl_cache *cache = NULL;
2708	struct genl_family *nl80211 = NULL;
2709	int id = -1;
2710
2711	if (genl_ctrl_alloc_cache(handle, &cache) < 0) {
2712		wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
2713			   "netlink cache");
2714		goto fail;
2715	}
2716
2717	nl80211 = genl_ctrl_search_by_name(cache, name);
2718	if (nl80211 == NULL)
2719		goto fail;
2720
2721	id = genl_family_get_id(nl80211);
2722
2723fail:
2724	if (nl80211)
2725		genl_family_put(nl80211);
2726	if (cache)
2727		nl_cache_free(cache);
2728
2729	return id;
2730}
2731#define genl_ctrl_resolve android_genl_ctrl_resolve
2732#endif /* ANDROID */
2733
2734
2735static int wpa_driver_nl80211_init_nl_global(struct nl80211_global *global)
2736{
2737	int ret;
2738
2739	global->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2740	if (global->nl_cb == NULL) {
2741		wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
2742			   "callbacks");
2743		return -1;
2744	}
2745
2746	global->nl = nl_create_handle(global->nl_cb, "nl");
2747	if (global->nl == NULL)
2748		goto err;
2749
2750	global->nl80211_id = genl_ctrl_resolve(global->nl, "nl80211");
2751	if (global->nl80211_id < 0) {
2752		wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
2753			   "found");
2754		goto err;
2755	}
2756
2757	global->nl_event = nl_create_handle(global->nl_cb, "event");
2758	if (global->nl_event == NULL)
2759		goto err;
2760
2761	ret = nl_get_multicast_id(global, "nl80211", "scan");
2762	if (ret >= 0)
2763		ret = nl_socket_add_membership(global->nl_event, ret);
2764	if (ret < 0) {
2765		wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
2766			   "membership for scan events: %d (%s)",
2767			   ret, strerror(-ret));
2768		goto err;
2769	}
2770
2771	ret = nl_get_multicast_id(global, "nl80211", "mlme");
2772	if (ret >= 0)
2773		ret = nl_socket_add_membership(global->nl_event, ret);
2774	if (ret < 0) {
2775		wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
2776			   "membership for mlme events: %d (%s)",
2777			   ret, strerror(-ret));
2778		goto err;
2779	}
2780
2781	ret = nl_get_multicast_id(global, "nl80211", "regulatory");
2782	if (ret >= 0)
2783		ret = nl_socket_add_membership(global->nl_event, ret);
2784	if (ret < 0) {
2785		wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
2786			   "membership for regulatory events: %d (%s)",
2787			   ret, strerror(-ret));
2788		/* Continue without regulatory events */
2789	}
2790
2791	nl_cb_set(global->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2792		  no_seq_check, NULL);
2793	nl_cb_set(global->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2794		  process_global_event, global);
2795
2796	eloop_register_read_sock(nl_socket_get_fd(global->nl_event),
2797				 wpa_driver_nl80211_event_receive,
2798				 global->nl_cb, global->nl_event);
2799
2800	return 0;
2801
2802err:
2803	nl_destroy_handles(&global->nl_event);
2804	nl_destroy_handles(&global->nl);
2805	nl_cb_put(global->nl_cb);
2806	global->nl_cb = NULL;
2807	return -1;
2808}
2809
2810
2811static int wpa_driver_nl80211_init_nl(struct wpa_driver_nl80211_data *drv)
2812{
2813	drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2814	if (!drv->nl_cb) {
2815		wpa_printf(MSG_ERROR, "nl80211: Failed to alloc cb struct");
2816		return -1;
2817	}
2818
2819	nl_cb_set(drv->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2820		  no_seq_check, NULL);
2821	nl_cb_set(drv->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2822		  process_drv_event, drv);
2823
2824	return 0;
2825}
2826
2827
2828static void wpa_driver_nl80211_rfkill_blocked(void *ctx)
2829{
2830	wpa_printf(MSG_DEBUG, "nl80211: RFKILL blocked");
2831	/*
2832	 * This may be for any interface; use ifdown event to disable
2833	 * interface.
2834	 */
2835}
2836
2837
2838static void wpa_driver_nl80211_rfkill_unblocked(void *ctx)
2839{
2840	struct wpa_driver_nl80211_data *drv = ctx;
2841	wpa_printf(MSG_DEBUG, "nl80211: RFKILL unblocked");
2842	if (linux_set_iface_flags(drv->global->ioctl_sock,
2843				  drv->first_bss.ifname, 1)) {
2844		wpa_printf(MSG_DEBUG, "nl80211: Could not set interface UP "
2845			   "after rfkill unblock");
2846		return;
2847	}
2848	/* rtnetlink ifup handler will report interface as enabled */
2849}
2850
2851
2852static void nl80211_get_phy_name(struct wpa_driver_nl80211_data *drv)
2853{
2854	/* Find phy (radio) to which this interface belongs */
2855	char buf[90], *pos;
2856	int f, rv;
2857
2858	drv->phyname[0] = '\0';
2859	snprintf(buf, sizeof(buf) - 1, "/sys/class/net/%s/phy80211/name",
2860		 drv->first_bss.ifname);
2861	f = open(buf, O_RDONLY);
2862	if (f < 0) {
2863		wpa_printf(MSG_DEBUG, "Could not open file %s: %s",
2864			   buf, strerror(errno));
2865		return;
2866	}
2867
2868	rv = read(f, drv->phyname, sizeof(drv->phyname) - 1);
2869	close(f);
2870	if (rv < 0) {
2871		wpa_printf(MSG_DEBUG, "Could not read file %s: %s",
2872			   buf, strerror(errno));
2873		return;
2874	}
2875
2876	drv->phyname[rv] = '\0';
2877	pos = os_strchr(drv->phyname, '\n');
2878	if (pos)
2879		*pos = '\0';
2880	wpa_printf(MSG_DEBUG, "nl80211: interface %s in phy %s",
2881		   drv->first_bss.ifname, drv->phyname);
2882}
2883
2884
2885static void wpa_driver_nl80211_handle_eapol_tx_status(int sock,
2886						      void *eloop_ctx,
2887						      void *handle)
2888{
2889	struct wpa_driver_nl80211_data *drv = eloop_ctx;
2890	u8 data[2048];
2891	struct msghdr msg;
2892	struct iovec entry;
2893	u8 control[512];
2894	struct cmsghdr *cmsg;
2895	int res, found_ee = 0, found_wifi = 0, acked = 0;
2896	union wpa_event_data event;
2897
2898	memset(&msg, 0, sizeof(msg));
2899	msg.msg_iov = &entry;
2900	msg.msg_iovlen = 1;
2901	entry.iov_base = data;
2902	entry.iov_len = sizeof(data);
2903	msg.msg_control = &control;
2904	msg.msg_controllen = sizeof(control);
2905
2906	res = recvmsg(sock, &msg, MSG_ERRQUEUE);
2907	/* if error or not fitting 802.3 header, return */
2908	if (res < 14)
2909		return;
2910
2911	for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg))
2912	{
2913		if (cmsg->cmsg_level == SOL_SOCKET &&
2914		    cmsg->cmsg_type == SCM_WIFI_STATUS) {
2915			int *ack;
2916
2917			found_wifi = 1;
2918			ack = (void *)CMSG_DATA(cmsg);
2919			acked = *ack;
2920		}
2921
2922		if (cmsg->cmsg_level == SOL_PACKET &&
2923		    cmsg->cmsg_type == PACKET_TX_TIMESTAMP) {
2924			struct sock_extended_err *err =
2925				(struct sock_extended_err *)CMSG_DATA(cmsg);
2926
2927			if (err->ee_origin == SO_EE_ORIGIN_TXSTATUS)
2928				found_ee = 1;
2929		}
2930	}
2931
2932	if (!found_ee || !found_wifi)
2933		return;
2934
2935	memset(&event, 0, sizeof(event));
2936	event.eapol_tx_status.dst = data;
2937	event.eapol_tx_status.data = data + 14;
2938	event.eapol_tx_status.data_len = res - 14;
2939	event.eapol_tx_status.ack = acked;
2940	wpa_supplicant_event(drv->ctx, EVENT_EAPOL_TX_STATUS, &event);
2941}
2942
2943
2944static int nl80211_init_bss(struct i802_bss *bss)
2945{
2946	bss->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2947	if (!bss->nl_cb)
2948		return -1;
2949
2950	nl_cb_set(bss->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2951		  no_seq_check, NULL);
2952	nl_cb_set(bss->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2953		  process_bss_event, bss);
2954
2955	return 0;
2956}
2957
2958
2959static void nl80211_destroy_bss(struct i802_bss *bss)
2960{
2961	nl_cb_put(bss->nl_cb);
2962	bss->nl_cb = NULL;
2963}
2964
2965
2966/**
2967 * wpa_driver_nl80211_init - Initialize nl80211 driver interface
2968 * @ctx: context to be used when calling wpa_supplicant functions,
2969 * e.g., wpa_supplicant_event()
2970 * @ifname: interface name, e.g., wlan0
2971 * @global_priv: private driver global data from global_init()
2972 * Returns: Pointer to private data, %NULL on failure
2973 */
2974static void * wpa_driver_nl80211_init(void *ctx, const char *ifname,
2975				      void *global_priv)
2976{
2977	struct wpa_driver_nl80211_data *drv;
2978	struct rfkill_config *rcfg;
2979	struct i802_bss *bss;
2980
2981	if (global_priv == NULL)
2982		return NULL;
2983	drv = os_zalloc(sizeof(*drv));
2984	if (drv == NULL)
2985		return NULL;
2986	drv->global = global_priv;
2987	drv->ctx = ctx;
2988	bss = &drv->first_bss;
2989	bss->drv = drv;
2990	os_strlcpy(bss->ifname, ifname, sizeof(bss->ifname));
2991	drv->monitor_ifidx = -1;
2992	drv->monitor_sock = -1;
2993	drv->eapol_tx_sock = -1;
2994	drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
2995
2996	if (wpa_driver_nl80211_init_nl(drv)) {
2997		os_free(drv);
2998		return NULL;
2999	}
3000
3001	if (nl80211_init_bss(bss))
3002		goto failed;
3003
3004	nl80211_get_phy_name(drv);
3005
3006	rcfg = os_zalloc(sizeof(*rcfg));
3007	if (rcfg == NULL)
3008		goto failed;
3009	rcfg->ctx = drv;
3010	os_strlcpy(rcfg->ifname, ifname, sizeof(rcfg->ifname));
3011	rcfg->blocked_cb = wpa_driver_nl80211_rfkill_blocked;
3012	rcfg->unblocked_cb = wpa_driver_nl80211_rfkill_unblocked;
3013	drv->rfkill = rfkill_init(rcfg);
3014	if (drv->rfkill == NULL) {
3015		wpa_printf(MSG_DEBUG, "nl80211: RFKILL status not available");
3016		os_free(rcfg);
3017	}
3018
3019	if (wpa_driver_nl80211_finish_drv_init(drv))
3020		goto failed;
3021
3022	drv->eapol_tx_sock = socket(PF_PACKET, SOCK_DGRAM, 0);
3023	if (drv->eapol_tx_sock < 0)
3024		goto failed;
3025
3026	if (drv->data_tx_status) {
3027		int enabled = 1;
3028
3029		if (setsockopt(drv->eapol_tx_sock, SOL_SOCKET, SO_WIFI_STATUS,
3030			       &enabled, sizeof(enabled)) < 0) {
3031			wpa_printf(MSG_DEBUG,
3032				"nl80211: wifi status sockopt failed\n");
3033			drv->data_tx_status = 0;
3034			if (!drv->use_monitor)
3035				drv->capa.flags &=
3036					~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
3037		} else {
3038			eloop_register_read_sock(drv->eapol_tx_sock,
3039				wpa_driver_nl80211_handle_eapol_tx_status,
3040				drv, NULL);
3041		}
3042	}
3043
3044	if (drv->global) {
3045		dl_list_add(&drv->global->interfaces, &drv->list);
3046		drv->in_interface_list = 1;
3047	}
3048
3049	return bss;
3050
3051failed:
3052	wpa_driver_nl80211_deinit(bss);
3053	return NULL;
3054}
3055
3056
3057static int nl80211_register_frame(struct i802_bss *bss,
3058				  struct nl_handle *nl_handle,
3059				  u16 type, const u8 *match, size_t match_len)
3060{
3061	struct wpa_driver_nl80211_data *drv = bss->drv;
3062	struct nl_msg *msg;
3063	int ret = -1;
3064
3065	msg = nlmsg_alloc();
3066	if (!msg)
3067		return -1;
3068
3069	wpa_printf(MSG_DEBUG, "nl80211: Register frame type=0x%x nl_handle=%p",
3070		   type, nl_handle);
3071	wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
3072		    match, match_len);
3073
3074	nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_ACTION);
3075
3076	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3077	NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE, type);
3078	NLA_PUT(msg, NL80211_ATTR_FRAME_MATCH, match_len, match);
3079
3080	ret = send_and_recv(drv->global, nl_handle, msg, NULL, NULL);
3081	msg = NULL;
3082	if (ret) {
3083		wpa_printf(MSG_DEBUG, "nl80211: Register frame command "
3084			   "failed (type=%u): ret=%d (%s)",
3085			   type, ret, strerror(-ret));
3086		wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
3087			    match, match_len);
3088		goto nla_put_failure;
3089	}
3090	ret = 0;
3091nla_put_failure:
3092	nlmsg_free(msg);
3093	return ret;
3094}
3095
3096
3097static int nl80211_alloc_mgmt_handle(struct i802_bss *bss)
3098{
3099	struct wpa_driver_nl80211_data *drv = bss->drv;
3100
3101	if (bss->nl_mgmt) {
3102		wpa_printf(MSG_DEBUG, "nl80211: Mgmt reporting "
3103			   "already on! (nl_mgmt=%p)", bss->nl_mgmt);
3104		return -1;
3105	}
3106
3107	bss->nl_mgmt = nl_create_handle(drv->nl_cb, "mgmt");
3108	if (bss->nl_mgmt == NULL)
3109		return -1;
3110
3111	eloop_register_read_sock(nl_socket_get_fd(bss->nl_mgmt),
3112				 wpa_driver_nl80211_event_receive, bss->nl_cb,
3113				 bss->nl_mgmt);
3114
3115	return 0;
3116}
3117
3118
3119static int nl80211_register_action_frame(struct i802_bss *bss,
3120					 const u8 *match, size_t match_len)
3121{
3122	u16 type = (WLAN_FC_TYPE_MGMT << 2) | (WLAN_FC_STYPE_ACTION << 4);
3123	return nl80211_register_frame(bss, bss->nl_mgmt,
3124				      type, match, match_len);
3125}
3126
3127
3128static int nl80211_mgmt_subscribe_non_ap(struct i802_bss *bss)
3129{
3130	struct wpa_driver_nl80211_data *drv = bss->drv;
3131
3132	if (nl80211_alloc_mgmt_handle(bss))
3133		return -1;
3134	wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with non-AP "
3135		   "handle %p", bss->nl_mgmt);
3136
3137#if defined(CONFIG_P2P) || defined(CONFIG_INTERWORKING)
3138	/* GAS Initial Request */
3139	if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0a", 2) < 0)
3140		return -1;
3141	/* GAS Initial Response */
3142	if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0b", 2) < 0)
3143		return -1;
3144	/* GAS Comeback Request */
3145	if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0c", 2) < 0)
3146		return -1;
3147	/* GAS Comeback Response */
3148	if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0d", 2) < 0)
3149		return -1;
3150#endif /* CONFIG_P2P || CONFIG_INTERWORKING */
3151#ifdef CONFIG_P2P
3152	/* P2P Public Action */
3153	if (nl80211_register_action_frame(bss,
3154					  (u8 *) "\x04\x09\x50\x6f\x9a\x09",
3155					  6) < 0)
3156		return -1;
3157	/* P2P Action */
3158	if (nl80211_register_action_frame(bss,
3159					  (u8 *) "\x7f\x50\x6f\x9a\x09",
3160					  5) < 0)
3161		return -1;
3162#endif /* CONFIG_P2P */
3163#ifdef CONFIG_IEEE80211W
3164	/* SA Query Response */
3165	if (nl80211_register_action_frame(bss, (u8 *) "\x08\x01", 2) < 0)
3166		return -1;
3167#endif /* CONFIG_IEEE80211W */
3168#ifdef CONFIG_TDLS
3169	if ((drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT)) {
3170		/* TDLS Discovery Response */
3171		if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0e", 2) <
3172		    0)
3173			return -1;
3174	}
3175#endif /* CONFIG_TDLS */
3176
3177	/* FT Action frames */
3178	if (nl80211_register_action_frame(bss, (u8 *) "\x06", 1) < 0)
3179		return -1;
3180	else
3181		drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_FT |
3182			WPA_DRIVER_CAPA_KEY_MGMT_FT_PSK;
3183
3184	/* WNM - BSS Transition Management Request */
3185	if (nl80211_register_action_frame(bss, (u8 *) "\x0a\x07", 2) < 0)
3186		return -1;
3187
3188	return 0;
3189}
3190
3191
3192static int nl80211_register_spurious_class3(struct i802_bss *bss)
3193{
3194	struct wpa_driver_nl80211_data *drv = bss->drv;
3195	struct nl_msg *msg;
3196	int ret = -1;
3197
3198	msg = nlmsg_alloc();
3199	if (!msg)
3200		return -1;
3201
3202	nl80211_cmd(drv, msg, 0, NL80211_CMD_UNEXPECTED_FRAME);
3203
3204	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3205
3206	ret = send_and_recv(drv->global, bss->nl_mgmt, msg, NULL, NULL);
3207	msg = NULL;
3208	if (ret) {
3209		wpa_printf(MSG_DEBUG, "nl80211: Register spurious class3 "
3210			   "failed: ret=%d (%s)",
3211			   ret, strerror(-ret));
3212		goto nla_put_failure;
3213	}
3214	ret = 0;
3215nla_put_failure:
3216	nlmsg_free(msg);
3217	return ret;
3218}
3219
3220
3221static int nl80211_mgmt_subscribe_ap(struct i802_bss *bss)
3222{
3223	static const int stypes[] = {
3224		WLAN_FC_STYPE_AUTH,
3225		WLAN_FC_STYPE_ASSOC_REQ,
3226		WLAN_FC_STYPE_REASSOC_REQ,
3227		WLAN_FC_STYPE_DISASSOC,
3228		WLAN_FC_STYPE_DEAUTH,
3229		WLAN_FC_STYPE_ACTION,
3230		WLAN_FC_STYPE_PROBE_REQ,
3231/* Beacon doesn't work as mac80211 doesn't currently allow
3232 * it, but it wouldn't really be the right thing anyway as
3233 * it isn't per interface ... maybe just dump the scan
3234 * results periodically for OLBC?
3235 */
3236//		WLAN_FC_STYPE_BEACON,
3237	};
3238	unsigned int i;
3239
3240	if (nl80211_alloc_mgmt_handle(bss))
3241		return -1;
3242	wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3243		   "handle %p", bss->nl_mgmt);
3244
3245	for (i = 0; i < sizeof(stypes) / sizeof(stypes[0]); i++) {
3246		if (nl80211_register_frame(bss, bss->nl_mgmt,
3247					   (WLAN_FC_TYPE_MGMT << 2) |
3248					   (stypes[i] << 4),
3249					   NULL, 0) < 0) {
3250			goto out_err;
3251		}
3252	}
3253
3254	if (nl80211_register_spurious_class3(bss))
3255		goto out_err;
3256
3257	if (nl80211_get_wiphy_data_ap(bss) == NULL)
3258		goto out_err;
3259
3260	return 0;
3261
3262out_err:
3263	eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3264	nl_destroy_handles(&bss->nl_mgmt);
3265	return -1;
3266}
3267
3268
3269static int nl80211_mgmt_subscribe_ap_dev_sme(struct i802_bss *bss)
3270{
3271	if (nl80211_alloc_mgmt_handle(bss))
3272		return -1;
3273	wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3274		   "handle %p (device SME)", bss->nl_mgmt);
3275
3276	if (nl80211_register_frame(bss, bss->nl_mgmt,
3277				   (WLAN_FC_TYPE_MGMT << 2) |
3278				   (WLAN_FC_STYPE_ACTION << 4),
3279				   NULL, 0) < 0)
3280		goto out_err;
3281
3282	return 0;
3283
3284out_err:
3285	eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3286	nl_destroy_handles(&bss->nl_mgmt);
3287	return -1;
3288}
3289
3290
3291static void nl80211_mgmt_unsubscribe(struct i802_bss *bss, const char *reason)
3292{
3293	if (bss->nl_mgmt == NULL)
3294		return;
3295	wpa_printf(MSG_DEBUG, "nl80211: Unsubscribe mgmt frames handle %p "
3296		   "(%s)", bss->nl_mgmt, reason);
3297	eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3298	nl_destroy_handles(&bss->nl_mgmt);
3299
3300	nl80211_put_wiphy_data_ap(bss);
3301}
3302
3303
3304static void wpa_driver_nl80211_send_rfkill(void *eloop_ctx, void *timeout_ctx)
3305{
3306	wpa_supplicant_event(timeout_ctx, EVENT_INTERFACE_DISABLED, NULL);
3307}
3308
3309
3310static int
3311wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv)
3312{
3313	struct i802_bss *bss = &drv->first_bss;
3314	int send_rfkill_event = 0;
3315
3316	drv->ifindex = if_nametoindex(bss->ifname);
3317	drv->first_bss.ifindex = drv->ifindex;
3318
3319#ifndef HOSTAPD
3320	/*
3321	 * Make sure the interface starts up in station mode unless this is a
3322	 * dynamically added interface (e.g., P2P) that was already configured
3323	 * with proper iftype.
3324	 */
3325	if (drv->ifindex != drv->global->if_add_ifindex &&
3326	    wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION) < 0) {
3327		wpa_printf(MSG_ERROR, "nl80211: Could not configure driver to "
3328			   "use managed mode");
3329		return -1;
3330	}
3331
3332	if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
3333		if (rfkill_is_blocked(drv->rfkill)) {
3334			wpa_printf(MSG_DEBUG, "nl80211: Could not yet enable "
3335				   "interface '%s' due to rfkill",
3336				   bss->ifname);
3337			drv->if_disabled = 1;
3338			send_rfkill_event = 1;
3339		} else {
3340			wpa_printf(MSG_ERROR, "nl80211: Could not set "
3341				   "interface '%s' UP", bss->ifname);
3342			return -1;
3343		}
3344	}
3345
3346	netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
3347			       1, IF_OPER_DORMANT);
3348#endif /* HOSTAPD */
3349
3350	if (wpa_driver_nl80211_capa(drv))
3351		return -1;
3352
3353	if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
3354			       bss->addr))
3355		return -1;
3356
3357	if (send_rfkill_event) {
3358		eloop_register_timeout(0, 0, wpa_driver_nl80211_send_rfkill,
3359				       drv, drv->ctx);
3360	}
3361
3362	return 0;
3363}
3364
3365
3366static int wpa_driver_nl80211_del_beacon(struct wpa_driver_nl80211_data *drv)
3367{
3368	struct nl_msg *msg;
3369
3370	msg = nlmsg_alloc();
3371	if (!msg)
3372		return -ENOMEM;
3373
3374	nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_BEACON);
3375	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3376
3377	return send_and_recv_msgs(drv, msg, NULL, NULL);
3378 nla_put_failure:
3379	nlmsg_free(msg);
3380	return -ENOBUFS;
3381}
3382
3383
3384/**
3385 * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
3386 * @priv: Pointer to private nl80211 data from wpa_driver_nl80211_init()
3387 *
3388 * Shut down driver interface and processing of driver events. Free
3389 * private data buffer if one was allocated in wpa_driver_nl80211_init().
3390 */
3391static void wpa_driver_nl80211_deinit(void *priv)
3392{
3393	struct i802_bss *bss = priv;
3394	struct wpa_driver_nl80211_data *drv = bss->drv;
3395
3396	bss->in_deinit = 1;
3397	if (drv->data_tx_status)
3398		eloop_unregister_read_sock(drv->eapol_tx_sock);
3399	if (drv->eapol_tx_sock >= 0)
3400		close(drv->eapol_tx_sock);
3401
3402	if (bss->nl_preq)
3403		wpa_driver_nl80211_probe_req_report(bss, 0);
3404	if (bss->added_if_into_bridge) {
3405		if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
3406				    bss->ifname) < 0)
3407			wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3408				   "interface %s from bridge %s: %s",
3409				   bss->ifname, bss->brname, strerror(errno));
3410	}
3411	if (bss->added_bridge) {
3412		if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
3413			wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3414				   "bridge %s: %s",
3415				   bss->brname, strerror(errno));
3416	}
3417
3418	nl80211_remove_monitor_interface(drv);
3419
3420	if (is_ap_interface(drv->nlmode))
3421		wpa_driver_nl80211_del_beacon(drv);
3422
3423#ifdef HOSTAPD
3424	if (drv->last_freq_ht) {
3425		/* Clear HT flags from the driver */
3426		struct hostapd_freq_params freq;
3427		os_memset(&freq, 0, sizeof(freq));
3428		freq.freq = drv->last_freq;
3429		i802_set_freq(priv, &freq);
3430	}
3431
3432	if (drv->eapol_sock >= 0) {
3433		eloop_unregister_read_sock(drv->eapol_sock);
3434		close(drv->eapol_sock);
3435	}
3436
3437	if (drv->if_indices != drv->default_if_indices)
3438		os_free(drv->if_indices);
3439#endif /* HOSTAPD */
3440
3441	if (drv->disabled_11b_rates)
3442		nl80211_disable_11b_rates(drv, drv->ifindex, 0);
3443
3444	netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, 0,
3445			       IF_OPER_UP);
3446	rfkill_deinit(drv->rfkill);
3447
3448	eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3449
3450	(void) linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0);
3451	wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION);
3452	nl80211_mgmt_unsubscribe(bss, "deinit");
3453
3454	nl_cb_put(drv->nl_cb);
3455
3456	nl80211_destroy_bss(&drv->first_bss);
3457
3458	os_free(drv->filter_ssids);
3459
3460	os_free(drv->auth_ie);
3461
3462	if (drv->in_interface_list)
3463		dl_list_del(&drv->list);
3464
3465	os_free(drv);
3466}
3467
3468
3469/**
3470 * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
3471 * @eloop_ctx: Driver private data
3472 * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
3473 *
3474 * This function can be used as registered timeout when starting a scan to
3475 * generate a scan completed event if the driver does not report this.
3476 */
3477static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
3478{
3479	struct wpa_driver_nl80211_data *drv = eloop_ctx;
3480	if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED) {
3481		wpa_driver_nl80211_set_mode(&drv->first_bss,
3482					    drv->ap_scan_as_station);
3483		drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
3484	}
3485	wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
3486	wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
3487}
3488
3489
3490/**
3491 * wpa_driver_nl80211_scan - Request the driver to initiate scan
3492 * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3493 * @params: Scan parameters
3494 * Returns: 0 on success, -1 on failure
3495 */
3496static int wpa_driver_nl80211_scan(void *priv,
3497				   struct wpa_driver_scan_params *params)
3498{
3499	struct i802_bss *bss = priv;
3500	struct wpa_driver_nl80211_data *drv = bss->drv;
3501	int ret = 0, timeout;
3502	struct nl_msg *msg, *ssids, *freqs, *rates;
3503	size_t i;
3504
3505	drv->scan_for_auth = 0;
3506
3507	msg = nlmsg_alloc();
3508	ssids = nlmsg_alloc();
3509	freqs = nlmsg_alloc();
3510	rates = nlmsg_alloc();
3511	if (!msg || !ssids || !freqs || !rates) {
3512		nlmsg_free(msg);
3513		nlmsg_free(ssids);
3514		nlmsg_free(freqs);
3515		nlmsg_free(rates);
3516		return -1;
3517	}
3518
3519	os_free(drv->filter_ssids);
3520	drv->filter_ssids = params->filter_ssids;
3521	params->filter_ssids = NULL;
3522	drv->num_filter_ssids = params->num_filter_ssids;
3523
3524	nl80211_cmd(drv, msg, 0, NL80211_CMD_TRIGGER_SCAN);
3525
3526	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3527
3528	for (i = 0; i < params->num_ssids; i++) {
3529		wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan SSID",
3530				  params->ssids[i].ssid,
3531				  params->ssids[i].ssid_len);
3532		NLA_PUT(ssids, i + 1, params->ssids[i].ssid_len,
3533			params->ssids[i].ssid);
3534	}
3535	if (params->num_ssids)
3536		nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
3537
3538	if (params->extra_ies) {
3539		wpa_hexdump(MSG_MSGDUMP, "nl80211: Scan extra IEs",
3540			    params->extra_ies, params->extra_ies_len);
3541		NLA_PUT(msg, NL80211_ATTR_IE, params->extra_ies_len,
3542			params->extra_ies);
3543	}
3544
3545	if (params->freqs) {
3546		for (i = 0; params->freqs[i]; i++) {
3547			wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
3548				   "MHz", params->freqs[i]);
3549			NLA_PUT_U32(freqs, i + 1, params->freqs[i]);
3550		}
3551		nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs);
3552	}
3553
3554	if (params->p2p_probe) {
3555		wpa_printf(MSG_DEBUG, "nl80211: P2P probe - mask SuppRates");
3556
3557		/*
3558		 * Remove 2.4 GHz rates 1, 2, 5.5, 11 Mbps from supported rates
3559		 * by masking out everything else apart from the OFDM rates 6,
3560		 * 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS rates. All 5 GHz
3561		 * rates are left enabled.
3562		 */
3563		NLA_PUT(rates, NL80211_BAND_2GHZ, 8,
3564			"\x0c\x12\x18\x24\x30\x48\x60\x6c");
3565		nla_put_nested(msg, NL80211_ATTR_SCAN_SUPP_RATES, rates);
3566
3567		NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
3568	}
3569
3570	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3571	msg = NULL;
3572	if (ret) {
3573		wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
3574			   "(%s)", ret, strerror(-ret));
3575#ifdef HOSTAPD
3576		if (is_ap_interface(drv->nlmode)) {
3577			/*
3578			 * mac80211 does not allow scan requests in AP mode, so
3579			 * try to do this in station mode.
3580			 */
3581			if (wpa_driver_nl80211_set_mode(
3582				    bss, NL80211_IFTYPE_STATION))
3583				goto nla_put_failure;
3584
3585			if (wpa_driver_nl80211_scan(drv, params)) {
3586				wpa_driver_nl80211_set_mode(bss, drv->nlmode);
3587				goto nla_put_failure;
3588			}
3589
3590			/* Restore AP mode when processing scan results */
3591			drv->ap_scan_as_station = drv->nlmode;
3592			ret = 0;
3593		} else
3594			goto nla_put_failure;
3595#else /* HOSTAPD */
3596		goto nla_put_failure;
3597#endif /* HOSTAPD */
3598	}
3599
3600	/* Not all drivers generate "scan completed" wireless event, so try to
3601	 * read results after a timeout. */
3602	timeout = 10;
3603	if (drv->scan_complete_events) {
3604		/*
3605		 * The driver seems to deliver events to notify when scan is
3606		 * complete, so use longer timeout to avoid race conditions
3607		 * with scanning and following association request.
3608		 */
3609		timeout = 30;
3610	}
3611	wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
3612		   "seconds", ret, timeout);
3613	eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3614	eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
3615			       drv, drv->ctx);
3616
3617nla_put_failure:
3618	nlmsg_free(ssids);
3619	nlmsg_free(msg);
3620	nlmsg_free(freqs);
3621	nlmsg_free(rates);
3622	return ret;
3623}
3624
3625
3626/**
3627 * wpa_driver_nl80211_sched_scan - Initiate a scheduled scan
3628 * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3629 * @params: Scan parameters
3630 * @interval: Interval between scan cycles in milliseconds
3631 * Returns: 0 on success, -1 on failure or if not supported
3632 */
3633static int wpa_driver_nl80211_sched_scan(void *priv,
3634					 struct wpa_driver_scan_params *params,
3635					 u32 interval)
3636{
3637	struct i802_bss *bss = priv;
3638	struct wpa_driver_nl80211_data *drv = bss->drv;
3639	int ret = 0;
3640	struct nl_msg *msg, *ssids, *freqs, *match_set_ssid, *match_sets;
3641	size_t i;
3642
3643#ifdef ANDROID
3644	if (!drv->capa.sched_scan_supported)
3645		return android_pno_start(bss, params);
3646#endif /* ANDROID */
3647
3648	msg = nlmsg_alloc();
3649	ssids = nlmsg_alloc();
3650	freqs = nlmsg_alloc();
3651	if (!msg || !ssids || !freqs) {
3652		nlmsg_free(msg);
3653		nlmsg_free(ssids);
3654		nlmsg_free(freqs);
3655		return -1;
3656	}
3657
3658	os_free(drv->filter_ssids);
3659	drv->filter_ssids = params->filter_ssids;
3660	params->filter_ssids = NULL;
3661	drv->num_filter_ssids = params->num_filter_ssids;
3662
3663	nl80211_cmd(drv, msg, 0, NL80211_CMD_START_SCHED_SCAN);
3664
3665	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3666
3667	NLA_PUT_U32(msg, NL80211_ATTR_SCHED_SCAN_INTERVAL, interval);
3668
3669	if (drv->num_filter_ssids &&
3670	    (int) drv->num_filter_ssids <= drv->capa.max_match_sets) {
3671		match_sets = nlmsg_alloc();
3672
3673		for (i = 0; i < drv->num_filter_ssids; i++) {
3674			wpa_hexdump_ascii(MSG_MSGDUMP,
3675					  "nl80211: Sched scan filter SSID",
3676					  drv->filter_ssids[i].ssid,
3677					  drv->filter_ssids[i].ssid_len);
3678
3679			match_set_ssid = nlmsg_alloc();
3680			nla_put(match_set_ssid,
3681				NL80211_ATTR_SCHED_SCAN_MATCH_SSID,
3682				drv->filter_ssids[i].ssid_len,
3683				drv->filter_ssids[i].ssid);
3684
3685			nla_put_nested(match_sets, i + 1, match_set_ssid);
3686
3687			nlmsg_free(match_set_ssid);
3688		}
3689
3690		nla_put_nested(msg, NL80211_ATTR_SCHED_SCAN_MATCH,
3691			       match_sets);
3692		nlmsg_free(match_sets);
3693	}
3694
3695	for (i = 0; i < params->num_ssids; i++) {
3696		wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Sched scan SSID",
3697				  params->ssids[i].ssid,
3698				  params->ssids[i].ssid_len);
3699		NLA_PUT(ssids, i + 1, params->ssids[i].ssid_len,
3700			params->ssids[i].ssid);
3701	}
3702	if (params->num_ssids)
3703		nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
3704
3705	if (params->extra_ies) {
3706		wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Sched scan extra IEs",
3707				  params->extra_ies, params->extra_ies_len);
3708		NLA_PUT(msg, NL80211_ATTR_IE, params->extra_ies_len,
3709			params->extra_ies);
3710	}
3711
3712	if (params->freqs) {
3713		for (i = 0; params->freqs[i]; i++) {
3714			wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
3715				   "MHz", params->freqs[i]);
3716			NLA_PUT_U32(freqs, i + 1, params->freqs[i]);
3717		}
3718		nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs);
3719	}
3720
3721	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3722
3723	/* TODO: if we get an error here, we should fall back to normal scan */
3724
3725	msg = NULL;
3726	if (ret) {
3727		wpa_printf(MSG_DEBUG, "nl80211: Sched scan start failed: "
3728			   "ret=%d (%s)", ret, strerror(-ret));
3729		goto nla_put_failure;
3730	}
3731
3732	wpa_printf(MSG_DEBUG, "nl80211: Sched scan requested (ret=%d) - "
3733		   "scan interval %d msec", ret, interval);
3734
3735nla_put_failure:
3736	nlmsg_free(ssids);
3737	nlmsg_free(msg);
3738	nlmsg_free(freqs);
3739	return ret;
3740}
3741
3742
3743/**
3744 * wpa_driver_nl80211_stop_sched_scan - Stop a scheduled scan
3745 * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3746 * Returns: 0 on success, -1 on failure or if not supported
3747 */
3748static int wpa_driver_nl80211_stop_sched_scan(void *priv)
3749{
3750	struct i802_bss *bss = priv;
3751	struct wpa_driver_nl80211_data *drv = bss->drv;
3752	int ret = 0;
3753	struct nl_msg *msg;
3754
3755#ifdef ANDROID
3756	if (!drv->capa.sched_scan_supported)
3757		return android_pno_stop(bss);
3758#endif /* ANDROID */
3759
3760	msg = nlmsg_alloc();
3761	if (!msg)
3762		return -1;
3763
3764	nl80211_cmd(drv, msg, 0, NL80211_CMD_STOP_SCHED_SCAN);
3765
3766	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3767
3768	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3769	msg = NULL;
3770	if (ret) {
3771		wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop failed: "
3772			   "ret=%d (%s)", ret, strerror(-ret));
3773		goto nla_put_failure;
3774	}
3775
3776	wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop sent (ret=%d)", ret);
3777
3778nla_put_failure:
3779	nlmsg_free(msg);
3780	return ret;
3781}
3782
3783
3784static const u8 * nl80211_get_ie(const u8 *ies, size_t ies_len, u8 ie)
3785{
3786	const u8 *end, *pos;
3787
3788	if (ies == NULL)
3789		return NULL;
3790
3791	pos = ies;
3792	end = ies + ies_len;
3793
3794	while (pos + 1 < end) {
3795		if (pos + 2 + pos[1] > end)
3796			break;
3797		if (pos[0] == ie)
3798			return pos;
3799		pos += 2 + pos[1];
3800	}
3801
3802	return NULL;
3803}
3804
3805
3806static int nl80211_scan_filtered(struct wpa_driver_nl80211_data *drv,
3807				 const u8 *ie, size_t ie_len)
3808{
3809	const u8 *ssid;
3810	size_t i;
3811
3812	if (drv->filter_ssids == NULL)
3813		return 0;
3814
3815	ssid = nl80211_get_ie(ie, ie_len, WLAN_EID_SSID);
3816	if (ssid == NULL)
3817		return 1;
3818
3819	for (i = 0; i < drv->num_filter_ssids; i++) {
3820		if (ssid[1] == drv->filter_ssids[i].ssid_len &&
3821		    os_memcmp(ssid + 2, drv->filter_ssids[i].ssid, ssid[1]) ==
3822		    0)
3823			return 0;
3824	}
3825
3826	return 1;
3827}
3828
3829
3830static int bss_info_handler(struct nl_msg *msg, void *arg)
3831{
3832	struct nlattr *tb[NL80211_ATTR_MAX + 1];
3833	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3834	struct nlattr *bss[NL80211_BSS_MAX + 1];
3835	static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
3836		[NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
3837		[NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
3838		[NL80211_BSS_TSF] = { .type = NLA_U64 },
3839		[NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
3840		[NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
3841		[NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
3842		[NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
3843		[NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
3844		[NL80211_BSS_STATUS] = { .type = NLA_U32 },
3845		[NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
3846		[NL80211_BSS_BEACON_IES] = { .type = NLA_UNSPEC },
3847	};
3848	struct nl80211_bss_info_arg *_arg = arg;
3849	struct wpa_scan_results *res = _arg->res;
3850	struct wpa_scan_res **tmp;
3851	struct wpa_scan_res *r;
3852	const u8 *ie, *beacon_ie;
3853	size_t ie_len, beacon_ie_len;
3854	u8 *pos;
3855	size_t i;
3856
3857	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3858		  genlmsg_attrlen(gnlh, 0), NULL);
3859	if (!tb[NL80211_ATTR_BSS])
3860		return NL_SKIP;
3861	if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
3862			     bss_policy))
3863		return NL_SKIP;
3864	if (bss[NL80211_BSS_STATUS]) {
3865		enum nl80211_bss_status status;
3866		status = nla_get_u32(bss[NL80211_BSS_STATUS]);
3867		if (status == NL80211_BSS_STATUS_ASSOCIATED &&
3868		    bss[NL80211_BSS_FREQUENCY]) {
3869			_arg->assoc_freq =
3870				nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
3871			wpa_printf(MSG_DEBUG, "nl80211: Associated on %u MHz",
3872				   _arg->assoc_freq);
3873		}
3874		if (status == NL80211_BSS_STATUS_ASSOCIATED &&
3875		    bss[NL80211_BSS_BSSID]) {
3876			os_memcpy(_arg->assoc_bssid,
3877				  nla_data(bss[NL80211_BSS_BSSID]), ETH_ALEN);
3878			wpa_printf(MSG_DEBUG, "nl80211: Associated with "
3879				   MACSTR, MAC2STR(_arg->assoc_bssid));
3880		}
3881	}
3882	if (!res)
3883		return NL_SKIP;
3884	if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
3885		ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
3886		ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
3887	} else {
3888		ie = NULL;
3889		ie_len = 0;
3890	}
3891	if (bss[NL80211_BSS_BEACON_IES]) {
3892		beacon_ie = nla_data(bss[NL80211_BSS_BEACON_IES]);
3893		beacon_ie_len = nla_len(bss[NL80211_BSS_BEACON_IES]);
3894	} else {
3895		beacon_ie = NULL;
3896		beacon_ie_len = 0;
3897	}
3898
3899	if (nl80211_scan_filtered(_arg->drv, ie ? ie : beacon_ie,
3900				  ie ? ie_len : beacon_ie_len))
3901		return NL_SKIP;
3902
3903	r = os_zalloc(sizeof(*r) + ie_len + beacon_ie_len);
3904	if (r == NULL)
3905		return NL_SKIP;
3906	if (bss[NL80211_BSS_BSSID])
3907		os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
3908			  ETH_ALEN);
3909	if (bss[NL80211_BSS_FREQUENCY])
3910		r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
3911	if (bss[NL80211_BSS_BEACON_INTERVAL])
3912		r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
3913	if (bss[NL80211_BSS_CAPABILITY])
3914		r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
3915	r->flags |= WPA_SCAN_NOISE_INVALID;
3916	if (bss[NL80211_BSS_SIGNAL_MBM]) {
3917		r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
3918		r->level /= 100; /* mBm to dBm */
3919		r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
3920	} else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
3921		r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
3922		r->flags |= WPA_SCAN_QUAL_INVALID;
3923	} else
3924		r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
3925	if (bss[NL80211_BSS_TSF])
3926		r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
3927	if (bss[NL80211_BSS_SEEN_MS_AGO])
3928		r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
3929	r->ie_len = ie_len;
3930	pos = (u8 *) (r + 1);
3931	if (ie) {
3932		os_memcpy(pos, ie, ie_len);
3933		pos += ie_len;
3934	}
3935	r->beacon_ie_len = beacon_ie_len;
3936	if (beacon_ie)
3937		os_memcpy(pos, beacon_ie, beacon_ie_len);
3938
3939	if (bss[NL80211_BSS_STATUS]) {
3940		enum nl80211_bss_status status;
3941		status = nla_get_u32(bss[NL80211_BSS_STATUS]);
3942		switch (status) {
3943		case NL80211_BSS_STATUS_AUTHENTICATED:
3944			r->flags |= WPA_SCAN_AUTHENTICATED;
3945			break;
3946		case NL80211_BSS_STATUS_ASSOCIATED:
3947			r->flags |= WPA_SCAN_ASSOCIATED;
3948			break;
3949		default:
3950			break;
3951		}
3952	}
3953
3954	/*
3955	 * cfg80211 maintains separate BSS table entries for APs if the same
3956	 * BSSID,SSID pair is seen on multiple channels. wpa_supplicant does
3957	 * not use frequency as a separate key in the BSS table, so filter out
3958	 * duplicated entries. Prefer associated BSS entry in such a case in
3959	 * order to get the correct frequency into the BSS table.
3960	 */
3961	for (i = 0; i < res->num; i++) {
3962		const u8 *s1, *s2;
3963		if (os_memcmp(res->res[i]->bssid, r->bssid, ETH_ALEN) != 0)
3964			continue;
3965
3966		s1 = nl80211_get_ie((u8 *) (res->res[i] + 1),
3967				    res->res[i]->ie_len, WLAN_EID_SSID);
3968		s2 = nl80211_get_ie((u8 *) (r + 1), r->ie_len, WLAN_EID_SSID);
3969		if (s1 == NULL || s2 == NULL || s1[1] != s2[1] ||
3970		    os_memcmp(s1, s2, 2 + s1[1]) != 0)
3971			continue;
3972
3973		/* Same BSSID,SSID was already included in scan results */
3974		wpa_printf(MSG_DEBUG, "nl80211: Remove duplicated scan result "
3975			   "for " MACSTR, MAC2STR(r->bssid));
3976
3977		if ((r->flags & WPA_SCAN_ASSOCIATED) &&
3978		    !(res->res[i]->flags & WPA_SCAN_ASSOCIATED)) {
3979			os_free(res->res[i]);
3980			res->res[i] = r;
3981		} else
3982			os_free(r);
3983		return NL_SKIP;
3984	}
3985
3986	tmp = os_realloc(res->res,
3987			 (res->num + 1) * sizeof(struct wpa_scan_res *));
3988	if (tmp == NULL) {
3989		os_free(r);
3990		return NL_SKIP;
3991	}
3992	tmp[res->num++] = r;
3993	res->res = tmp;
3994
3995	return NL_SKIP;
3996}
3997
3998
3999static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
4000				 const u8 *addr)
4001{
4002	if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
4003		wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
4004			   "mismatch (" MACSTR ")", MAC2STR(addr));
4005		wpa_driver_nl80211_mlme(drv, addr,
4006					NL80211_CMD_DEAUTHENTICATE,
4007					WLAN_REASON_PREV_AUTH_NOT_VALID, 1);
4008	}
4009}
4010
4011
4012static void wpa_driver_nl80211_check_bss_status(
4013	struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
4014{
4015	size_t i;
4016
4017	for (i = 0; i < res->num; i++) {
4018		struct wpa_scan_res *r = res->res[i];
4019		if (r->flags & WPA_SCAN_AUTHENTICATED) {
4020			wpa_printf(MSG_DEBUG, "nl80211: Scan results "
4021				   "indicates BSS status with " MACSTR
4022				   " as authenticated",
4023				   MAC2STR(r->bssid));
4024			if (is_sta_interface(drv->nlmode) &&
4025			    os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
4026			    os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
4027			    0) {
4028				wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
4029					   " in local state (auth=" MACSTR
4030					   " assoc=" MACSTR ")",
4031					   MAC2STR(drv->auth_bssid),
4032					   MAC2STR(drv->bssid));
4033				clear_state_mismatch(drv, r->bssid);
4034			}
4035		}
4036
4037		if (r->flags & WPA_SCAN_ASSOCIATED) {
4038			wpa_printf(MSG_DEBUG, "nl80211: Scan results "
4039				   "indicate BSS status with " MACSTR
4040				   " as associated",
4041				   MAC2STR(r->bssid));
4042			if (is_sta_interface(drv->nlmode) &&
4043			    !drv->associated) {
4044				wpa_printf(MSG_DEBUG, "nl80211: Local state "
4045					   "(not associated) does not match "
4046					   "with BSS state");
4047				clear_state_mismatch(drv, r->bssid);
4048			} else if (is_sta_interface(drv->nlmode) &&
4049				   os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
4050				   0) {
4051				wpa_printf(MSG_DEBUG, "nl80211: Local state "
4052					   "(associated with " MACSTR ") does "
4053					   "not match with BSS state",
4054					   MAC2STR(drv->bssid));
4055				clear_state_mismatch(drv, r->bssid);
4056				clear_state_mismatch(drv, drv->bssid);
4057			}
4058		}
4059	}
4060}
4061
4062
4063static struct wpa_scan_results *
4064nl80211_get_scan_results(struct wpa_driver_nl80211_data *drv)
4065{
4066	struct nl_msg *msg;
4067	struct wpa_scan_results *res;
4068	int ret;
4069	struct nl80211_bss_info_arg arg;
4070
4071	res = os_zalloc(sizeof(*res));
4072	if (res == NULL)
4073		return NULL;
4074	msg = nlmsg_alloc();
4075	if (!msg)
4076		goto nla_put_failure;
4077
4078	nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
4079	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4080
4081	arg.drv = drv;
4082	arg.res = res;
4083	ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
4084	msg = NULL;
4085	if (ret == 0) {
4086		wpa_printf(MSG_DEBUG, "nl80211: Received scan results (%lu "
4087			   "BSSes)", (unsigned long) res->num);
4088		nl80211_get_noise_for_scan_results(drv, res);
4089		return res;
4090	}
4091	wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
4092		   "(%s)", ret, strerror(-ret));
4093nla_put_failure:
4094	nlmsg_free(msg);
4095	wpa_scan_results_free(res);
4096	return NULL;
4097}
4098
4099
4100/**
4101 * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
4102 * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
4103 * Returns: Scan results on success, -1 on failure
4104 */
4105static struct wpa_scan_results *
4106wpa_driver_nl80211_get_scan_results(void *priv)
4107{
4108	struct i802_bss *bss = priv;
4109	struct wpa_driver_nl80211_data *drv = bss->drv;
4110	struct wpa_scan_results *res;
4111
4112	res = nl80211_get_scan_results(drv);
4113	if (res)
4114		wpa_driver_nl80211_check_bss_status(drv, res);
4115	return res;
4116}
4117
4118
4119static void nl80211_dump_scan(struct wpa_driver_nl80211_data *drv)
4120{
4121	struct wpa_scan_results *res;
4122	size_t i;
4123
4124	res = nl80211_get_scan_results(drv);
4125	if (res == NULL) {
4126		wpa_printf(MSG_DEBUG, "nl80211: Failed to get scan results");
4127		return;
4128	}
4129
4130	wpa_printf(MSG_DEBUG, "nl80211: Scan result dump");
4131	for (i = 0; i < res->num; i++) {
4132		struct wpa_scan_res *r = res->res[i];
4133		wpa_printf(MSG_DEBUG, "nl80211: %d/%d " MACSTR "%s%s",
4134			   (int) i, (int) res->num, MAC2STR(r->bssid),
4135			   r->flags & WPA_SCAN_AUTHENTICATED ? " [auth]" : "",
4136			   r->flags & WPA_SCAN_ASSOCIATED ? " [assoc]" : "");
4137	}
4138
4139	wpa_scan_results_free(res);
4140}
4141
4142
4143static int wpa_driver_nl80211_set_key(const char *ifname, void *priv,
4144				      enum wpa_alg alg, const u8 *addr,
4145				      int key_idx, int set_tx,
4146				      const u8 *seq, size_t seq_len,
4147				      const u8 *key, size_t key_len)
4148{
4149	struct i802_bss *bss = priv;
4150	struct wpa_driver_nl80211_data *drv = bss->drv;
4151	int ifindex = if_nametoindex(ifname);
4152	struct nl_msg *msg;
4153	int ret;
4154
4155	wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
4156		   "set_tx=%d seq_len=%lu key_len=%lu",
4157		   __func__, ifindex, alg, addr, key_idx, set_tx,
4158		   (unsigned long) seq_len, (unsigned long) key_len);
4159#ifdef CONFIG_TDLS
4160	if (key_idx == -1)
4161		key_idx = 0;
4162#endif /* CONFIG_TDLS */
4163
4164	msg = nlmsg_alloc();
4165	if (!msg)
4166		return -ENOMEM;
4167
4168	if (alg == WPA_ALG_NONE) {
4169		nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_KEY);
4170	} else {
4171		nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_KEY);
4172		NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
4173		switch (alg) {
4174		case WPA_ALG_WEP:
4175			if (key_len == 5)
4176				NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4177					    WLAN_CIPHER_SUITE_WEP40);
4178			else
4179				NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4180					    WLAN_CIPHER_SUITE_WEP104);
4181			break;
4182		case WPA_ALG_TKIP:
4183			NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4184				    WLAN_CIPHER_SUITE_TKIP);
4185			break;
4186		case WPA_ALG_CCMP:
4187			NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4188				    WLAN_CIPHER_SUITE_CCMP);
4189			break;
4190		case WPA_ALG_IGTK:
4191			NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4192				    WLAN_CIPHER_SUITE_AES_CMAC);
4193			break;
4194		default:
4195			wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4196				   "algorithm %d", __func__, alg);
4197			nlmsg_free(msg);
4198			return -1;
4199		}
4200	}
4201
4202	if (seq && seq_len)
4203		NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
4204
4205	if (addr && !is_broadcast_ether_addr(addr)) {
4206		wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
4207		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4208
4209		if (alg != WPA_ALG_WEP && key_idx && !set_tx) {
4210			wpa_printf(MSG_DEBUG, "   RSN IBSS RX GTK");
4211			NLA_PUT_U32(msg, NL80211_ATTR_KEY_TYPE,
4212				    NL80211_KEYTYPE_GROUP);
4213		}
4214	} else if (addr && is_broadcast_ether_addr(addr)) {
4215		struct nl_msg *types;
4216		int err;
4217		wpa_printf(MSG_DEBUG, "   broadcast key");
4218		types = nlmsg_alloc();
4219		if (!types)
4220			goto nla_put_failure;
4221		NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4222		err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4223				     types);
4224		nlmsg_free(types);
4225		if (err)
4226			goto nla_put_failure;
4227	}
4228	NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4229	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4230
4231	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4232	if ((ret == -ENOENT || ret == -ENOLINK) && alg == WPA_ALG_NONE)
4233		ret = 0;
4234	if (ret)
4235		wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
4236			   ret, strerror(-ret));
4237
4238	/*
4239	 * If we failed or don't need to set the default TX key (below),
4240	 * we're done here.
4241	 */
4242	if (ret || !set_tx || alg == WPA_ALG_NONE)
4243		return ret;
4244	if (is_ap_interface(drv->nlmode) && addr &&
4245	    !is_broadcast_ether_addr(addr))
4246		return ret;
4247
4248	msg = nlmsg_alloc();
4249	if (!msg)
4250		return -ENOMEM;
4251
4252	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_KEY);
4253	NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4254	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4255	if (alg == WPA_ALG_IGTK)
4256		NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
4257	else
4258		NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
4259	if (addr && is_broadcast_ether_addr(addr)) {
4260		struct nl_msg *types;
4261		int err;
4262		types = nlmsg_alloc();
4263		if (!types)
4264			goto nla_put_failure;
4265		NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4266		err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4267				     types);
4268		nlmsg_free(types);
4269		if (err)
4270			goto nla_put_failure;
4271	} else if (addr) {
4272		struct nl_msg *types;
4273		int err;
4274		types = nlmsg_alloc();
4275		if (!types)
4276			goto nla_put_failure;
4277		NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_UNICAST);
4278		err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4279				     types);
4280		nlmsg_free(types);
4281		if (err)
4282			goto nla_put_failure;
4283	}
4284
4285	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4286	if (ret == -ENOENT)
4287		ret = 0;
4288	if (ret)
4289		wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
4290			   "err=%d %s)", ret, strerror(-ret));
4291	return ret;
4292
4293nla_put_failure:
4294	nlmsg_free(msg);
4295	return -ENOBUFS;
4296}
4297
4298
4299static int nl_add_key(struct nl_msg *msg, enum wpa_alg alg,
4300		      int key_idx, int defkey,
4301		      const u8 *seq, size_t seq_len,
4302		      const u8 *key, size_t key_len)
4303{
4304	struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
4305	if (!key_attr)
4306		return -1;
4307
4308	if (defkey && alg == WPA_ALG_IGTK)
4309		NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
4310	else if (defkey)
4311		NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4312
4313	NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
4314
4315	switch (alg) {
4316	case WPA_ALG_WEP:
4317		if (key_len == 5)
4318			NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4319				    WLAN_CIPHER_SUITE_WEP40);
4320		else
4321			NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4322				    WLAN_CIPHER_SUITE_WEP104);
4323		break;
4324	case WPA_ALG_TKIP:
4325		NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_TKIP);
4326		break;
4327	case WPA_ALG_CCMP:
4328		NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_CCMP);
4329		break;
4330	case WPA_ALG_IGTK:
4331		NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4332			    WLAN_CIPHER_SUITE_AES_CMAC);
4333		break;
4334	default:
4335		wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4336			   "algorithm %d", __func__, alg);
4337		return -1;
4338	}
4339
4340	if (seq && seq_len)
4341		NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
4342
4343	NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
4344
4345	nla_nest_end(msg, key_attr);
4346
4347	return 0;
4348 nla_put_failure:
4349	return -1;
4350}
4351
4352
4353static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
4354				 struct nl_msg *msg)
4355{
4356	int i, privacy = 0;
4357	struct nlattr *nl_keys, *nl_key;
4358
4359	for (i = 0; i < 4; i++) {
4360		if (!params->wep_key[i])
4361			continue;
4362		privacy = 1;
4363		break;
4364	}
4365	if (params->wps == WPS_MODE_PRIVACY)
4366		privacy = 1;
4367	if (params->pairwise_suite &&
4368	    params->pairwise_suite != WPA_CIPHER_NONE)
4369		privacy = 1;
4370
4371	if (!privacy)
4372		return 0;
4373
4374	NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
4375
4376	nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
4377	if (!nl_keys)
4378		goto nla_put_failure;
4379
4380	for (i = 0; i < 4; i++) {
4381		if (!params->wep_key[i])
4382			continue;
4383
4384		nl_key = nla_nest_start(msg, i);
4385		if (!nl_key)
4386			goto nla_put_failure;
4387
4388		NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
4389			params->wep_key[i]);
4390		if (params->wep_key_len[i] == 5)
4391			NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4392				    WLAN_CIPHER_SUITE_WEP40);
4393		else
4394			NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4395				    WLAN_CIPHER_SUITE_WEP104);
4396
4397		NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
4398
4399		if (i == params->wep_tx_keyidx)
4400			NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4401
4402		nla_nest_end(msg, nl_key);
4403	}
4404	nla_nest_end(msg, nl_keys);
4405
4406	return 0;
4407
4408nla_put_failure:
4409	return -ENOBUFS;
4410}
4411
4412
4413static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
4414				   const u8 *addr, int cmd, u16 reason_code,
4415				   int local_state_change)
4416{
4417	int ret = -1;
4418	struct nl_msg *msg;
4419
4420	msg = nlmsg_alloc();
4421	if (!msg)
4422		return -1;
4423
4424	nl80211_cmd(drv, msg, 0, cmd);
4425
4426	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4427	NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
4428	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4429	if (local_state_change)
4430		NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4431
4432	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4433	msg = NULL;
4434	if (ret) {
4435		wpa_dbg(drv->ctx, MSG_DEBUG,
4436			"nl80211: MLME command failed: reason=%u ret=%d (%s)",
4437			reason_code, ret, strerror(-ret));
4438		goto nla_put_failure;
4439	}
4440	ret = 0;
4441
4442nla_put_failure:
4443	nlmsg_free(msg);
4444	return ret;
4445}
4446
4447
4448static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
4449					 const u8 *addr, int reason_code)
4450{
4451	wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
4452		   __func__, MAC2STR(addr), reason_code);
4453	drv->associated = 0;
4454	return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISCONNECT,
4455				       reason_code, 0);
4456}
4457
4458
4459static int wpa_driver_nl80211_deauthenticate(void *priv, const u8 *addr,
4460					     int reason_code)
4461{
4462	struct i802_bss *bss = priv;
4463	struct wpa_driver_nl80211_data *drv = bss->drv;
4464	if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
4465		return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
4466	wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
4467		   __func__, MAC2STR(addr), reason_code);
4468	drv->associated = 0;
4469	if (drv->nlmode == NL80211_IFTYPE_ADHOC)
4470		return nl80211_leave_ibss(drv);
4471	return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
4472				       reason_code, 0);
4473}
4474
4475
4476static int wpa_driver_nl80211_disassociate(void *priv, const u8 *addr,
4477					   int reason_code)
4478{
4479	struct i802_bss *bss = priv;
4480	struct wpa_driver_nl80211_data *drv = bss->drv;
4481	if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
4482		return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
4483	wpa_printf(MSG_DEBUG, "%s", __func__);
4484	drv->associated = 0;
4485	return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISASSOCIATE,
4486				       reason_code, 0);
4487}
4488
4489
4490static void nl80211_copy_auth_params(struct wpa_driver_nl80211_data *drv,
4491				     struct wpa_driver_auth_params *params)
4492{
4493	int i;
4494
4495	drv->auth_freq = params->freq;
4496	drv->auth_alg = params->auth_alg;
4497	drv->auth_wep_tx_keyidx = params->wep_tx_keyidx;
4498	drv->auth_local_state_change = params->local_state_change;
4499	drv->auth_p2p = params->p2p;
4500
4501	if (params->bssid)
4502		os_memcpy(drv->auth_bssid_, params->bssid, ETH_ALEN);
4503	else
4504		os_memset(drv->auth_bssid_, 0, ETH_ALEN);
4505
4506	if (params->ssid) {
4507		os_memcpy(drv->auth_ssid, params->ssid, params->ssid_len);
4508		drv->auth_ssid_len = params->ssid_len;
4509	} else
4510		drv->auth_ssid_len = 0;
4511
4512
4513	os_free(drv->auth_ie);
4514	drv->auth_ie = NULL;
4515	drv->auth_ie_len = 0;
4516	if (params->ie) {
4517		drv->auth_ie = os_malloc(params->ie_len);
4518		if (drv->auth_ie) {
4519			os_memcpy(drv->auth_ie, params->ie, params->ie_len);
4520			drv->auth_ie_len = params->ie_len;
4521		}
4522	}
4523
4524	for (i = 0; i < 4; i++) {
4525		if (params->wep_key[i] && params->wep_key_len[i] &&
4526		    params->wep_key_len[i] <= 16) {
4527			os_memcpy(drv->auth_wep_key[i], params->wep_key[i],
4528				  params->wep_key_len[i]);
4529			drv->auth_wep_key_len[i] = params->wep_key_len[i];
4530		} else
4531			drv->auth_wep_key_len[i] = 0;
4532	}
4533}
4534
4535
4536static int wpa_driver_nl80211_authenticate(
4537	void *priv, struct wpa_driver_auth_params *params)
4538{
4539	struct i802_bss *bss = priv;
4540	struct wpa_driver_nl80211_data *drv = bss->drv;
4541	int ret = -1, i;
4542	struct nl_msg *msg;
4543	enum nl80211_auth_type type;
4544	enum nl80211_iftype nlmode;
4545	int count = 0;
4546	int is_retry;
4547
4548	is_retry = drv->retry_auth;
4549	drv->retry_auth = 0;
4550
4551	drv->associated = 0;
4552	os_memset(drv->auth_bssid, 0, ETH_ALEN);
4553	/* FIX: IBSS mode */
4554	nlmode = params->p2p ?
4555		NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
4556	if (drv->nlmode != nlmode &&
4557	    wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
4558		return -1;
4559
4560retry:
4561	msg = nlmsg_alloc();
4562	if (!msg)
4563		return -1;
4564
4565	wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
4566		   drv->ifindex);
4567
4568	nl80211_cmd(drv, msg, 0, NL80211_CMD_AUTHENTICATE);
4569
4570	for (i = 0; i < 4; i++) {
4571		if (!params->wep_key[i])
4572			continue;
4573		wpa_driver_nl80211_set_key(bss->ifname, priv, WPA_ALG_WEP,
4574					   NULL, i,
4575					   i == params->wep_tx_keyidx, NULL, 0,
4576					   params->wep_key[i],
4577					   params->wep_key_len[i]);
4578		if (params->wep_tx_keyidx != i)
4579			continue;
4580		if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
4581			       params->wep_key[i], params->wep_key_len[i])) {
4582			nlmsg_free(msg);
4583			return -1;
4584		}
4585	}
4586
4587	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4588	if (params->bssid) {
4589		wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4590			   MAC2STR(params->bssid));
4591		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4592	}
4593	if (params->freq) {
4594		wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4595		NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4596	}
4597	if (params->ssid) {
4598		wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4599				  params->ssid, params->ssid_len);
4600		NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4601			params->ssid);
4602	}
4603	wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
4604	if (params->ie)
4605		NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
4606	if (params->auth_alg & WPA_AUTH_ALG_OPEN)
4607		type = NL80211_AUTHTYPE_OPEN_SYSTEM;
4608	else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
4609		type = NL80211_AUTHTYPE_SHARED_KEY;
4610	else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
4611		type = NL80211_AUTHTYPE_NETWORK_EAP;
4612	else if (params->auth_alg & WPA_AUTH_ALG_FT)
4613		type = NL80211_AUTHTYPE_FT;
4614	else
4615		goto nla_put_failure;
4616	wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
4617	NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
4618	if (params->local_state_change) {
4619		wpa_printf(MSG_DEBUG, "  * Local state change only");
4620		NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4621	}
4622
4623	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4624	msg = NULL;
4625	if (ret) {
4626		wpa_dbg(drv->ctx, MSG_DEBUG,
4627			"nl80211: MLME command failed (auth): ret=%d (%s)",
4628			ret, strerror(-ret));
4629		count++;
4630		if (ret == -EALREADY && count == 1 && params->bssid &&
4631		    !params->local_state_change) {
4632			/*
4633			 * mac80211 does not currently accept new
4634			 * authentication if we are already authenticated. As a
4635			 * workaround, force deauthentication and try again.
4636			 */
4637			wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
4638				   "after forced deauthentication");
4639			wpa_driver_nl80211_deauthenticate(
4640				bss, params->bssid,
4641				WLAN_REASON_PREV_AUTH_NOT_VALID);
4642			nlmsg_free(msg);
4643			goto retry;
4644		}
4645
4646		if (ret == -ENOENT && params->freq && !is_retry) {
4647			/*
4648			 * cfg80211 has likely expired the BSS entry even
4649			 * though it was previously available in our internal
4650			 * BSS table. To recover quickly, start a single
4651			 * channel scan on the specified channel.
4652			 */
4653			struct wpa_driver_scan_params scan;
4654			int freqs[2];
4655
4656			os_memset(&scan, 0, sizeof(scan));
4657			scan.num_ssids = 1;
4658			if (params->ssid) {
4659				scan.ssids[0].ssid = params->ssid;
4660				scan.ssids[0].ssid_len = params->ssid_len;
4661			}
4662			freqs[0] = params->freq;
4663			freqs[1] = 0;
4664			scan.freqs = freqs;
4665			wpa_printf(MSG_DEBUG, "nl80211: Trigger single "
4666				   "channel scan to refresh cfg80211 BSS "
4667				   "entry");
4668			ret = wpa_driver_nl80211_scan(bss, &scan);
4669			if (ret == 0) {
4670				nl80211_copy_auth_params(drv, params);
4671				drv->scan_for_auth = 1;
4672			}
4673		} else if (is_retry) {
4674			/*
4675			 * Need to indicate this with an event since the return
4676			 * value from the retry is not delivered to core code.
4677			 */
4678			union wpa_event_data event;
4679			wpa_printf(MSG_DEBUG, "nl80211: Authentication retry "
4680				   "failed");
4681			os_memset(&event, 0, sizeof(event));
4682			os_memcpy(event.timeout_event.addr, drv->auth_bssid_,
4683				  ETH_ALEN);
4684			wpa_supplicant_event(drv->ctx, EVENT_AUTH_TIMED_OUT,
4685					     &event);
4686		}
4687
4688		goto nla_put_failure;
4689	}
4690	ret = 0;
4691	wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
4692		   "successfully");
4693
4694nla_put_failure:
4695	nlmsg_free(msg);
4696	return ret;
4697}
4698
4699
4700static int wpa_driver_nl80211_authenticate_retry(
4701	struct wpa_driver_nl80211_data *drv)
4702{
4703	struct wpa_driver_auth_params params;
4704	struct i802_bss *bss = &drv->first_bss;
4705	int i;
4706
4707	wpa_printf(MSG_DEBUG, "nl80211: Try to authenticate again");
4708
4709	os_memset(&params, 0, sizeof(params));
4710	params.freq = drv->auth_freq;
4711	params.auth_alg = drv->auth_alg;
4712	params.wep_tx_keyidx = drv->auth_wep_tx_keyidx;
4713	params.local_state_change = drv->auth_local_state_change;
4714	params.p2p = drv->auth_p2p;
4715
4716	if (!is_zero_ether_addr(drv->auth_bssid_))
4717		params.bssid = drv->auth_bssid_;
4718
4719	if (drv->auth_ssid_len) {
4720		params.ssid = drv->auth_ssid;
4721		params.ssid_len = drv->auth_ssid_len;
4722	}
4723
4724	params.ie = drv->auth_ie;
4725	params.ie_len = drv->auth_ie_len;
4726
4727	for (i = 0; i < 4; i++) {
4728		if (drv->auth_wep_key_len[i]) {
4729			params.wep_key[i] = drv->auth_wep_key[i];
4730			params.wep_key_len[i] = drv->auth_wep_key_len[i];
4731		}
4732	}
4733
4734	drv->retry_auth = 1;
4735	return wpa_driver_nl80211_authenticate(bss, &params);
4736}
4737
4738
4739struct phy_info_arg {
4740	u16 *num_modes;
4741	struct hostapd_hw_modes *modes;
4742};
4743
4744static int phy_info_handler(struct nl_msg *msg, void *arg)
4745{
4746	struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
4747	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
4748	struct phy_info_arg *phy_info = arg;
4749
4750	struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
4751
4752	struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
4753	static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
4754		[NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
4755		[NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
4756		[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
4757		[NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
4758		[NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
4759		[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
4760	};
4761
4762	struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
4763	static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
4764		[NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
4765		[NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
4766	};
4767
4768	struct nlattr *nl_band;
4769	struct nlattr *nl_freq;
4770	struct nlattr *nl_rate;
4771	int rem_band, rem_freq, rem_rate;
4772	struct hostapd_hw_modes *mode;
4773	int idx, mode_is_set;
4774
4775	nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
4776		  genlmsg_attrlen(gnlh, 0), NULL);
4777
4778	if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
4779		return NL_SKIP;
4780
4781	nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
4782		mode = os_realloc(phy_info->modes, (*phy_info->num_modes + 1) * sizeof(*mode));
4783		if (!mode)
4784			return NL_SKIP;
4785		phy_info->modes = mode;
4786
4787		mode_is_set = 0;
4788
4789		mode = &phy_info->modes[*(phy_info->num_modes)];
4790		memset(mode, 0, sizeof(*mode));
4791		mode->flags = HOSTAPD_MODE_FLAG_HT_INFO_KNOWN;
4792		*(phy_info->num_modes) += 1;
4793
4794		nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
4795			  nla_len(nl_band), NULL);
4796
4797		if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
4798			mode->ht_capab = nla_get_u16(
4799				tb_band[NL80211_BAND_ATTR_HT_CAPA]);
4800		}
4801
4802		if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) {
4803			mode->a_mpdu_params |= nla_get_u8(
4804				tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) &
4805				0x03;
4806		}
4807
4808		if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) {
4809			mode->a_mpdu_params |= nla_get_u8(
4810				tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) <<
4811				2;
4812		}
4813
4814		if (tb_band[NL80211_BAND_ATTR_HT_MCS_SET] &&
4815		    nla_len(tb_band[NL80211_BAND_ATTR_HT_MCS_SET])) {
4816			u8 *mcs;
4817			mcs = nla_data(tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
4818			os_memcpy(mode->mcs_set, mcs, 16);
4819		}
4820
4821		if (tb_band[NL80211_BAND_ATTR_VHT_CAPA]) {
4822			mode->vht_capab = nla_get_u32(
4823				tb_band[NL80211_BAND_ATTR_VHT_CAPA]);
4824		}
4825
4826		if (tb_band[NL80211_BAND_ATTR_VHT_MCS_SET] &&
4827		    nla_len(tb_band[NL80211_BAND_ATTR_VHT_MCS_SET])) {
4828			u8 *mcs;
4829			mcs = nla_data(tb_band[NL80211_BAND_ATTR_VHT_MCS_SET]);
4830			os_memcpy(mode->vht_mcs_set, mcs, 8);
4831		}
4832
4833		nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
4834			nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
4835				  nla_len(nl_freq), freq_policy);
4836			if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
4837				continue;
4838			mode->num_channels++;
4839		}
4840
4841		mode->channels = os_zalloc(mode->num_channels * sizeof(struct hostapd_channel_data));
4842		if (!mode->channels)
4843			return NL_SKIP;
4844
4845		idx = 0;
4846
4847		nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
4848			nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
4849				  nla_len(nl_freq), freq_policy);
4850			if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
4851				continue;
4852
4853			mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
4854			mode->channels[idx].flag = 0;
4855
4856			if (!mode_is_set) {
4857				/* crude heuristic */
4858				if (mode->channels[idx].freq < 4000)
4859					mode->mode = HOSTAPD_MODE_IEEE80211B;
4860				else
4861					mode->mode = HOSTAPD_MODE_IEEE80211A;
4862				mode_is_set = 1;
4863			}
4864
4865			/* crude heuristic */
4866			if (mode->channels[idx].freq < 4000)
4867				if (mode->channels[idx].freq == 2484)
4868					mode->channels[idx].chan = 14;
4869				else
4870					mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
4871			else
4872				mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
4873
4874			if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
4875				mode->channels[idx].flag |=
4876					HOSTAPD_CHAN_DISABLED;
4877			if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
4878				mode->channels[idx].flag |=
4879					HOSTAPD_CHAN_PASSIVE_SCAN;
4880			if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
4881				mode->channels[idx].flag |=
4882					HOSTAPD_CHAN_NO_IBSS;
4883			if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
4884				mode->channels[idx].flag |=
4885					HOSTAPD_CHAN_RADAR;
4886
4887			if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
4888			    !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
4889				mode->channels[idx].max_tx_power =
4890					nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
4891
4892			idx++;
4893		}
4894
4895		nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
4896			nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
4897				  nla_len(nl_rate), rate_policy);
4898			if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
4899				continue;
4900			mode->num_rates++;
4901		}
4902
4903		mode->rates = os_zalloc(mode->num_rates * sizeof(int));
4904		if (!mode->rates)
4905			return NL_SKIP;
4906
4907		idx = 0;
4908
4909		nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
4910			nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
4911				  nla_len(nl_rate), rate_policy);
4912			if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
4913				continue;
4914			mode->rates[idx] = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
4915
4916			/* crude heuristic */
4917			if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
4918			    mode->rates[idx] > 200)
4919				mode->mode = HOSTAPD_MODE_IEEE80211G;
4920
4921			idx++;
4922		}
4923	}
4924
4925	return NL_SKIP;
4926}
4927
4928static struct hostapd_hw_modes *
4929wpa_driver_nl80211_add_11b(struct hostapd_hw_modes *modes, u16 *num_modes)
4930{
4931	u16 m;
4932	struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
4933	int i, mode11g_idx = -1;
4934
4935	/* If only 802.11g mode is included, use it to construct matching
4936	 * 802.11b mode data. */
4937
4938	for (m = 0; m < *num_modes; m++) {
4939		if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
4940			return modes; /* 802.11b already included */
4941		if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
4942			mode11g_idx = m;
4943	}
4944
4945	if (mode11g_idx < 0)
4946		return modes; /* 2.4 GHz band not supported at all */
4947
4948	nmodes = os_realloc(modes, (*num_modes + 1) * sizeof(*nmodes));
4949	if (nmodes == NULL)
4950		return modes; /* Could not add 802.11b mode */
4951
4952	mode = &nmodes[*num_modes];
4953	os_memset(mode, 0, sizeof(*mode));
4954	(*num_modes)++;
4955	modes = nmodes;
4956
4957	mode->mode = HOSTAPD_MODE_IEEE80211B;
4958
4959	mode11g = &modes[mode11g_idx];
4960	mode->num_channels = mode11g->num_channels;
4961	mode->channels = os_malloc(mode11g->num_channels *
4962				   sizeof(struct hostapd_channel_data));
4963	if (mode->channels == NULL) {
4964		(*num_modes)--;
4965		return modes; /* Could not add 802.11b mode */
4966	}
4967	os_memcpy(mode->channels, mode11g->channels,
4968		  mode11g->num_channels * sizeof(struct hostapd_channel_data));
4969
4970	mode->num_rates = 0;
4971	mode->rates = os_malloc(4 * sizeof(int));
4972	if (mode->rates == NULL) {
4973		os_free(mode->channels);
4974		(*num_modes)--;
4975		return modes; /* Could not add 802.11b mode */
4976	}
4977
4978	for (i = 0; i < mode11g->num_rates; i++) {
4979		if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 &&
4980		    mode11g->rates[i] != 55 && mode11g->rates[i] != 110)
4981			continue;
4982		mode->rates[mode->num_rates] = mode11g->rates[i];
4983		mode->num_rates++;
4984		if (mode->num_rates == 4)
4985			break;
4986	}
4987
4988	if (mode->num_rates == 0) {
4989		os_free(mode->channels);
4990		os_free(mode->rates);
4991		(*num_modes)--;
4992		return modes; /* No 802.11b rates */
4993	}
4994
4995	wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
4996		   "information");
4997
4998	return modes;
4999}
5000
5001
5002static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start,
5003				  int end)
5004{
5005	int c;
5006
5007	for (c = 0; c < mode->num_channels; c++) {
5008		struct hostapd_channel_data *chan = &mode->channels[c];
5009		if (chan->freq - 10 >= start && chan->freq + 10 <= end)
5010			chan->flag |= HOSTAPD_CHAN_HT40;
5011	}
5012}
5013
5014
5015static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start,
5016				      int end)
5017{
5018	int c;
5019
5020	for (c = 0; c < mode->num_channels; c++) {
5021		struct hostapd_channel_data *chan = &mode->channels[c];
5022		if (!(chan->flag & HOSTAPD_CHAN_HT40))
5023			continue;
5024		if (chan->freq - 30 >= start && chan->freq - 10 <= end)
5025			chan->flag |= HOSTAPD_CHAN_HT40MINUS;
5026		if (chan->freq + 10 >= start && chan->freq + 30 <= end)
5027			chan->flag |= HOSTAPD_CHAN_HT40PLUS;
5028	}
5029}
5030
5031
5032static void nl80211_reg_rule_ht40(struct nlattr *tb[],
5033				  struct phy_info_arg *results)
5034{
5035	u32 start, end, max_bw;
5036	u16 m;
5037
5038	if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
5039	    tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
5040	    tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
5041		return;
5042
5043	start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
5044	end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
5045	max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
5046
5047	wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz",
5048		   start, end, max_bw);
5049	if (max_bw < 40)
5050		return;
5051
5052	for (m = 0; m < *results->num_modes; m++) {
5053		if (!(results->modes[m].ht_capab &
5054		      HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
5055			continue;
5056		nl80211_set_ht40_mode(&results->modes[m], start, end);
5057	}
5058}
5059
5060
5061static void nl80211_reg_rule_sec(struct nlattr *tb[],
5062				 struct phy_info_arg *results)
5063{
5064	u32 start, end, max_bw;
5065	u16 m;
5066
5067	if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
5068	    tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
5069	    tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
5070		return;
5071
5072	start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
5073	end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
5074	max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
5075
5076	if (max_bw < 20)
5077		return;
5078
5079	for (m = 0; m < *results->num_modes; m++) {
5080		if (!(results->modes[m].ht_capab &
5081		      HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
5082			continue;
5083		nl80211_set_ht40_mode_sec(&results->modes[m], start, end);
5084	}
5085}
5086
5087
5088static int nl80211_get_reg(struct nl_msg *msg, void *arg)
5089{
5090	struct phy_info_arg *results = arg;
5091	struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
5092	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5093	struct nlattr *nl_rule;
5094	struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1];
5095	int rem_rule;
5096	static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
5097		[NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
5098		[NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
5099		[NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
5100		[NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
5101		[NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
5102		[NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
5103	};
5104
5105	nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5106		  genlmsg_attrlen(gnlh, 0), NULL);
5107	if (!tb_msg[NL80211_ATTR_REG_ALPHA2] ||
5108	    !tb_msg[NL80211_ATTR_REG_RULES]) {
5109		wpa_printf(MSG_DEBUG, "nl80211: No regulatory information "
5110			   "available");
5111		return NL_SKIP;
5112	}
5113
5114	wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s",
5115		   (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]));
5116
5117	nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5118	{
5119		nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5120			  nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5121		nl80211_reg_rule_ht40(tb_rule, results);
5122	}
5123
5124	nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5125	{
5126		nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5127			  nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5128		nl80211_reg_rule_sec(tb_rule, results);
5129	}
5130
5131	return NL_SKIP;
5132}
5133
5134
5135static int nl80211_set_ht40_flags(struct wpa_driver_nl80211_data *drv,
5136				  struct phy_info_arg *results)
5137{
5138	struct nl_msg *msg;
5139
5140	msg = nlmsg_alloc();
5141	if (!msg)
5142		return -ENOMEM;
5143
5144	nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_REG);
5145	return send_and_recv_msgs(drv, msg, nl80211_get_reg, results);
5146}
5147
5148
5149static struct hostapd_hw_modes *
5150wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
5151{
5152	struct i802_bss *bss = priv;
5153	struct wpa_driver_nl80211_data *drv = bss->drv;
5154	struct nl_msg *msg;
5155	struct phy_info_arg result = {
5156		.num_modes = num_modes,
5157		.modes = NULL,
5158	};
5159
5160	*num_modes = 0;
5161	*flags = 0;
5162
5163	msg = nlmsg_alloc();
5164	if (!msg)
5165		return NULL;
5166
5167	nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
5168
5169	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5170
5171	if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) {
5172		nl80211_set_ht40_flags(drv, &result);
5173		return wpa_driver_nl80211_add_11b(result.modes, num_modes);
5174	}
5175	msg = NULL;
5176 nla_put_failure:
5177	nlmsg_free(msg);
5178	return NULL;
5179}
5180
5181
5182static int wpa_driver_nl80211_send_mntr(struct wpa_driver_nl80211_data *drv,
5183					const void *data, size_t len,
5184					int encrypt, int noack)
5185{
5186	__u8 rtap_hdr[] = {
5187		0x00, 0x00, /* radiotap version */
5188		0x0e, 0x00, /* radiotap length */
5189		0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
5190		IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
5191		0x00,       /* padding */
5192		0x00, 0x00, /* RX and TX flags to indicate that */
5193		0x00, 0x00, /* this is the injected frame directly */
5194	};
5195	struct iovec iov[2] = {
5196		{
5197			.iov_base = &rtap_hdr,
5198			.iov_len = sizeof(rtap_hdr),
5199		},
5200		{
5201			.iov_base = (void *) data,
5202			.iov_len = len,
5203		}
5204	};
5205	struct msghdr msg = {
5206		.msg_name = NULL,
5207		.msg_namelen = 0,
5208		.msg_iov = iov,
5209		.msg_iovlen = 2,
5210		.msg_control = NULL,
5211		.msg_controllen = 0,
5212		.msg_flags = 0,
5213	};
5214	int res;
5215	u16 txflags = 0;
5216
5217	if (encrypt)
5218		rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
5219
5220	if (drv->monitor_sock < 0) {
5221		wpa_printf(MSG_DEBUG, "nl80211: No monitor socket available "
5222			   "for %s", __func__);
5223		return -1;
5224	}
5225
5226	if (noack)
5227		txflags |= IEEE80211_RADIOTAP_F_TX_NOACK;
5228	*(le16 *) &rtap_hdr[12] = host_to_le16(txflags);
5229
5230	res = sendmsg(drv->monitor_sock, &msg, 0);
5231	if (res < 0) {
5232		wpa_printf(MSG_INFO, "nl80211: sendmsg: %s", strerror(errno));
5233		return -1;
5234	}
5235	return 0;
5236}
5237
5238
5239static int wpa_driver_nl80211_send_frame(struct i802_bss *bss,
5240					 const void *data, size_t len,
5241					 int encrypt, int noack,
5242					 unsigned int freq, int no_cck,
5243					 int offchanok, unsigned int wait_time)
5244{
5245	struct wpa_driver_nl80211_data *drv = bss->drv;
5246	u64 cookie;
5247
5248	if (freq == 0)
5249		freq = bss->freq;
5250
5251	if (drv->use_monitor)
5252		return wpa_driver_nl80211_send_mntr(drv, data, len,
5253						    encrypt, noack);
5254
5255	return nl80211_send_frame_cmd(bss, freq, wait_time, data, len,
5256				      &cookie, no_cck, noack, offchanok);
5257}
5258
5259
5260static int wpa_driver_nl80211_send_mlme_freq(struct i802_bss *bss,
5261					     const u8 *data,
5262					     size_t data_len, int noack,
5263					     unsigned int freq, int no_cck,
5264					     int offchanok,
5265					     unsigned int wait_time)
5266{
5267	struct wpa_driver_nl80211_data *drv = bss->drv;
5268	struct ieee80211_mgmt *mgmt;
5269	int encrypt = 1;
5270	u16 fc;
5271
5272	mgmt = (struct ieee80211_mgmt *) data;
5273	fc = le_to_host16(mgmt->frame_control);
5274
5275	if (is_sta_interface(drv->nlmode) &&
5276	    WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5277	    WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_PROBE_RESP) {
5278		/*
5279		 * The use of last_mgmt_freq is a bit of a hack,
5280		 * but it works due to the single-threaded nature
5281		 * of wpa_supplicant.
5282		 */
5283		if (freq == 0)
5284			freq = drv->last_mgmt_freq;
5285		return nl80211_send_frame_cmd(bss, freq, 0,
5286					      data, data_len, NULL, 1, noack,
5287					      1);
5288	}
5289
5290	if (drv->device_ap_sme && is_ap_interface(drv->nlmode)) {
5291		if (freq == 0)
5292			freq = bss->freq;
5293		return nl80211_send_frame_cmd(bss, freq,
5294					      (int) freq == bss->freq ? 0 :
5295					      wait_time,
5296					      data, data_len,
5297					      &drv->send_action_cookie,
5298					      no_cck, noack, offchanok);
5299	}
5300
5301	if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5302	    WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
5303		/*
5304		 * Only one of the authentication frame types is encrypted.
5305		 * In order for static WEP encryption to work properly (i.e.,
5306		 * to not encrypt the frame), we need to tell mac80211 about
5307		 * the frames that must not be encrypted.
5308		 */
5309		u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
5310		u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
5311		if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
5312			encrypt = 0;
5313	}
5314
5315	return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt,
5316					     noack, freq, no_cck, offchanok,
5317					     wait_time);
5318}
5319
5320
5321static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
5322					size_t data_len, int noack)
5323{
5324	struct i802_bss *bss = priv;
5325	return wpa_driver_nl80211_send_mlme_freq(bss, data, data_len, noack,
5326						 0, 0, 0, 0);
5327}
5328
5329
5330static int nl80211_set_bss(struct i802_bss *bss, int cts, int preamble,
5331			   int slot, int ht_opmode, int ap_isolate,
5332			   int *basic_rates)
5333{
5334	struct wpa_driver_nl80211_data *drv = bss->drv;
5335	struct nl_msg *msg;
5336
5337	msg = nlmsg_alloc();
5338	if (!msg)
5339		return -ENOMEM;
5340
5341	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_BSS);
5342
5343	if (cts >= 0)
5344		NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
5345	if (preamble >= 0)
5346		NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
5347	if (slot >= 0)
5348		NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
5349	if (ht_opmode >= 0)
5350		NLA_PUT_U16(msg, NL80211_ATTR_BSS_HT_OPMODE, ht_opmode);
5351	if (ap_isolate >= 0)
5352		NLA_PUT_U8(msg, NL80211_ATTR_AP_ISOLATE, ap_isolate);
5353
5354	if (basic_rates) {
5355		u8 rates[NL80211_MAX_SUPP_RATES];
5356		u8 rates_len = 0;
5357		int i;
5358
5359		for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0;
5360		     i++)
5361			rates[rates_len++] = basic_rates[i] / 5;
5362
5363		NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
5364	}
5365
5366	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5367
5368	return send_and_recv_msgs(drv, msg, NULL, NULL);
5369 nla_put_failure:
5370	nlmsg_free(msg);
5371	return -ENOBUFS;
5372}
5373
5374
5375static int wpa_driver_nl80211_set_ap(void *priv,
5376				     struct wpa_driver_ap_params *params)
5377{
5378	struct i802_bss *bss = priv;
5379	struct wpa_driver_nl80211_data *drv = bss->drv;
5380	struct nl_msg *msg;
5381	u8 cmd = NL80211_CMD_NEW_BEACON;
5382	int ret;
5383	int beacon_set;
5384	int ifindex = if_nametoindex(bss->ifname);
5385	int num_suites;
5386	u32 suites[10];
5387	u32 ver;
5388
5389	beacon_set = bss->beacon_set;
5390
5391	msg = nlmsg_alloc();
5392	if (!msg)
5393		return -ENOMEM;
5394
5395	wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
5396		   beacon_set);
5397	if (beacon_set)
5398		cmd = NL80211_CMD_SET_BEACON;
5399
5400	nl80211_cmd(drv, msg, 0, cmd);
5401	NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, params->head_len, params->head);
5402	NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, params->tail_len, params->tail);
5403	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
5404	NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, params->beacon_int);
5405	NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, params->dtim_period);
5406	NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
5407		params->ssid);
5408	if (params->proberesp && params->proberesp_len)
5409		NLA_PUT(msg, NL80211_ATTR_PROBE_RESP, params->proberesp_len,
5410			params->proberesp);
5411	switch (params->hide_ssid) {
5412	case NO_SSID_HIDING:
5413		NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5414			    NL80211_HIDDEN_SSID_NOT_IN_USE);
5415		break;
5416	case HIDDEN_SSID_ZERO_LEN:
5417		NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5418			    NL80211_HIDDEN_SSID_ZERO_LEN);
5419		break;
5420	case HIDDEN_SSID_ZERO_CONTENTS:
5421		NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5422			    NL80211_HIDDEN_SSID_ZERO_CONTENTS);
5423		break;
5424	}
5425	if (params->privacy)
5426		NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
5427	if ((params->auth_algs & (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) ==
5428	    (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) {
5429		/* Leave out the attribute */
5430	} else if (params->auth_algs & WPA_AUTH_ALG_SHARED)
5431		NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5432			    NL80211_AUTHTYPE_SHARED_KEY);
5433	else
5434		NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5435			    NL80211_AUTHTYPE_OPEN_SYSTEM);
5436
5437	ver = 0;
5438	if (params->wpa_version & WPA_PROTO_WPA)
5439		ver |= NL80211_WPA_VERSION_1;
5440	if (params->wpa_version & WPA_PROTO_RSN)
5441		ver |= NL80211_WPA_VERSION_2;
5442	if (ver)
5443		NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
5444
5445	num_suites = 0;
5446	if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X)
5447		suites[num_suites++] = WLAN_AKM_SUITE_8021X;
5448	if (params->key_mgmt_suites & WPA_KEY_MGMT_PSK)
5449		suites[num_suites++] = WLAN_AKM_SUITE_PSK;
5450	if (num_suites) {
5451		NLA_PUT(msg, NL80211_ATTR_AKM_SUITES,
5452			num_suites * sizeof(u32), suites);
5453	}
5454
5455	if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X &&
5456	    params->pairwise_ciphers & (WPA_CIPHER_WEP104 | WPA_CIPHER_WEP40))
5457		NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT);
5458
5459	num_suites = 0;
5460	if (params->pairwise_ciphers & WPA_CIPHER_CCMP)
5461		suites[num_suites++] = WLAN_CIPHER_SUITE_CCMP;
5462	if (params->pairwise_ciphers & WPA_CIPHER_TKIP)
5463		suites[num_suites++] = WLAN_CIPHER_SUITE_TKIP;
5464	if (params->pairwise_ciphers & WPA_CIPHER_WEP104)
5465		suites[num_suites++] = WLAN_CIPHER_SUITE_WEP104;
5466	if (params->pairwise_ciphers & WPA_CIPHER_WEP40)
5467		suites[num_suites++] = WLAN_CIPHER_SUITE_WEP40;
5468	if (num_suites) {
5469		NLA_PUT(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE,
5470			num_suites * sizeof(u32), suites);
5471	}
5472
5473	switch (params->group_cipher) {
5474	case WPA_CIPHER_CCMP:
5475		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5476			    WLAN_CIPHER_SUITE_CCMP);
5477		break;
5478	case WPA_CIPHER_TKIP:
5479		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5480			    WLAN_CIPHER_SUITE_TKIP);
5481		break;
5482	case WPA_CIPHER_WEP104:
5483		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5484			    WLAN_CIPHER_SUITE_WEP104);
5485		break;
5486	case WPA_CIPHER_WEP40:
5487		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5488			    WLAN_CIPHER_SUITE_WEP40);
5489		break;
5490	}
5491
5492	if (params->beacon_ies) {
5493		NLA_PUT(msg, NL80211_ATTR_IE, wpabuf_len(params->beacon_ies),
5494			wpabuf_head(params->beacon_ies));
5495	}
5496	if (params->proberesp_ies) {
5497		NLA_PUT(msg, NL80211_ATTR_IE_PROBE_RESP,
5498			wpabuf_len(params->proberesp_ies),
5499			wpabuf_head(params->proberesp_ies));
5500	}
5501	if (params->assocresp_ies) {
5502		NLA_PUT(msg, NL80211_ATTR_IE_ASSOC_RESP,
5503			wpabuf_len(params->assocresp_ies),
5504			wpabuf_head(params->assocresp_ies));
5505	}
5506
5507	if (drv->capa.flags & WPA_DRIVER_FLAGS_INACTIVITY_TIMER)  {
5508		NLA_PUT_U16(msg, NL80211_ATTR_INACTIVITY_TIMEOUT,
5509			    params->ap_max_inactivity);
5510	}
5511
5512	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5513	if (ret) {
5514		wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
5515			   ret, strerror(-ret));
5516	} else {
5517		bss->beacon_set = 1;
5518		nl80211_set_bss(bss, params->cts_protect, params->preamble,
5519				params->short_slot_time, params->ht_opmode,
5520				params->isolate, params->basic_rates);
5521	}
5522	return ret;
5523 nla_put_failure:
5524	nlmsg_free(msg);
5525	return -ENOBUFS;
5526}
5527
5528
5529static int wpa_driver_nl80211_set_freq(struct i802_bss *bss,
5530				       int freq, int ht_enabled,
5531				       int sec_channel_offset)
5532{
5533	struct wpa_driver_nl80211_data *drv = bss->drv;
5534	struct nl_msg *msg;
5535	int ret;
5536
5537	wpa_printf(MSG_DEBUG, "nl80211: Set freq %d (ht_enabled=%d "
5538		   "sec_channel_offset=%d)",
5539		   freq, ht_enabled, sec_channel_offset);
5540	msg = nlmsg_alloc();
5541	if (!msg)
5542		return -1;
5543
5544	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
5545
5546	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5547	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
5548	if (ht_enabled) {
5549		switch (sec_channel_offset) {
5550		case -1:
5551			NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5552				    NL80211_CHAN_HT40MINUS);
5553			break;
5554		case 1:
5555			NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5556				    NL80211_CHAN_HT40PLUS);
5557			break;
5558		default:
5559			NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5560				    NL80211_CHAN_HT20);
5561			break;
5562		}
5563	}
5564
5565	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5566	msg = NULL;
5567	if (ret == 0) {
5568		bss->freq = freq;
5569		return 0;
5570	}
5571	wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
5572		   "%d (%s)", freq, ret, strerror(-ret));
5573nla_put_failure:
5574	nlmsg_free(msg);
5575	return -1;
5576}
5577
5578
5579static u32 sta_flags_nl80211(int flags)
5580{
5581	u32 f = 0;
5582
5583	if (flags & WPA_STA_AUTHORIZED)
5584		f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
5585	if (flags & WPA_STA_WMM)
5586		f |= BIT(NL80211_STA_FLAG_WME);
5587	if (flags & WPA_STA_SHORT_PREAMBLE)
5588		f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
5589	if (flags & WPA_STA_MFP)
5590		f |= BIT(NL80211_STA_FLAG_MFP);
5591	if (flags & WPA_STA_TDLS_PEER)
5592		f |= BIT(NL80211_STA_FLAG_TDLS_PEER);
5593
5594	return f;
5595}
5596
5597
5598static int wpa_driver_nl80211_sta_add(void *priv,
5599				      struct hostapd_sta_add_params *params)
5600{
5601	struct i802_bss *bss = priv;
5602	struct wpa_driver_nl80211_data *drv = bss->drv;
5603	struct nl_msg *msg, *wme = NULL;
5604	struct nl80211_sta_flag_update upd;
5605	int ret = -ENOBUFS;
5606
5607	if ((params->flags & WPA_STA_TDLS_PEER) &&
5608	    !(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
5609		return -EOPNOTSUPP;
5610
5611	msg = nlmsg_alloc();
5612	if (!msg)
5613		return -ENOMEM;
5614
5615	nl80211_cmd(drv, msg, 0, params->set ? NL80211_CMD_SET_STATION :
5616		    NL80211_CMD_NEW_STATION);
5617
5618	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5619	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
5620	NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
5621		params->supp_rates);
5622	if (!params->set) {
5623		NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
5624		NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
5625			    params->listen_interval);
5626	}
5627	if (params->ht_capabilities) {
5628		NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
5629			sizeof(*params->ht_capabilities),
5630			params->ht_capabilities);
5631	}
5632
5633	os_memset(&upd, 0, sizeof(upd));
5634	upd.mask = sta_flags_nl80211(params->flags);
5635	upd.set = upd.mask;
5636	NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
5637
5638	if (params->flags & WPA_STA_WMM) {
5639		wme = nlmsg_alloc();
5640		if (!wme)
5641			goto nla_put_failure;
5642
5643		NLA_PUT_U8(wme, NL80211_STA_WME_UAPSD_QUEUES,
5644				params->qosinfo & WMM_QOSINFO_STA_AC_MASK);
5645		NLA_PUT_U8(wme, NL80211_STA_WME_MAX_SP,
5646				(params->qosinfo > WMM_QOSINFO_STA_SP_SHIFT) &
5647				WMM_QOSINFO_STA_SP_MASK);
5648		nla_put_nested(msg, NL80211_ATTR_STA_WME, wme);
5649	}
5650
5651	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5652	msg = NULL;
5653	if (ret)
5654		wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_%s_STATION "
5655			   "result: %d (%s)", params->set ? "SET" : "NEW", ret,
5656			   strerror(-ret));
5657	if (ret == -EEXIST)
5658		ret = 0;
5659 nla_put_failure:
5660	nlmsg_free(wme);
5661	nlmsg_free(msg);
5662	return ret;
5663}
5664
5665
5666static int wpa_driver_nl80211_sta_remove(void *priv, const u8 *addr)
5667{
5668	struct i802_bss *bss = priv;
5669	struct wpa_driver_nl80211_data *drv = bss->drv;
5670	struct nl_msg *msg;
5671	int ret;
5672
5673	msg = nlmsg_alloc();
5674	if (!msg)
5675		return -ENOMEM;
5676
5677	nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
5678
5679	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5680		    if_nametoindex(bss->ifname));
5681	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5682
5683	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5684	if (ret == -ENOENT)
5685		return 0;
5686	return ret;
5687 nla_put_failure:
5688	nlmsg_free(msg);
5689	return -ENOBUFS;
5690}
5691
5692
5693static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
5694				 int ifidx)
5695{
5696	struct nl_msg *msg;
5697
5698	wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
5699
5700	/* stop listening for EAPOL on this interface */
5701	del_ifidx(drv, ifidx);
5702
5703	msg = nlmsg_alloc();
5704	if (!msg)
5705		goto nla_put_failure;
5706
5707	nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_INTERFACE);
5708	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
5709
5710	if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
5711		return;
5712	msg = NULL;
5713 nla_put_failure:
5714	nlmsg_free(msg);
5715	wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
5716}
5717
5718
5719static const char * nl80211_iftype_str(enum nl80211_iftype mode)
5720{
5721	switch (mode) {
5722	case NL80211_IFTYPE_ADHOC:
5723		return "ADHOC";
5724	case NL80211_IFTYPE_STATION:
5725		return "STATION";
5726	case NL80211_IFTYPE_AP:
5727		return "AP";
5728	case NL80211_IFTYPE_MONITOR:
5729		return "MONITOR";
5730	case NL80211_IFTYPE_P2P_CLIENT:
5731		return "P2P_CLIENT";
5732	case NL80211_IFTYPE_P2P_GO:
5733		return "P2P_GO";
5734	default:
5735		return "unknown";
5736	}
5737}
5738
5739
5740static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
5741				     const char *ifname,
5742				     enum nl80211_iftype iftype,
5743				     const u8 *addr, int wds)
5744{
5745	struct nl_msg *msg, *flags = NULL;
5746	int ifidx;
5747	int ret = -ENOBUFS;
5748
5749	wpa_printf(MSG_DEBUG, "nl80211: Create interface iftype %d (%s)",
5750		   iftype, nl80211_iftype_str(iftype));
5751
5752	msg = nlmsg_alloc();
5753	if (!msg)
5754		return -1;
5755
5756	nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_INTERFACE);
5757	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5758	NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
5759	NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
5760
5761	if (iftype == NL80211_IFTYPE_MONITOR) {
5762		int err;
5763
5764		flags = nlmsg_alloc();
5765		if (!flags)
5766			goto nla_put_failure;
5767
5768		NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
5769
5770		err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
5771
5772		nlmsg_free(flags);
5773
5774		if (err)
5775			goto nla_put_failure;
5776	} else if (wds) {
5777		NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
5778	}
5779
5780	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5781	msg = NULL;
5782	if (ret) {
5783 nla_put_failure:
5784		nlmsg_free(msg);
5785		wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
5786			   ifname, ret, strerror(-ret));
5787		return ret;
5788	}
5789
5790	ifidx = if_nametoindex(ifname);
5791	wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
5792		   ifname, ifidx);
5793
5794	if (ifidx <= 0)
5795		return -1;
5796
5797	/* start listening for EAPOL on this interface */
5798	add_ifidx(drv, ifidx);
5799
5800	if (addr && iftype != NL80211_IFTYPE_MONITOR &&
5801	    linux_set_ifhwaddr(drv->global->ioctl_sock, ifname, addr)) {
5802		nl80211_remove_iface(drv, ifidx);
5803		return -1;
5804	}
5805
5806	return ifidx;
5807}
5808
5809
5810static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
5811				const char *ifname, enum nl80211_iftype iftype,
5812				const u8 *addr, int wds)
5813{
5814	int ret;
5815
5816	ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds);
5817
5818	/* if error occurred and interface exists already */
5819	if (ret == -ENFILE && if_nametoindex(ifname)) {
5820		wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
5821
5822		/* Try to remove the interface that was already there. */
5823		nl80211_remove_iface(drv, if_nametoindex(ifname));
5824
5825		/* Try to create the interface again */
5826		ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
5827						wds);
5828	}
5829
5830	if (ret >= 0 && is_p2p_interface(iftype))
5831		nl80211_disable_11b_rates(drv, ret, 1);
5832
5833	return ret;
5834}
5835
5836
5837static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
5838{
5839	struct ieee80211_hdr *hdr;
5840	u16 fc;
5841	union wpa_event_data event;
5842
5843	hdr = (struct ieee80211_hdr *) buf;
5844	fc = le_to_host16(hdr->frame_control);
5845
5846	os_memset(&event, 0, sizeof(event));
5847	event.tx_status.type = WLAN_FC_GET_TYPE(fc);
5848	event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
5849	event.tx_status.dst = hdr->addr1;
5850	event.tx_status.data = buf;
5851	event.tx_status.data_len = len;
5852	event.tx_status.ack = ok;
5853	wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
5854}
5855
5856
5857static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
5858			     u8 *buf, size_t len)
5859{
5860	struct ieee80211_hdr *hdr = (void *)buf;
5861	u16 fc;
5862	union wpa_event_data event;
5863
5864	if (len < sizeof(*hdr))
5865		return;
5866
5867	fc = le_to_host16(hdr->frame_control);
5868
5869	os_memset(&event, 0, sizeof(event));
5870	event.rx_from_unknown.bssid = get_hdr_bssid(hdr, len);
5871	event.rx_from_unknown.addr = hdr->addr2;
5872	event.rx_from_unknown.wds = (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) ==
5873		(WLAN_FC_FROMDS | WLAN_FC_TODS);
5874	wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
5875}
5876
5877
5878static void handle_frame(struct wpa_driver_nl80211_data *drv,
5879			 u8 *buf, size_t len, int datarate, int ssi_signal)
5880{
5881	struct ieee80211_hdr *hdr;
5882	u16 fc;
5883	union wpa_event_data event;
5884
5885	hdr = (struct ieee80211_hdr *) buf;
5886	fc = le_to_host16(hdr->frame_control);
5887
5888	switch (WLAN_FC_GET_TYPE(fc)) {
5889	case WLAN_FC_TYPE_MGMT:
5890		os_memset(&event, 0, sizeof(event));
5891		event.rx_mgmt.frame = buf;
5892		event.rx_mgmt.frame_len = len;
5893		event.rx_mgmt.datarate = datarate;
5894		event.rx_mgmt.ssi_signal = ssi_signal;
5895		wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
5896		break;
5897	case WLAN_FC_TYPE_CTRL:
5898		/* can only get here with PS-Poll frames */
5899		wpa_printf(MSG_DEBUG, "CTRL");
5900		from_unknown_sta(drv, buf, len);
5901		break;
5902	case WLAN_FC_TYPE_DATA:
5903		from_unknown_sta(drv, buf, len);
5904		break;
5905	}
5906}
5907
5908
5909static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
5910{
5911	struct wpa_driver_nl80211_data *drv = eloop_ctx;
5912	int len;
5913	unsigned char buf[3000];
5914	struct ieee80211_radiotap_iterator iter;
5915	int ret;
5916	int datarate = 0, ssi_signal = 0;
5917	int injected = 0, failed = 0, rxflags = 0;
5918
5919	len = recv(sock, buf, sizeof(buf), 0);
5920	if (len < 0) {
5921		perror("recv");
5922		return;
5923	}
5924
5925	if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
5926		printf("received invalid radiotap frame\n");
5927		return;
5928	}
5929
5930	while (1) {
5931		ret = ieee80211_radiotap_iterator_next(&iter);
5932		if (ret == -ENOENT)
5933			break;
5934		if (ret) {
5935			printf("received invalid radiotap frame (%d)\n", ret);
5936			return;
5937		}
5938		switch (iter.this_arg_index) {
5939		case IEEE80211_RADIOTAP_FLAGS:
5940			if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
5941				len -= 4;
5942			break;
5943		case IEEE80211_RADIOTAP_RX_FLAGS:
5944			rxflags = 1;
5945			break;
5946		case IEEE80211_RADIOTAP_TX_FLAGS:
5947			injected = 1;
5948			failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
5949					IEEE80211_RADIOTAP_F_TX_FAIL;
5950			break;
5951		case IEEE80211_RADIOTAP_DATA_RETRIES:
5952			break;
5953		case IEEE80211_RADIOTAP_CHANNEL:
5954			/* TODO: convert from freq/flags to channel number */
5955			break;
5956		case IEEE80211_RADIOTAP_RATE:
5957			datarate = *iter.this_arg * 5;
5958			break;
5959		case IEEE80211_RADIOTAP_DBM_ANTSIGNAL:
5960			ssi_signal = (s8) *iter.this_arg;
5961			break;
5962		}
5963	}
5964
5965	if (rxflags && injected)
5966		return;
5967
5968	if (!injected)
5969		handle_frame(drv, buf + iter.max_length,
5970			     len - iter.max_length, datarate, ssi_signal);
5971	else
5972		handle_tx_callback(drv->ctx, buf + iter.max_length,
5973				   len - iter.max_length, !failed);
5974}
5975
5976
5977/*
5978 * we post-process the filter code later and rewrite
5979 * this to the offset to the last instruction
5980 */
5981#define PASS	0xFF
5982#define FAIL	0xFE
5983
5984static struct sock_filter msock_filter_insns[] = {
5985	/*
5986	 * do a little-endian load of the radiotap length field
5987	 */
5988	/* load lower byte into A */
5989	BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
5990	/* put it into X (== index register) */
5991	BPF_STMT(BPF_MISC| BPF_TAX, 0),
5992	/* load upper byte into A */
5993	BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
5994	/* left-shift it by 8 */
5995	BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
5996	/* or with X */
5997	BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
5998	/* put result into X */
5999	BPF_STMT(BPF_MISC| BPF_TAX, 0),
6000
6001	/*
6002	 * Allow management frames through, this also gives us those
6003	 * management frames that we sent ourselves with status
6004	 */
6005	/* load the lower byte of the IEEE 802.11 frame control field */
6006	BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
6007	/* mask off frame type and version */
6008	BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
6009	/* accept frame if it's both 0, fall through otherwise */
6010	BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
6011
6012	/*
6013	 * TODO: add a bit to radiotap RX flags that indicates
6014	 * that the sending station is not associated, then
6015	 * add a filter here that filters on our DA and that flag
6016	 * to allow us to deauth frames to that bad station.
6017	 *
6018	 * For now allow all To DS data frames through.
6019	 */
6020	/* load the IEEE 802.11 frame control field */
6021	BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
6022	/* mask off frame type, version and DS status */
6023	BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
6024	/* accept frame if version 0, type 2 and To DS, fall through otherwise
6025	 */
6026	BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
6027
6028#if 0
6029	/*
6030	 * drop non-data frames
6031	 */
6032	/* load the lower byte of the frame control field */
6033	BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
6034	/* mask off QoS bit */
6035	BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
6036	/* drop non-data frames */
6037	BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
6038#endif
6039	/* load the upper byte of the frame control field */
6040	BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
6041	/* mask off toDS/fromDS */
6042	BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
6043	/* accept WDS frames */
6044	BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
6045
6046	/*
6047	 * add header length to index
6048	 */
6049	/* load the lower byte of the frame control field */
6050	BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
6051	/* mask off QoS bit */
6052	BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
6053	/* right shift it by 6 to give 0 or 2 */
6054	BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
6055	/* add data frame header length */
6056	BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
6057	/* add index, was start of 802.11 header */
6058	BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
6059	/* move to index, now start of LL header */
6060	BPF_STMT(BPF_MISC | BPF_TAX, 0),
6061
6062	/*
6063	 * Accept empty data frames, we use those for
6064	 * polling activity.
6065	 */
6066	BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
6067	BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
6068
6069	/*
6070	 * Accept EAPOL frames
6071	 */
6072	BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
6073	BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
6074	BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
6075	BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
6076
6077	/* keep these last two statements or change the code below */
6078	/* return 0 == "DROP" */
6079	BPF_STMT(BPF_RET | BPF_K, 0),
6080	/* return ~0 == "keep all" */
6081	BPF_STMT(BPF_RET | BPF_K, ~0),
6082};
6083
6084static struct sock_fprog msock_filter = {
6085	.len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
6086	.filter = msock_filter_insns,
6087};
6088
6089
6090static int add_monitor_filter(int s)
6091{
6092	int idx;
6093
6094	/* rewrite all PASS/FAIL jump offsets */
6095	for (idx = 0; idx < msock_filter.len; idx++) {
6096		struct sock_filter *insn = &msock_filter_insns[idx];
6097
6098		if (BPF_CLASS(insn->code) == BPF_JMP) {
6099			if (insn->code == (BPF_JMP|BPF_JA)) {
6100				if (insn->k == PASS)
6101					insn->k = msock_filter.len - idx - 2;
6102				else if (insn->k == FAIL)
6103					insn->k = msock_filter.len - idx - 3;
6104			}
6105
6106			if (insn->jt == PASS)
6107				insn->jt = msock_filter.len - idx - 2;
6108			else if (insn->jt == FAIL)
6109				insn->jt = msock_filter.len - idx - 3;
6110
6111			if (insn->jf == PASS)
6112				insn->jf = msock_filter.len - idx - 2;
6113			else if (insn->jf == FAIL)
6114				insn->jf = msock_filter.len - idx - 3;
6115		}
6116	}
6117
6118	if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
6119		       &msock_filter, sizeof(msock_filter))) {
6120		perror("SO_ATTACH_FILTER");
6121		return -1;
6122	}
6123
6124	return 0;
6125}
6126
6127
6128static void nl80211_remove_monitor_interface(
6129	struct wpa_driver_nl80211_data *drv)
6130{
6131	drv->monitor_refcount--;
6132	if (drv->monitor_refcount > 0)
6133		return;
6134
6135	if (drv->monitor_ifidx >= 0) {
6136		nl80211_remove_iface(drv, drv->monitor_ifidx);
6137		drv->monitor_ifidx = -1;
6138	}
6139	if (drv->monitor_sock >= 0) {
6140		eloop_unregister_read_sock(drv->monitor_sock);
6141		close(drv->monitor_sock);
6142		drv->monitor_sock = -1;
6143	}
6144}
6145
6146
6147static int
6148nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
6149{
6150	char buf[IFNAMSIZ];
6151	struct sockaddr_ll ll;
6152	int optval;
6153	socklen_t optlen;
6154
6155	if (drv->monitor_ifidx >= 0) {
6156		drv->monitor_refcount++;
6157		return 0;
6158	}
6159
6160	if (os_strncmp(drv->first_bss.ifname, "p2p-", 4) == 0) {
6161		/*
6162		 * P2P interface name is of the format p2p-%s-%d. For monitor
6163		 * interface name corresponding to P2P GO, replace "p2p-" with
6164		 * "mon-" to retain the same interface name length and to
6165		 * indicate that it is a monitor interface.
6166		 */
6167		snprintf(buf, IFNAMSIZ, "mon-%s", drv->first_bss.ifname + 4);
6168	} else {
6169		/* Non-P2P interface with AP functionality. */
6170		snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss.ifname);
6171	}
6172
6173	buf[IFNAMSIZ - 1] = '\0';
6174
6175	drv->monitor_ifidx =
6176		nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
6177				     0);
6178
6179	if (drv->monitor_ifidx == -EOPNOTSUPP) {
6180		/*
6181		 * This is backward compatibility for a few versions of
6182		 * the kernel only that didn't advertise the right
6183		 * attributes for the only driver that then supported
6184		 * AP mode w/o monitor -- ath6kl.
6185		 */
6186		wpa_printf(MSG_DEBUG, "nl80211: Driver does not support "
6187			   "monitor interface type - try to run without it");
6188		drv->device_ap_sme = 1;
6189	}
6190
6191	if (drv->monitor_ifidx < 0)
6192		return -1;
6193
6194	if (linux_set_iface_flags(drv->global->ioctl_sock, buf, 1))
6195		goto error;
6196
6197	memset(&ll, 0, sizeof(ll));
6198	ll.sll_family = AF_PACKET;
6199	ll.sll_ifindex = drv->monitor_ifidx;
6200	drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
6201	if (drv->monitor_sock < 0) {
6202		perror("socket[PF_PACKET,SOCK_RAW]");
6203		goto error;
6204	}
6205
6206	if (add_monitor_filter(drv->monitor_sock)) {
6207		wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
6208			   "interface; do filtering in user space");
6209		/* This works, but will cost in performance. */
6210	}
6211
6212	if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
6213		perror("monitor socket bind");
6214		goto error;
6215	}
6216
6217	optlen = sizeof(optval);
6218	optval = 20;
6219	if (setsockopt
6220	    (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
6221		perror("Failed to set socket priority");
6222		goto error;
6223	}
6224
6225	if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
6226				     drv, NULL)) {
6227		printf("Could not register monitor read socket\n");
6228		goto error;
6229	}
6230
6231	return 0;
6232 error:
6233	nl80211_remove_monitor_interface(drv);
6234	return -1;
6235}
6236
6237
6238static int nl80211_setup_ap(struct i802_bss *bss)
6239{
6240	struct wpa_driver_nl80211_data *drv = bss->drv;
6241
6242	wpa_printf(MSG_DEBUG, "nl80211: Setup AP - device_ap_sme=%d "
6243		   "use_monitor=%d", drv->device_ap_sme, drv->use_monitor);
6244
6245	/*
6246	 * Disable Probe Request reporting unless we need it in this way for
6247	 * devices that include the AP SME, in the other case (unless using
6248	 * monitor iface) we'll get it through the nl_mgmt socket instead.
6249	 */
6250	if (!drv->device_ap_sme)
6251		wpa_driver_nl80211_probe_req_report(bss, 0);
6252
6253	if (!drv->device_ap_sme && !drv->use_monitor)
6254		if (nl80211_mgmt_subscribe_ap(bss))
6255			return -1;
6256
6257	if (drv->device_ap_sme && !drv->use_monitor)
6258		if (nl80211_mgmt_subscribe_ap_dev_sme(bss))
6259			return -1;
6260
6261	if (!drv->device_ap_sme && drv->use_monitor &&
6262	    nl80211_create_monitor_interface(drv) &&
6263	    !drv->device_ap_sme)
6264		return -1;
6265
6266#ifdef ANDROID_P2P
6267	if (drv->device_ap_sme && drv->use_monitor)
6268		if (nl80211_mgmt_subscribe_ap_dev_sme(bss))
6269			return -1;
6270
6271	if (drv->use_monitor &&
6272	    nl80211_create_monitor_interface(drv))
6273		return -1;
6274#endif
6275
6276	if (drv->device_ap_sme &&
6277	    wpa_driver_nl80211_probe_req_report(bss, 1) < 0) {
6278		wpa_printf(MSG_DEBUG, "nl80211: Failed to enable "
6279			   "Probe Request frame reporting in AP mode");
6280		/* Try to survive without this */
6281	}
6282
6283	return 0;
6284}
6285
6286
6287static void nl80211_teardown_ap(struct i802_bss *bss)
6288{
6289	struct wpa_driver_nl80211_data *drv = bss->drv;
6290
6291	if (drv->device_ap_sme) {
6292		wpa_driver_nl80211_probe_req_report(bss, 0);
6293		if (!drv->use_monitor)
6294			nl80211_mgmt_unsubscribe(bss, "AP teardown (dev SME)");
6295	} else if (drv->use_monitor)
6296		nl80211_remove_monitor_interface(drv);
6297	else
6298		nl80211_mgmt_unsubscribe(bss, "AP teardown");
6299
6300	bss->beacon_set = 0;
6301}
6302
6303
6304static int nl80211_send_eapol_data(struct i802_bss *bss,
6305				   const u8 *addr, const u8 *data,
6306				   size_t data_len)
6307{
6308	struct sockaddr_ll ll;
6309	int ret;
6310
6311	if (bss->drv->eapol_tx_sock < 0) {
6312		wpa_printf(MSG_DEBUG, "nl80211: No socket to send EAPOL");
6313		return -1;
6314	}
6315
6316	os_memset(&ll, 0, sizeof(ll));
6317	ll.sll_family = AF_PACKET;
6318	ll.sll_ifindex = bss->ifindex;
6319	ll.sll_protocol = htons(ETH_P_PAE);
6320	ll.sll_halen = ETH_ALEN;
6321	os_memcpy(ll.sll_addr, addr, ETH_ALEN);
6322	ret = sendto(bss->drv->eapol_tx_sock, data, data_len, 0,
6323		     (struct sockaddr *) &ll, sizeof(ll));
6324	if (ret < 0)
6325		wpa_printf(MSG_ERROR, "nl80211: EAPOL TX: %s",
6326			   strerror(errno));
6327
6328	return ret;
6329}
6330
6331
6332static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
6333
6334static int wpa_driver_nl80211_hapd_send_eapol(
6335	void *priv, const u8 *addr, const u8 *data,
6336	size_t data_len, int encrypt, const u8 *own_addr, u32 flags)
6337{
6338	struct i802_bss *bss = priv;
6339	struct wpa_driver_nl80211_data *drv = bss->drv;
6340	struct ieee80211_hdr *hdr;
6341	size_t len;
6342	u8 *pos;
6343	int res;
6344	int qos = flags & WPA_STA_WMM;
6345#ifndef ANDROID_P2P
6346	if (drv->device_ap_sme || !drv->use_monitor)
6347#else
6348	if (drv->device_ap_sme && !drv->use_monitor)
6349#endif
6350		return nl80211_send_eapol_data(bss, addr, data, data_len);
6351
6352	len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
6353		data_len;
6354	hdr = os_zalloc(len);
6355	if (hdr == NULL) {
6356		printf("malloc() failed for i802_send_data(len=%lu)\n",
6357		       (unsigned long) len);
6358		return -1;
6359	}
6360
6361	hdr->frame_control =
6362		IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
6363	hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
6364	if (encrypt)
6365		hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
6366	if (qos) {
6367		hdr->frame_control |=
6368			host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
6369	}
6370
6371	memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
6372	memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
6373	memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
6374	pos = (u8 *) (hdr + 1);
6375
6376	if (qos) {
6377		/* add an empty QoS header if needed */
6378		pos[0] = 0;
6379		pos[1] = 0;
6380		pos += 2;
6381	}
6382
6383	memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
6384	pos += sizeof(rfc1042_header);
6385	WPA_PUT_BE16(pos, ETH_P_PAE);
6386	pos += 2;
6387	memcpy(pos, data, data_len);
6388
6389	res = wpa_driver_nl80211_send_frame(bss, (u8 *) hdr, len, encrypt, 0,
6390					    0, 0, 0, 0);
6391	if (res < 0) {
6392		wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
6393			   "failed: %d (%s)",
6394			   (unsigned long) len, errno, strerror(errno));
6395	}
6396	os_free(hdr);
6397
6398	return res;
6399}
6400
6401
6402static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
6403					    int total_flags,
6404					    int flags_or, int flags_and)
6405{
6406	struct i802_bss *bss = priv;
6407	struct wpa_driver_nl80211_data *drv = bss->drv;
6408	struct nl_msg *msg, *flags = NULL;
6409	struct nl80211_sta_flag_update upd;
6410
6411	msg = nlmsg_alloc();
6412	if (!msg)
6413		return -ENOMEM;
6414
6415	flags = nlmsg_alloc();
6416	if (!flags) {
6417		nlmsg_free(msg);
6418		return -ENOMEM;
6419	}
6420
6421	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
6422
6423	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
6424		    if_nametoindex(bss->ifname));
6425	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
6426
6427	/*
6428	 * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
6429	 * can be removed eventually.
6430	 */
6431	if (total_flags & WPA_STA_AUTHORIZED)
6432		NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
6433
6434	if (total_flags & WPA_STA_WMM)
6435		NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
6436
6437	if (total_flags & WPA_STA_SHORT_PREAMBLE)
6438		NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
6439
6440	if (total_flags & WPA_STA_MFP)
6441		NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
6442
6443	if (total_flags & WPA_STA_TDLS_PEER)
6444		NLA_PUT_FLAG(flags, NL80211_STA_FLAG_TDLS_PEER);
6445
6446	if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
6447		goto nla_put_failure;
6448
6449	os_memset(&upd, 0, sizeof(upd));
6450	upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
6451	upd.set = sta_flags_nl80211(flags_or);
6452	NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
6453
6454	nlmsg_free(flags);
6455
6456	return send_and_recv_msgs(drv, msg, NULL, NULL);
6457 nla_put_failure:
6458	nlmsg_free(msg);
6459	nlmsg_free(flags);
6460	return -ENOBUFS;
6461}
6462
6463
6464static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
6465				 struct wpa_driver_associate_params *params)
6466{
6467	enum nl80211_iftype nlmode;
6468
6469	if (params->p2p) {
6470		wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
6471			   "group (GO)");
6472		nlmode = NL80211_IFTYPE_P2P_GO;
6473	} else
6474		nlmode = NL80211_IFTYPE_AP;
6475
6476	if (wpa_driver_nl80211_set_mode(&drv->first_bss, nlmode) ||
6477	    wpa_driver_nl80211_set_freq(&drv->first_bss, params->freq, 0, 0)) {
6478		nl80211_remove_monitor_interface(drv);
6479		return -1;
6480	}
6481
6482	return 0;
6483}
6484
6485
6486static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
6487{
6488	struct nl_msg *msg;
6489	int ret = -1;
6490
6491	msg = nlmsg_alloc();
6492	if (!msg)
6493		return -1;
6494
6495	nl80211_cmd(drv, msg, 0, NL80211_CMD_LEAVE_IBSS);
6496	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6497	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6498	msg = NULL;
6499	if (ret) {
6500		wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
6501			   "(%s)", ret, strerror(-ret));
6502		goto nla_put_failure;
6503	}
6504
6505	ret = 0;
6506	wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
6507
6508nla_put_failure:
6509	nlmsg_free(msg);
6510	return ret;
6511}
6512
6513
6514static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
6515				   struct wpa_driver_associate_params *params)
6516{
6517	struct nl_msg *msg;
6518	int ret = -1;
6519	int count = 0;
6520
6521	wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
6522
6523	if (wpa_driver_nl80211_set_mode(&drv->first_bss,
6524					NL80211_IFTYPE_ADHOC)) {
6525		wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
6526			   "IBSS mode");
6527		return -1;
6528	}
6529
6530retry:
6531	msg = nlmsg_alloc();
6532	if (!msg)
6533		return -1;
6534
6535	nl80211_cmd(drv, msg, 0, NL80211_CMD_JOIN_IBSS);
6536	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6537
6538	if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
6539		goto nla_put_failure;
6540
6541	wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6542			  params->ssid, params->ssid_len);
6543	NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6544		params->ssid);
6545	os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6546	drv->ssid_len = params->ssid_len;
6547
6548	wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6549	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6550
6551	ret = nl80211_set_conn_keys(params, msg);
6552	if (ret)
6553		goto nla_put_failure;
6554
6555	if (params->bssid && params->fixed_bssid) {
6556		wpa_printf(MSG_DEBUG, "  * BSSID=" MACSTR,
6557			   MAC2STR(params->bssid));
6558		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6559	}
6560
6561	if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
6562	    params->key_mgmt_suite == KEY_MGMT_PSK ||
6563	    params->key_mgmt_suite == KEY_MGMT_802_1X_SHA256 ||
6564	    params->key_mgmt_suite == KEY_MGMT_PSK_SHA256) {
6565		wpa_printf(MSG_DEBUG, "  * control port");
6566		NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
6567	}
6568
6569	if (params->wpa_ie) {
6570		wpa_hexdump(MSG_DEBUG,
6571			    "  * Extra IEs for Beacon/Probe Response frames",
6572			    params->wpa_ie, params->wpa_ie_len);
6573		NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6574			params->wpa_ie);
6575	}
6576
6577	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6578	msg = NULL;
6579	if (ret) {
6580		wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
6581			   ret, strerror(-ret));
6582		count++;
6583		if (ret == -EALREADY && count == 1) {
6584			wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
6585				   "forced leave");
6586			nl80211_leave_ibss(drv);
6587			nlmsg_free(msg);
6588			goto retry;
6589		}
6590
6591		goto nla_put_failure;
6592	}
6593	ret = 0;
6594	wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
6595
6596nla_put_failure:
6597	nlmsg_free(msg);
6598	return ret;
6599}
6600
6601
6602static unsigned int nl80211_get_assoc_bssid(struct wpa_driver_nl80211_data *drv,
6603					    u8 *bssid)
6604{
6605	struct nl_msg *msg;
6606	int ret;
6607	struct nl80211_bss_info_arg arg;
6608
6609	os_memset(&arg, 0, sizeof(arg));
6610	msg = nlmsg_alloc();
6611	if (!msg)
6612		goto nla_put_failure;
6613
6614	nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
6615	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6616
6617	arg.drv = drv;
6618	ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
6619	msg = NULL;
6620	if (ret == 0) {
6621		if (is_zero_ether_addr(arg.assoc_bssid))
6622			return -ENOTCONN;
6623		os_memcpy(bssid, arg.assoc_bssid, ETH_ALEN);
6624		return 0;
6625	}
6626	wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
6627		   "(%s)", ret, strerror(-ret));
6628nla_put_failure:
6629	nlmsg_free(msg);
6630	return drv->assoc_freq;
6631}
6632
6633
6634static int nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
6635			      const u8 *bssid)
6636{
6637	u8 addr[ETH_ALEN];
6638
6639	if (bssid == NULL) {
6640		int res = nl80211_get_assoc_bssid(drv, addr);
6641		if (res)
6642			return res;
6643		bssid = addr;
6644	}
6645
6646	return wpa_driver_nl80211_disconnect(drv, bssid,
6647					     WLAN_REASON_PREV_AUTH_NOT_VALID);
6648}
6649
6650
6651static int wpa_driver_nl80211_connect(
6652	struct wpa_driver_nl80211_data *drv,
6653	struct wpa_driver_associate_params *params)
6654{
6655	struct nl_msg *msg;
6656	enum nl80211_auth_type type;
6657	int ret = 0;
6658	int algs;
6659
6660	msg = nlmsg_alloc();
6661	if (!msg)
6662		return -1;
6663
6664	wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
6665	nl80211_cmd(drv, msg, 0, NL80211_CMD_CONNECT);
6666
6667	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6668	if (params->bssid) {
6669		wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
6670			   MAC2STR(params->bssid));
6671		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6672	}
6673	if (params->freq) {
6674		wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6675		NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6676	}
6677	if (params->bg_scan_period >= 0) {
6678		wpa_printf(MSG_DEBUG, "  * bg scan period=%d",
6679			   params->bg_scan_period);
6680		NLA_PUT_U16(msg, NL80211_ATTR_BG_SCAN_PERIOD,
6681			    params->bg_scan_period);
6682	}
6683	if (params->ssid) {
6684		wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6685				  params->ssid, params->ssid_len);
6686		NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6687			params->ssid);
6688		if (params->ssid_len > sizeof(drv->ssid))
6689			goto nla_put_failure;
6690		os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6691		drv->ssid_len = params->ssid_len;
6692	}
6693	wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
6694	if (params->wpa_ie)
6695		NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6696			params->wpa_ie);
6697
6698	algs = 0;
6699	if (params->auth_alg & WPA_AUTH_ALG_OPEN)
6700		algs++;
6701	if (params->auth_alg & WPA_AUTH_ALG_SHARED)
6702		algs++;
6703	if (params->auth_alg & WPA_AUTH_ALG_LEAP)
6704		algs++;
6705	if (algs > 1) {
6706		wpa_printf(MSG_DEBUG, "  * Leave out Auth Type for automatic "
6707			   "selection");
6708		goto skip_auth_type;
6709	}
6710
6711	if (params->auth_alg & WPA_AUTH_ALG_OPEN)
6712		type = NL80211_AUTHTYPE_OPEN_SYSTEM;
6713	else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
6714		type = NL80211_AUTHTYPE_SHARED_KEY;
6715	else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
6716		type = NL80211_AUTHTYPE_NETWORK_EAP;
6717	else if (params->auth_alg & WPA_AUTH_ALG_FT)
6718		type = NL80211_AUTHTYPE_FT;
6719	else
6720		goto nla_put_failure;
6721
6722	wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
6723	NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
6724
6725skip_auth_type:
6726	if (params->wpa_proto) {
6727		enum nl80211_wpa_versions ver = 0;
6728
6729		if (params->wpa_proto & WPA_PROTO_WPA)
6730			ver |= NL80211_WPA_VERSION_1;
6731		if (params->wpa_proto & WPA_PROTO_RSN)
6732			ver |= NL80211_WPA_VERSION_2;
6733
6734		wpa_printf(MSG_DEBUG, "  * WPA Versions 0x%x", ver);
6735		NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
6736	}
6737
6738	if (params->pairwise_suite != CIPHER_NONE) {
6739		int cipher;
6740
6741		switch (params->pairwise_suite) {
6742		case CIPHER_WEP40:
6743			cipher = WLAN_CIPHER_SUITE_WEP40;
6744			break;
6745		case CIPHER_WEP104:
6746			cipher = WLAN_CIPHER_SUITE_WEP104;
6747			break;
6748		case CIPHER_CCMP:
6749			cipher = WLAN_CIPHER_SUITE_CCMP;
6750			break;
6751		case CIPHER_TKIP:
6752		default:
6753			cipher = WLAN_CIPHER_SUITE_TKIP;
6754			break;
6755		}
6756		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
6757	}
6758
6759	if (params->group_suite != CIPHER_NONE) {
6760		int cipher;
6761
6762		switch (params->group_suite) {
6763		case CIPHER_WEP40:
6764			cipher = WLAN_CIPHER_SUITE_WEP40;
6765			break;
6766		case CIPHER_WEP104:
6767			cipher = WLAN_CIPHER_SUITE_WEP104;
6768			break;
6769		case CIPHER_CCMP:
6770			cipher = WLAN_CIPHER_SUITE_CCMP;
6771			break;
6772		case CIPHER_TKIP:
6773		default:
6774			cipher = WLAN_CIPHER_SUITE_TKIP;
6775			break;
6776		}
6777		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
6778	}
6779
6780	if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
6781	    params->key_mgmt_suite == KEY_MGMT_PSK) {
6782		int mgmt = WLAN_AKM_SUITE_PSK;
6783
6784		switch (params->key_mgmt_suite) {
6785		case KEY_MGMT_802_1X:
6786			mgmt = WLAN_AKM_SUITE_8021X;
6787			break;
6788		case KEY_MGMT_PSK:
6789		default:
6790			mgmt = WLAN_AKM_SUITE_PSK;
6791			break;
6792		}
6793		NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
6794	}
6795
6796	if (params->disable_ht)
6797		NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
6798
6799	if (params->htcaps && params->htcaps_mask) {
6800		int sz = sizeof(struct ieee80211_ht_capabilities);
6801		NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
6802		NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
6803			params->htcaps_mask);
6804	}
6805
6806	ret = nl80211_set_conn_keys(params, msg);
6807	if (ret)
6808		goto nla_put_failure;
6809
6810	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6811	msg = NULL;
6812	if (ret) {
6813		wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
6814			   "(%s)", ret, strerror(-ret));
6815		/*
6816		 * cfg80211 does not currently accept new connection if we are
6817		 * already connected. As a workaround, force disconnection and
6818		 * try again once the driver indicates it completed
6819		 * disconnection.
6820		 */
6821		if (ret == -EALREADY)
6822			nl80211_disconnect(drv, params->bssid);
6823		goto nla_put_failure;
6824	}
6825	ret = 0;
6826	wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
6827
6828nla_put_failure:
6829	nlmsg_free(msg);
6830	return ret;
6831
6832}
6833
6834
6835static int wpa_driver_nl80211_associate(
6836	void *priv, struct wpa_driver_associate_params *params)
6837{
6838	struct i802_bss *bss = priv;
6839	struct wpa_driver_nl80211_data *drv = bss->drv;
6840	int ret = -1;
6841	struct nl_msg *msg;
6842
6843	if (params->mode == IEEE80211_MODE_AP)
6844		return wpa_driver_nl80211_ap(drv, params);
6845
6846	if (params->mode == IEEE80211_MODE_IBSS)
6847		return wpa_driver_nl80211_ibss(drv, params);
6848
6849	if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
6850		enum nl80211_iftype nlmode = params->p2p ?
6851			NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
6852
6853		if (wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
6854			return -1;
6855		return wpa_driver_nl80211_connect(drv, params);
6856	}
6857
6858	drv->associated = 0;
6859
6860	msg = nlmsg_alloc();
6861	if (!msg)
6862		return -1;
6863
6864	wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
6865		   drv->ifindex);
6866	nl80211_cmd(drv, msg, 0, NL80211_CMD_ASSOCIATE);
6867
6868	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6869	if (params->bssid) {
6870		wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
6871			   MAC2STR(params->bssid));
6872		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6873	}
6874	if (params->freq) {
6875		wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6876		NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6877		drv->assoc_freq = params->freq;
6878	} else
6879		drv->assoc_freq = 0;
6880	if (params->bg_scan_period >= 0) {
6881		wpa_printf(MSG_DEBUG, "  * bg scan period=%d",
6882			   params->bg_scan_period);
6883		NLA_PUT_U16(msg, NL80211_ATTR_BG_SCAN_PERIOD,
6884			    params->bg_scan_period);
6885	}
6886	if (params->ssid) {
6887		wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6888				  params->ssid, params->ssid_len);
6889		NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6890			params->ssid);
6891		if (params->ssid_len > sizeof(drv->ssid))
6892			goto nla_put_failure;
6893		os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6894		drv->ssid_len = params->ssid_len;
6895	}
6896	wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
6897	if (params->wpa_ie)
6898		NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6899			params->wpa_ie);
6900
6901	if (params->pairwise_suite != CIPHER_NONE) {
6902		int cipher;
6903
6904		switch (params->pairwise_suite) {
6905		case CIPHER_WEP40:
6906			cipher = WLAN_CIPHER_SUITE_WEP40;
6907			break;
6908		case CIPHER_WEP104:
6909			cipher = WLAN_CIPHER_SUITE_WEP104;
6910			break;
6911		case CIPHER_CCMP:
6912			cipher = WLAN_CIPHER_SUITE_CCMP;
6913			break;
6914		case CIPHER_TKIP:
6915		default:
6916			cipher = WLAN_CIPHER_SUITE_TKIP;
6917			break;
6918		}
6919		wpa_printf(MSG_DEBUG, "  * pairwise=0x%x", cipher);
6920		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
6921	}
6922
6923	if (params->group_suite != CIPHER_NONE) {
6924		int cipher;
6925
6926		switch (params->group_suite) {
6927		case CIPHER_WEP40:
6928			cipher = WLAN_CIPHER_SUITE_WEP40;
6929			break;
6930		case CIPHER_WEP104:
6931			cipher = WLAN_CIPHER_SUITE_WEP104;
6932			break;
6933		case CIPHER_CCMP:
6934			cipher = WLAN_CIPHER_SUITE_CCMP;
6935			break;
6936		case CIPHER_TKIP:
6937		default:
6938			cipher = WLAN_CIPHER_SUITE_TKIP;
6939			break;
6940		}
6941		wpa_printf(MSG_DEBUG, "  * group=0x%x", cipher);
6942		NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
6943	}
6944
6945#ifdef CONFIG_IEEE80211W
6946	if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
6947		NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
6948#endif /* CONFIG_IEEE80211W */
6949
6950	NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
6951
6952	if (params->prev_bssid) {
6953		wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
6954			   MAC2STR(params->prev_bssid));
6955		NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
6956			params->prev_bssid);
6957	}
6958
6959	if (params->disable_ht)
6960		NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
6961
6962	if (params->htcaps && params->htcaps_mask) {
6963		int sz = sizeof(struct ieee80211_ht_capabilities);
6964		NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
6965		NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
6966			params->htcaps_mask);
6967	}
6968
6969	if (params->p2p)
6970		wpa_printf(MSG_DEBUG, "  * P2P group");
6971
6972	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6973	msg = NULL;
6974	if (ret) {
6975		wpa_dbg(drv->ctx, MSG_DEBUG,
6976			"nl80211: MLME command failed (assoc): ret=%d (%s)",
6977			ret, strerror(-ret));
6978		nl80211_dump_scan(drv);
6979		goto nla_put_failure;
6980	}
6981	ret = 0;
6982	wpa_printf(MSG_DEBUG, "nl80211: Association request send "
6983		   "successfully");
6984
6985nla_put_failure:
6986	nlmsg_free(msg);
6987	return ret;
6988}
6989
6990
6991static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
6992			    int ifindex, enum nl80211_iftype mode)
6993{
6994	struct nl_msg *msg;
6995	int ret = -ENOBUFS;
6996
6997	wpa_printf(MSG_DEBUG, "nl80211: Set mode ifindex %d iftype %d (%s)",
6998		   ifindex, mode, nl80211_iftype_str(mode));
6999
7000	msg = nlmsg_alloc();
7001	if (!msg)
7002		return -ENOMEM;
7003
7004	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_INTERFACE);
7005	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
7006	NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
7007
7008	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7009	msg = NULL;
7010	if (!ret)
7011		return 0;
7012nla_put_failure:
7013	nlmsg_free(msg);
7014	wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
7015		   " %d (%s)", ifindex, mode, ret, strerror(-ret));
7016	return ret;
7017}
7018
7019
7020static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
7021				       enum nl80211_iftype nlmode)
7022{
7023	struct wpa_driver_nl80211_data *drv = bss->drv;
7024	int ret = -1;
7025	int i;
7026	int was_ap = is_ap_interface(drv->nlmode);
7027	int res;
7028
7029	res = nl80211_set_mode(drv, drv->ifindex, nlmode);
7030	if (res == 0) {
7031		drv->nlmode = nlmode;
7032		ret = 0;
7033		goto done;
7034	}
7035
7036	if (res == -ENODEV)
7037		return -1;
7038
7039	if (nlmode == drv->nlmode) {
7040		wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
7041			   "requested mode - ignore error");
7042		ret = 0;
7043		goto done; /* Already in the requested mode */
7044	}
7045
7046	/* mac80211 doesn't allow mode changes while the device is up, so
7047	 * take the device down, try to set the mode again, and bring the
7048	 * device back up.
7049	 */
7050	wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
7051		   "interface down");
7052	for (i = 0; i < 10; i++) {
7053		res = linux_set_iface_flags(drv->global->ioctl_sock,
7054					    bss->ifname, 0);
7055		if (res == -EACCES || res == -ENODEV)
7056			break;
7057		if (res == 0) {
7058			/* Try to set the mode again while the interface is
7059			 * down */
7060			ret = nl80211_set_mode(drv, drv->ifindex, nlmode);
7061			if (ret == -EACCES)
7062				break;
7063			res = linux_set_iface_flags(drv->global->ioctl_sock,
7064						    bss->ifname, 1);
7065			if (res && !ret)
7066				ret = -1;
7067			else if (ret != -EBUSY)
7068				break;
7069		} else
7070			wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
7071				   "interface down");
7072		os_sleep(0, 100000);
7073	}
7074
7075	if (!ret) {
7076		wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
7077			   "interface is down");
7078		drv->nlmode = nlmode;
7079		drv->ignore_if_down_event = 1;
7080	}
7081
7082done:
7083	if (ret) {
7084		wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
7085			   "from %d failed", nlmode, drv->nlmode);
7086		return ret;
7087	}
7088
7089	if (is_ap_interface(nlmode)) {
7090		nl80211_mgmt_unsubscribe(bss, "start AP");
7091		/* Setup additional AP mode functionality if needed */
7092		if (nl80211_setup_ap(bss))
7093			return -1;
7094	} else if (was_ap) {
7095		/* Remove additional AP mode functionality */
7096		nl80211_teardown_ap(bss);
7097	} else {
7098		nl80211_mgmt_unsubscribe(bss, "mode change");
7099	}
7100
7101	if (!bss->in_deinit && !is_ap_interface(nlmode) &&
7102	    nl80211_mgmt_subscribe_non_ap(bss) < 0)
7103		wpa_printf(MSG_DEBUG, "nl80211: Failed to register Action "
7104			   "frame processing - ignore for now");
7105
7106	return 0;
7107}
7108
7109
7110static int wpa_driver_nl80211_get_capa(void *priv,
7111				       struct wpa_driver_capa *capa)
7112{
7113	struct i802_bss *bss = priv;
7114	struct wpa_driver_nl80211_data *drv = bss->drv;
7115	if (!drv->has_capability)
7116		return -1;
7117	os_memcpy(capa, &drv->capa, sizeof(*capa));
7118	return 0;
7119}
7120
7121
7122static int wpa_driver_nl80211_set_operstate(void *priv, int state)
7123{
7124	struct i802_bss *bss = priv;
7125	struct wpa_driver_nl80211_data *drv = bss->drv;
7126
7127	wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
7128		   __func__, drv->operstate, state, state ? "UP" : "DORMANT");
7129	drv->operstate = state;
7130	return netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, -1,
7131				      state ? IF_OPER_UP : IF_OPER_DORMANT);
7132}
7133
7134
7135static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
7136{
7137	struct i802_bss *bss = priv;
7138	struct wpa_driver_nl80211_data *drv = bss->drv;
7139	struct nl_msg *msg;
7140	struct nl80211_sta_flag_update upd;
7141
7142	msg = nlmsg_alloc();
7143	if (!msg)
7144		return -ENOMEM;
7145
7146	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
7147
7148	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7149		    if_nametoindex(bss->ifname));
7150	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
7151
7152	os_memset(&upd, 0, sizeof(upd));
7153	upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
7154	if (authorized)
7155		upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
7156	NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
7157
7158	return send_and_recv_msgs(drv, msg, NULL, NULL);
7159 nla_put_failure:
7160	nlmsg_free(msg);
7161	return -ENOBUFS;
7162}
7163
7164
7165/* Set kernel driver on given frequency (MHz) */
7166static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
7167{
7168	struct i802_bss *bss = priv;
7169	return wpa_driver_nl80211_set_freq(bss, freq->freq, freq->ht_enabled,
7170					   freq->sec_channel_offset);
7171}
7172
7173
7174#if defined(HOSTAPD) || defined(CONFIG_AP)
7175
7176static inline int min_int(int a, int b)
7177{
7178	if (a < b)
7179		return a;
7180	return b;
7181}
7182
7183
7184static int get_key_handler(struct nl_msg *msg, void *arg)
7185{
7186	struct nlattr *tb[NL80211_ATTR_MAX + 1];
7187	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7188
7189	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7190		  genlmsg_attrlen(gnlh, 0), NULL);
7191
7192	/*
7193	 * TODO: validate the key index and mac address!
7194	 * Otherwise, there's a race condition as soon as
7195	 * the kernel starts sending key notifications.
7196	 */
7197
7198	if (tb[NL80211_ATTR_KEY_SEQ])
7199		memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
7200		       min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
7201	return NL_SKIP;
7202}
7203
7204
7205static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
7206			   int idx, u8 *seq)
7207{
7208	struct i802_bss *bss = priv;
7209	struct wpa_driver_nl80211_data *drv = bss->drv;
7210	struct nl_msg *msg;
7211
7212	msg = nlmsg_alloc();
7213	if (!msg)
7214		return -ENOMEM;
7215
7216	nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_KEY);
7217
7218	if (addr)
7219		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7220	NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
7221	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
7222
7223	memset(seq, 0, 6);
7224
7225	return send_and_recv_msgs(drv, msg, get_key_handler, seq);
7226 nla_put_failure:
7227	nlmsg_free(msg);
7228	return -ENOBUFS;
7229}
7230
7231
7232static int i802_set_rts(void *priv, int rts)
7233{
7234	struct i802_bss *bss = priv;
7235	struct wpa_driver_nl80211_data *drv = bss->drv;
7236	struct nl_msg *msg;
7237	int ret = -ENOBUFS;
7238	u32 val;
7239
7240	msg = nlmsg_alloc();
7241	if (!msg)
7242		return -ENOMEM;
7243
7244	if (rts >= 2347)
7245		val = (u32) -1;
7246	else
7247		val = rts;
7248
7249	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7250	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7251	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
7252
7253	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7254	msg = NULL;
7255	if (!ret)
7256		return 0;
7257nla_put_failure:
7258	nlmsg_free(msg);
7259	wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
7260		   "%d (%s)", rts, ret, strerror(-ret));
7261	return ret;
7262}
7263
7264
7265static int i802_set_frag(void *priv, int frag)
7266{
7267	struct i802_bss *bss = priv;
7268	struct wpa_driver_nl80211_data *drv = bss->drv;
7269	struct nl_msg *msg;
7270	int ret = -ENOBUFS;
7271	u32 val;
7272
7273	msg = nlmsg_alloc();
7274	if (!msg)
7275		return -ENOMEM;
7276
7277	if (frag >= 2346)
7278		val = (u32) -1;
7279	else
7280		val = frag;
7281
7282	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7283	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7284	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
7285
7286	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7287	msg = NULL;
7288	if (!ret)
7289		return 0;
7290nla_put_failure:
7291	nlmsg_free(msg);
7292	wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
7293		   "%d: %d (%s)", frag, ret, strerror(-ret));
7294	return ret;
7295}
7296
7297
7298static int i802_flush(void *priv)
7299{
7300	struct i802_bss *bss = priv;
7301	struct wpa_driver_nl80211_data *drv = bss->drv;
7302	struct nl_msg *msg;
7303	int res;
7304
7305	msg = nlmsg_alloc();
7306	if (!msg)
7307		return -1;
7308
7309	nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
7310
7311	/*
7312	 * XXX: FIX! this needs to flush all VLANs too
7313	 */
7314	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7315		    if_nametoindex(bss->ifname));
7316
7317	res = send_and_recv_msgs(drv, msg, NULL, NULL);
7318	if (res) {
7319		wpa_printf(MSG_DEBUG, "nl80211: Station flush failed: ret=%d "
7320			   "(%s)", res, strerror(-res));
7321	}
7322	return res;
7323 nla_put_failure:
7324	nlmsg_free(msg);
7325	return -ENOBUFS;
7326}
7327
7328
7329static int get_sta_handler(struct nl_msg *msg, void *arg)
7330{
7331	struct nlattr *tb[NL80211_ATTR_MAX + 1];
7332	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7333	struct hostap_sta_driver_data *data = arg;
7334	struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
7335	static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
7336		[NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
7337		[NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
7338		[NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
7339		[NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
7340		[NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
7341		[NL80211_STA_INFO_TX_FAILED] = { .type = NLA_U32 },
7342	};
7343
7344	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7345		  genlmsg_attrlen(gnlh, 0), NULL);
7346
7347	/*
7348	 * TODO: validate the interface and mac address!
7349	 * Otherwise, there's a race condition as soon as
7350	 * the kernel starts sending station notifications.
7351	 */
7352
7353	if (!tb[NL80211_ATTR_STA_INFO]) {
7354		wpa_printf(MSG_DEBUG, "sta stats missing!");
7355		return NL_SKIP;
7356	}
7357	if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
7358			     tb[NL80211_ATTR_STA_INFO],
7359			     stats_policy)) {
7360		wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
7361		return NL_SKIP;
7362	}
7363
7364	if (stats[NL80211_STA_INFO_INACTIVE_TIME])
7365		data->inactive_msec =
7366			nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
7367	if (stats[NL80211_STA_INFO_RX_BYTES])
7368		data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
7369	if (stats[NL80211_STA_INFO_TX_BYTES])
7370		data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
7371	if (stats[NL80211_STA_INFO_RX_PACKETS])
7372		data->rx_packets =
7373			nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
7374	if (stats[NL80211_STA_INFO_TX_PACKETS])
7375		data->tx_packets =
7376			nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
7377	if (stats[NL80211_STA_INFO_TX_FAILED])
7378		data->tx_retry_failed =
7379			nla_get_u32(stats[NL80211_STA_INFO_TX_FAILED]);
7380
7381	return NL_SKIP;
7382}
7383
7384static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
7385			      const u8 *addr)
7386{
7387	struct i802_bss *bss = priv;
7388	struct wpa_driver_nl80211_data *drv = bss->drv;
7389	struct nl_msg *msg;
7390
7391	os_memset(data, 0, sizeof(*data));
7392	msg = nlmsg_alloc();
7393	if (!msg)
7394		return -ENOMEM;
7395
7396	nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
7397
7398	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7399	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7400
7401	return send_and_recv_msgs(drv, msg, get_sta_handler, data);
7402 nla_put_failure:
7403	nlmsg_free(msg);
7404	return -ENOBUFS;
7405}
7406
7407
7408static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
7409				    int cw_min, int cw_max, int burst_time)
7410{
7411	struct i802_bss *bss = priv;
7412	struct wpa_driver_nl80211_data *drv = bss->drv;
7413	struct nl_msg *msg;
7414	struct nlattr *txq, *params;
7415
7416	msg = nlmsg_alloc();
7417	if (!msg)
7418		return -1;
7419
7420	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7421
7422	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7423
7424	txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
7425	if (!txq)
7426		goto nla_put_failure;
7427
7428	/* We are only sending parameters for a single TXQ at a time */
7429	params = nla_nest_start(msg, 1);
7430	if (!params)
7431		goto nla_put_failure;
7432
7433	switch (queue) {
7434	case 0:
7435		NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
7436		break;
7437	case 1:
7438		NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
7439		break;
7440	case 2:
7441		NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
7442		break;
7443	case 3:
7444		NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
7445		break;
7446	}
7447	/* Burst time is configured in units of 0.1 msec and TXOP parameter in
7448	 * 32 usec, so need to convert the value here. */
7449	NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
7450	NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
7451	NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
7452	NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
7453
7454	nla_nest_end(msg, params);
7455
7456	nla_nest_end(msg, txq);
7457
7458	if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
7459		return 0;
7460	msg = NULL;
7461 nla_put_failure:
7462	nlmsg_free(msg);
7463	return -1;
7464}
7465
7466
7467static int i802_set_sta_vlan(void *priv, const u8 *addr,
7468			     const char *ifname, int vlan_id)
7469{
7470	struct i802_bss *bss = priv;
7471	struct wpa_driver_nl80211_data *drv = bss->drv;
7472	struct nl_msg *msg;
7473	int ret = -ENOBUFS;
7474
7475	msg = nlmsg_alloc();
7476	if (!msg)
7477		return -ENOMEM;
7478
7479	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
7480
7481	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7482		    if_nametoindex(bss->ifname));
7483	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7484	NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
7485		    if_nametoindex(ifname));
7486
7487	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7488	msg = NULL;
7489	if (ret < 0) {
7490		wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
7491			   MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
7492			   MAC2STR(addr), ifname, vlan_id, ret,
7493			   strerror(-ret));
7494	}
7495 nla_put_failure:
7496	nlmsg_free(msg);
7497	return ret;
7498}
7499
7500
7501static int i802_get_inact_sec(void *priv, const u8 *addr)
7502{
7503	struct hostap_sta_driver_data data;
7504	int ret;
7505
7506	data.inactive_msec = (unsigned long) -1;
7507	ret = i802_read_sta_data(priv, &data, addr);
7508	if (ret || data.inactive_msec == (unsigned long) -1)
7509		return -1;
7510	return data.inactive_msec / 1000;
7511}
7512
7513
7514static int i802_sta_clear_stats(void *priv, const u8 *addr)
7515{
7516#if 0
7517	/* TODO */
7518#endif
7519	return 0;
7520}
7521
7522
7523static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
7524			   int reason)
7525{
7526	struct i802_bss *bss = priv;
7527	struct wpa_driver_nl80211_data *drv = bss->drv;
7528	struct ieee80211_mgmt mgmt;
7529
7530	if (drv->device_ap_sme)
7531		return wpa_driver_nl80211_sta_remove(bss, addr);
7532
7533	memset(&mgmt, 0, sizeof(mgmt));
7534	mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
7535					  WLAN_FC_STYPE_DEAUTH);
7536	memcpy(mgmt.da, addr, ETH_ALEN);
7537	memcpy(mgmt.sa, own_addr, ETH_ALEN);
7538	memcpy(mgmt.bssid, own_addr, ETH_ALEN);
7539	mgmt.u.deauth.reason_code = host_to_le16(reason);
7540	return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
7541					    IEEE80211_HDRLEN +
7542					    sizeof(mgmt.u.deauth), 0);
7543}
7544
7545
7546static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
7547			     int reason)
7548{
7549	struct i802_bss *bss = priv;
7550	struct wpa_driver_nl80211_data *drv = bss->drv;
7551	struct ieee80211_mgmt mgmt;
7552
7553	if (drv->device_ap_sme)
7554		return wpa_driver_nl80211_sta_remove(bss, addr);
7555
7556	memset(&mgmt, 0, sizeof(mgmt));
7557	mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
7558					  WLAN_FC_STYPE_DISASSOC);
7559	memcpy(mgmt.da, addr, ETH_ALEN);
7560	memcpy(mgmt.sa, own_addr, ETH_ALEN);
7561	memcpy(mgmt.bssid, own_addr, ETH_ALEN);
7562	mgmt.u.disassoc.reason_code = host_to_le16(reason);
7563	return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
7564					    IEEE80211_HDRLEN +
7565					    sizeof(mgmt.u.disassoc), 0);
7566}
7567
7568#endif /* HOSTAPD || CONFIG_AP */
7569
7570#ifdef HOSTAPD
7571
7572static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7573{
7574	int i;
7575	int *old;
7576
7577	wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
7578		   ifidx);
7579	for (i = 0; i < drv->num_if_indices; i++) {
7580		if (drv->if_indices[i] == 0) {
7581			drv->if_indices[i] = ifidx;
7582			return;
7583		}
7584	}
7585
7586	if (drv->if_indices != drv->default_if_indices)
7587		old = drv->if_indices;
7588	else
7589		old = NULL;
7590
7591	drv->if_indices = os_realloc(old,
7592				     sizeof(int) * (drv->num_if_indices + 1));
7593	if (!drv->if_indices) {
7594		if (!old)
7595			drv->if_indices = drv->default_if_indices;
7596		else
7597			drv->if_indices = old;
7598		wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
7599			   "interfaces");
7600		wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
7601		return;
7602	} else if (!old)
7603		os_memcpy(drv->if_indices, drv->default_if_indices,
7604			  sizeof(drv->default_if_indices));
7605	drv->if_indices[drv->num_if_indices] = ifidx;
7606	drv->num_if_indices++;
7607}
7608
7609
7610static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7611{
7612	int i;
7613
7614	for (i = 0; i < drv->num_if_indices; i++) {
7615		if (drv->if_indices[i] == ifidx) {
7616			drv->if_indices[i] = 0;
7617			break;
7618		}
7619	}
7620}
7621
7622
7623static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7624{
7625	int i;
7626
7627	for (i = 0; i < drv->num_if_indices; i++)
7628		if (drv->if_indices[i] == ifidx)
7629			return 1;
7630
7631	return 0;
7632}
7633
7634
7635static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
7636                            const char *bridge_ifname)
7637{
7638	struct i802_bss *bss = priv;
7639	struct wpa_driver_nl80211_data *drv = bss->drv;
7640	char name[IFNAMSIZ + 1];
7641
7642	os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
7643	wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
7644		   " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
7645	if (val) {
7646		if (!if_nametoindex(name)) {
7647			if (nl80211_create_iface(drv, name,
7648						 NL80211_IFTYPE_AP_VLAN,
7649						 NULL, 1) < 0)
7650				return -1;
7651			if (bridge_ifname &&
7652			    linux_br_add_if(drv->global->ioctl_sock,
7653					    bridge_ifname, name) < 0)
7654				return -1;
7655		}
7656		linux_set_iface_flags(drv->global->ioctl_sock, name, 1);
7657		return i802_set_sta_vlan(priv, addr, name, 0);
7658	} else {
7659		i802_set_sta_vlan(priv, addr, bss->ifname, 0);
7660		return wpa_driver_nl80211_if_remove(priv, WPA_IF_AP_VLAN,
7661						    name);
7662	}
7663}
7664
7665
7666static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
7667{
7668	struct wpa_driver_nl80211_data *drv = eloop_ctx;
7669	struct sockaddr_ll lladdr;
7670	unsigned char buf[3000];
7671	int len;
7672	socklen_t fromlen = sizeof(lladdr);
7673
7674	len = recvfrom(sock, buf, sizeof(buf), 0,
7675		       (struct sockaddr *)&lladdr, &fromlen);
7676	if (len < 0) {
7677		perror("recv");
7678		return;
7679	}
7680
7681	if (have_ifidx(drv, lladdr.sll_ifindex))
7682		drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
7683}
7684
7685
7686static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
7687			     struct i802_bss *bss,
7688			     const char *brname, const char *ifname)
7689{
7690	int ifindex;
7691	char in_br[IFNAMSIZ];
7692
7693	os_strlcpy(bss->brname, brname, IFNAMSIZ);
7694	ifindex = if_nametoindex(brname);
7695	if (ifindex == 0) {
7696		/*
7697		 * Bridge was configured, but the bridge device does
7698		 * not exist. Try to add it now.
7699		 */
7700		if (linux_br_add(drv->global->ioctl_sock, brname) < 0) {
7701			wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
7702				   "bridge interface %s: %s",
7703				   brname, strerror(errno));
7704			return -1;
7705		}
7706		bss->added_bridge = 1;
7707		add_ifidx(drv, if_nametoindex(brname));
7708	}
7709
7710	if (linux_br_get(in_br, ifname) == 0) {
7711		if (os_strcmp(in_br, brname) == 0)
7712			return 0; /* already in the bridge */
7713
7714		wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
7715			   "bridge %s", ifname, in_br);
7716		if (linux_br_del_if(drv->global->ioctl_sock, in_br, ifname) <
7717		    0) {
7718			wpa_printf(MSG_ERROR, "nl80211: Failed to "
7719				   "remove interface %s from bridge "
7720				   "%s: %s",
7721				   ifname, brname, strerror(errno));
7722			return -1;
7723		}
7724	}
7725
7726	wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
7727		   ifname, brname);
7728	if (linux_br_add_if(drv->global->ioctl_sock, brname, ifname) < 0) {
7729		wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
7730			   "into bridge %s: %s",
7731			   ifname, brname, strerror(errno));
7732		return -1;
7733	}
7734	bss->added_if_into_bridge = 1;
7735
7736	return 0;
7737}
7738
7739
7740static void *i802_init(struct hostapd_data *hapd,
7741		       struct wpa_init_params *params)
7742{
7743	struct wpa_driver_nl80211_data *drv;
7744	struct i802_bss *bss;
7745	size_t i;
7746	char brname[IFNAMSIZ];
7747	int ifindex, br_ifindex;
7748	int br_added = 0;
7749
7750	bss = wpa_driver_nl80211_init(hapd, params->ifname,
7751				      params->global_priv);
7752	if (bss == NULL)
7753		return NULL;
7754
7755	drv = bss->drv;
7756	drv->nlmode = NL80211_IFTYPE_AP;
7757	drv->eapol_sock = -1;
7758
7759	if (linux_br_get(brname, params->ifname) == 0) {
7760		wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
7761			   params->ifname, brname);
7762		br_ifindex = if_nametoindex(brname);
7763	} else {
7764		brname[0] = '\0';
7765		br_ifindex = 0;
7766	}
7767
7768	drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
7769	drv->if_indices = drv->default_if_indices;
7770	for (i = 0; i < params->num_bridge; i++) {
7771		if (params->bridge[i]) {
7772			ifindex = if_nametoindex(params->bridge[i]);
7773			if (ifindex)
7774				add_ifidx(drv, ifindex);
7775			if (ifindex == br_ifindex)
7776				br_added = 1;
7777		}
7778	}
7779	if (!br_added && br_ifindex &&
7780	    (params->num_bridge == 0 || !params->bridge[0]))
7781		add_ifidx(drv, br_ifindex);
7782
7783	/* start listening for EAPOL on the default AP interface */
7784	add_ifidx(drv, drv->ifindex);
7785
7786	if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0))
7787		goto failed;
7788
7789	if (params->bssid) {
7790		if (linux_set_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7791				       params->bssid))
7792			goto failed;
7793	}
7794
7795	if (wpa_driver_nl80211_set_mode(bss, drv->nlmode)) {
7796		wpa_printf(MSG_ERROR, "nl80211: Failed to set interface %s "
7797			   "into AP mode", bss->ifname);
7798		goto failed;
7799	}
7800
7801	if (params->num_bridge && params->bridge[0] &&
7802	    i802_check_bridge(drv, bss, params->bridge[0], params->ifname) < 0)
7803		goto failed;
7804
7805	if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1))
7806		goto failed;
7807
7808	drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
7809	if (drv->eapol_sock < 0) {
7810		perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
7811		goto failed;
7812	}
7813
7814	if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
7815	{
7816		printf("Could not register read socket for eapol\n");
7817		goto failed;
7818	}
7819
7820	if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7821			       params->own_addr))
7822		goto failed;
7823
7824	memcpy(bss->addr, params->own_addr, ETH_ALEN);
7825
7826	return bss;
7827
7828failed:
7829	wpa_driver_nl80211_deinit(bss);
7830	return NULL;
7831}
7832
7833
7834static void i802_deinit(void *priv)
7835{
7836	wpa_driver_nl80211_deinit(priv);
7837}
7838
7839#endif /* HOSTAPD */
7840
7841
7842static enum nl80211_iftype wpa_driver_nl80211_if_type(
7843	enum wpa_driver_if_type type)
7844{
7845	switch (type) {
7846	case WPA_IF_STATION:
7847		return NL80211_IFTYPE_STATION;
7848	case WPA_IF_P2P_CLIENT:
7849	case WPA_IF_P2P_GROUP:
7850		return NL80211_IFTYPE_P2P_CLIENT;
7851	case WPA_IF_AP_VLAN:
7852		return NL80211_IFTYPE_AP_VLAN;
7853	case WPA_IF_AP_BSS:
7854		return NL80211_IFTYPE_AP;
7855	case WPA_IF_P2P_GO:
7856		return NL80211_IFTYPE_P2P_GO;
7857	}
7858	return -1;
7859}
7860
7861
7862#ifdef CONFIG_P2P
7863
7864static int nl80211_addr_in_use(struct nl80211_global *global, const u8 *addr)
7865{
7866	struct wpa_driver_nl80211_data *drv;
7867	dl_list_for_each(drv, &global->interfaces,
7868			 struct wpa_driver_nl80211_data, list) {
7869		if (os_memcmp(addr, drv->first_bss.addr, ETH_ALEN) == 0)
7870			return 1;
7871	}
7872	return 0;
7873}
7874
7875
7876static int nl80211_p2p_interface_addr(struct wpa_driver_nl80211_data *drv,
7877				      u8 *new_addr)
7878{
7879	unsigned int idx;
7880
7881	if (!drv->global)
7882		return -1;
7883
7884	os_memcpy(new_addr, drv->first_bss.addr, ETH_ALEN);
7885	for (idx = 0; idx < 64; idx++) {
7886		new_addr[0] = drv->first_bss.addr[0] | 0x02;
7887		new_addr[0] ^= idx << 2;
7888		if (!nl80211_addr_in_use(drv->global, new_addr))
7889			break;
7890	}
7891	if (idx == 64)
7892		return -1;
7893
7894	wpa_printf(MSG_DEBUG, "nl80211: Assigned new P2P Interface Address "
7895		   MACSTR, MAC2STR(new_addr));
7896
7897	return 0;
7898}
7899
7900#endif /* CONFIG_P2P */
7901
7902
7903static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
7904				     const char *ifname, const u8 *addr,
7905				     void *bss_ctx, void **drv_priv,
7906				     char *force_ifname, u8 *if_addr,
7907				     const char *bridge)
7908{
7909	struct i802_bss *bss = priv;
7910	struct wpa_driver_nl80211_data *drv = bss->drv;
7911	int ifidx;
7912#ifdef HOSTAPD
7913	struct i802_bss *new_bss = NULL;
7914
7915	if (type == WPA_IF_AP_BSS) {
7916		new_bss = os_zalloc(sizeof(*new_bss));
7917		if (new_bss == NULL)
7918			return -1;
7919	}
7920#endif /* HOSTAPD */
7921
7922	if (addr)
7923		os_memcpy(if_addr, addr, ETH_ALEN);
7924	ifidx = nl80211_create_iface(drv, ifname,
7925				     wpa_driver_nl80211_if_type(type), addr,
7926				     0);
7927	if (ifidx < 0) {
7928#ifdef HOSTAPD
7929		os_free(new_bss);
7930#endif /* HOSTAPD */
7931		return -1;
7932	}
7933
7934	if (!addr &&
7935	    linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7936			       if_addr) < 0) {
7937		nl80211_remove_iface(drv, ifidx);
7938		return -1;
7939	}
7940
7941#ifdef CONFIG_P2P
7942	if (!addr &&
7943	    (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
7944	     type == WPA_IF_P2P_GO)) {
7945		/* Enforce unique P2P Interface Address */
7946		u8 new_addr[ETH_ALEN], own_addr[ETH_ALEN];
7947
7948		if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7949				       own_addr) < 0 ||
7950		    linux_get_ifhwaddr(drv->global->ioctl_sock, ifname,
7951				       new_addr) < 0) {
7952			nl80211_remove_iface(drv, ifidx);
7953			return -1;
7954		}
7955		if (os_memcmp(own_addr, new_addr, ETH_ALEN) == 0) {
7956			wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
7957				   "for P2P group interface");
7958			if (nl80211_p2p_interface_addr(drv, new_addr) < 0) {
7959				nl80211_remove_iface(drv, ifidx);
7960				return -1;
7961			}
7962			if (linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
7963					       new_addr) < 0) {
7964				nl80211_remove_iface(drv, ifidx);
7965				return -1;
7966			}
7967		}
7968		os_memcpy(if_addr, new_addr, ETH_ALEN);
7969	}
7970#endif /* CONFIG_P2P */
7971
7972#ifdef HOSTAPD
7973	if (bridge &&
7974	    i802_check_bridge(drv, new_bss, bridge, ifname) < 0) {
7975		wpa_printf(MSG_ERROR, "nl80211: Failed to add the new "
7976			   "interface %s to a bridge %s", ifname, bridge);
7977		nl80211_remove_iface(drv, ifidx);
7978		os_free(new_bss);
7979		return -1;
7980	}
7981
7982	if (type == WPA_IF_AP_BSS) {
7983		if (linux_set_iface_flags(drv->global->ioctl_sock, ifname, 1))
7984		{
7985			nl80211_remove_iface(drv, ifidx);
7986			os_free(new_bss);
7987			return -1;
7988		}
7989		os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
7990		os_memcpy(new_bss->addr, if_addr, ETH_ALEN);
7991		new_bss->ifindex = ifidx;
7992		new_bss->drv = drv;
7993		new_bss->next = drv->first_bss.next;
7994		new_bss->freq = drv->first_bss.freq;
7995		drv->first_bss.next = new_bss;
7996		if (drv_priv)
7997			*drv_priv = new_bss;
7998		nl80211_init_bss(new_bss);
7999
8000		/* Subscribe management frames for this WPA_IF_AP_BSS */
8001		if (nl80211_setup_ap(new_bss))
8002			return -1;
8003	}
8004#endif /* HOSTAPD */
8005
8006	if (drv->global)
8007		drv->global->if_add_ifindex = ifidx;
8008
8009	return 0;
8010}
8011
8012
8013static int wpa_driver_nl80211_if_remove(void *priv,
8014					enum wpa_driver_if_type type,
8015					const char *ifname)
8016{
8017	struct i802_bss *bss = priv;
8018	struct wpa_driver_nl80211_data *drv = bss->drv;
8019	int ifindex = if_nametoindex(ifname);
8020
8021	wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d",
8022		   __func__, type, ifname, ifindex);
8023	if (ifindex <= 0)
8024		return -1;
8025
8026#ifdef HOSTAPD
8027	if (bss->added_if_into_bridge) {
8028		if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
8029				    bss->ifname) < 0)
8030			wpa_printf(MSG_INFO, "nl80211: Failed to remove "
8031				   "interface %s from bridge %s: %s",
8032				   bss->ifname, bss->brname, strerror(errno));
8033	}
8034	if (bss->added_bridge) {
8035		if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
8036			wpa_printf(MSG_INFO, "nl80211: Failed to remove "
8037				   "bridge %s: %s",
8038				   bss->brname, strerror(errno));
8039	}
8040#endif /* HOSTAPD */
8041
8042	nl80211_remove_iface(drv, ifindex);
8043
8044#ifdef HOSTAPD
8045	if (type != WPA_IF_AP_BSS)
8046		return 0;
8047
8048	if (bss != &drv->first_bss) {
8049		struct i802_bss *tbss;
8050
8051		for (tbss = &drv->first_bss; tbss; tbss = tbss->next) {
8052			if (tbss->next == bss) {
8053				tbss->next = bss->next;
8054				/* Unsubscribe management frames */
8055				nl80211_teardown_ap(bss);
8056				nl80211_destroy_bss(bss);
8057				os_free(bss);
8058				bss = NULL;
8059				break;
8060			}
8061		}
8062		if (bss)
8063			wpa_printf(MSG_INFO, "nl80211: %s - could not find "
8064				   "BSS %p in the list", __func__, bss);
8065	}
8066#endif /* HOSTAPD */
8067
8068	return 0;
8069}
8070
8071
8072static int cookie_handler(struct nl_msg *msg, void *arg)
8073{
8074	struct nlattr *tb[NL80211_ATTR_MAX + 1];
8075	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
8076	u64 *cookie = arg;
8077	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
8078		  genlmsg_attrlen(gnlh, 0), NULL);
8079	if (tb[NL80211_ATTR_COOKIE])
8080		*cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
8081	return NL_SKIP;
8082}
8083
8084
8085static int nl80211_send_frame_cmd(struct i802_bss *bss,
8086				  unsigned int freq, unsigned int wait,
8087				  const u8 *buf, size_t buf_len,
8088				  u64 *cookie_out, int no_cck, int no_ack,
8089				  int offchanok)
8090{
8091	struct wpa_driver_nl80211_data *drv = bss->drv;
8092	struct nl_msg *msg;
8093	u64 cookie;
8094	int ret = -1;
8095
8096	msg = nlmsg_alloc();
8097	if (!msg)
8098		return -1;
8099
8100	wpa_printf(MSG_DEBUG, "nl80211: CMD_FRAME freq=%u wait=%u no_cck=%d "
8101		   "no_ack=%d offchanok=%d",
8102		   freq, wait, no_cck, no_ack, offchanok);
8103	nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME);
8104
8105	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8106	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
8107#ifndef ANDROID_P2P
8108	if (wait)
8109		NLA_PUT_U32(msg, NL80211_ATTR_DURATION, wait);
8110#endif
8111	if (offchanok && (drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX))
8112		NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
8113	if (no_cck)
8114		NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
8115	if (no_ack)
8116		NLA_PUT_FLAG(msg, NL80211_ATTR_DONT_WAIT_FOR_ACK);
8117
8118	NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
8119
8120	cookie = 0;
8121	ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
8122	msg = NULL;
8123	if (ret) {
8124		wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
8125			   "(%s) (freq=%u wait=%u)", ret, strerror(-ret),
8126			   freq, wait);
8127		goto nla_put_failure;
8128	}
8129	wpa_printf(MSG_DEBUG, "nl80211: Frame TX command accepted%s; "
8130		   "cookie 0x%llx", no_ack ? " (no ACK)" : "",
8131		   (long long unsigned int) cookie);
8132
8133	if (cookie_out)
8134		*cookie_out = no_ack ? (u64) -1 : cookie;
8135
8136nla_put_failure:
8137	nlmsg_free(msg);
8138	return ret;
8139}
8140
8141
8142static int wpa_driver_nl80211_send_action(void *priv, unsigned int freq,
8143					  unsigned int wait_time,
8144					  const u8 *dst, const u8 *src,
8145					  const u8 *bssid,
8146					  const u8 *data, size_t data_len,
8147					  int no_cck)
8148{
8149	struct i802_bss *bss = priv;
8150	struct wpa_driver_nl80211_data *drv = bss->drv;
8151	int ret = -1;
8152	u8 *buf;
8153	struct ieee80211_hdr *hdr;
8154
8155	wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d, "
8156		   "freq=%u MHz wait=%d ms no_cck=%d)",
8157		   drv->ifindex, freq, wait_time, no_cck);
8158
8159	buf = os_zalloc(24 + data_len);
8160	if (buf == NULL)
8161		return ret;
8162	os_memcpy(buf + 24, data, data_len);
8163	hdr = (struct ieee80211_hdr *) buf;
8164	hdr->frame_control =
8165		IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
8166	os_memcpy(hdr->addr1, dst, ETH_ALEN);
8167	os_memcpy(hdr->addr2, src, ETH_ALEN);
8168	os_memcpy(hdr->addr3, bssid, ETH_ALEN);
8169
8170	if (is_ap_interface(drv->nlmode))
8171		ret = wpa_driver_nl80211_send_mlme_freq(priv, buf,
8172							24 + data_len,
8173							0, freq, no_cck, 1,
8174							wait_time);
8175	else
8176		ret = nl80211_send_frame_cmd(bss, freq, wait_time, buf,
8177					     24 + data_len,
8178					     &drv->send_action_cookie,
8179					     no_cck, 0, 1);
8180
8181	os_free(buf);
8182	return ret;
8183}
8184
8185
8186static void wpa_driver_nl80211_send_action_cancel_wait(void *priv)
8187{
8188	struct i802_bss *bss = priv;
8189	struct wpa_driver_nl80211_data *drv = bss->drv;
8190	struct nl_msg *msg;
8191	int ret;
8192
8193	msg = nlmsg_alloc();
8194	if (!msg)
8195		return;
8196
8197	nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME_WAIT_CANCEL);
8198
8199	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8200	NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->send_action_cookie);
8201
8202	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8203	msg = NULL;
8204	if (ret)
8205		wpa_printf(MSG_DEBUG, "nl80211: wait cancel failed: ret=%d "
8206			   "(%s)", ret, strerror(-ret));
8207
8208 nla_put_failure:
8209	nlmsg_free(msg);
8210}
8211
8212
8213static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
8214						unsigned int duration)
8215{
8216	struct i802_bss *bss = priv;
8217	struct wpa_driver_nl80211_data *drv = bss->drv;
8218	struct nl_msg *msg;
8219	int ret;
8220	u64 cookie;
8221
8222	msg = nlmsg_alloc();
8223	if (!msg)
8224		return -1;
8225
8226	nl80211_cmd(drv, msg, 0, NL80211_CMD_REMAIN_ON_CHANNEL);
8227
8228	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8229	NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
8230	NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
8231
8232	cookie = 0;
8233	ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
8234	msg = NULL;
8235	if (ret == 0) {
8236		wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
8237			   "0x%llx for freq=%u MHz duration=%u",
8238			   (long long unsigned int) cookie, freq, duration);
8239		drv->remain_on_chan_cookie = cookie;
8240		drv->pending_remain_on_chan = 1;
8241		return 0;
8242	}
8243	wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
8244		   "(freq=%d duration=%u): %d (%s)",
8245		   freq, duration, ret, strerror(-ret));
8246nla_put_failure:
8247	nlmsg_free(msg);
8248	return -1;
8249}
8250
8251
8252static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
8253{
8254	struct i802_bss *bss = priv;
8255	struct wpa_driver_nl80211_data *drv = bss->drv;
8256	struct nl_msg *msg;
8257	int ret;
8258
8259	if (!drv->pending_remain_on_chan) {
8260		wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
8261			   "to cancel");
8262		return -1;
8263	}
8264
8265	wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
8266		   "0x%llx",
8267		   (long long unsigned int) drv->remain_on_chan_cookie);
8268
8269	msg = nlmsg_alloc();
8270	if (!msg)
8271		return -1;
8272
8273	nl80211_cmd(drv, msg, 0, NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL);
8274
8275	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8276	NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
8277
8278	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8279	msg = NULL;
8280	if (ret == 0)
8281		return 0;
8282	wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
8283		   "%d (%s)", ret, strerror(-ret));
8284nla_put_failure:
8285	nlmsg_free(msg);
8286	return -1;
8287}
8288
8289
8290static int wpa_driver_nl80211_probe_req_report(void *priv, int report)
8291{
8292	struct i802_bss *bss = priv;
8293	struct wpa_driver_nl80211_data *drv = bss->drv;
8294
8295	if (!report) {
8296		if (bss->nl_preq && drv->device_ap_sme &&
8297		    is_ap_interface(drv->nlmode)) {
8298			/*
8299			 * Do not disable Probe Request reporting that was
8300			 * enabled in nl80211_setup_ap().
8301			 */
8302			wpa_printf(MSG_DEBUG, "nl80211: Skip disabling of "
8303				   "Probe Request reporting nl_preq=%p while "
8304				   "in AP mode", bss->nl_preq);
8305		} else if (bss->nl_preq) {
8306			wpa_printf(MSG_DEBUG, "nl80211: Disable Probe Request "
8307				   "reporting nl_preq=%p", bss->nl_preq);
8308			eloop_unregister_read_sock(
8309				nl_socket_get_fd(bss->nl_preq));
8310			nl_destroy_handles(&bss->nl_preq);
8311		}
8312		return 0;
8313	}
8314
8315	if (bss->nl_preq) {
8316		wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
8317			   "already on! nl_preq=%p", bss->nl_preq);
8318		return 0;
8319	}
8320
8321	bss->nl_preq = nl_create_handle(drv->global->nl_cb, "preq");
8322	if (bss->nl_preq == NULL)
8323		return -1;
8324	wpa_printf(MSG_DEBUG, "nl80211: Enable Probe Request "
8325		   "reporting nl_preq=%p", bss->nl_preq);
8326
8327	if (nl80211_register_frame(bss, bss->nl_preq,
8328				   (WLAN_FC_TYPE_MGMT << 2) |
8329				   (WLAN_FC_STYPE_PROBE_REQ << 4),
8330				   NULL, 0) < 0)
8331		goto out_err;
8332
8333	eloop_register_read_sock(nl_socket_get_fd(bss->nl_preq),
8334				 wpa_driver_nl80211_event_receive, bss->nl_cb,
8335				 bss->nl_preq);
8336
8337	return 0;
8338
8339 out_err:
8340	nl_destroy_handles(&bss->nl_preq);
8341	return -1;
8342}
8343
8344
8345static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
8346				     int ifindex, int disabled)
8347{
8348	struct nl_msg *msg;
8349	struct nlattr *bands, *band;
8350	int ret;
8351
8352	msg = nlmsg_alloc();
8353	if (!msg)
8354		return -1;
8355
8356	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_TX_BITRATE_MASK);
8357	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
8358
8359	bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
8360	if (!bands)
8361		goto nla_put_failure;
8362
8363	/*
8364	 * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
8365	 * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
8366	 * rates. All 5 GHz rates are left enabled.
8367	 */
8368	band = nla_nest_start(msg, NL80211_BAND_2GHZ);
8369	if (!band)
8370		goto nla_put_failure;
8371	if (disabled) {
8372		NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
8373			"\x0c\x12\x18\x24\x30\x48\x60\x6c");
8374	}
8375	nla_nest_end(msg, band);
8376
8377	nla_nest_end(msg, bands);
8378
8379	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8380	msg = NULL;
8381	if (ret) {
8382		wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
8383			   "(%s)", ret, strerror(-ret));
8384	}
8385	return ret;
8386
8387nla_put_failure:
8388	nlmsg_free(msg);
8389	return -1;
8390}
8391
8392
8393static int wpa_driver_nl80211_deinit_ap(void *priv)
8394{
8395	struct i802_bss *bss = priv;
8396	struct wpa_driver_nl80211_data *drv = bss->drv;
8397	if (!is_ap_interface(drv->nlmode))
8398		return -1;
8399	wpa_driver_nl80211_del_beacon(drv);
8400	return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
8401}
8402
8403
8404static int wpa_driver_nl80211_deinit_p2p_cli(void *priv)
8405{
8406	struct i802_bss *bss = priv;
8407	struct wpa_driver_nl80211_data *drv = bss->drv;
8408	if (drv->nlmode != NL80211_IFTYPE_P2P_CLIENT)
8409		return -1;
8410	return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
8411}
8412
8413
8414static void wpa_driver_nl80211_resume(void *priv)
8415{
8416	struct i802_bss *bss = priv;
8417	struct wpa_driver_nl80211_data *drv = bss->drv;
8418	if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
8419		wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on "
8420			   "resume event");
8421	}
8422}
8423
8424
8425static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
8426				  const u8 *ies, size_t ies_len)
8427{
8428	struct i802_bss *bss = priv;
8429	struct wpa_driver_nl80211_data *drv = bss->drv;
8430	int ret;
8431	u8 *data, *pos;
8432	size_t data_len;
8433	const u8 *own_addr = bss->addr;
8434
8435	if (action != 1) {
8436		wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
8437			   "action %d", action);
8438		return -1;
8439	}
8440
8441	/*
8442	 * Action frame payload:
8443	 * Category[1] = 6 (Fast BSS Transition)
8444	 * Action[1] = 1 (Fast BSS Transition Request)
8445	 * STA Address
8446	 * Target AP Address
8447	 * FT IEs
8448	 */
8449
8450	data_len = 2 + 2 * ETH_ALEN + ies_len;
8451	data = os_malloc(data_len);
8452	if (data == NULL)
8453		return -1;
8454	pos = data;
8455	*pos++ = 0x06; /* FT Action category */
8456	*pos++ = action;
8457	os_memcpy(pos, own_addr, ETH_ALEN);
8458	pos += ETH_ALEN;
8459	os_memcpy(pos, target_ap, ETH_ALEN);
8460	pos += ETH_ALEN;
8461	os_memcpy(pos, ies, ies_len);
8462
8463	ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, 0,
8464					     drv->bssid, own_addr, drv->bssid,
8465					     data, data_len, 0);
8466	os_free(data);
8467
8468	return ret;
8469}
8470
8471
8472static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
8473{
8474	struct i802_bss *bss = priv;
8475	struct wpa_driver_nl80211_data *drv = bss->drv;
8476	struct nl_msg *msg, *cqm = NULL;
8477
8478	wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
8479		   "hysteresis=%d", threshold, hysteresis);
8480
8481	msg = nlmsg_alloc();
8482	if (!msg)
8483		return -1;
8484
8485	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_CQM);
8486
8487	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8488
8489	cqm = nlmsg_alloc();
8490	if (cqm == NULL)
8491		return -1;
8492
8493	NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
8494	NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
8495	nla_put_nested(msg, NL80211_ATTR_CQM, cqm);
8496
8497	if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
8498		return 0;
8499	msg = NULL;
8500
8501nla_put_failure:
8502	nlmsg_free(cqm);
8503	nlmsg_free(msg);
8504	return -1;
8505}
8506
8507
8508static int nl80211_signal_poll(void *priv, struct wpa_signal_info *si)
8509{
8510	struct i802_bss *bss = priv;
8511	struct wpa_driver_nl80211_data *drv = bss->drv;
8512	int res;
8513
8514	os_memset(si, 0, sizeof(*si));
8515	res = nl80211_get_link_signal(drv, si);
8516	if (res != 0)
8517		return res;
8518
8519	return nl80211_get_link_noise(drv, si);
8520}
8521
8522
8523static int wpa_driver_nl80211_shared_freq(void *priv)
8524{
8525	struct i802_bss *bss = priv;
8526	struct wpa_driver_nl80211_data *drv = bss->drv;
8527	struct wpa_driver_nl80211_data *driver;
8528	int freq = 0;
8529
8530	/*
8531	 * If the same PHY is in connected state with some other interface,
8532	 * then retrieve the assoc freq.
8533	 */
8534	wpa_printf(MSG_DEBUG, "nl80211: Get shared freq for PHY %s",
8535		   drv->phyname);
8536
8537	dl_list_for_each(driver, &drv->global->interfaces,
8538			 struct wpa_driver_nl80211_data, list) {
8539		if (drv == driver ||
8540		    os_strcmp(drv->phyname, driver->phyname) != 0 ||
8541#ifdef ANDROID_P2P
8542		    (!driver->associated && !is_ap_interface(driver->nlmode)))
8543#else
8544		    !driver->associated)
8545#endif
8546			continue;
8547
8548		wpa_printf(MSG_DEBUG, "nl80211: Found a match for PHY %s - %s "
8549			   MACSTR,
8550			   driver->phyname, driver->first_bss.ifname,
8551			   MAC2STR(driver->first_bss.addr));
8552		if (is_ap_interface(driver->nlmode))
8553			freq = driver->first_bss.freq;
8554		else
8555			freq = nl80211_get_assoc_freq(driver);
8556		wpa_printf(MSG_DEBUG, "nl80211: Shared freq for PHY %s: %d",
8557			   drv->phyname, freq);
8558	}
8559
8560	if (!freq)
8561		wpa_printf(MSG_DEBUG, "nl80211: No shared interface for "
8562			   "PHY (%s) in associated state", drv->phyname);
8563
8564	return freq;
8565}
8566
8567
8568static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
8569			      int encrypt)
8570{
8571	struct i802_bss *bss = priv;
8572	return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt, 0,
8573					     0, 0, 0, 0);
8574}
8575
8576
8577static int nl80211_set_param(void *priv, const char *param)
8578{
8579	wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
8580	if (param == NULL)
8581		return 0;
8582
8583#ifdef CONFIG_P2P
8584	if (os_strstr(param, "use_p2p_group_interface=1")) {
8585		struct i802_bss *bss = priv;
8586		struct wpa_driver_nl80211_data *drv = bss->drv;
8587
8588		wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
8589			   "interface");
8590		drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
8591		drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
8592	}
8593#ifdef ANDROID_P2P
8594	if(os_strstr(param, "use_multi_chan_concurrent=1")) {
8595		struct i802_bss *bss = priv;
8596		struct wpa_driver_nl80211_data *drv = bss->drv;
8597		wpa_printf(MSG_DEBUG, "nl80211: Use Multi channel "
8598			   "concurrency");
8599		drv->capa.flags |= WPA_DRIVER_FLAGS_MULTI_CHANNEL_CONCURRENT;
8600	}
8601#endif
8602#endif /* CONFIG_P2P */
8603
8604	return 0;
8605}
8606
8607
8608static void * nl80211_global_init(void)
8609{
8610	struct nl80211_global *global;
8611	struct netlink_config *cfg;
8612
8613	global = os_zalloc(sizeof(*global));
8614	if (global == NULL)
8615		return NULL;
8616	global->ioctl_sock = -1;
8617	dl_list_init(&global->interfaces);
8618	global->if_add_ifindex = -1;
8619
8620	cfg = os_zalloc(sizeof(*cfg));
8621	if (cfg == NULL)
8622		goto err;
8623
8624	cfg->ctx = global;
8625	cfg->newlink_cb = wpa_driver_nl80211_event_rtm_newlink;
8626	cfg->dellink_cb = wpa_driver_nl80211_event_rtm_dellink;
8627	global->netlink = netlink_init(cfg);
8628	if (global->netlink == NULL) {
8629		os_free(cfg);
8630		goto err;
8631	}
8632
8633	if (wpa_driver_nl80211_init_nl_global(global) < 0)
8634		goto err;
8635
8636	global->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
8637	if (global->ioctl_sock < 0) {
8638		perror("socket(PF_INET,SOCK_DGRAM)");
8639		goto err;
8640	}
8641
8642	return global;
8643
8644err:
8645	nl80211_global_deinit(global);
8646	return NULL;
8647}
8648
8649
8650static void nl80211_global_deinit(void *priv)
8651{
8652	struct nl80211_global *global = priv;
8653	if (global == NULL)
8654		return;
8655	if (!dl_list_empty(&global->interfaces)) {
8656		wpa_printf(MSG_ERROR, "nl80211: %u interface(s) remain at "
8657			   "nl80211_global_deinit",
8658			   dl_list_len(&global->interfaces));
8659	}
8660
8661	if (global->netlink)
8662		netlink_deinit(global->netlink);
8663
8664	nl_destroy_handles(&global->nl);
8665
8666	if (global->nl_event) {
8667		eloop_unregister_read_sock(
8668			nl_socket_get_fd(global->nl_event));
8669		nl_destroy_handles(&global->nl_event);
8670	}
8671
8672	nl_cb_put(global->nl_cb);
8673
8674	if (global->ioctl_sock >= 0)
8675		close(global->ioctl_sock);
8676
8677	os_free(global);
8678}
8679
8680
8681static const char * nl80211_get_radio_name(void *priv)
8682{
8683	struct i802_bss *bss = priv;
8684	struct wpa_driver_nl80211_data *drv = bss->drv;
8685	return drv->phyname;
8686}
8687
8688
8689static int nl80211_pmkid(struct i802_bss *bss, int cmd, const u8 *bssid,
8690			 const u8 *pmkid)
8691{
8692	struct nl_msg *msg;
8693
8694	msg = nlmsg_alloc();
8695	if (!msg)
8696		return -ENOMEM;
8697
8698	nl80211_cmd(bss->drv, msg, 0, cmd);
8699
8700	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
8701	if (pmkid)
8702		NLA_PUT(msg, NL80211_ATTR_PMKID, 16, pmkid);
8703	if (bssid)
8704		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
8705
8706	return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
8707 nla_put_failure:
8708	nlmsg_free(msg);
8709	return -ENOBUFS;
8710}
8711
8712
8713static int nl80211_add_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
8714{
8715	struct i802_bss *bss = priv;
8716	wpa_printf(MSG_DEBUG, "nl80211: Add PMKID for " MACSTR, MAC2STR(bssid));
8717	return nl80211_pmkid(bss, NL80211_CMD_SET_PMKSA, bssid, pmkid);
8718}
8719
8720
8721static int nl80211_remove_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
8722{
8723	struct i802_bss *bss = priv;
8724	wpa_printf(MSG_DEBUG, "nl80211: Delete PMKID for " MACSTR,
8725		   MAC2STR(bssid));
8726	return nl80211_pmkid(bss, NL80211_CMD_DEL_PMKSA, bssid, pmkid);
8727}
8728
8729
8730static int nl80211_flush_pmkid(void *priv)
8731{
8732	struct i802_bss *bss = priv;
8733	wpa_printf(MSG_DEBUG, "nl80211: Flush PMKIDs");
8734	return nl80211_pmkid(bss, NL80211_CMD_FLUSH_PMKSA, NULL, NULL);
8735}
8736
8737
8738static void nl80211_set_rekey_info(void *priv, const u8 *kek, const u8 *kck,
8739				   const u8 *replay_ctr)
8740{
8741	struct i802_bss *bss = priv;
8742	struct wpa_driver_nl80211_data *drv = bss->drv;
8743	struct nlattr *replay_nested;
8744	struct nl_msg *msg;
8745
8746	msg = nlmsg_alloc();
8747	if (!msg)
8748		return;
8749
8750	nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_REKEY_OFFLOAD);
8751
8752	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8753
8754	replay_nested = nla_nest_start(msg, NL80211_ATTR_REKEY_DATA);
8755	if (!replay_nested)
8756		goto nla_put_failure;
8757
8758	NLA_PUT(msg, NL80211_REKEY_DATA_KEK, NL80211_KEK_LEN, kek);
8759	NLA_PUT(msg, NL80211_REKEY_DATA_KCK, NL80211_KCK_LEN, kck);
8760	NLA_PUT(msg, NL80211_REKEY_DATA_REPLAY_CTR, NL80211_REPLAY_CTR_LEN,
8761		replay_ctr);
8762
8763	nla_nest_end(msg, replay_nested);
8764
8765	send_and_recv_msgs(drv, msg, NULL, NULL);
8766	return;
8767 nla_put_failure:
8768	nlmsg_free(msg);
8769}
8770
8771
8772static void nl80211_send_null_frame(struct i802_bss *bss, const u8 *own_addr,
8773				    const u8 *addr, int qos)
8774{
8775	/* send data frame to poll STA and check whether
8776	 * this frame is ACKed */
8777	struct {
8778		struct ieee80211_hdr hdr;
8779		u16 qos_ctl;
8780	} STRUCT_PACKED nulldata;
8781	size_t size;
8782
8783	/* Send data frame to poll STA and check whether this frame is ACKed */
8784
8785	os_memset(&nulldata, 0, sizeof(nulldata));
8786
8787	if (qos) {
8788		nulldata.hdr.frame_control =
8789			IEEE80211_FC(WLAN_FC_TYPE_DATA,
8790				     WLAN_FC_STYPE_QOS_NULL);
8791		size = sizeof(nulldata);
8792	} else {
8793		nulldata.hdr.frame_control =
8794			IEEE80211_FC(WLAN_FC_TYPE_DATA,
8795				     WLAN_FC_STYPE_NULLFUNC);
8796		size = sizeof(struct ieee80211_hdr);
8797	}
8798
8799	nulldata.hdr.frame_control |= host_to_le16(WLAN_FC_FROMDS);
8800	os_memcpy(nulldata.hdr.IEEE80211_DA_FROMDS, addr, ETH_ALEN);
8801	os_memcpy(nulldata.hdr.IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
8802	os_memcpy(nulldata.hdr.IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
8803
8804	if (wpa_driver_nl80211_send_mlme(bss, (u8 *) &nulldata, size, 0) < 0)
8805		wpa_printf(MSG_DEBUG, "nl80211_send_null_frame: Failed to "
8806			   "send poll frame");
8807}
8808
8809static void nl80211_poll_client(void *priv, const u8 *own_addr, const u8 *addr,
8810				int qos)
8811{
8812	struct i802_bss *bss = priv;
8813	struct wpa_driver_nl80211_data *drv = bss->drv;
8814	struct nl_msg *msg;
8815
8816	if (!drv->poll_command_supported) {
8817		nl80211_send_null_frame(bss, own_addr, addr, qos);
8818		return;
8819	}
8820
8821	msg = nlmsg_alloc();
8822	if (!msg)
8823		return;
8824
8825	nl80211_cmd(drv, msg, 0, NL80211_CMD_PROBE_CLIENT);
8826
8827	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8828	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
8829
8830	send_and_recv_msgs(drv, msg, NULL, NULL);
8831	return;
8832 nla_put_failure:
8833	nlmsg_free(msg);
8834}
8835
8836
8837static int nl80211_set_power_save(struct i802_bss *bss, int enabled)
8838{
8839	struct nl_msg *msg;
8840
8841	msg = nlmsg_alloc();
8842	if (!msg)
8843		return -ENOMEM;
8844
8845	nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_SET_POWER_SAVE);
8846	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8847	NLA_PUT_U32(msg, NL80211_ATTR_PS_STATE,
8848		    enabled ? NL80211_PS_ENABLED : NL80211_PS_DISABLED);
8849	return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
8850nla_put_failure:
8851	nlmsg_free(msg);
8852	return -ENOBUFS;
8853}
8854
8855
8856static int nl80211_set_p2p_powersave(void *priv, int legacy_ps, int opp_ps,
8857				     int ctwindow)
8858{
8859	struct i802_bss *bss = priv;
8860
8861	wpa_printf(MSG_DEBUG, "nl80211: set_p2p_powersave (legacy_ps=%d "
8862		   "opp_ps=%d ctwindow=%d)", legacy_ps, opp_ps, ctwindow);
8863
8864	if (opp_ps != -1 || ctwindow != -1)
8865#ifdef ANDROID_P2P
8866		wpa_driver_set_p2p_ps(priv, legacy_ps, opp_ps, ctwindow);
8867#else
8868		return -1; /* Not yet supported */
8869#endif
8870
8871	if (legacy_ps == -1)
8872		return 0;
8873	if (legacy_ps != 0 && legacy_ps != 1)
8874		return -1; /* Not yet supported */
8875
8876	return nl80211_set_power_save(bss, legacy_ps);
8877}
8878
8879
8880#ifdef CONFIG_TDLS
8881
8882static int nl80211_send_tdls_mgmt(void *priv, const u8 *dst, u8 action_code,
8883				  u8 dialog_token, u16 status_code,
8884				  const u8 *buf, size_t len)
8885{
8886	struct i802_bss *bss = priv;
8887	struct wpa_driver_nl80211_data *drv = bss->drv;
8888	struct nl_msg *msg;
8889
8890	if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
8891		return -EOPNOTSUPP;
8892
8893	if (!dst)
8894		return -EINVAL;
8895
8896	msg = nlmsg_alloc();
8897	if (!msg)
8898		return -ENOMEM;
8899
8900	nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_MGMT);
8901	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8902	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, dst);
8903	NLA_PUT_U8(msg, NL80211_ATTR_TDLS_ACTION, action_code);
8904	NLA_PUT_U8(msg, NL80211_ATTR_TDLS_DIALOG_TOKEN, dialog_token);
8905	NLA_PUT_U16(msg, NL80211_ATTR_STATUS_CODE, status_code);
8906	NLA_PUT(msg, NL80211_ATTR_IE, len, buf);
8907
8908	return send_and_recv_msgs(drv, msg, NULL, NULL);
8909
8910nla_put_failure:
8911	nlmsg_free(msg);
8912	return -ENOBUFS;
8913}
8914
8915
8916static int nl80211_tdls_oper(void *priv, enum tdls_oper oper, const u8 *peer)
8917{
8918	struct i802_bss *bss = priv;
8919	struct wpa_driver_nl80211_data *drv = bss->drv;
8920	struct nl_msg *msg;
8921	enum nl80211_tdls_operation nl80211_oper;
8922
8923	if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
8924		return -EOPNOTSUPP;
8925
8926	switch (oper) {
8927	case TDLS_DISCOVERY_REQ:
8928		nl80211_oper = NL80211_TDLS_DISCOVERY_REQ;
8929		break;
8930	case TDLS_SETUP:
8931		nl80211_oper = NL80211_TDLS_SETUP;
8932		break;
8933	case TDLS_TEARDOWN:
8934		nl80211_oper = NL80211_TDLS_TEARDOWN;
8935		break;
8936	case TDLS_ENABLE_LINK:
8937		nl80211_oper = NL80211_TDLS_ENABLE_LINK;
8938		break;
8939	case TDLS_DISABLE_LINK:
8940		nl80211_oper = NL80211_TDLS_DISABLE_LINK;
8941		break;
8942	case TDLS_ENABLE:
8943		return 0;
8944	case TDLS_DISABLE:
8945		return 0;
8946	default:
8947		return -EINVAL;
8948	}
8949
8950	msg = nlmsg_alloc();
8951	if (!msg)
8952		return -ENOMEM;
8953
8954	nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_OPER);
8955	NLA_PUT_U8(msg, NL80211_ATTR_TDLS_OPERATION, nl80211_oper);
8956	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8957	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, peer);
8958
8959	return send_and_recv_msgs(drv, msg, NULL, NULL);
8960
8961nla_put_failure:
8962	nlmsg_free(msg);
8963	return -ENOBUFS;
8964}
8965
8966#endif /* CONFIG TDLS */
8967
8968
8969#ifdef ANDROID
8970
8971typedef struct android_wifi_priv_cmd {
8972	char *buf;
8973	int used_len;
8974	int total_len;
8975} android_wifi_priv_cmd;
8976
8977static int drv_errors = 0;
8978
8979static void wpa_driver_send_hang_msg(struct wpa_driver_nl80211_data *drv)
8980{
8981	drv_errors++;
8982	if (drv_errors > DRV_NUMBER_SEQUENTIAL_ERRORS) {
8983		drv_errors = 0;
8984		wpa_msg(drv->ctx, MSG_INFO, WPA_EVENT_DRIVER_STATE "HANGED");
8985	}
8986}
8987
8988
8989static int android_priv_cmd(struct i802_bss *bss, const char *cmd)
8990{
8991	struct wpa_driver_nl80211_data *drv = bss->drv;
8992	struct ifreq ifr;
8993	android_wifi_priv_cmd priv_cmd;
8994	char buf[MAX_DRV_CMD_SIZE];
8995	int ret;
8996
8997	os_memset(&ifr, 0, sizeof(ifr));
8998	os_memset(&priv_cmd, 0, sizeof(priv_cmd));
8999	os_strlcpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
9000
9001	os_memset(buf, 0, sizeof(buf));
9002	os_strlcpy(buf, cmd, sizeof(buf));
9003
9004	priv_cmd.buf = buf;
9005	priv_cmd.used_len = sizeof(buf);
9006	priv_cmd.total_len = sizeof(buf);
9007	ifr.ifr_data = &priv_cmd;
9008
9009	ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
9010	if (ret < 0) {
9011		wpa_printf(MSG_ERROR, "%s: failed to issue private commands",
9012			   __func__);
9013		wpa_driver_send_hang_msg(drv);
9014		return ret;
9015	}
9016
9017	drv_errors = 0;
9018	return 0;
9019}
9020
9021
9022static int android_pno_start(struct i802_bss *bss,
9023			     struct wpa_driver_scan_params *params)
9024{
9025	struct wpa_driver_nl80211_data *drv = bss->drv;
9026	struct ifreq ifr;
9027	android_wifi_priv_cmd priv_cmd;
9028	int ret = 0, i = 0, bp;
9029	char buf[WEXT_PNO_MAX_COMMAND_SIZE];
9030
9031	bp = WEXT_PNOSETUP_HEADER_SIZE;
9032	os_memcpy(buf, WEXT_PNOSETUP_HEADER, bp);
9033	buf[bp++] = WEXT_PNO_TLV_PREFIX;
9034	buf[bp++] = WEXT_PNO_TLV_VERSION;
9035	buf[bp++] = WEXT_PNO_TLV_SUBVERSION;
9036	buf[bp++] = WEXT_PNO_TLV_RESERVED;
9037
9038	while (i < WEXT_PNO_AMOUNT && (size_t) i < params->num_ssids) {
9039		/* Check that there is enough space needed for 1 more SSID, the
9040		 * other sections and null termination */
9041		if ((bp + WEXT_PNO_SSID_HEADER_SIZE + MAX_SSID_LEN +
9042		     WEXT_PNO_NONSSID_SECTIONS_SIZE + 1) >= (int) sizeof(buf))
9043			break;
9044		wpa_hexdump_ascii(MSG_DEBUG, "For PNO Scan",
9045				  params->ssids[i].ssid,
9046				  params->ssids[i].ssid_len);
9047		buf[bp++] = WEXT_PNO_SSID_SECTION;
9048		buf[bp++] = params->ssids[i].ssid_len;
9049		os_memcpy(&buf[bp], params->ssids[i].ssid,
9050			  params->ssids[i].ssid_len);
9051		bp += params->ssids[i].ssid_len;
9052		i++;
9053	}
9054
9055	buf[bp++] = WEXT_PNO_SCAN_INTERVAL_SECTION;
9056	os_snprintf(&buf[bp], WEXT_PNO_SCAN_INTERVAL_LENGTH + 1, "%x",
9057		    WEXT_PNO_SCAN_INTERVAL);
9058	bp += WEXT_PNO_SCAN_INTERVAL_LENGTH;
9059
9060	buf[bp++] = WEXT_PNO_REPEAT_SECTION;
9061	os_snprintf(&buf[bp], WEXT_PNO_REPEAT_LENGTH + 1, "%x",
9062		    WEXT_PNO_REPEAT);
9063	bp += WEXT_PNO_REPEAT_LENGTH;
9064
9065	buf[bp++] = WEXT_PNO_MAX_REPEAT_SECTION;
9066	os_snprintf(&buf[bp], WEXT_PNO_MAX_REPEAT_LENGTH + 1, "%x",
9067		    WEXT_PNO_MAX_REPEAT);
9068	bp += WEXT_PNO_MAX_REPEAT_LENGTH + 1;
9069
9070	memset(&ifr, 0, sizeof(ifr));
9071	memset(&priv_cmd, 0, sizeof(priv_cmd));
9072	os_strncpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
9073
9074	priv_cmd.buf = buf;
9075	priv_cmd.used_len = bp;
9076	priv_cmd.total_len = bp;
9077	ifr.ifr_data = &priv_cmd;
9078
9079	ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
9080
9081	if (ret < 0) {
9082		wpa_printf(MSG_ERROR, "ioctl[SIOCSIWPRIV] (pnosetup): %d",
9083			   ret);
9084		wpa_driver_send_hang_msg(drv);
9085		return ret;
9086	}
9087
9088	drv_errors = 0;
9089
9090	return android_priv_cmd(bss, "PNOFORCE 1");
9091}
9092
9093
9094static int android_pno_stop(struct i802_bss *bss)
9095{
9096	return android_priv_cmd(bss, "PNOFORCE 0");
9097}
9098
9099#endif /* ANDROID */
9100
9101
9102const struct wpa_driver_ops wpa_driver_nl80211_ops = {
9103	.name = "nl80211",
9104	.desc = "Linux nl80211/cfg80211",
9105	.get_bssid = wpa_driver_nl80211_get_bssid,
9106	.get_ssid = wpa_driver_nl80211_get_ssid,
9107	.set_key = wpa_driver_nl80211_set_key,
9108	.scan2 = wpa_driver_nl80211_scan,
9109	.sched_scan = wpa_driver_nl80211_sched_scan,
9110	.stop_sched_scan = wpa_driver_nl80211_stop_sched_scan,
9111	.get_scan_results2 = wpa_driver_nl80211_get_scan_results,
9112	.deauthenticate = wpa_driver_nl80211_deauthenticate,
9113	.disassociate = wpa_driver_nl80211_disassociate,
9114	.authenticate = wpa_driver_nl80211_authenticate,
9115	.associate = wpa_driver_nl80211_associate,
9116	.global_init = nl80211_global_init,
9117	.global_deinit = nl80211_global_deinit,
9118	.init2 = wpa_driver_nl80211_init,
9119	.deinit = wpa_driver_nl80211_deinit,
9120	.get_capa = wpa_driver_nl80211_get_capa,
9121	.set_operstate = wpa_driver_nl80211_set_operstate,
9122	.set_supp_port = wpa_driver_nl80211_set_supp_port,
9123	.set_country = wpa_driver_nl80211_set_country,
9124	.set_ap = wpa_driver_nl80211_set_ap,
9125	.if_add = wpa_driver_nl80211_if_add,
9126	.if_remove = wpa_driver_nl80211_if_remove,
9127	.send_mlme = wpa_driver_nl80211_send_mlme,
9128	.get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
9129	.sta_add = wpa_driver_nl80211_sta_add,
9130	.sta_remove = wpa_driver_nl80211_sta_remove,
9131	.hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
9132	.sta_set_flags = wpa_driver_nl80211_sta_set_flags,
9133#ifdef HOSTAPD
9134	.hapd_init = i802_init,
9135	.hapd_deinit = i802_deinit,
9136	.set_wds_sta = i802_set_wds_sta,
9137#endif /* HOSTAPD */
9138#if defined(HOSTAPD) || defined(CONFIG_AP)
9139	.get_seqnum = i802_get_seqnum,
9140	.flush = i802_flush,
9141	.read_sta_data = i802_read_sta_data,
9142	.get_inact_sec = i802_get_inact_sec,
9143	.sta_clear_stats = i802_sta_clear_stats,
9144	.set_rts = i802_set_rts,
9145	.set_frag = i802_set_frag,
9146	.set_tx_queue_params = i802_set_tx_queue_params,
9147	.set_sta_vlan = i802_set_sta_vlan,
9148	.sta_deauth = i802_sta_deauth,
9149	.sta_disassoc = i802_sta_disassoc,
9150#endif /* HOSTAPD || CONFIG_AP */
9151	.set_freq = i802_set_freq,
9152	.send_action = wpa_driver_nl80211_send_action,
9153	.send_action_cancel_wait = wpa_driver_nl80211_send_action_cancel_wait,
9154	.remain_on_channel = wpa_driver_nl80211_remain_on_channel,
9155	.cancel_remain_on_channel =
9156	wpa_driver_nl80211_cancel_remain_on_channel,
9157	.probe_req_report = wpa_driver_nl80211_probe_req_report,
9158	.deinit_ap = wpa_driver_nl80211_deinit_ap,
9159	.deinit_p2p_cli = wpa_driver_nl80211_deinit_p2p_cli,
9160	.resume = wpa_driver_nl80211_resume,
9161	.send_ft_action = nl80211_send_ft_action,
9162	.signal_monitor = nl80211_signal_monitor,
9163	.signal_poll = nl80211_signal_poll,
9164	.send_frame = nl80211_send_frame,
9165	.shared_freq = wpa_driver_nl80211_shared_freq,
9166	.set_param = nl80211_set_param,
9167	.get_radio_name = nl80211_get_radio_name,
9168	.add_pmkid = nl80211_add_pmkid,
9169	.remove_pmkid = nl80211_remove_pmkid,
9170	.flush_pmkid = nl80211_flush_pmkid,
9171	.set_rekey_info = nl80211_set_rekey_info,
9172	.poll_client = nl80211_poll_client,
9173	.set_p2p_powersave = nl80211_set_p2p_powersave,
9174#ifdef CONFIG_TDLS
9175	.send_tdls_mgmt = nl80211_send_tdls_mgmt,
9176	.tdls_oper = nl80211_tdls_oper,
9177#endif /* CONFIG_TDLS */
9178#ifdef ANDROID_P2P
9179	.set_noa = wpa_driver_set_p2p_noa,
9180	.get_noa = wpa_driver_get_p2p_noa,
9181	.set_ap_wps_ie = wpa_driver_set_ap_wps_p2p_ie,
9182#endif
9183#ifdef ANDROID
9184	.driver_cmd = wpa_driver_nl80211_driver_cmd,
9185#endif
9186};
9187