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