1/*
2 * WPA Supplicant - driver interaction with Linux nl80211/cfg80211
3 * Copyright (c) 2003-2008, Jouni Malinen <j@w1.fi>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2 as
7 * published by the Free Software Foundation.
8 *
9 * Alternatively, this software may be distributed under the terms of BSD
10 * license.
11 *
12 * See README and COPYING for more details.
13 */
14
15#include "includes.h"
16#include <sys/ioctl.h>
17#include <net/if_arp.h>
18#include <netlink/genl/genl.h>
19#include <netlink/genl/family.h>
20#include <netlink/genl/ctrl.h>
21#include "nl80211_copy.h"
22#ifdef CONFIG_CLIENT_MLME
23#include <netpacket/packet.h>
24#include <linux/if_ether.h>
25#include "radiotap.h"
26#include "radiotap_iter.h"
27#endif /* CONFIG_CLIENT_MLME */
28
29#include "wireless_copy.h"
30#include "common.h"
31#include "driver.h"
32#include "eloop.h"
33#include "ieee802_11_defs.h"
34
35#ifndef IFF_LOWER_UP
36#define IFF_LOWER_UP   0x10000         /* driver signals L1 up         */
37#endif
38#ifndef IFF_DORMANT
39#define IFF_DORMANT    0x20000         /* driver signals dormant       */
40#endif
41
42#ifndef IF_OPER_DORMANT
43#define IF_OPER_DORMANT 5
44#endif
45#ifndef IF_OPER_UP
46#define IF_OPER_UP 6
47#endif
48
49
50struct wpa_driver_nl80211_data {
51	void *ctx;
52	int wext_event_sock;
53	int ioctl_sock;
54	char ifname[IFNAMSIZ + 1];
55	int ifindex;
56	int if_removed;
57	u8 *assoc_req_ies;
58	size_t assoc_req_ies_len;
59	u8 *assoc_resp_ies;
60	size_t assoc_resp_ies_len;
61	struct wpa_driver_capa capa;
62	int has_capability;
63	int we_version_compiled;
64
65	/* for set_auth_alg fallback */
66	int use_crypt;
67	int auth_alg_fallback;
68
69	int operstate;
70
71	char mlmedev[IFNAMSIZ + 1];
72
73	int scan_complete_events;
74
75	struct nl_handle *nl_handle;
76	struct nl_cache *nl_cache;
77	struct nl_cb *nl_cb;
78	struct genl_family *nl80211;
79
80#ifdef CONFIG_CLIENT_MLME
81	int monitor_sock; /* socket for monitor */
82	int monitor_ifidx;
83#endif /* CONFIG_CLIENT_MLME */
84};
85
86
87static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx,
88					    void *timeout_ctx);
89static int wpa_driver_nl80211_set_mode(void *priv, int mode);
90static int wpa_driver_nl80211_flush_pmkid(void *priv);
91static int wpa_driver_nl80211_get_range(void *priv);
92static void
93wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv);
94
95
96/* nl80211 code */
97static int ack_handler(struct nl_msg *msg, void *arg)
98{
99	int *err = arg;
100	*err = 0;
101	return NL_STOP;
102}
103
104static int finish_handler(struct nl_msg *msg, void *arg)
105{
106	int *ret = arg;
107	*ret = 0;
108	return NL_SKIP;
109}
110
111static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err,
112			 void *arg)
113{
114	int *ret = arg;
115	*ret = err->error;
116	return NL_SKIP;
117}
118
119static int send_and_recv_msgs(struct wpa_driver_nl80211_data *drv,
120			      struct nl_msg *msg,
121			      int (*valid_handler)(struct nl_msg *, void *),
122			      void *valid_data)
123{
124	struct nl_cb *cb;
125	int err = -ENOMEM;
126
127	cb = nl_cb_clone(drv->nl_cb);
128	if (!cb)
129		goto out;
130
131	err = nl_send_auto_complete(drv->nl_handle, msg);
132	if (err < 0)
133		goto out;
134
135	err = 1;
136
137	nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
138	nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
139	nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
140
141	if (valid_handler)
142		nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM,
143			  valid_handler, valid_data);
144
145	while (err > 0)
146		nl_recvmsgs(drv->nl_handle, cb);
147 out:
148	nl_cb_put(cb);
149	nlmsg_free(msg);
150	return err;
151}
152
153
154struct family_data {
155	const char *group;
156	int id;
157};
158
159
160static int family_handler(struct nl_msg *msg, void *arg)
161{
162	struct family_data *res = arg;
163	struct nlattr *tb[CTRL_ATTR_MAX + 1];
164	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
165	struct nlattr *mcgrp;
166	int i;
167
168	nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
169		  genlmsg_attrlen(gnlh, 0), NULL);
170	if (!tb[CTRL_ATTR_MCAST_GROUPS])
171		return NL_SKIP;
172
173	nla_for_each_nested(mcgrp, tb[CTRL_ATTR_MCAST_GROUPS], i) {
174		struct nlattr *tb2[CTRL_ATTR_MCAST_GRP_MAX + 1];
175		nla_parse(tb2, CTRL_ATTR_MCAST_GRP_MAX, nla_data(mcgrp),
176			  nla_len(mcgrp), NULL);
177		if (!tb2[CTRL_ATTR_MCAST_GRP_NAME] ||
178		    !tb2[CTRL_ATTR_MCAST_GRP_ID] ||
179		    os_strncmp(nla_data(tb2[CTRL_ATTR_MCAST_GRP_NAME]),
180			       res->group,
181			       nla_len(tb2[CTRL_ATTR_MCAST_GRP_NAME])) != 0)
182			continue;
183		res->id = nla_get_u32(tb2[CTRL_ATTR_MCAST_GRP_ID]);
184		break;
185	};
186
187	return NL_SKIP;
188}
189
190
191static int nl_get_multicast_id(struct wpa_driver_nl80211_data *drv,
192			       const char *family, const char *group)
193{
194	struct nl_msg *msg;
195	int ret = -1;
196	struct family_data res = { group, -ENOENT };
197
198	msg = nlmsg_alloc();
199	if (!msg)
200		return -ENOMEM;
201	genlmsg_put(msg, 0, 0, genl_ctrl_resolve(drv->nl_handle, "nlctrl"),
202		    0, 0, CTRL_CMD_GETFAMILY, 0);
203	NLA_PUT_STRING(msg, CTRL_ATTR_FAMILY_NAME, family);
204
205	ret = send_and_recv_msgs(drv, msg, family_handler, &res);
206	msg = NULL;
207	if (ret == 0)
208		ret = res.id;
209
210nla_put_failure:
211	nlmsg_free(msg);
212	return ret;
213}
214
215
216static int wpa_driver_nl80211_send_oper_ifla(
217	struct wpa_driver_nl80211_data *drv,
218	int linkmode, int operstate)
219{
220	struct {
221		struct nlmsghdr hdr;
222		struct ifinfomsg ifinfo;
223		char opts[16];
224	} req;
225	struct rtattr *rta;
226	static int nl_seq;
227	ssize_t ret;
228
229	os_memset(&req, 0, sizeof(req));
230
231	req.hdr.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));
232	req.hdr.nlmsg_type = RTM_SETLINK;
233	req.hdr.nlmsg_flags = NLM_F_REQUEST;
234	req.hdr.nlmsg_seq = ++nl_seq;
235	req.hdr.nlmsg_pid = 0;
236
237	req.ifinfo.ifi_family = AF_UNSPEC;
238	req.ifinfo.ifi_type = 0;
239	req.ifinfo.ifi_index = drv->ifindex;
240	req.ifinfo.ifi_flags = 0;
241	req.ifinfo.ifi_change = 0;
242
243	if (linkmode != -1) {
244		rta = aliasing_hide_typecast(
245			((char *) &req + NLMSG_ALIGN(req.hdr.nlmsg_len)),
246			struct rtattr);
247		rta->rta_type = IFLA_LINKMODE;
248		rta->rta_len = RTA_LENGTH(sizeof(char));
249		*((char *) RTA_DATA(rta)) = linkmode;
250		req.hdr.nlmsg_len = NLMSG_ALIGN(req.hdr.nlmsg_len) +
251			RTA_LENGTH(sizeof(char));
252	}
253	if (operstate != -1) {
254		rta = (struct rtattr *)
255			((char *) &req + NLMSG_ALIGN(req.hdr.nlmsg_len));
256		rta->rta_type = IFLA_OPERSTATE;
257		rta->rta_len = RTA_LENGTH(sizeof(char));
258		*((char *) RTA_DATA(rta)) = operstate;
259		req.hdr.nlmsg_len = NLMSG_ALIGN(req.hdr.nlmsg_len) +
260			RTA_LENGTH(sizeof(char));
261	}
262
263	wpa_printf(MSG_DEBUG, "WEXT: Operstate: linkmode=%d, operstate=%d",
264		   linkmode, operstate);
265
266	ret = send(drv->wext_event_sock, &req, req.hdr.nlmsg_len, 0);
267	if (ret < 0) {
268		wpa_printf(MSG_DEBUG, "WEXT: Sending operstate IFLA failed: "
269			   "%s (assume operstate is not supported)",
270			   strerror(errno));
271	}
272
273	return ret < 0 ? -1 : 0;
274}
275
276
277static int wpa_driver_nl80211_set_auth_param(
278	struct wpa_driver_nl80211_data *drv, int idx, u32 value)
279{
280	struct iwreq iwr;
281	int ret = 0;
282
283	os_memset(&iwr, 0, sizeof(iwr));
284	os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
285	iwr.u.param.flags = idx & IW_AUTH_INDEX;
286	iwr.u.param.value = value;
287
288	if (ioctl(drv->ioctl_sock, SIOCSIWAUTH, &iwr) < 0) {
289		if (errno != EOPNOTSUPP) {
290			wpa_printf(MSG_DEBUG, "WEXT: SIOCSIWAUTH(param %d "
291				   "value 0x%x) failed: %s)",
292				   idx, value, strerror(errno));
293		}
294		ret = errno == EOPNOTSUPP ? -2 : -1;
295	}
296
297	return ret;
298}
299
300
301static int wpa_driver_nl80211_get_bssid(void *priv, u8 *bssid)
302{
303	struct wpa_driver_nl80211_data *drv = priv;
304	struct iwreq iwr;
305	int ret = 0;
306
307	os_memset(&iwr, 0, sizeof(iwr));
308	os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
309
310	if (ioctl(drv->ioctl_sock, SIOCGIWAP, &iwr) < 0) {
311		perror("ioctl[SIOCGIWAP]");
312		ret = -1;
313	}
314	os_memcpy(bssid, iwr.u.ap_addr.sa_data, ETH_ALEN);
315
316	return ret;
317}
318
319
320static int wpa_driver_nl80211_set_bssid(void *priv, const u8 *bssid)
321{
322	struct wpa_driver_nl80211_data *drv = priv;
323	struct iwreq iwr;
324	int ret = 0;
325
326	os_memset(&iwr, 0, sizeof(iwr));
327	os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
328	iwr.u.ap_addr.sa_family = ARPHRD_ETHER;
329	if (bssid)
330		os_memcpy(iwr.u.ap_addr.sa_data, bssid, ETH_ALEN);
331	else
332		os_memset(iwr.u.ap_addr.sa_data, 0, ETH_ALEN);
333
334	if (ioctl(drv->ioctl_sock, SIOCSIWAP, &iwr) < 0) {
335		perror("ioctl[SIOCSIWAP]");
336		ret = -1;
337	}
338
339	return ret;
340}
341
342
343static int wpa_driver_nl80211_get_ssid(void *priv, u8 *ssid)
344{
345	struct wpa_driver_nl80211_data *drv = priv;
346	struct iwreq iwr;
347	int ret = 0;
348
349	os_memset(&iwr, 0, sizeof(iwr));
350	os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
351	iwr.u.essid.pointer = (caddr_t) ssid;
352	iwr.u.essid.length = 32;
353
354	if (ioctl(drv->ioctl_sock, SIOCGIWESSID, &iwr) < 0) {
355		perror("ioctl[SIOCGIWESSID]");
356		ret = -1;
357	} else {
358		ret = iwr.u.essid.length;
359		if (ret > 32)
360			ret = 32;
361		/* Some drivers include nul termination in the SSID, so let's
362		 * remove it here before further processing. WE-21 changes this
363		 * to explicitly require the length _not_ to include nul
364		 * termination. */
365		if (ret > 0 && ssid[ret - 1] == '\0' &&
366		    drv->we_version_compiled < 21)
367			ret--;
368	}
369
370	return ret;
371}
372
373
374static int wpa_driver_nl80211_set_ssid(void *priv, const u8 *ssid,
375				       size_t ssid_len)
376{
377	struct wpa_driver_nl80211_data *drv = priv;
378	struct iwreq iwr;
379	int ret = 0;
380	char buf[33];
381
382	if (ssid_len > 32)
383		return -1;
384
385	os_memset(&iwr, 0, sizeof(iwr));
386	os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
387	/* flags: 1 = ESSID is active, 0 = not (promiscuous) */
388	iwr.u.essid.flags = (ssid_len != 0);
389	os_memset(buf, 0, sizeof(buf));
390	os_memcpy(buf, ssid, ssid_len);
391	iwr.u.essid.pointer = (caddr_t) buf;
392	if (drv->we_version_compiled < 21) {
393		/* For historic reasons, set SSID length to include one extra
394		 * character, C string nul termination, even though SSID is
395		 * really an octet string that should not be presented as a C
396		 * string. Some Linux drivers decrement the length by one and
397		 * can thus end up missing the last octet of the SSID if the
398		 * length is not incremented here. WE-21 changes this to
399		 * explicitly require the length _not_ to include nul
400		 * termination. */
401		if (ssid_len)
402			ssid_len++;
403	}
404	iwr.u.essid.length = ssid_len;
405
406	if (ioctl(drv->ioctl_sock, SIOCSIWESSID, &iwr) < 0) {
407		perror("ioctl[SIOCSIWESSID]");
408		ret = -1;
409	}
410
411	return ret;
412}
413
414
415static int wpa_driver_nl80211_set_freq(void *priv, int freq)
416{
417	struct wpa_driver_nl80211_data *drv = priv;
418	struct iwreq iwr;
419	int ret = 0;
420
421	os_memset(&iwr, 0, sizeof(iwr));
422	os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
423	iwr.u.freq.m = freq * 100000;
424	iwr.u.freq.e = 1;
425
426	if (ioctl(drv->ioctl_sock, SIOCSIWFREQ, &iwr) < 0) {
427		perror("ioctl[SIOCSIWFREQ]");
428		ret = -1;
429	}
430
431	return ret;
432}
433
434
435static void
436wpa_driver_nl80211_event_wireless_custom(void *ctx, char *custom)
437{
438	union wpa_event_data data;
439
440	wpa_printf(MSG_MSGDUMP, "WEXT: Custom wireless event: '%s'",
441		   custom);
442
443	os_memset(&data, 0, sizeof(data));
444	/* Host AP driver */
445	if (os_strncmp(custom, "MLME-MICHAELMICFAILURE.indication", 33) == 0) {
446		data.michael_mic_failure.unicast =
447			os_strstr(custom, " unicast ") != NULL;
448		/* TODO: parse parameters(?) */
449		wpa_supplicant_event(ctx, EVENT_MICHAEL_MIC_FAILURE, &data);
450	} else if (os_strncmp(custom, "ASSOCINFO(ReqIEs=", 17) == 0) {
451		char *spos;
452		int bytes;
453
454		spos = custom + 17;
455
456		bytes = strspn(spos, "0123456789abcdefABCDEF");
457		if (!bytes || (bytes & 1))
458			return;
459		bytes /= 2;
460
461		data.assoc_info.req_ies = os_malloc(bytes);
462		if (data.assoc_info.req_ies == NULL)
463			return;
464
465		data.assoc_info.req_ies_len = bytes;
466		hexstr2bin(spos, data.assoc_info.req_ies, bytes);
467
468		spos += bytes * 2;
469
470		data.assoc_info.resp_ies = NULL;
471		data.assoc_info.resp_ies_len = 0;
472
473		if (os_strncmp(spos, " RespIEs=", 9) == 0) {
474			spos += 9;
475
476			bytes = strspn(spos, "0123456789abcdefABCDEF");
477			if (!bytes || (bytes & 1))
478				goto done;
479			bytes /= 2;
480
481			data.assoc_info.resp_ies = os_malloc(bytes);
482			if (data.assoc_info.resp_ies == NULL)
483				goto done;
484
485			data.assoc_info.resp_ies_len = bytes;
486			hexstr2bin(spos, data.assoc_info.resp_ies, bytes);
487		}
488
489		wpa_supplicant_event(ctx, EVENT_ASSOCINFO, &data);
490
491	done:
492		os_free(data.assoc_info.resp_ies);
493		os_free(data.assoc_info.req_ies);
494#ifdef CONFIG_PEERKEY
495	} else if (os_strncmp(custom, "STKSTART.request=", 17) == 0) {
496		if (hwaddr_aton(custom + 17, data.stkstart.peer)) {
497			wpa_printf(MSG_DEBUG, "WEXT: unrecognized "
498				   "STKSTART.request '%s'", custom + 17);
499			return;
500		}
501		wpa_supplicant_event(ctx, EVENT_STKSTART, &data);
502#endif /* CONFIG_PEERKEY */
503	}
504}
505
506
507static int wpa_driver_nl80211_event_wireless_michaelmicfailure(
508	void *ctx, const char *ev, size_t len)
509{
510	const struct iw_michaelmicfailure *mic;
511	union wpa_event_data data;
512
513	if (len < sizeof(*mic))
514		return -1;
515
516	mic = (const struct iw_michaelmicfailure *) ev;
517
518	wpa_printf(MSG_DEBUG, "Michael MIC failure wireless event: "
519		   "flags=0x%x src_addr=" MACSTR, mic->flags,
520		   MAC2STR(mic->src_addr.sa_data));
521
522	os_memset(&data, 0, sizeof(data));
523	data.michael_mic_failure.unicast = !(mic->flags & IW_MICFAILURE_GROUP);
524	wpa_supplicant_event(ctx, EVENT_MICHAEL_MIC_FAILURE, &data);
525
526	return 0;
527}
528
529
530static int wpa_driver_nl80211_event_wireless_pmkidcand(
531	struct wpa_driver_nl80211_data *drv, const char *ev, size_t len)
532{
533	const struct iw_pmkid_cand *cand;
534	union wpa_event_data data;
535	const u8 *addr;
536
537	if (len < sizeof(*cand))
538		return -1;
539
540	cand = (const struct iw_pmkid_cand *) ev;
541	addr = (const u8 *) cand->bssid.sa_data;
542
543	wpa_printf(MSG_DEBUG, "PMKID candidate wireless event: "
544		   "flags=0x%x index=%d bssid=" MACSTR, cand->flags,
545		   cand->index, MAC2STR(addr));
546
547	os_memset(&data, 0, sizeof(data));
548	os_memcpy(data.pmkid_candidate.bssid, addr, ETH_ALEN);
549	data.pmkid_candidate.index = cand->index;
550	data.pmkid_candidate.preauth = cand->flags & IW_PMKID_CAND_PREAUTH;
551	wpa_supplicant_event(drv->ctx, EVENT_PMKID_CANDIDATE, &data);
552
553	return 0;
554}
555
556
557static int wpa_driver_nl80211_event_wireless_assocreqie(
558	struct wpa_driver_nl80211_data *drv, const char *ev, int len)
559{
560	if (len < 0)
561		return -1;
562
563	wpa_hexdump(MSG_DEBUG, "AssocReq IE wireless event", (const u8 *) ev,
564		    len);
565	os_free(drv->assoc_req_ies);
566	drv->assoc_req_ies = os_malloc(len);
567	if (drv->assoc_req_ies == NULL) {
568		drv->assoc_req_ies_len = 0;
569		return -1;
570	}
571	os_memcpy(drv->assoc_req_ies, ev, len);
572	drv->assoc_req_ies_len = len;
573
574	return 0;
575}
576
577
578static int wpa_driver_nl80211_event_wireless_assocrespie(
579	struct wpa_driver_nl80211_data *drv, const char *ev, int len)
580{
581	if (len < 0)
582		return -1;
583
584	wpa_hexdump(MSG_DEBUG, "AssocResp IE wireless event", (const u8 *) ev,
585		    len);
586	os_free(drv->assoc_resp_ies);
587	drv->assoc_resp_ies = os_malloc(len);
588	if (drv->assoc_resp_ies == NULL) {
589		drv->assoc_resp_ies_len = 0;
590		return -1;
591	}
592	os_memcpy(drv->assoc_resp_ies, ev, len);
593	drv->assoc_resp_ies_len = len;
594
595	return 0;
596}
597
598
599static void wpa_driver_nl80211_event_assoc_ies(struct wpa_driver_nl80211_data *drv)
600{
601	union wpa_event_data data;
602
603	if (drv->assoc_req_ies == NULL && drv->assoc_resp_ies == NULL)
604		return;
605
606	os_memset(&data, 0, sizeof(data));
607	if (drv->assoc_req_ies) {
608		data.assoc_info.req_ies = drv->assoc_req_ies;
609		drv->assoc_req_ies = NULL;
610		data.assoc_info.req_ies_len = drv->assoc_req_ies_len;
611	}
612	if (drv->assoc_resp_ies) {
613		data.assoc_info.resp_ies = drv->assoc_resp_ies;
614		drv->assoc_resp_ies = NULL;
615		data.assoc_info.resp_ies_len = drv->assoc_resp_ies_len;
616	}
617
618	wpa_supplicant_event(drv->ctx, EVENT_ASSOCINFO, &data);
619
620	os_free(data.assoc_info.req_ies);
621	os_free(data.assoc_info.resp_ies);
622}
623
624
625static void wpa_driver_nl80211_event_wireless(struct wpa_driver_nl80211_data *drv,
626					   void *ctx, char *data, int len)
627{
628	struct iw_event iwe_buf, *iwe = &iwe_buf;
629	char *pos, *end, *custom, *buf;
630
631	pos = data;
632	end = data + len;
633
634	while (pos + IW_EV_LCP_LEN <= end) {
635		/* Event data may be unaligned, so make a local, aligned copy
636		 * before processing. */
637		os_memcpy(&iwe_buf, pos, IW_EV_LCP_LEN);
638		wpa_printf(MSG_DEBUG, "Wireless event: cmd=0x%x len=%d",
639			   iwe->cmd, iwe->len);
640		if (iwe->len <= IW_EV_LCP_LEN)
641			return;
642
643		custom = pos + IW_EV_POINT_LEN;
644		if (drv->we_version_compiled > 18 &&
645		    (iwe->cmd == IWEVMICHAELMICFAILURE ||
646		     iwe->cmd == IWEVCUSTOM ||
647		     iwe->cmd == IWEVASSOCREQIE ||
648		     iwe->cmd == IWEVASSOCRESPIE ||
649		     iwe->cmd == IWEVPMKIDCAND)) {
650			/* WE-19 removed the pointer from struct iw_point */
651			char *dpos = (char *) &iwe_buf.u.data.length;
652			int dlen = dpos - (char *) &iwe_buf;
653			os_memcpy(dpos, pos + IW_EV_LCP_LEN,
654				  sizeof(struct iw_event) - dlen);
655		} else {
656			os_memcpy(&iwe_buf, pos, sizeof(struct iw_event));
657			custom += IW_EV_POINT_OFF;
658		}
659
660		switch (iwe->cmd) {
661		case SIOCGIWAP:
662			wpa_printf(MSG_DEBUG, "Wireless event: new AP: "
663				   MACSTR,
664				   MAC2STR((u8 *) iwe->u.ap_addr.sa_data));
665			if (is_zero_ether_addr(
666				    (const u8 *) iwe->u.ap_addr.sa_data) ||
667			    os_memcmp(iwe->u.ap_addr.sa_data,
668				      "\x44\x44\x44\x44\x44\x44", ETH_ALEN) ==
669			    0) {
670				os_free(drv->assoc_req_ies);
671				drv->assoc_req_ies = NULL;
672				os_free(drv->assoc_resp_ies);
673				drv->assoc_resp_ies = NULL;
674				wpa_supplicant_event(ctx, EVENT_DISASSOC,
675						     NULL);
676
677			} else {
678				wpa_driver_nl80211_event_assoc_ies(drv);
679				wpa_supplicant_event(ctx, EVENT_ASSOC, NULL);
680			}
681			break;
682		case IWEVMICHAELMICFAILURE:
683			wpa_driver_nl80211_event_wireless_michaelmicfailure(
684				ctx, custom, iwe->u.data.length);
685			break;
686		case IWEVCUSTOM:
687			if (custom + iwe->u.data.length > end)
688				return;
689			buf = os_malloc(iwe->u.data.length + 1);
690			if (buf == NULL)
691				return;
692			os_memcpy(buf, custom, iwe->u.data.length);
693			buf[iwe->u.data.length] = '\0';
694			wpa_driver_nl80211_event_wireless_custom(ctx, buf);
695			os_free(buf);
696			break;
697		case IWEVASSOCREQIE:
698			wpa_driver_nl80211_event_wireless_assocreqie(
699				drv, custom, iwe->u.data.length);
700			break;
701		case IWEVASSOCRESPIE:
702			wpa_driver_nl80211_event_wireless_assocrespie(
703				drv, custom, iwe->u.data.length);
704			break;
705		case IWEVPMKIDCAND:
706			wpa_driver_nl80211_event_wireless_pmkidcand(
707				drv, custom, iwe->u.data.length);
708			break;
709		}
710
711		pos += iwe->len;
712	}
713}
714
715
716static void wpa_driver_nl80211_event_link(struct wpa_driver_nl80211_data *drv,
717					  void *ctx, char *buf, size_t len,
718					  int del)
719{
720	union wpa_event_data event;
721
722	os_memset(&event, 0, sizeof(event));
723	if (len > sizeof(event.interface_status.ifname))
724		len = sizeof(event.interface_status.ifname) - 1;
725	os_memcpy(event.interface_status.ifname, buf, len);
726	event.interface_status.ievent = del ? EVENT_INTERFACE_REMOVED :
727		EVENT_INTERFACE_ADDED;
728
729	wpa_printf(MSG_DEBUG, "RTM_%sLINK, IFLA_IFNAME: Interface '%s' %s",
730		   del ? "DEL" : "NEW",
731		   event.interface_status.ifname,
732		   del ? "removed" : "added");
733
734	if (os_strcmp(drv->ifname, event.interface_status.ifname) == 0) {
735		if (del)
736			drv->if_removed = 1;
737		else
738			drv->if_removed = 0;
739	}
740
741	wpa_supplicant_event(ctx, EVENT_INTERFACE_STATUS, &event);
742}
743
744
745static int wpa_driver_nl80211_own_ifname(struct wpa_driver_nl80211_data *drv,
746					 struct nlmsghdr *h)
747{
748	struct ifinfomsg *ifi;
749	int attrlen, _nlmsg_len, rta_len;
750	struct rtattr *attr;
751
752	ifi = NLMSG_DATA(h);
753
754	_nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
755
756	attrlen = h->nlmsg_len - _nlmsg_len;
757	if (attrlen < 0)
758		return 0;
759
760	attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
761
762	rta_len = RTA_ALIGN(sizeof(struct rtattr));
763	while (RTA_OK(attr, attrlen)) {
764		if (attr->rta_type == IFLA_IFNAME) {
765			if (os_strcmp(((char *) attr) + rta_len, drv->ifname)
766			    == 0)
767				return 1;
768			else
769				break;
770		}
771		attr = RTA_NEXT(attr, attrlen);
772	}
773
774	return 0;
775}
776
777
778static int wpa_driver_nl80211_own_ifindex(struct wpa_driver_nl80211_data *drv,
779					  int ifindex, struct nlmsghdr *h)
780{
781	if (drv->ifindex == ifindex)
782		return 1;
783
784	if (drv->if_removed && wpa_driver_nl80211_own_ifname(drv, h)) {
785		drv->ifindex = if_nametoindex(drv->ifname);
786		wpa_printf(MSG_DEBUG, "nl80211: Update ifindex for a removed "
787			   "interface");
788		wpa_driver_nl80211_finish_drv_init(drv);
789		return 1;
790	}
791
792	return 0;
793}
794
795
796static void wpa_driver_nl80211_event_rtm_newlink(struct wpa_driver_nl80211_data *drv,
797					      void *ctx, struct nlmsghdr *h,
798					      size_t len)
799{
800	struct ifinfomsg *ifi;
801	int attrlen, _nlmsg_len, rta_len;
802	struct rtattr * attr;
803
804	if (len < sizeof(*ifi))
805		return;
806
807	ifi = NLMSG_DATA(h);
808
809	if (!wpa_driver_nl80211_own_ifindex(drv, ifi->ifi_index, h)) {
810		wpa_printf(MSG_DEBUG, "Ignore event for foreign ifindex %d",
811			   ifi->ifi_index);
812		return;
813	}
814
815	wpa_printf(MSG_DEBUG, "RTM_NEWLINK: operstate=%d ifi_flags=0x%x "
816		   "(%s%s%s%s)",
817		   drv->operstate, ifi->ifi_flags,
818		   (ifi->ifi_flags & IFF_UP) ? "[UP]" : "",
819		   (ifi->ifi_flags & IFF_RUNNING) ? "[RUNNING]" : "",
820		   (ifi->ifi_flags & IFF_LOWER_UP) ? "[LOWER_UP]" : "",
821		   (ifi->ifi_flags & IFF_DORMANT) ? "[DORMANT]" : "");
822	/*
823	 * Some drivers send the association event before the operup event--in
824	 * this case, lifting operstate in wpa_driver_nl80211_set_operstate()
825	 * fails. This will hit us when wpa_supplicant does not need to do
826	 * IEEE 802.1X authentication
827	 */
828	if (drv->operstate == 1 &&
829	    (ifi->ifi_flags & (IFF_LOWER_UP | IFF_DORMANT)) == IFF_LOWER_UP &&
830	    !(ifi->ifi_flags & IFF_RUNNING))
831		wpa_driver_nl80211_send_oper_ifla(drv, -1, IF_OPER_UP);
832
833	_nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
834
835	attrlen = h->nlmsg_len - _nlmsg_len;
836	if (attrlen < 0)
837		return;
838
839	attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
840
841	rta_len = RTA_ALIGN(sizeof(struct rtattr));
842	while (RTA_OK(attr, attrlen)) {
843		if (attr->rta_type == IFLA_WIRELESS) {
844			wpa_driver_nl80211_event_wireless(
845				drv, ctx, ((char *) attr) + rta_len,
846				attr->rta_len - rta_len);
847		} else if (attr->rta_type == IFLA_IFNAME) {
848			wpa_driver_nl80211_event_link(
849				drv, ctx,
850				((char *) attr) + rta_len,
851				attr->rta_len - rta_len, 0);
852		}
853		attr = RTA_NEXT(attr, attrlen);
854	}
855}
856
857
858static void wpa_driver_nl80211_event_rtm_dellink(struct wpa_driver_nl80211_data *drv,
859					      void *ctx, struct nlmsghdr *h,
860					      size_t len)
861{
862	struct ifinfomsg *ifi;
863	int attrlen, _nlmsg_len, rta_len;
864	struct rtattr * attr;
865
866	if (len < sizeof(*ifi))
867		return;
868
869	ifi = NLMSG_DATA(h);
870
871	_nlmsg_len = NLMSG_ALIGN(sizeof(struct ifinfomsg));
872
873	attrlen = h->nlmsg_len - _nlmsg_len;
874	if (attrlen < 0)
875		return;
876
877	attr = (struct rtattr *) (((char *) ifi) + _nlmsg_len);
878
879	rta_len = RTA_ALIGN(sizeof(struct rtattr));
880	while (RTA_OK(attr, attrlen)) {
881		if (attr->rta_type == IFLA_IFNAME) {
882			wpa_driver_nl80211_event_link(
883				drv, ctx,
884				((char *) attr) + rta_len,
885				attr->rta_len - rta_len, 1);
886		}
887		attr = RTA_NEXT(attr, attrlen);
888	}
889}
890
891
892static void wpa_driver_nl80211_event_receive_wext(int sock, void *eloop_ctx,
893						  void *sock_ctx)
894{
895	char buf[8192];
896	int left;
897	struct sockaddr_nl from;
898	socklen_t fromlen;
899	struct nlmsghdr *h;
900	int max_events = 10;
901
902try_again:
903	fromlen = sizeof(from);
904	left = recvfrom(sock, buf, sizeof(buf), MSG_DONTWAIT,
905			(struct sockaddr *) &from, &fromlen);
906	if (left < 0) {
907		if (errno != EINTR && errno != EAGAIN)
908			perror("recvfrom(netlink)");
909		return;
910	}
911
912	h = (struct nlmsghdr *) buf;
913	while (left >= (int) sizeof(*h)) {
914		int len, plen;
915
916		len = h->nlmsg_len;
917		plen = len - sizeof(*h);
918		if (len > left || plen < 0) {
919			wpa_printf(MSG_DEBUG, "Malformed netlink message: "
920				   "len=%d left=%d plen=%d",
921				   len, left, plen);
922			break;
923		}
924
925		switch (h->nlmsg_type) {
926		case RTM_NEWLINK:
927			wpa_driver_nl80211_event_rtm_newlink(eloop_ctx, sock_ctx,
928							  h, plen);
929			break;
930		case RTM_DELLINK:
931			wpa_driver_nl80211_event_rtm_dellink(eloop_ctx, sock_ctx,
932							  h, plen);
933			break;
934		}
935
936		len = NLMSG_ALIGN(len);
937		left -= len;
938		h = (struct nlmsghdr *) ((char *) h + len);
939	}
940
941	if (left > 0) {
942		wpa_printf(MSG_DEBUG, "%d extra bytes in the end of netlink "
943			   "message", left);
944	}
945
946	if (--max_events > 0) {
947		/*
948		 * Try to receive all events in one eloop call in order to
949		 * limit race condition on cases where AssocInfo event, Assoc
950		 * event, and EAPOL frames are received more or less at the
951		 * same time. We want to process the event messages first
952		 * before starting EAPOL processing.
953		 */
954		goto try_again;
955	}
956}
957
958
959static int no_seq_check(struct nl_msg *msg, void *arg)
960{
961	return NL_OK;
962}
963
964
965static int process_event(struct nl_msg *msg, void *arg)
966{
967	struct wpa_driver_nl80211_data *drv = arg;
968	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
969	struct nlattr *tb[NL80211_ATTR_MAX + 1];
970
971	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
972		  genlmsg_attrlen(gnlh, 0), NULL);
973
974	if (tb[NL80211_ATTR_IFINDEX]) {
975		int ifindex = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
976		if (ifindex != drv->ifindex) {
977			wpa_printf(MSG_DEBUG, "nl80211: Ignored event (cmd=%d)"
978				   " for foreign interface (ifindex %d)",
979				   gnlh->cmd, ifindex);
980			return NL_SKIP;
981		}
982	}
983
984	switch (gnlh->cmd) {
985	case NL80211_CMD_TRIGGER_SCAN:
986		wpa_printf(MSG_DEBUG, "nl80211: Scan trigger");
987		break;
988	case NL80211_CMD_NEW_SCAN_RESULTS:
989		wpa_printf(MSG_DEBUG, "nl80211: New scan results available");
990		drv->scan_complete_events = 1;
991		eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
992				     drv->ctx);
993		wpa_supplicant_event(drv->ctx, EVENT_SCAN_RESULTS, NULL);
994		break;
995	case NL80211_CMD_SCAN_ABORTED:
996		wpa_printf(MSG_DEBUG, "nl80211: Scan aborted");
997		/*
998		 * Need to indicate that scan results are available in order
999		 * not to make wpa_supplicant stop its scanning.
1000		 */
1001		eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
1002				     drv->ctx);
1003		wpa_supplicant_event(drv->ctx, EVENT_SCAN_RESULTS, NULL);
1004		break;
1005	default:
1006		wpa_printf(MSG_DEBUG, "nl0211: Ignored unknown event (cmd=%d)",
1007			   gnlh->cmd);
1008		break;
1009	}
1010
1011	return NL_SKIP;
1012}
1013
1014
1015static void wpa_driver_nl80211_event_receive(int sock, void *eloop_ctx,
1016					     void *sock_ctx)
1017{
1018	struct nl_cb *cb;
1019	struct wpa_driver_nl80211_data *drv = eloop_ctx;
1020
1021	wpa_printf(MSG_DEBUG, "nl80211: Event message available");
1022
1023	cb = nl_cb_clone(drv->nl_cb);
1024	if (!cb)
1025		return;
1026	nl_cb_set(cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, no_seq_check, NULL);
1027	nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, process_event, drv);
1028	nl_recvmsgs(drv->nl_handle, cb);
1029	nl_cb_put(cb);
1030}
1031
1032
1033static int wpa_driver_nl80211_get_ifflags_ifname(struct wpa_driver_nl80211_data *drv,
1034					      const char *ifname, int *flags)
1035{
1036	struct ifreq ifr;
1037
1038	os_memset(&ifr, 0, sizeof(ifr));
1039	os_strlcpy(ifr.ifr_name, ifname, IFNAMSIZ);
1040	if (ioctl(drv->ioctl_sock, SIOCGIFFLAGS, (caddr_t) &ifr) < 0) {
1041		perror("ioctl[SIOCGIFFLAGS]");
1042		return -1;
1043	}
1044	*flags = ifr.ifr_flags & 0xffff;
1045	return 0;
1046}
1047
1048
1049/**
1050 * wpa_driver_nl80211_get_ifflags - Get interface flags (SIOCGIFFLAGS)
1051 * @drv: driver_nl80211 private data
1052 * @flags: Pointer to returned flags value
1053 * Returns: 0 on success, -1 on failure
1054 */
1055static int wpa_driver_nl80211_get_ifflags(struct wpa_driver_nl80211_data *drv,
1056					  int *flags)
1057{
1058	return wpa_driver_nl80211_get_ifflags_ifname(drv, drv->ifname, flags);
1059}
1060
1061
1062static int wpa_driver_nl80211_set_ifflags_ifname(
1063	struct wpa_driver_nl80211_data *drv,
1064	const char *ifname, int flags)
1065{
1066	struct ifreq ifr;
1067
1068	os_memset(&ifr, 0, sizeof(ifr));
1069	os_strlcpy(ifr.ifr_name, ifname, IFNAMSIZ);
1070	ifr.ifr_flags = flags & 0xffff;
1071	if (ioctl(drv->ioctl_sock, SIOCSIFFLAGS, (caddr_t) &ifr) < 0) {
1072		perror("SIOCSIFFLAGS");
1073		return -1;
1074	}
1075	return 0;
1076}
1077
1078
1079/**
1080 * wpa_driver_nl80211_set_ifflags - Set interface flags (SIOCSIFFLAGS)
1081 * @drv: driver_nl80211 private data
1082 * @flags: New value for flags
1083 * Returns: 0 on success, -1 on failure
1084 */
1085static int wpa_driver_nl80211_set_ifflags(struct wpa_driver_nl80211_data *drv,
1086					  int flags)
1087{
1088	return wpa_driver_nl80211_set_ifflags_ifname(drv, drv->ifname, flags);
1089}
1090
1091
1092/**
1093 * wpa_driver_nl80211_set_country - ask nl80211 to set the regulatory domain
1094 * @priv: driver_nl80211 private data
1095 * @alpha2_arg: country to which to switch to
1096 * Returns: 0 on success, -1 on failure
1097 *
1098 * This asks nl80211 to set the regulatory domain for given
1099 * country ISO / IEC alpha2.
1100 */
1101static int wpa_driver_nl80211_set_country(void *priv, const char *alpha2_arg)
1102{
1103	struct wpa_driver_nl80211_data *drv = priv;
1104	char alpha2[3];
1105	struct nl_msg *msg;
1106
1107	msg = nlmsg_alloc();
1108	if (!msg)
1109		goto nla_put_failure;
1110
1111	alpha2[0] = alpha2_arg[0];
1112	alpha2[1] = alpha2_arg[1];
1113	alpha2[2] = '\0';
1114
1115	genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1116		    0, NL80211_CMD_REQ_SET_REG, 0);
1117
1118	NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
1119	if (send_and_recv_msgs(drv, msg, NULL, NULL))
1120		return -EINVAL;
1121	return 0;
1122nla_put_failure:
1123	return -EINVAL;
1124}
1125
1126
1127static int wpa_driver_nl80211_set_probe_req_ie(void *priv, const u8 *ies,
1128					       size_t ies_len)
1129{
1130	struct wpa_driver_nl80211_data *drv = priv;
1131	struct nl_msg *msg;
1132	int ret = -1;
1133
1134	msg = nlmsg_alloc();
1135	if (!msg)
1136		return -ENOMEM;
1137
1138	genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
1139		    NL80211_CMD_SET_MGMT_EXTRA_IE, 0);
1140
1141	NLA_PUT_U8(msg, NL80211_ATTR_MGMT_SUBTYPE, 4 /* ProbeReq */);
1142	if (ies)
1143		NLA_PUT(msg, NL80211_ATTR_IE, ies_len, ies);
1144
1145	ret = 0;
1146
1147	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1148
1149	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1150	return ret;
1151
1152nla_put_failure:
1153	return -ENOBUFS;
1154}
1155
1156
1157#ifdef CONFIG_CLIENT_MLME
1158
1159static int nl80211_set_vif(struct wpa_driver_nl80211_data *drv,
1160			   int drop_unencrypted, int userspace_mlme)
1161{
1162#ifdef NL80211_CMD_SET_VIF
1163	struct nl_msg *msg;
1164	int ret = -1;
1165
1166	msg = nlmsg_alloc();
1167	if (!msg)
1168		return -ENOMEM;
1169
1170	genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
1171		    NL80211_CMD_SET_VIF, 0);
1172
1173	if (drop_unencrypted >= 0)
1174		NLA_PUT_U8(msg, NL80211_ATTR_VIF_DROP_UNENCRYPTED,
1175			   drop_unencrypted);
1176	if (userspace_mlme >= 0)
1177		NLA_PUT_U8(msg, NL80211_ATTR_VIF_USERSPACE_MLME,
1178			   userspace_mlme);
1179
1180	ret = 0;
1181
1182	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1183
1184	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1185	return ret;
1186
1187nla_put_failure:
1188	return -ENOBUFS;
1189#else /* NL80211_CMD_SET_VIF */
1190	return -1;
1191#endif /* NL80211_CMD_SET_VIF */
1192}
1193
1194
1195static int wpa_driver_nl80211_set_userspace_mlme(
1196	struct wpa_driver_nl80211_data *drv, int enabled)
1197{
1198	return nl80211_set_vif(drv, -1, enabled);
1199}
1200
1201
1202static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
1203				 int ifidx)
1204{
1205	struct nl_msg *msg;
1206
1207	msg = nlmsg_alloc();
1208	if (!msg)
1209		goto nla_put_failure;
1210
1211	genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1212		    0, NL80211_CMD_DEL_INTERFACE, 0);
1213	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
1214	if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
1215		return;
1216nla_put_failure:
1217	wpa_printf(MSG_ERROR, "nl80211: Failed to remove interface.");
1218}
1219
1220
1221static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
1222				const char *ifname, enum nl80211_iftype iftype)
1223{
1224	struct nl_msg *msg, *flags = NULL;
1225	int ifidx, err;
1226	int ret = -ENOBUFS;
1227
1228	msg = nlmsg_alloc();
1229	if (!msg)
1230		return -1;
1231
1232	genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1233		    0, NL80211_CMD_NEW_INTERFACE, 0);
1234	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(drv->ifname));
1235	NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
1236	NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
1237
1238	if (iftype == NL80211_IFTYPE_MONITOR) {
1239		flags = nlmsg_alloc();
1240		if (!flags)
1241			goto nla_put_failure;
1242
1243		NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
1244
1245		err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
1246
1247		nlmsg_free(flags);
1248
1249		if (err)
1250			goto nla_put_failure;
1251	}
1252
1253	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1254	if (ret) {
1255	nla_put_failure:
1256		wpa_printf(MSG_ERROR, "nl80211: Failed to create interface %d",
1257			   ret);
1258		return ret;
1259	}
1260
1261	ifidx = if_nametoindex(ifname);
1262	if (ifidx <= 0)
1263		return -1;
1264
1265	return ifidx;
1266}
1267
1268
1269static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
1270{
1271	struct wpa_driver_nl80211_data *drv = eloop_ctx;
1272	int len;
1273	unsigned char buf[3000];
1274	struct ieee80211_radiotap_iterator iter;
1275	int ret;
1276	int injected = 0, failed = 0, rxflags = 0;
1277	struct ieee80211_rx_status rx_status;
1278
1279	len = recv(sock, buf, sizeof(buf), 0);
1280	if (len < 0) {
1281		perror("recv");
1282		return;
1283	}
1284
1285	if (ieee80211_radiotap_iterator_init(&iter, (void *) buf, len)) {
1286		wpa_printf(MSG_DEBUG, "nl80211: received invalid radiotap "
1287			   "frame");
1288		return;
1289	}
1290
1291	os_memset(&rx_status, 0, sizeof(rx_status));
1292
1293	while (1) {
1294		ret = ieee80211_radiotap_iterator_next(&iter);
1295		if (ret == -ENOENT)
1296			break;
1297		if (ret) {
1298			wpa_printf(MSG_DEBUG, "nl80211: received invalid "
1299				   "radiotap frame (%d)", ret);
1300			return;
1301		}
1302		switch (iter.this_arg_index) {
1303		case IEEE80211_RADIOTAP_FLAGS:
1304			if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
1305				len -= 4;
1306			break;
1307		case IEEE80211_RADIOTAP_RX_FLAGS:
1308			rxflags = 1;
1309			break;
1310		case IEEE80211_RADIOTAP_TX_FLAGS:
1311			injected = 1;
1312			failed = le_to_host16((*(u16 *) iter.this_arg)) &
1313				IEEE80211_RADIOTAP_F_TX_FAIL;
1314			break;
1315		case IEEE80211_RADIOTAP_DATA_RETRIES:
1316			break;
1317		case IEEE80211_RADIOTAP_CHANNEL:
1318			/* TODO convert from freq/flags to channel number
1319			 * rx_status.channel = XXX;
1320			*/
1321			break;
1322		case IEEE80211_RADIOTAP_RATE:
1323			break;
1324		case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
1325			rx_status.ssi = *iter.this_arg;
1326			break;
1327		}
1328	}
1329
1330	if (rxflags && injected)
1331		return;
1332
1333	if (!injected) {
1334		wpa_supplicant_sta_rx(drv->ctx, buf + iter.max_length,
1335				      len - iter.max_length, &rx_status);
1336	} else if (failed) {
1337		/* TX failure callback */
1338	} else {
1339		/* TX success (ACK) callback */
1340	}
1341}
1342
1343
1344static int wpa_driver_nl80211_create_monitor_interface(
1345	struct wpa_driver_nl80211_data *drv)
1346{
1347	char buf[IFNAMSIZ];
1348	struct sockaddr_ll ll;
1349	int optval, flags;
1350	socklen_t optlen;
1351
1352	os_snprintf(buf, IFNAMSIZ, "mon.%s", drv->ifname);
1353	buf[IFNAMSIZ - 1] = '\0';
1354
1355	drv->monitor_ifidx =
1356		nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR);
1357
1358	if (drv->monitor_ifidx < 0)
1359		return -1;
1360
1361	if (wpa_driver_nl80211_get_ifflags_ifname(drv, buf, &flags) != 0 ||
1362	    wpa_driver_nl80211_set_ifflags_ifname(drv, buf, flags | IFF_UP) !=
1363	    0) {
1364		wpa_printf(MSG_ERROR, "nl80211: Could not set interface '%s' "
1365			   "UP", buf);
1366		goto error;
1367	}
1368
1369	os_memset(&ll, 0, sizeof(ll));
1370	ll.sll_family = AF_PACKET;
1371	ll.sll_ifindex = drv->monitor_ifidx;
1372	drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
1373	if (drv->monitor_sock < 0) {
1374		perror("socket[PF_PACKET,SOCK_RAW]");
1375		goto error;
1376	}
1377
1378	if (bind(drv->monitor_sock, (struct sockaddr *) &ll,
1379		 sizeof(ll)) < 0) {
1380		perror("monitor socket bind");
1381		goto error;
1382	}
1383
1384	optlen = sizeof(optval);
1385	optval = 20;
1386	if (setsockopt
1387	    (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
1388		perror("Failed to set socket priority");
1389		goto error;
1390	}
1391
1392	if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
1393				     drv, NULL)) {
1394		wpa_printf(MSG_ERROR, "nl80211: Could not register monitor "
1395			   "read socket");
1396		goto error;
1397	}
1398
1399	return 0;
1400
1401 error:
1402	nl80211_remove_iface(drv, drv->monitor_ifidx);
1403	return -1;
1404}
1405
1406#endif /* CONFIG_CLIENT_MLME */
1407
1408
1409/**
1410 * wpa_driver_nl80211_init - Initialize nl80211 driver interface
1411 * @ctx: context to be used when calling wpa_supplicant functions,
1412 * e.g., wpa_supplicant_event()
1413 * @ifname: interface name, e.g., wlan0
1414 * Returns: Pointer to private data, %NULL on failure
1415 */
1416static void * wpa_driver_nl80211_init(void *ctx, const char *ifname)
1417{
1418	int s, ret;
1419	struct sockaddr_nl local;
1420	struct wpa_driver_nl80211_data *drv;
1421
1422	drv = os_zalloc(sizeof(*drv));
1423	if (drv == NULL)
1424		return NULL;
1425	drv->ctx = ctx;
1426	os_strlcpy(drv->ifname, ifname, sizeof(drv->ifname));
1427
1428	drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
1429	if (drv->nl_cb == NULL) {
1430		wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1431			   "callbacks");
1432		goto err1;
1433	}
1434
1435	drv->nl_handle = nl_handle_alloc_cb(drv->nl_cb);
1436	if (drv->nl_handle == NULL) {
1437		wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1438			   "callbacks");
1439		goto err2;
1440	}
1441
1442	if (genl_connect(drv->nl_handle)) {
1443		wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
1444			   "netlink");
1445		goto err3;
1446	}
1447
1448	drv->nl_cache = genl_ctrl_alloc_cache(drv->nl_handle);
1449	if (drv->nl_cache == NULL) {
1450		wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1451			   "netlink cache");
1452		goto err3;
1453	}
1454
1455	drv->nl80211 = genl_ctrl_search_by_name(drv->nl_cache, "nl80211");
1456	if (drv->nl80211 == NULL) {
1457		wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
1458			   "found");
1459		goto err4;
1460	}
1461
1462	ret = nl_get_multicast_id(drv, "nl80211", "scan");
1463	if (ret >= 0)
1464		ret = nl_socket_add_membership(drv->nl_handle, ret);
1465	if (ret < 0) {
1466		wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
1467			   "membership for scan events: %d (%s)",
1468			   ret, strerror(-ret));
1469		goto err4;
1470	}
1471	eloop_register_read_sock(nl_socket_get_fd(drv->nl_handle),
1472				 wpa_driver_nl80211_event_receive, drv, ctx);
1473
1474	drv->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
1475	if (drv->ioctl_sock < 0) {
1476		perror("socket(PF_INET,SOCK_DGRAM)");
1477		goto err5;
1478	}
1479
1480	s = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
1481	if (s < 0) {
1482		perror("socket(PF_NETLINK,SOCK_RAW,NETLINK_ROUTE)");
1483		goto err6;
1484	}
1485
1486	os_memset(&local, 0, sizeof(local));
1487	local.nl_family = AF_NETLINK;
1488	local.nl_groups = RTMGRP_LINK;
1489	if (bind(s, (struct sockaddr *) &local, sizeof(local)) < 0) {
1490		perror("bind(netlink)");
1491		close(s);
1492		goto err6;
1493	}
1494
1495	eloop_register_read_sock(s, wpa_driver_nl80211_event_receive_wext, drv,
1496				 ctx);
1497	drv->wext_event_sock = s;
1498
1499	wpa_driver_nl80211_finish_drv_init(drv);
1500
1501	return drv;
1502
1503err6:
1504	close(drv->ioctl_sock);
1505err5:
1506	genl_family_put(drv->nl80211);
1507err4:
1508	nl_cache_free(drv->nl_cache);
1509err3:
1510	nl_handle_destroy(drv->nl_handle);
1511err2:
1512	nl_cb_put(drv->nl_cb);
1513err1:
1514	os_free(drv);
1515	return NULL;
1516}
1517
1518
1519static void
1520wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv)
1521{
1522	int flags;
1523
1524	drv->ifindex = if_nametoindex(drv->ifname);
1525
1526	if (wpa_driver_nl80211_set_mode(drv, 0) < 0) {
1527		printf("Could not configure driver to use managed mode\n");
1528	}
1529
1530	if (wpa_driver_nl80211_get_ifflags(drv, &flags) != 0)
1531		printf("Could not get interface '%s' flags\n", drv->ifname);
1532	else if (!(flags & IFF_UP)) {
1533		if (wpa_driver_nl80211_set_ifflags(drv, flags | IFF_UP) != 0) {
1534			printf("Could not set interface '%s' UP\n",
1535			       drv->ifname);
1536		}
1537	}
1538
1539	/*
1540	 * Make sure that the driver does not have any obsolete PMKID entries.
1541	 */
1542	wpa_driver_nl80211_flush_pmkid(drv);
1543
1544	wpa_driver_nl80211_get_range(drv);
1545
1546	wpa_driver_nl80211_send_oper_ifla(drv, 1, IF_OPER_DORMANT);
1547}
1548
1549
1550/**
1551 * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
1552 * @priv: Pointer to private nl80211 data from wpa_driver_nl80211_init()
1553 *
1554 * Shut down driver interface and processing of driver events. Free
1555 * private data buffer if one was allocated in wpa_driver_nl80211_init().
1556 */
1557static void wpa_driver_nl80211_deinit(void *priv)
1558{
1559	struct wpa_driver_nl80211_data *drv = priv;
1560	int flags;
1561
1562#ifdef CONFIG_CLIENT_MLME
1563	if (drv->monitor_sock >= 0) {
1564		eloop_unregister_read_sock(drv->monitor_sock);
1565		close(drv->monitor_sock);
1566	}
1567	if (drv->monitor_ifidx > 0)
1568		nl80211_remove_iface(drv, drv->monitor_ifidx);
1569	if (drv->capa.flags & WPA_DRIVER_FLAGS_USER_SPACE_MLME)
1570		wpa_driver_nl80211_set_userspace_mlme(drv, 0);
1571#endif /* CONFIG_CLIENT_MLME */
1572
1573	eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
1574
1575	/*
1576	 * Clear possibly configured driver parameters in order to make it
1577	 * easier to use the driver after wpa_supplicant has been terminated.
1578	 */
1579	(void) wpa_driver_nl80211_set_bssid(drv,
1580					 (u8 *) "\x00\x00\x00\x00\x00\x00");
1581
1582	wpa_driver_nl80211_send_oper_ifla(priv, 0, IF_OPER_UP);
1583
1584	eloop_unregister_read_sock(drv->wext_event_sock);
1585
1586	if (wpa_driver_nl80211_get_ifflags(drv, &flags) == 0)
1587		(void) wpa_driver_nl80211_set_ifflags(drv, flags & ~IFF_UP);
1588
1589	close(drv->wext_event_sock);
1590	close(drv->ioctl_sock);
1591	os_free(drv->assoc_req_ies);
1592	os_free(drv->assoc_resp_ies);
1593
1594	eloop_unregister_read_sock(nl_socket_get_fd(drv->nl_handle));
1595	genl_family_put(drv->nl80211);
1596	nl_cache_free(drv->nl_cache);
1597	nl_handle_destroy(drv->nl_handle);
1598	nl_cb_put(drv->nl_cb);
1599
1600	os_free(drv);
1601}
1602
1603
1604/**
1605 * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
1606 * @eloop_ctx: Unused
1607 * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
1608 *
1609 * This function can be used as registered timeout when starting a scan to
1610 * generate a scan completed event if the driver does not report this.
1611 */
1612static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
1613{
1614	wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
1615	wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
1616}
1617
1618
1619/**
1620 * wpa_driver_nl80211_scan - Request the driver to initiate scan
1621 * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
1622 * @ssid: Specific SSID to scan for (ProbeReq) or %NULL to scan for
1623 *	all SSIDs (either active scan with broadcast SSID or passive
1624 *	scan
1625 * @ssid_len: Length of the SSID
1626 * Returns: 0 on success, -1 on failure
1627 */
1628static int wpa_driver_nl80211_scan(void *priv, const u8 *ssid, size_t ssid_len)
1629{
1630	struct wpa_driver_nl80211_data *drv = priv;
1631	int ret = 0, timeout;
1632	struct nl_msg *msg, *ssids;
1633
1634	msg = nlmsg_alloc();
1635	ssids = nlmsg_alloc();
1636	if (!msg || !ssids) {
1637		nlmsg_free(msg);
1638		nlmsg_free(ssids);
1639		return -1;
1640	}
1641
1642	genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
1643		    NL80211_CMD_TRIGGER_SCAN, 0);
1644
1645	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1646
1647	if (ssid && ssid_len) {
1648		/* Request an active scan for a specific SSID */
1649		NLA_PUT(ssids, 1, ssid_len, ssid);
1650	} else {
1651		/* Request an active scan for wildcard SSID */
1652		NLA_PUT(ssids, 1, 0, "");
1653	}
1654	nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
1655
1656	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
1657	msg = NULL;
1658	if (ret) {
1659		wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
1660			   "(%s)", ret, strerror(-ret));
1661		goto nla_put_failure;
1662	}
1663
1664	/* Not all drivers generate "scan completed" wireless event, so try to
1665	 * read results after a timeout. */
1666	timeout = 10;
1667	if (drv->scan_complete_events) {
1668		/*
1669		 * The driver seems to deliver SIOCGIWSCAN events to notify
1670		 * when scan is complete, so use longer timeout to avoid race
1671		 * conditions with scanning and following association request.
1672		 */
1673		timeout = 30;
1674	}
1675	wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
1676		   "seconds", ret, timeout);
1677	eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
1678	eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
1679			       drv, drv->ctx);
1680
1681nla_put_failure:
1682	nlmsg_free(ssids);
1683	nlmsg_free(msg);
1684	return ret;
1685}
1686
1687
1688static int bss_info_handler(struct nl_msg *msg, void *arg)
1689{
1690	struct nlattr *tb[NL80211_ATTR_MAX + 1];
1691	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1692	struct nlattr *bss[NL80211_BSS_MAX + 1];
1693	static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
1694		[NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
1695		[NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
1696		[NL80211_BSS_TSF] = { .type = NLA_U64 },
1697		[NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
1698		[NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
1699		[NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
1700		[NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
1701		[NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
1702	};
1703	struct wpa_scan_results *res = arg;
1704	struct wpa_scan_res **tmp;
1705	struct wpa_scan_res *r;
1706	const u8 *ie;
1707	size_t ie_len;
1708
1709	nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1710		  genlmsg_attrlen(gnlh, 0), NULL);
1711	if (!tb[NL80211_ATTR_BSS])
1712		return NL_SKIP;
1713	if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
1714			     bss_policy))
1715		return NL_SKIP;
1716	if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
1717		ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
1718		ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
1719	} else {
1720		ie = NULL;
1721		ie_len = 0;
1722	}
1723
1724	r = os_zalloc(sizeof(*r) + ie_len);
1725	if (r == NULL)
1726		return NL_SKIP;
1727	if (bss[NL80211_BSS_BSSID])
1728		os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
1729			  ETH_ALEN);
1730	if (bss[NL80211_BSS_FREQUENCY])
1731		r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
1732	if (bss[NL80211_BSS_BEACON_INTERVAL])
1733		r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
1734	if (bss[NL80211_BSS_CAPABILITY])
1735		r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
1736	if (bss[NL80211_BSS_SIGNAL_UNSPEC])
1737		r->qual = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
1738	if (bss[NL80211_BSS_SIGNAL_MBM])
1739		r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
1740	if (bss[NL80211_BSS_TSF])
1741		r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
1742	r->ie_len = ie_len;
1743	if (ie)
1744		os_memcpy(r + 1, ie, ie_len);
1745
1746	tmp = os_realloc(res->res,
1747			 (res->num + 1) * sizeof(struct wpa_scan_res *));
1748	if (tmp == NULL) {
1749		os_free(r);
1750		return NL_SKIP;
1751	}
1752	tmp[res->num++] = r;
1753	res->res = tmp;
1754
1755	return NL_SKIP;
1756}
1757
1758
1759/**
1760 * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
1761 * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
1762 * Returns: Scan results on success, -1 on failure
1763 */
1764static struct wpa_scan_results *
1765wpa_driver_nl80211_get_scan_results(void *priv)
1766{
1767	struct wpa_driver_nl80211_data *drv = priv;
1768	struct nl_msg *msg;
1769	struct wpa_scan_results *res;
1770	int ret;
1771
1772	res = os_zalloc(sizeof(*res));
1773	if (res == NULL)
1774		return 0;
1775	msg = nlmsg_alloc();
1776	if (!msg)
1777		goto nla_put_failure;
1778
1779	genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, NLM_F_DUMP,
1780		    NL80211_CMD_GET_SCAN, 0);
1781	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1782
1783	ret = send_and_recv_msgs(drv, msg, bss_info_handler, res);
1784	msg = NULL;
1785	if (ret == 0) {
1786		wpa_printf(MSG_DEBUG, "Received scan results (%lu BSSes)",
1787			   (unsigned long) res->num);
1788		return res;
1789	}
1790	wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
1791		   "(%s)", ret, strerror(-ret));
1792nla_put_failure:
1793	nlmsg_free(msg);
1794	wpa_scan_results_free(res);
1795	return NULL;
1796}
1797
1798
1799static int wpa_driver_nl80211_get_range(void *priv)
1800{
1801	struct wpa_driver_nl80211_data *drv = priv;
1802	struct iw_range *range;
1803	struct iwreq iwr;
1804	int minlen;
1805	size_t buflen;
1806
1807	/*
1808	 * Use larger buffer than struct iw_range in order to allow the
1809	 * structure to grow in the future.
1810	 */
1811	buflen = sizeof(struct iw_range) + 500;
1812	range = os_zalloc(buflen);
1813	if (range == NULL)
1814		return -1;
1815
1816	os_memset(&iwr, 0, sizeof(iwr));
1817	os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
1818	iwr.u.data.pointer = (caddr_t) range;
1819	iwr.u.data.length = buflen;
1820
1821	minlen = ((char *) &range->enc_capa) - (char *) range +
1822		sizeof(range->enc_capa);
1823
1824	if (ioctl(drv->ioctl_sock, SIOCGIWRANGE, &iwr) < 0) {
1825		perror("ioctl[SIOCGIWRANGE]");
1826		os_free(range);
1827		return -1;
1828	} else if (iwr.u.data.length >= minlen &&
1829		   range->we_version_compiled >= 18) {
1830		wpa_printf(MSG_DEBUG, "SIOCGIWRANGE: WE(compiled)=%d "
1831			   "WE(source)=%d enc_capa=0x%x",
1832			   range->we_version_compiled,
1833			   range->we_version_source,
1834			   range->enc_capa);
1835		drv->has_capability = 1;
1836		drv->we_version_compiled = range->we_version_compiled;
1837		if (range->enc_capa & IW_ENC_CAPA_WPA) {
1838			drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_WPA |
1839				WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK;
1840		}
1841		if (range->enc_capa & IW_ENC_CAPA_WPA2) {
1842			drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_WPA2 |
1843				WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK;
1844		}
1845		drv->capa.enc |= WPA_DRIVER_CAPA_ENC_WEP40 |
1846			WPA_DRIVER_CAPA_ENC_WEP104;
1847		if (range->enc_capa & IW_ENC_CAPA_CIPHER_TKIP)
1848			drv->capa.enc |= WPA_DRIVER_CAPA_ENC_TKIP;
1849		if (range->enc_capa & IW_ENC_CAPA_CIPHER_CCMP)
1850			drv->capa.enc |= WPA_DRIVER_CAPA_ENC_CCMP;
1851		drv->capa.auth = WPA_DRIVER_AUTH_OPEN |
1852			WPA_DRIVER_AUTH_SHARED |
1853			WPA_DRIVER_AUTH_LEAP;
1854		wpa_printf(MSG_DEBUG, "  capabilities: key_mgmt 0x%x enc 0x%x",
1855			   drv->capa.key_mgmt, drv->capa.enc);
1856	} else {
1857		wpa_printf(MSG_DEBUG, "SIOCGIWRANGE: too old (short) data - "
1858			   "assuming WPA is not supported");
1859	}
1860
1861	os_free(range);
1862	return 0;
1863}
1864
1865
1866static int wpa_driver_nl80211_set_wpa(void *priv, int enabled)
1867{
1868	struct wpa_driver_nl80211_data *drv = priv;
1869	wpa_printf(MSG_DEBUG, "%s", __FUNCTION__);
1870
1871	return wpa_driver_nl80211_set_auth_param(drv, IW_AUTH_WPA_ENABLED,
1872					      enabled);
1873}
1874
1875
1876static int wpa_driver_nl80211_set_key(void *priv, wpa_alg alg,
1877				      const u8 *addr, int key_idx,
1878				      int set_tx, const u8 *seq,
1879				      size_t seq_len,
1880				      const u8 *key, size_t key_len)
1881{
1882	struct wpa_driver_nl80211_data *drv = priv;
1883	int err;
1884	struct nl_msg *msg;
1885
1886	wpa_printf(MSG_DEBUG, "%s: alg=%d addr=%p key_idx=%d set_tx=%d "
1887		   "seq_len=%lu key_len=%lu",
1888		   __func__, alg, addr, key_idx, set_tx,
1889		   (unsigned long) seq_len, (unsigned long) key_len);
1890
1891	msg = nlmsg_alloc();
1892	if (msg == NULL)
1893		return -1;
1894
1895	if (alg == WPA_ALG_NONE) {
1896		genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
1897			    NL80211_CMD_DEL_KEY, 0);
1898	} else {
1899		genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
1900			    NL80211_CMD_NEW_KEY, 0);
1901		NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
1902		switch (alg) {
1903		case WPA_ALG_WEP:
1904			if (key_len == 5)
1905				NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
1906					    0x000FAC01);
1907			else
1908				NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
1909					    0x000FAC05);
1910			break;
1911		case WPA_ALG_TKIP:
1912			NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER, 0x000FAC02);
1913			break;
1914		case WPA_ALG_CCMP:
1915			NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER, 0x000FAC04);
1916			break;
1917#ifdef CONFIG_IEEE80211W
1918		case WPA_ALG_IGTK:
1919			NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER, 0x000FAC06);
1920			break;
1921#endif /* CONFIG_IEEE80211W */
1922		default:
1923			nlmsg_free(msg);
1924			return -1;
1925		}
1926	}
1927
1928	if (addr && os_memcmp(addr, "\xff\xff\xff\xff\xff\xff", ETH_ALEN) != 0)
1929	{
1930		wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
1931		NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
1932	}
1933	NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
1934	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1935
1936	err = send_and_recv_msgs(drv, msg, NULL, NULL);
1937	if (err) {
1938		wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d", err);
1939		return -1;
1940	}
1941
1942	if (set_tx && alg != WPA_ALG_NONE) {
1943		msg = nlmsg_alloc();
1944		if (msg == NULL)
1945			return -1;
1946
1947		genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1948			    0, NL80211_CMD_SET_KEY, 0);
1949		NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
1950		NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1951		NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
1952
1953		err = send_and_recv_msgs(drv, msg, NULL, NULL);
1954		if (err) {
1955			wpa_printf(MSG_DEBUG, "nl80211: set default key "
1956				   "failed; err=%d", err);
1957			return -1;
1958		}
1959	}
1960
1961	return 0;
1962
1963nla_put_failure:
1964	return -ENOBUFS;
1965}
1966
1967
1968static int wpa_driver_nl80211_set_countermeasures(void *priv,
1969					       int enabled)
1970{
1971	struct wpa_driver_nl80211_data *drv = priv;
1972	wpa_printf(MSG_DEBUG, "%s", __FUNCTION__);
1973	return wpa_driver_nl80211_set_auth_param(drv,
1974					      IW_AUTH_TKIP_COUNTERMEASURES,
1975					      enabled);
1976}
1977
1978
1979static int wpa_driver_nl80211_set_drop_unencrypted(void *priv,
1980						int enabled)
1981{
1982	struct wpa_driver_nl80211_data *drv = priv;
1983	wpa_printf(MSG_DEBUG, "%s", __FUNCTION__);
1984	drv->use_crypt = enabled;
1985	return wpa_driver_nl80211_set_auth_param(drv, IW_AUTH_DROP_UNENCRYPTED,
1986					      enabled);
1987}
1988
1989
1990static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
1991				const u8 *addr, int cmd, int reason_code)
1992{
1993	struct iwreq iwr;
1994	struct iw_mlme mlme;
1995	int ret = 0;
1996
1997	os_memset(&iwr, 0, sizeof(iwr));
1998	os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
1999	os_memset(&mlme, 0, sizeof(mlme));
2000	mlme.cmd = cmd;
2001	mlme.reason_code = reason_code;
2002	mlme.addr.sa_family = ARPHRD_ETHER;
2003	os_memcpy(mlme.addr.sa_data, addr, ETH_ALEN);
2004	iwr.u.data.pointer = (caddr_t) &mlme;
2005	iwr.u.data.length = sizeof(mlme);
2006
2007	if (ioctl(drv->ioctl_sock, SIOCSIWMLME, &iwr) < 0) {
2008		perror("ioctl[SIOCSIWMLME]");
2009		ret = -1;
2010	}
2011
2012	return ret;
2013}
2014
2015
2016static int wpa_driver_nl80211_deauthenticate(void *priv, const u8 *addr,
2017					  int reason_code)
2018{
2019	struct wpa_driver_nl80211_data *drv = priv;
2020	wpa_printf(MSG_DEBUG, "%s", __FUNCTION__);
2021	return wpa_driver_nl80211_mlme(drv, addr, IW_MLME_DEAUTH, reason_code);
2022}
2023
2024
2025static int wpa_driver_nl80211_disassociate(void *priv, const u8 *addr,
2026					int reason_code)
2027{
2028	struct wpa_driver_nl80211_data *drv = priv;
2029	wpa_printf(MSG_DEBUG, "%s", __FUNCTION__);
2030	return wpa_driver_nl80211_mlme(drv, addr, IW_MLME_DISASSOC,
2031				    reason_code);
2032}
2033
2034
2035static int wpa_driver_nl80211_set_gen_ie(void *priv, const u8 *ie,
2036				      size_t ie_len)
2037{
2038	struct wpa_driver_nl80211_data *drv = priv;
2039	struct iwreq iwr;
2040	int ret = 0;
2041
2042	os_memset(&iwr, 0, sizeof(iwr));
2043	os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
2044	iwr.u.data.pointer = (caddr_t) ie;
2045	iwr.u.data.length = ie_len;
2046
2047	if (ioctl(drv->ioctl_sock, SIOCSIWGENIE, &iwr) < 0) {
2048		perror("ioctl[SIOCSIWGENIE]");
2049		ret = -1;
2050	}
2051
2052	return ret;
2053}
2054
2055
2056static int wpa_driver_nl80211_cipher2wext(int cipher)
2057{
2058	switch (cipher) {
2059	case CIPHER_NONE:
2060		return IW_AUTH_CIPHER_NONE;
2061	case CIPHER_WEP40:
2062		return IW_AUTH_CIPHER_WEP40;
2063	case CIPHER_TKIP:
2064		return IW_AUTH_CIPHER_TKIP;
2065	case CIPHER_CCMP:
2066		return IW_AUTH_CIPHER_CCMP;
2067	case CIPHER_WEP104:
2068		return IW_AUTH_CIPHER_WEP104;
2069	default:
2070		return 0;
2071	}
2072}
2073
2074
2075static int wpa_driver_nl80211_keymgmt2wext(int keymgmt)
2076{
2077	switch (keymgmt) {
2078	case KEY_MGMT_802_1X:
2079	case KEY_MGMT_802_1X_NO_WPA:
2080		return IW_AUTH_KEY_MGMT_802_1X;
2081	case KEY_MGMT_PSK:
2082		return IW_AUTH_KEY_MGMT_PSK;
2083	default:
2084		return 0;
2085	}
2086}
2087
2088
2089static int
2090wpa_driver_nl80211_auth_alg_fallback(struct wpa_driver_nl80211_data *drv,
2091				  struct wpa_driver_associate_params *params)
2092{
2093	struct iwreq iwr;
2094	int ret = 0;
2095
2096	wpa_printf(MSG_DEBUG, "WEXT: Driver did not support "
2097		   "SIOCSIWAUTH for AUTH_ALG, trying SIOCSIWENCODE");
2098
2099	os_memset(&iwr, 0, sizeof(iwr));
2100	os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
2101	/* Just changing mode, not actual keys */
2102	iwr.u.encoding.flags = 0;
2103	iwr.u.encoding.pointer = (caddr_t) NULL;
2104	iwr.u.encoding.length = 0;
2105
2106	/*
2107	 * Note: IW_ENCODE_{OPEN,RESTRICTED} can be interpreted to mean two
2108	 * different things. Here they are used to indicate Open System vs.
2109	 * Shared Key authentication algorithm. However, some drivers may use
2110	 * them to select between open/restricted WEP encrypted (open = allow
2111	 * both unencrypted and encrypted frames; restricted = only allow
2112	 * encrypted frames).
2113	 */
2114
2115	if (!drv->use_crypt) {
2116		iwr.u.encoding.flags |= IW_ENCODE_DISABLED;
2117	} else {
2118		if (params->auth_alg & AUTH_ALG_OPEN_SYSTEM)
2119			iwr.u.encoding.flags |= IW_ENCODE_OPEN;
2120		if (params->auth_alg & AUTH_ALG_SHARED_KEY)
2121			iwr.u.encoding.flags |= IW_ENCODE_RESTRICTED;
2122	}
2123
2124	if (ioctl(drv->ioctl_sock, SIOCSIWENCODE, &iwr) < 0) {
2125		perror("ioctl[SIOCSIWENCODE]");
2126		ret = -1;
2127	}
2128
2129	return ret;
2130}
2131
2132
2133static int wpa_driver_nl80211_associate(
2134	void *priv, struct wpa_driver_associate_params *params)
2135{
2136	struct wpa_driver_nl80211_data *drv = priv;
2137	int ret = 0;
2138	int allow_unencrypted_eapol;
2139	int value;
2140
2141	wpa_printf(MSG_DEBUG, "%s", __FUNCTION__);
2142
2143	/*
2144	 * If the driver did not support SIOCSIWAUTH, fallback to
2145	 * SIOCSIWENCODE here.
2146	 */
2147	if (drv->auth_alg_fallback &&
2148	    wpa_driver_nl80211_auth_alg_fallback(drv, params) < 0)
2149		ret = -1;
2150
2151	if (!params->bssid &&
2152	    wpa_driver_nl80211_set_bssid(drv, NULL) < 0)
2153		ret = -1;
2154
2155	/* TODO: should consider getting wpa version and cipher/key_mgmt suites
2156	 * from configuration, not from here, where only the selected suite is
2157	 * available */
2158	if (wpa_driver_nl80211_set_gen_ie(drv, params->wpa_ie, params->wpa_ie_len)
2159	    < 0)
2160		ret = -1;
2161	if (params->wpa_ie == NULL || params->wpa_ie_len == 0)
2162		value = IW_AUTH_WPA_VERSION_DISABLED;
2163	else if (params->wpa_ie[0] == WLAN_EID_RSN)
2164		value = IW_AUTH_WPA_VERSION_WPA2;
2165	else
2166		value = IW_AUTH_WPA_VERSION_WPA;
2167	if (wpa_driver_nl80211_set_auth_param(drv,
2168					   IW_AUTH_WPA_VERSION, value) < 0)
2169		ret = -1;
2170	value = wpa_driver_nl80211_cipher2wext(params->pairwise_suite);
2171	if (wpa_driver_nl80211_set_auth_param(drv,
2172					   IW_AUTH_CIPHER_PAIRWISE, value) < 0)
2173		ret = -1;
2174	value = wpa_driver_nl80211_cipher2wext(params->group_suite);
2175	if (wpa_driver_nl80211_set_auth_param(drv,
2176					   IW_AUTH_CIPHER_GROUP, value) < 0)
2177		ret = -1;
2178	value = wpa_driver_nl80211_keymgmt2wext(params->key_mgmt_suite);
2179	if (wpa_driver_nl80211_set_auth_param(drv,
2180					   IW_AUTH_KEY_MGMT, value) < 0)
2181		ret = -1;
2182	value = params->key_mgmt_suite != KEY_MGMT_NONE ||
2183		params->pairwise_suite != CIPHER_NONE ||
2184		params->group_suite != CIPHER_NONE ||
2185		params->wpa_ie_len;
2186	if (wpa_driver_nl80211_set_auth_param(drv,
2187					   IW_AUTH_PRIVACY_INVOKED, value) < 0)
2188		ret = -1;
2189
2190	/* Allow unencrypted EAPOL messages even if pairwise keys are set when
2191	 * not using WPA. IEEE 802.1X specifies that these frames are not
2192	 * encrypted, but WPA encrypts them when pairwise keys are in use. */
2193	if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
2194	    params->key_mgmt_suite == KEY_MGMT_PSK)
2195		allow_unencrypted_eapol = 0;
2196	else
2197		allow_unencrypted_eapol = 1;
2198
2199	if (wpa_driver_nl80211_set_auth_param(drv,
2200					   IW_AUTH_RX_UNENCRYPTED_EAPOL,
2201					   allow_unencrypted_eapol) < 0)
2202		ret = -1;
2203	if (params->freq && wpa_driver_nl80211_set_freq(drv, params->freq) < 0)
2204		ret = -1;
2205	if (wpa_driver_nl80211_set_ssid(drv, params->ssid, params->ssid_len) < 0)
2206		ret = -1;
2207	if (params->bssid &&
2208	    wpa_driver_nl80211_set_bssid(drv, params->bssid) < 0)
2209		ret = -1;
2210
2211	return ret;
2212}
2213
2214
2215static int wpa_driver_nl80211_set_auth_alg(void *priv, int auth_alg)
2216{
2217	struct wpa_driver_nl80211_data *drv = priv;
2218	int algs = 0, res;
2219
2220	if (auth_alg & AUTH_ALG_OPEN_SYSTEM)
2221		algs |= IW_AUTH_ALG_OPEN_SYSTEM;
2222	if (auth_alg & AUTH_ALG_SHARED_KEY)
2223		algs |= IW_AUTH_ALG_SHARED_KEY;
2224	if (auth_alg & AUTH_ALG_LEAP)
2225		algs |= IW_AUTH_ALG_LEAP;
2226	if (algs == 0) {
2227		/* at least one algorithm should be set */
2228		algs = IW_AUTH_ALG_OPEN_SYSTEM;
2229	}
2230
2231	res = wpa_driver_nl80211_set_auth_param(drv, IW_AUTH_80211_AUTH_ALG,
2232					     algs);
2233	drv->auth_alg_fallback = res == -2;
2234	return res;
2235}
2236
2237
2238/**
2239 * wpa_driver_nl80211_set_mode - Set wireless mode (infra/adhoc), SIOCSIWMODE
2240 * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
2241 * @mode: 0 = infra/BSS (associate with an AP), 1 = adhoc/IBSS
2242 * Returns: 0 on success, -1 on failure
2243 */
2244static int wpa_driver_nl80211_set_mode(void *priv, int mode)
2245{
2246	struct wpa_driver_nl80211_data *drv = priv;
2247	int ret = -1, flags;
2248	struct nl_msg *msg;
2249
2250	msg = nlmsg_alloc();
2251	if (!msg)
2252		return -1;
2253
2254	genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2255		    0, NL80211_CMD_SET_INTERFACE, 0);
2256	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2257	NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE,
2258		    mode ? NL80211_IFTYPE_ADHOC : NL80211_IFTYPE_STATION);
2259
2260	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2261	if (!ret)
2262		return 0;
2263	else
2264		goto try_again;
2265
2266nla_put_failure:
2267	wpa_printf(MSG_ERROR, "nl80211: Failed to set interface mode: %d (%s)",
2268		   ret, strerror(-ret));
2269	return -1;
2270
2271try_again:
2272	/* mac80211 doesn't allow mode changes while the device is up, so
2273	 * take the device down, try to set the mode again, and bring the
2274	 * device back up.
2275	 */
2276	if (wpa_driver_nl80211_get_ifflags(drv, &flags) == 0) {
2277		(void) wpa_driver_nl80211_set_ifflags(drv, flags & ~IFF_UP);
2278
2279		/* Try to set the mode again while the interface is down */
2280		msg = nlmsg_alloc();
2281		if (!msg)
2282			return -1;
2283
2284		genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2285			    0, NL80211_CMD_SET_INTERFACE, 0);
2286		NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2287		NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE,
2288			    mode ? NL80211_IFTYPE_ADHOC :
2289			    NL80211_IFTYPE_STATION);
2290		ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2291		if (ret) {
2292			wpa_printf(MSG_ERROR, "Failed to set interface %s "
2293				   "mode(try_again): %d (%s)",
2294				   drv->ifname, ret, strerror(-ret));
2295		}
2296
2297		/* Ignore return value of get_ifflags to ensure that the device
2298		 * is always up like it was before this function was called.
2299		 */
2300		(void) wpa_driver_nl80211_get_ifflags(drv, &flags);
2301		(void) wpa_driver_nl80211_set_ifflags(drv, flags | IFF_UP);
2302	}
2303
2304	return ret;
2305}
2306
2307
2308static int wpa_driver_nl80211_pmksa(struct wpa_driver_nl80211_data *drv,
2309				 u32 cmd, const u8 *bssid, const u8 *pmkid)
2310{
2311	struct iwreq iwr;
2312	struct iw_pmksa pmksa;
2313	int ret = 0;
2314
2315	os_memset(&iwr, 0, sizeof(iwr));
2316	os_strlcpy(iwr.ifr_name, drv->ifname, IFNAMSIZ);
2317	os_memset(&pmksa, 0, sizeof(pmksa));
2318	pmksa.cmd = cmd;
2319	pmksa.bssid.sa_family = ARPHRD_ETHER;
2320	if (bssid)
2321		os_memcpy(pmksa.bssid.sa_data, bssid, ETH_ALEN);
2322	if (pmkid)
2323		os_memcpy(pmksa.pmkid, pmkid, IW_PMKID_LEN);
2324	iwr.u.data.pointer = (caddr_t) &pmksa;
2325	iwr.u.data.length = sizeof(pmksa);
2326
2327	if (ioctl(drv->ioctl_sock, SIOCSIWPMKSA, &iwr) < 0) {
2328		if (errno != EOPNOTSUPP)
2329			perror("ioctl[SIOCSIWPMKSA]");
2330		ret = -1;
2331	}
2332
2333	return ret;
2334}
2335
2336
2337static int wpa_driver_nl80211_add_pmkid(void *priv, const u8 *bssid,
2338				     const u8 *pmkid)
2339{
2340	struct wpa_driver_nl80211_data *drv = priv;
2341	return wpa_driver_nl80211_pmksa(drv, IW_PMKSA_ADD, bssid, pmkid);
2342}
2343
2344
2345static int wpa_driver_nl80211_remove_pmkid(void *priv, const u8 *bssid,
2346		 			const u8 *pmkid)
2347{
2348	struct wpa_driver_nl80211_data *drv = priv;
2349	return wpa_driver_nl80211_pmksa(drv, IW_PMKSA_REMOVE, bssid, pmkid);
2350}
2351
2352
2353static int wpa_driver_nl80211_flush_pmkid(void *priv)
2354{
2355	struct wpa_driver_nl80211_data *drv = priv;
2356	return wpa_driver_nl80211_pmksa(drv, IW_PMKSA_FLUSH, NULL, NULL);
2357}
2358
2359
2360static int wpa_driver_nl80211_get_capa(void *priv,
2361				       struct wpa_driver_capa *capa)
2362{
2363	struct wpa_driver_nl80211_data *drv = priv;
2364	if (!drv->has_capability)
2365		return -1;
2366	os_memcpy(capa, &drv->capa, sizeof(*capa));
2367	return 0;
2368}
2369
2370
2371static int wpa_driver_nl80211_set_operstate(void *priv, int state)
2372{
2373	struct wpa_driver_nl80211_data *drv = priv;
2374
2375	wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
2376		   __func__, drv->operstate, state, state ? "UP" : "DORMANT");
2377	drv->operstate = state;
2378	return wpa_driver_nl80211_send_oper_ifla(
2379		drv, -1, state ? IF_OPER_UP : IF_OPER_DORMANT);
2380}
2381
2382
2383#ifdef CONFIG_CLIENT_MLME
2384static int wpa_driver_nl80211_open_mlme(struct wpa_driver_nl80211_data *drv)
2385{
2386	if (wpa_driver_nl80211_set_userspace_mlme(drv, 1) < 0) {
2387		wpa_printf(MSG_ERROR, "nl80211: Failed to enable userspace "
2388			   "MLME");
2389		return -1;
2390	}
2391	if (wpa_driver_nl80211_create_monitor_interface(drv)) {
2392		wpa_printf(MSG_ERROR, "nl80211: Failed to create monitor "
2393			   "interface");
2394		return -1;
2395	}
2396	return 0;
2397}
2398#endif /* CONFIG_CLIENT_MLME */
2399
2400
2401static int wpa_driver_nl80211_set_param(void *priv, const char *param)
2402{
2403#ifdef CONFIG_CLIENT_MLME
2404	struct wpa_driver_nl80211_data *drv = priv;
2405
2406	if (param == NULL)
2407		return 0;
2408
2409	wpa_printf(MSG_DEBUG, "%s: param='%s'", __func__, param);
2410
2411	if (os_strstr(param, "use_mlme=1")) {
2412		wpa_printf(MSG_DEBUG, "nl80211: Using user space MLME");
2413		drv->capa.flags |= WPA_DRIVER_FLAGS_USER_SPACE_MLME;
2414
2415		if (wpa_driver_nl80211_open_mlme(drv))
2416			return -1;
2417	}
2418#endif /* CONFIG_CLIENT_MLME */
2419
2420	return 0;
2421}
2422
2423
2424#ifdef CONFIG_CLIENT_MLME
2425
2426struct phy_info_arg {
2427	u16 *num_modes;
2428	struct wpa_hw_modes *modes;
2429};
2430
2431
2432static int phy_info_handler(struct nl_msg *msg, void *arg)
2433{
2434	struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
2435	struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2436	struct phy_info_arg *phy_info = arg;
2437
2438	struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
2439
2440	struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
2441	static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1]
2442		= {
2443		[NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
2444		[NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
2445		[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
2446		[NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
2447		[NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
2448	};
2449
2450	struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
2451	static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
2452		[NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
2453		[NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] =
2454		{ .type = NLA_FLAG },
2455	};
2456
2457	struct nlattr *nl_band;
2458	struct nlattr *nl_freq;
2459	struct nlattr *nl_rate;
2460	int rem_band, rem_freq, rem_rate;
2461	struct wpa_hw_modes *mode;
2462	int idx, mode_is_set;
2463
2464	nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2465		  genlmsg_attrlen(gnlh, 0), NULL);
2466
2467	if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
2468		return NL_SKIP;
2469
2470	nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS],
2471			    rem_band) {
2472		mode = os_realloc(phy_info->modes,
2473				  (*phy_info->num_modes + 1) * sizeof(*mode));
2474		if (!mode)
2475			return NL_SKIP;
2476		phy_info->modes = mode;
2477
2478		mode_is_set = 0;
2479
2480		mode = &phy_info->modes[*(phy_info->num_modes)];
2481		os_memset(mode, 0, sizeof(*mode));
2482		*(phy_info->num_modes) += 1;
2483
2484		nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
2485			  nla_len(nl_band), NULL);
2486
2487		nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS],
2488				    rem_freq) {
2489			nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX,
2490				  nla_data(nl_freq), nla_len(nl_freq),
2491				  freq_policy);
2492			if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
2493				continue;
2494			mode->num_channels++;
2495		}
2496
2497		mode->channels = os_zalloc(mode->num_channels *
2498					   sizeof(struct wpa_channel_data));
2499		if (!mode->channels)
2500			return NL_SKIP;
2501
2502		idx = 0;
2503
2504		nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS],
2505				    rem_freq) {
2506			nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX,
2507				  nla_data(nl_freq), nla_len(nl_freq),
2508				  freq_policy);
2509			if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
2510				continue;
2511
2512			mode->channels[idx].freq = nla_get_u32(
2513				tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
2514			mode->channels[idx].flag |= WPA_CHAN_W_SCAN |
2515				WPA_CHAN_W_ACTIVE_SCAN |
2516				WPA_CHAN_W_IBSS;
2517
2518			if (!mode_is_set) {
2519				/* crude heuristic */
2520				if (mode->channels[idx].freq < 4000)
2521					mode->mode = WPA_MODE_IEEE80211B;
2522				else
2523					mode->mode = WPA_MODE_IEEE80211A;
2524				mode_is_set = 1;
2525			}
2526
2527			/* crude heuristic */
2528			if (mode->channels[idx].freq < 4000) {
2529				if (mode->channels[idx].freq == 2484)
2530					mode->channels[idx].chan = 14;
2531				else
2532					mode->channels[idx].chan =
2533						(mode->channels[idx].freq -
2534						 2407) / 5;
2535			} else
2536				mode->channels[idx].chan =
2537					mode->channels[idx].freq / 5 - 1000;
2538
2539			if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
2540				mode->channels[idx].flag &= ~WPA_CHAN_W_SCAN;
2541			if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
2542				mode->channels[idx].flag &=
2543					~WPA_CHAN_W_ACTIVE_SCAN;
2544			if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
2545				mode->channels[idx].flag &= ~WPA_CHAN_W_IBSS;
2546			idx++;
2547		}
2548
2549		nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES],
2550				    rem_rate) {
2551			nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX,
2552				  nla_data(nl_rate), nla_len(nl_rate),
2553				  rate_policy);
2554			if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
2555				continue;
2556			mode->num_rates++;
2557		}
2558
2559		mode->rates = os_zalloc(mode->num_rates *
2560					sizeof(struct wpa_rate_data));
2561		if (!mode->rates)
2562			return NL_SKIP;
2563
2564		idx = 0;
2565
2566		nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES],
2567				    rem_rate) {
2568			nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX,
2569				  nla_data(nl_rate), nla_len(nl_rate),
2570				  rate_policy);
2571			if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
2572				continue;
2573			mode->rates[idx].rate = nla_get_u32(
2574				tb_rate[NL80211_BITRATE_ATTR_RATE]);
2575
2576			/* crude heuristic */
2577			if (mode->mode == WPA_MODE_IEEE80211B &&
2578			    mode->rates[idx].rate > 200)
2579				mode->mode = WPA_MODE_IEEE80211G;
2580
2581			if (tb_rate[NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE])
2582				mode->rates[idx].flags |= WPA_RATE_PREAMBLE2;
2583
2584			idx++;
2585		}
2586	}
2587
2588	return NL_SKIP;
2589}
2590
2591
2592static struct wpa_hw_modes *
2593wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
2594{
2595	struct wpa_driver_nl80211_data *drv = priv;
2596	struct nl_msg *msg;
2597	struct phy_info_arg result = {
2598		.num_modes = num_modes,
2599		.modes = NULL,
2600	};
2601
2602	*num_modes = 0;
2603	*flags = 0;
2604
2605	msg = nlmsg_alloc();
2606	if (!msg)
2607		return NULL;
2608
2609	genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2610		    0, NL80211_CMD_GET_WIPHY, 0);
2611
2612	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2613
2614	if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0)
2615		return result.modes;
2616nla_put_failure:
2617	return NULL;
2618}
2619
2620
2621static int wpa_driver_nl80211_set_channel(void *priv, wpa_hw_mode phymode,
2622					  int chan, int freq)
2623{
2624	return wpa_driver_nl80211_set_freq(priv, freq);
2625}
2626
2627
2628static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
2629					size_t data_len)
2630{
2631	struct wpa_driver_nl80211_data *drv = priv;
2632	__u8 rtap_hdr[] = {
2633		0x00, 0x00, /* radiotap version */
2634		0x0e, 0x00, /* radiotap length */
2635		0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
2636		0x0c,       /* F_WEP | F_FRAG (encrypt/fragment if required) */
2637		0x00,       /* padding */
2638		0x00, 0x00, /* RX and TX flags to indicate that */
2639		0x00, 0x00, /* this is the injected frame directly */
2640	};
2641	struct iovec iov[2] = {
2642		{
2643			.iov_base = &rtap_hdr,
2644			.iov_len = sizeof(rtap_hdr),
2645		},
2646		{
2647			.iov_base = (void *) data,
2648			.iov_len = data_len,
2649		}
2650	};
2651	struct msghdr msg = {
2652		.msg_name = NULL,
2653		.msg_namelen = 0,
2654		.msg_iov = iov,
2655		.msg_iovlen = 2,
2656		.msg_control = NULL,
2657		.msg_controllen = 0,
2658		.msg_flags = 0,
2659	};
2660
2661	if (sendmsg(drv->monitor_sock, &msg, 0) < 0) {
2662		perror("send[MLME]");
2663		return -1;
2664	}
2665
2666	return 0;
2667}
2668
2669
2670static int wpa_driver_nl80211_mlme_add_sta(void *priv, const u8 *addr,
2671					   const u8 *supp_rates,
2672					   size_t supp_rates_len)
2673{
2674	struct wpa_driver_nl80211_data *drv = priv;
2675	struct nl_msg *msg;
2676	int ret = -1;
2677
2678	msg = nlmsg_alloc();
2679	if (!msg)
2680		return -ENOMEM;
2681
2682	genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2683		    0, NL80211_CMD_NEW_STATION, 0);
2684
2685	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2686	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
2687	/* TODO: Get proper Association ID and listen interval */
2688	NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, 1);
2689	NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, supp_rates_len,
2690		supp_rates);
2691	NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL, 1);
2692
2693	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2694	/* ignore EEXIST, this happens if a STA associates while associated */
2695	if (ret == -EEXIST || ret >= 0)
2696		ret = 0;
2697
2698nla_put_failure:
2699	return ret;
2700}
2701
2702
2703static int wpa_driver_nl80211_mlme_remove_sta(void *priv, const u8 *addr)
2704{
2705	struct wpa_driver_nl80211_data *drv = priv;
2706	struct nl_msg *msg;
2707	int ret = -1;
2708
2709	msg = nlmsg_alloc();
2710	if (!msg)
2711		return -ENOMEM;
2712
2713	genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2714		    0, NL80211_CMD_DEL_STATION, 0);
2715
2716	NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2717	NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
2718
2719	ret = 0;
2720
2721	ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2722	return ret;
2723
2724nla_put_failure:
2725	return -ENOBUFS;
2726}
2727
2728#endif /* CONFIG_CLIENT_MLME */
2729
2730
2731const struct wpa_driver_ops wpa_driver_nl80211_ops = {
2732	.name = "nl80211",
2733	.desc = "Linux nl80211/cfg80211",
2734	.get_bssid = wpa_driver_nl80211_get_bssid,
2735	.get_ssid = wpa_driver_nl80211_get_ssid,
2736	.set_wpa = wpa_driver_nl80211_set_wpa,
2737	.set_key = wpa_driver_nl80211_set_key,
2738	.set_countermeasures = wpa_driver_nl80211_set_countermeasures,
2739	.set_drop_unencrypted = wpa_driver_nl80211_set_drop_unencrypted,
2740	.scan = wpa_driver_nl80211_scan,
2741	.get_scan_results2 = wpa_driver_nl80211_get_scan_results,
2742	.deauthenticate = wpa_driver_nl80211_deauthenticate,
2743	.disassociate = wpa_driver_nl80211_disassociate,
2744	.set_mode = wpa_driver_nl80211_set_mode,
2745	.associate = wpa_driver_nl80211_associate,
2746	.set_auth_alg = wpa_driver_nl80211_set_auth_alg,
2747	.init = wpa_driver_nl80211_init,
2748	.deinit = wpa_driver_nl80211_deinit,
2749	.set_param = wpa_driver_nl80211_set_param,
2750	.add_pmkid = wpa_driver_nl80211_add_pmkid,
2751	.remove_pmkid = wpa_driver_nl80211_remove_pmkid,
2752	.flush_pmkid = wpa_driver_nl80211_flush_pmkid,
2753	.get_capa = wpa_driver_nl80211_get_capa,
2754	.set_operstate = wpa_driver_nl80211_set_operstate,
2755	.set_country = wpa_driver_nl80211_set_country,
2756	.set_probe_req_ie = wpa_driver_nl80211_set_probe_req_ie,
2757#ifdef CONFIG_CLIENT_MLME
2758	.get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
2759	.set_channel = wpa_driver_nl80211_set_channel,
2760	.set_ssid = wpa_driver_nl80211_set_ssid,
2761	.set_bssid = wpa_driver_nl80211_set_bssid,
2762	.send_mlme = wpa_driver_nl80211_send_mlme,
2763	.mlme_add_sta = wpa_driver_nl80211_mlme_add_sta,
2764	.mlme_remove_sta = wpa_driver_nl80211_mlme_remove_sta,
2765#endif /* CONFIG_CLIENT_MLME */
2766};
2767