nl80211: Implement deauth/disassoc for non-HOSTAPD case
[mech_eap.git] / src / drivers / driver_nl80211.c
1 /*
2  * Driver interaction with Linux nl80211/cfg80211
3  * Copyright (c) 2002-2010, 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 program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * Alternatively, this software may be distributed under the terms of BSD
14  * license.
15  *
16  * See README and COPYING for more details.
17  */
18
19 #include "includes.h"
20 #include <sys/ioctl.h>
21 #include <sys/types.h>
22 #include <sys/stat.h>
23 #include <fcntl.h>
24 #include <net/if.h>
25 #include <netlink/genl/genl.h>
26 #include <netlink/genl/family.h>
27 #include <netlink/genl/ctrl.h>
28 #include <linux/rtnetlink.h>
29 #include <netpacket/packet.h>
30 #include <linux/filter.h>
31 #include "nl80211_copy.h"
32
33 #include "common.h"
34 #include "eloop.h"
35 #include "utils/list.h"
36 #include "common/ieee802_11_defs.h"
37 #include "netlink.h"
38 #include "linux_ioctl.h"
39 #include "radiotap.h"
40 #include "radiotap_iter.h"
41 #include "rfkill.h"
42 #include "driver.h"
43
44 #ifdef CONFIG_LIBNL20
45 /* libnl 2.0 compatibility code */
46 #define nl_handle nl_sock
47 #define nl80211_handle_alloc nl_socket_alloc_cb
48 #define nl80211_handle_destroy nl_socket_free
49 #else
50 /*
51  * libnl 1.1 has a bug, it tries to allocate socket numbers densely
52  * but when you free a socket again it will mess up its bitmap and
53  * and use the wrong number the next time it needs a socket ID.
54  * Therefore, we wrap the handle alloc/destroy and add our own pid
55  * accounting.
56  */
57 static uint32_t port_bitmap[32] = { 0 };
58
59 static struct nl_handle *nl80211_handle_alloc(void *cb)
60 {
61         struct nl_handle *handle;
62         uint32_t pid = getpid() & 0x3FFFFF;
63         int i;
64
65         handle = nl_handle_alloc_cb(cb);
66
67         for (i = 0; i < 1024; i++) {
68                 if (port_bitmap[i / 32] & (1 << (i % 32)))
69                         continue;
70                 port_bitmap[i / 32] |= 1 << (i % 32);
71                 pid += i << 22;
72                 break;
73         }
74
75         nl_socket_set_local_port(handle, pid);
76
77         return handle;
78 }
79
80 static void nl80211_handle_destroy(struct nl_handle *handle)
81 {
82         uint32_t port = nl_socket_get_local_port(handle);
83
84         port >>= 22;
85         port_bitmap[port / 32] &= ~(1 << (port % 32));
86
87         nl_handle_destroy(handle);
88 }
89 #endif /* CONFIG_LIBNL20 */
90
91
92 #ifndef IFF_LOWER_UP
93 #define IFF_LOWER_UP   0x10000         /* driver signals L1 up         */
94 #endif
95 #ifndef IFF_DORMANT
96 #define IFF_DORMANT    0x20000         /* driver signals dormant       */
97 #endif
98
99 #ifndef IF_OPER_DORMANT
100 #define IF_OPER_DORMANT 5
101 #endif
102 #ifndef IF_OPER_UP
103 #define IF_OPER_UP 6
104 #endif
105
106 struct nl80211_global {
107         struct dl_list interfaces;
108 };
109
110 struct i802_bss {
111         struct wpa_driver_nl80211_data *drv;
112         struct i802_bss *next;
113         int ifindex;
114         char ifname[IFNAMSIZ + 1];
115         char brname[IFNAMSIZ];
116         unsigned int beacon_set:1;
117         unsigned int added_if_into_bridge:1;
118         unsigned int added_bridge:1;
119 };
120
121 struct wpa_driver_nl80211_data {
122         struct nl80211_global *global;
123         struct dl_list list;
124         u8 addr[ETH_ALEN];
125         char phyname[32];
126         void *ctx;
127         struct netlink_data *netlink;
128         int ioctl_sock; /* socket for ioctl() use */
129         int ifindex;
130         int if_removed;
131         int if_disabled;
132         struct rfkill_data *rfkill;
133         struct wpa_driver_capa capa;
134         int has_capability;
135
136         int operstate;
137
138         int scan_complete_events;
139
140         struct nl_handle *nl_handle;
141         struct nl_handle *nl_handle_event;
142         struct nl_handle *nl_handle_preq;
143         struct nl_cache *nl_cache;
144         struct nl_cache *nl_cache_event;
145         struct nl_cache *nl_cache_preq;
146         struct nl_cb *nl_cb;
147         struct genl_family *nl80211;
148
149         u8 auth_bssid[ETH_ALEN];
150         u8 bssid[ETH_ALEN];
151         int associated;
152         u8 ssid[32];
153         size_t ssid_len;
154         int nlmode;
155         int ap_scan_as_station;
156         unsigned int assoc_freq;
157
158         int monitor_sock;
159         int monitor_ifidx;
160         int disable_11b_rates;
161
162         unsigned int pending_remain_on_chan:1;
163
164         u64 remain_on_chan_cookie;
165         u64 send_action_cookie;
166
167         unsigned int last_mgmt_freq;
168
169         struct wpa_driver_scan_filter *filter_ssids;
170         size_t num_filter_ssids;
171
172         struct i802_bss first_bss;
173
174 #ifdef HOSTAPD
175         int eapol_sock; /* socket for EAPOL frames */
176
177         int default_if_indices[16];
178         int *if_indices;
179         int num_if_indices;
180
181         int last_freq;
182         int last_freq_ht;
183 #endif /* HOSTAPD */
184 };
185
186
187 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx,
188                                             void *timeout_ctx);
189 static int wpa_driver_nl80211_set_mode(void *priv, int mode);
190 static int
191 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv);
192 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
193                                    const u8 *addr, int cmd, u16 reason_code,
194                                    int local_state_change);
195 static void nl80211_remove_monitor_interface(
196         struct wpa_driver_nl80211_data *drv);
197 static int nl80211_send_frame_cmd(struct wpa_driver_nl80211_data *drv,
198                                   unsigned int freq, unsigned int wait,
199                                   const u8 *buf, size_t buf_len, u64 *cookie);
200 static int wpa_driver_nl80211_probe_req_report(void *priv, int report);
201
202 #ifdef HOSTAPD
203 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
204 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
205 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
206 static int wpa_driver_nl80211_if_remove(void *priv,
207                                         enum wpa_driver_if_type type,
208                                         const char *ifname);
209 #else /* HOSTAPD */
210 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
211 {
212         return 0;
213 }
214 #endif /* HOSTAPD */
215
216 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq);
217 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
218                                      int ifindex, int disabled);
219
220
221 /* nl80211 code */
222 static int ack_handler(struct nl_msg *msg, void *arg)
223 {
224         int *err = arg;
225         *err = 0;
226         return NL_STOP;
227 }
228
229 static int finish_handler(struct nl_msg *msg, void *arg)
230 {
231         int *ret = arg;
232         *ret = 0;
233         return NL_SKIP;
234 }
235
236 static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err,
237                          void *arg)
238 {
239         int *ret = arg;
240         *ret = err->error;
241         return NL_SKIP;
242 }
243
244
245 static int no_seq_check(struct nl_msg *msg, void *arg)
246 {
247         return NL_OK;
248 }
249
250
251 static int send_and_recv(struct wpa_driver_nl80211_data *drv,
252                          struct nl_handle *nl_handle, struct nl_msg *msg,
253                          int (*valid_handler)(struct nl_msg *, void *),
254                          void *valid_data)
255 {
256         struct nl_cb *cb;
257         int err = -ENOMEM;
258
259         cb = nl_cb_clone(drv->nl_cb);
260         if (!cb)
261                 goto out;
262
263         err = nl_send_auto_complete(nl_handle, msg);
264         if (err < 0)
265                 goto out;
266
267         err = 1;
268
269         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
270         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
271         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
272
273         if (valid_handler)
274                 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM,
275                           valid_handler, valid_data);
276
277         while (err > 0)
278                 nl_recvmsgs(nl_handle, cb);
279  out:
280         nl_cb_put(cb);
281         nlmsg_free(msg);
282         return err;
283 }
284
285
286 static int send_and_recv_msgs(struct wpa_driver_nl80211_data *drv,
287                               struct nl_msg *msg,
288                               int (*valid_handler)(struct nl_msg *, void *),
289                               void *valid_data)
290 {
291         return send_and_recv(drv, drv->nl_handle, msg, valid_handler,
292                              valid_data);
293 }
294
295
296 struct family_data {
297         const char *group;
298         int id;
299 };
300
301
302 static int family_handler(struct nl_msg *msg, void *arg)
303 {
304         struct family_data *res = arg;
305         struct nlattr *tb[CTRL_ATTR_MAX + 1];
306         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
307         struct nlattr *mcgrp;
308         int i;
309
310         nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
311                   genlmsg_attrlen(gnlh, 0), NULL);
312         if (!tb[CTRL_ATTR_MCAST_GROUPS])
313                 return NL_SKIP;
314
315         nla_for_each_nested(mcgrp, tb[CTRL_ATTR_MCAST_GROUPS], i) {
316                 struct nlattr *tb2[CTRL_ATTR_MCAST_GRP_MAX + 1];
317                 nla_parse(tb2, CTRL_ATTR_MCAST_GRP_MAX, nla_data(mcgrp),
318                           nla_len(mcgrp), NULL);
319                 if (!tb2[CTRL_ATTR_MCAST_GRP_NAME] ||
320                     !tb2[CTRL_ATTR_MCAST_GRP_ID] ||
321                     os_strncmp(nla_data(tb2[CTRL_ATTR_MCAST_GRP_NAME]),
322                                res->group,
323                                nla_len(tb2[CTRL_ATTR_MCAST_GRP_NAME])) != 0)
324                         continue;
325                 res->id = nla_get_u32(tb2[CTRL_ATTR_MCAST_GRP_ID]);
326                 break;
327         };
328
329         return NL_SKIP;
330 }
331
332
333 static int nl_get_multicast_id(struct wpa_driver_nl80211_data *drv,
334                                const char *family, const char *group)
335 {
336         struct nl_msg *msg;
337         int ret = -1;
338         struct family_data res = { group, -ENOENT };
339
340         msg = nlmsg_alloc();
341         if (!msg)
342                 return -ENOMEM;
343         genlmsg_put(msg, 0, 0, genl_ctrl_resolve(drv->nl_handle, "nlctrl"),
344                     0, 0, CTRL_CMD_GETFAMILY, 0);
345         NLA_PUT_STRING(msg, CTRL_ATTR_FAMILY_NAME, family);
346
347         ret = send_and_recv_msgs(drv, msg, family_handler, &res);
348         msg = NULL;
349         if (ret == 0)
350                 ret = res.id;
351
352 nla_put_failure:
353         nlmsg_free(msg);
354         return ret;
355 }
356
357
358 static int wpa_driver_nl80211_get_bssid(void *priv, u8 *bssid)
359 {
360         struct i802_bss *bss = priv;
361         struct wpa_driver_nl80211_data *drv = bss->drv;
362         if (!drv->associated)
363                 return -1;
364         os_memcpy(bssid, drv->bssid, ETH_ALEN);
365         return 0;
366 }
367
368
369 static int wpa_driver_nl80211_get_ssid(void *priv, u8 *ssid)
370 {
371         struct i802_bss *bss = priv;
372         struct wpa_driver_nl80211_data *drv = bss->drv;
373         if (!drv->associated)
374                 return -1;
375         os_memcpy(ssid, drv->ssid, drv->ssid_len);
376         return drv->ssid_len;
377 }
378
379
380 static void wpa_driver_nl80211_event_link(struct wpa_driver_nl80211_data *drv,
381                                           char *buf, size_t len, int del)
382 {
383         union wpa_event_data event;
384
385         os_memset(&event, 0, sizeof(event));
386         if (len > sizeof(event.interface_status.ifname))
387                 len = sizeof(event.interface_status.ifname) - 1;
388         os_memcpy(event.interface_status.ifname, buf, len);
389         event.interface_status.ievent = del ? EVENT_INTERFACE_REMOVED :
390                 EVENT_INTERFACE_ADDED;
391
392         wpa_printf(MSG_DEBUG, "RTM_%sLINK, IFLA_IFNAME: Interface '%s' %s",
393                    del ? "DEL" : "NEW",
394                    event.interface_status.ifname,
395                    del ? "removed" : "added");
396
397         if (os_strcmp(drv->first_bss.ifname, event.interface_status.ifname) == 0) {
398                 if (del)
399                         drv->if_removed = 1;
400                 else
401                         drv->if_removed = 0;
402         }
403
404         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_STATUS, &event);
405 }
406
407
408 static int wpa_driver_nl80211_own_ifname(struct wpa_driver_nl80211_data *drv,
409                                          u8 *buf, size_t len)
410 {
411         int attrlen, rta_len;
412         struct rtattr *attr;
413
414         attrlen = len;
415         attr = (struct rtattr *) buf;
416
417         rta_len = RTA_ALIGN(sizeof(struct rtattr));
418         while (RTA_OK(attr, attrlen)) {
419                 if (attr->rta_type == IFLA_IFNAME) {
420                         if (os_strcmp(((char *) attr) + rta_len, drv->first_bss.ifname)
421                             == 0)
422                                 return 1;
423                         else
424                                 break;
425                 }
426                 attr = RTA_NEXT(attr, attrlen);
427         }
428
429         return 0;
430 }
431
432
433 static int wpa_driver_nl80211_own_ifindex(struct wpa_driver_nl80211_data *drv,
434                                           int ifindex, u8 *buf, size_t len)
435 {
436         if (drv->ifindex == ifindex)
437                 return 1;
438
439         if (drv->if_removed && wpa_driver_nl80211_own_ifname(drv, buf, len)) {
440                 drv->first_bss.ifindex = if_nametoindex(drv->first_bss.ifname);
441                 wpa_printf(MSG_DEBUG, "nl80211: Update ifindex for a removed "
442                            "interface");
443                 wpa_driver_nl80211_finish_drv_init(drv);
444                 return 1;
445         }
446
447         return 0;
448 }
449
450
451 static void wpa_driver_nl80211_event_rtm_newlink(void *ctx,
452                                                  struct ifinfomsg *ifi,
453                                                  u8 *buf, size_t len)
454 {
455         struct wpa_driver_nl80211_data *drv = ctx;
456         int attrlen, rta_len;
457         struct rtattr *attr;
458         u32 brid = 0;
459
460         if (!wpa_driver_nl80211_own_ifindex(drv, ifi->ifi_index, buf, len) &&
461             !have_ifidx(drv, ifi->ifi_index)) {
462                 wpa_printf(MSG_DEBUG, "nl80211: Ignore event for foreign "
463                            "ifindex %d", ifi->ifi_index);
464                 return;
465         }
466
467         wpa_printf(MSG_DEBUG, "RTM_NEWLINK: operstate=%d ifi_flags=0x%x "
468                    "(%s%s%s%s)",
469                    drv->operstate, ifi->ifi_flags,
470                    (ifi->ifi_flags & IFF_UP) ? "[UP]" : "",
471                    (ifi->ifi_flags & IFF_RUNNING) ? "[RUNNING]" : "",
472                    (ifi->ifi_flags & IFF_LOWER_UP) ? "[LOWER_UP]" : "",
473                    (ifi->ifi_flags & IFF_DORMANT) ? "[DORMANT]" : "");
474
475         if (!drv->if_disabled && !(ifi->ifi_flags & IFF_UP)) {
476                 wpa_printf(MSG_DEBUG, "nl80211: Interface down");
477                 drv->if_disabled = 1;
478                 wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_DISABLED, NULL);
479         }
480
481         if (drv->if_disabled && (ifi->ifi_flags & IFF_UP)) {
482                 wpa_printf(MSG_DEBUG, "nl80211: Interface up");
483                 drv->if_disabled = 0;
484                 wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_ENABLED, NULL);
485         }
486
487         /*
488          * Some drivers send the association event before the operup event--in
489          * this case, lifting operstate in wpa_driver_nl80211_set_operstate()
490          * fails. This will hit us when wpa_supplicant does not need to do
491          * IEEE 802.1X authentication
492          */
493         if (drv->operstate == 1 &&
494             (ifi->ifi_flags & (IFF_LOWER_UP | IFF_DORMANT)) == IFF_LOWER_UP &&
495             !(ifi->ifi_flags & IFF_RUNNING))
496                 netlink_send_oper_ifla(drv->netlink, drv->ifindex,
497                                        -1, IF_OPER_UP);
498
499         attrlen = len;
500         attr = (struct rtattr *) buf;
501         rta_len = RTA_ALIGN(sizeof(struct rtattr));
502         while (RTA_OK(attr, attrlen)) {
503                 if (attr->rta_type == IFLA_IFNAME) {
504                         wpa_driver_nl80211_event_link(
505                                 drv,
506                                 ((char *) attr) + rta_len,
507                                 attr->rta_len - rta_len, 0);
508                 } else if (attr->rta_type == IFLA_MASTER)
509                         brid = nla_get_u32((struct nlattr *) attr);
510                 attr = RTA_NEXT(attr, attrlen);
511         }
512
513 #ifdef HOSTAPD
514         if (ifi->ifi_family == AF_BRIDGE && brid) {
515                 /* device has been added to bridge */
516                 char namebuf[IFNAMSIZ];
517                 if_indextoname(brid, namebuf);
518                 wpa_printf(MSG_DEBUG, "nl80211: Add ifindex %u for bridge %s",
519                            brid, namebuf);
520                 add_ifidx(drv, brid);
521         }
522 #endif /* HOSTAPD */
523 }
524
525
526 static void wpa_driver_nl80211_event_rtm_dellink(void *ctx,
527                                                  struct ifinfomsg *ifi,
528                                                  u8 *buf, size_t len)
529 {
530         struct wpa_driver_nl80211_data *drv = ctx;
531         int attrlen, rta_len;
532         struct rtattr *attr;
533         u32 brid = 0;
534
535         attrlen = len;
536         attr = (struct rtattr *) buf;
537
538         rta_len = RTA_ALIGN(sizeof(struct rtattr));
539         while (RTA_OK(attr, attrlen)) {
540                 if (attr->rta_type == IFLA_IFNAME) {
541                         wpa_driver_nl80211_event_link(
542                                 drv,
543                                 ((char *) attr) + rta_len,
544                                 attr->rta_len - rta_len, 1);
545                 } else if (attr->rta_type == IFLA_MASTER)
546                         brid = nla_get_u32((struct nlattr *) attr);
547                 attr = RTA_NEXT(attr, attrlen);
548         }
549
550 #ifdef HOSTAPD
551         if (ifi->ifi_family == AF_BRIDGE && brid) {
552                 /* device has been removed from bridge */
553                 char namebuf[IFNAMSIZ];
554                 if_indextoname(brid, namebuf);
555                 wpa_printf(MSG_DEBUG, "nl80211: Remove ifindex %u for bridge "
556                            "%s", brid, namebuf);
557                 del_ifidx(drv, brid);
558         }
559 #endif /* HOSTAPD */
560 }
561
562
563 static void mlme_event_auth(struct wpa_driver_nl80211_data *drv,
564                             const u8 *frame, size_t len)
565 {
566         const struct ieee80211_mgmt *mgmt;
567         union wpa_event_data event;
568
569         mgmt = (const struct ieee80211_mgmt *) frame;
570         if (len < 24 + sizeof(mgmt->u.auth)) {
571                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
572                            "frame");
573                 return;
574         }
575
576         os_memcpy(drv->auth_bssid, mgmt->sa, ETH_ALEN);
577         os_memset(&event, 0, sizeof(event));
578         os_memcpy(event.auth.peer, mgmt->sa, ETH_ALEN);
579         event.auth.auth_type = le_to_host16(mgmt->u.auth.auth_alg);
580         event.auth.status_code = le_to_host16(mgmt->u.auth.status_code);
581         if (len > 24 + sizeof(mgmt->u.auth)) {
582                 event.auth.ies = mgmt->u.auth.variable;
583                 event.auth.ies_len = len - 24 - sizeof(mgmt->u.auth);
584         }
585
586         wpa_supplicant_event(drv->ctx, EVENT_AUTH, &event);
587 }
588
589
590 static void mlme_event_assoc(struct wpa_driver_nl80211_data *drv,
591                             const u8 *frame, size_t len)
592 {
593         const struct ieee80211_mgmt *mgmt;
594         union wpa_event_data event;
595         u16 status;
596
597         mgmt = (const struct ieee80211_mgmt *) frame;
598         if (len < 24 + sizeof(mgmt->u.assoc_resp)) {
599                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
600                            "frame");
601                 return;
602         }
603
604         status = le_to_host16(mgmt->u.assoc_resp.status_code);
605         if (status != WLAN_STATUS_SUCCESS) {
606                 os_memset(&event, 0, sizeof(event));
607                 event.assoc_reject.bssid = mgmt->bssid;
608                 if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
609                         event.assoc_reject.resp_ies =
610                                 (u8 *) mgmt->u.assoc_resp.variable;
611                         event.assoc_reject.resp_ies_len =
612                                 len - 24 - sizeof(mgmt->u.assoc_resp);
613                 }
614                 event.assoc_reject.status_code = status;
615
616                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
617                 return;
618         }
619
620         drv->associated = 1;
621         os_memcpy(drv->bssid, mgmt->sa, ETH_ALEN);
622
623         os_memset(&event, 0, sizeof(event));
624         if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
625                 event.assoc_info.resp_ies = (u8 *) mgmt->u.assoc_resp.variable;
626                 event.assoc_info.resp_ies_len =
627                         len - 24 - sizeof(mgmt->u.assoc_resp);
628         }
629
630         event.assoc_info.freq = drv->assoc_freq;
631
632         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
633 }
634
635
636 static void mlme_event_connect(struct wpa_driver_nl80211_data *drv,
637                                enum nl80211_commands cmd, struct nlattr *status,
638                                struct nlattr *addr, struct nlattr *req_ie,
639                                struct nlattr *resp_ie)
640 {
641         union wpa_event_data event;
642
643         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
644                 /*
645                  * Avoid reporting two association events that would confuse
646                  * the core code.
647                  */
648                 wpa_printf(MSG_DEBUG, "nl80211: Ignore connect event (cmd=%d) "
649                            "when using userspace SME", cmd);
650                 return;
651         }
652
653         os_memset(&event, 0, sizeof(event));
654         if (cmd == NL80211_CMD_CONNECT &&
655             nla_get_u16(status) != WLAN_STATUS_SUCCESS) {
656                 if (addr)
657                         event.assoc_reject.bssid = nla_data(addr);
658                 if (resp_ie) {
659                         event.assoc_reject.resp_ies = nla_data(resp_ie);
660                         event.assoc_reject.resp_ies_len = nla_len(resp_ie);
661                 }
662                 event.assoc_reject.status_code = nla_get_u16(status);
663                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
664                 return;
665         }
666
667         drv->associated = 1;
668         if (addr)
669                 os_memcpy(drv->bssid, nla_data(addr), ETH_ALEN);
670
671         if (req_ie) {
672                 event.assoc_info.req_ies = nla_data(req_ie);
673                 event.assoc_info.req_ies_len = nla_len(req_ie);
674         }
675         if (resp_ie) {
676                 event.assoc_info.resp_ies = nla_data(resp_ie);
677                 event.assoc_info.resp_ies_len = nla_len(resp_ie);
678         }
679
680         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
681 }
682
683
684 static void mlme_timeout_event(struct wpa_driver_nl80211_data *drv,
685                                enum nl80211_commands cmd, struct nlattr *addr)
686 {
687         union wpa_event_data event;
688         enum wpa_event_type ev;
689
690         if (nla_len(addr) != ETH_ALEN)
691                 return;
692
693         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d; timeout with " MACSTR,
694                    cmd, MAC2STR((u8 *) nla_data(addr)));
695
696         if (cmd == NL80211_CMD_AUTHENTICATE)
697                 ev = EVENT_AUTH_TIMED_OUT;
698         else if (cmd == NL80211_CMD_ASSOCIATE)
699                 ev = EVENT_ASSOC_TIMED_OUT;
700         else
701                 return;
702
703         os_memset(&event, 0, sizeof(event));
704         os_memcpy(event.timeout_event.addr, nla_data(addr), ETH_ALEN);
705         wpa_supplicant_event(drv->ctx, ev, &event);
706 }
707
708
709 static void mlme_event_mgmt(struct wpa_driver_nl80211_data *drv,
710                             struct nlattr *freq, const u8 *frame, size_t len)
711 {
712         const struct ieee80211_mgmt *mgmt;
713         union wpa_event_data event;
714         u16 fc, stype;
715
716         mgmt = (const struct ieee80211_mgmt *) frame;
717         if (len < 24) {
718                 wpa_printf(MSG_DEBUG, "nl80211: Too short action frame");
719                 return;
720         }
721
722         fc = le_to_host16(mgmt->frame_control);
723         stype = WLAN_FC_GET_STYPE(fc);
724
725         os_memset(&event, 0, sizeof(event));
726         if (freq) {
727                 event.rx_action.freq = nla_get_u32(freq);
728                 drv->last_mgmt_freq = event.rx_action.freq;
729         }
730         if (stype == WLAN_FC_STYPE_ACTION) {
731                 event.rx_action.da = mgmt->da;
732                 event.rx_action.sa = mgmt->sa;
733                 event.rx_action.bssid = mgmt->bssid;
734                 event.rx_action.category = mgmt->u.action.category;
735                 event.rx_action.data = &mgmt->u.action.category + 1;
736                 event.rx_action.len = frame + len - event.rx_action.data;
737                 wpa_supplicant_event(drv->ctx, EVENT_RX_ACTION, &event);
738         } else {
739                 event.rx_mgmt.frame = frame;
740                 event.rx_mgmt.frame_len = len;
741                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
742         }
743 }
744
745
746 static void mlme_event_action_tx_status(struct wpa_driver_nl80211_data *drv,
747                                         struct nlattr *cookie, const u8 *frame,
748                                         size_t len, struct nlattr *ack)
749 {
750         union wpa_event_data event;
751         const struct ieee80211_hdr *hdr;
752         u16 fc;
753         u64 cookie_val;
754
755         if (!cookie)
756                 return;
757
758         cookie_val = nla_get_u64(cookie);
759         wpa_printf(MSG_DEBUG, "nl80211: Action TX status: cookie=0%llx%s "
760                    "(ack=%d)",
761                    (long long unsigned int) cookie_val,
762                    cookie_val == drv->send_action_cookie ?
763                    " (match)" : " (unknown)", ack != NULL);
764         if (cookie_val != drv->send_action_cookie)
765                 return;
766
767         hdr = (const struct ieee80211_hdr *) frame;
768         fc = le_to_host16(hdr->frame_control);
769
770         os_memset(&event, 0, sizeof(event));
771         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
772         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
773         event.tx_status.dst = hdr->addr1;
774         event.tx_status.data = frame;
775         event.tx_status.data_len = len;
776         event.tx_status.ack = ack != NULL;
777         wpa_supplicant_event(drv->ctx, EVENT_TX_STATUS, &event);
778 }
779
780
781 static void mlme_event_deauth_disassoc(struct wpa_driver_nl80211_data *drv,
782                                        enum wpa_event_type type,
783                                        const u8 *frame, size_t len)
784 {
785         const struct ieee80211_mgmt *mgmt;
786         union wpa_event_data event;
787         const u8 *bssid = NULL;
788         u16 reason_code = 0;
789
790         mgmt = (const struct ieee80211_mgmt *) frame;
791         if (len >= 24) {
792                 bssid = mgmt->bssid;
793
794                 if (drv->associated != 0 &&
795                     os_memcmp(bssid, drv->bssid, ETH_ALEN) != 0 &&
796                     os_memcmp(bssid, drv->auth_bssid, ETH_ALEN) != 0) {
797                         /*
798                          * We have presumably received this deauth as a
799                          * response to a clear_state_mismatch() outgoing
800                          * deauth.  Don't let it take us offline!
801                          */
802                         wpa_printf(MSG_DEBUG, "nl80211: Deauth received "
803                                    "from Unknown BSSID " MACSTR " -- ignoring",
804                                    MAC2STR(bssid));
805                         return;
806                 }
807         }
808
809         drv->associated = 0;
810         os_memset(&event, 0, sizeof(event));
811
812         /* Note: Same offset for Reason Code in both frame subtypes */
813         if (len >= 24 + sizeof(mgmt->u.deauth))
814                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
815
816         if (type == EVENT_DISASSOC) {
817                 event.disassoc_info.addr = bssid;
818                 event.disassoc_info.reason_code = reason_code;
819                 if (frame + len > mgmt->u.disassoc.variable) {
820                         event.disassoc_info.ie = mgmt->u.disassoc.variable;
821                         event.disassoc_info.ie_len = frame + len -
822                                 mgmt->u.disassoc.variable;
823                 }
824         } else {
825                 event.deauth_info.addr = bssid;
826                 event.deauth_info.reason_code = reason_code;
827                 if (frame + len > mgmt->u.deauth.variable) {
828                         event.deauth_info.ie = mgmt->u.deauth.variable;
829                         event.deauth_info.ie_len = frame + len -
830                                 mgmt->u.deauth.variable;
831                 }
832         }
833
834         wpa_supplicant_event(drv->ctx, type, &event);
835 }
836
837
838 static void mlme_event_unprot_disconnect(struct wpa_driver_nl80211_data *drv,
839                                          enum wpa_event_type type,
840                                          const u8 *frame, size_t len)
841 {
842         const struct ieee80211_mgmt *mgmt;
843         union wpa_event_data event;
844         u16 reason_code = 0;
845
846         if (len < 24)
847                 return;
848
849         mgmt = (const struct ieee80211_mgmt *) frame;
850
851         os_memset(&event, 0, sizeof(event));
852         /* Note: Same offset for Reason Code in both frame subtypes */
853         if (len >= 24 + sizeof(mgmt->u.deauth))
854                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
855
856         if (type == EVENT_UNPROT_DISASSOC) {
857                 event.unprot_disassoc.sa = mgmt->sa;
858                 event.unprot_disassoc.da = mgmt->da;
859                 event.unprot_disassoc.reason_code = reason_code;
860         } else {
861                 event.unprot_deauth.sa = mgmt->sa;
862                 event.unprot_deauth.da = mgmt->da;
863                 event.unprot_deauth.reason_code = reason_code;
864         }
865
866         wpa_supplicant_event(drv->ctx, type, &event);
867 }
868
869
870 static void mlme_event(struct wpa_driver_nl80211_data *drv,
871                        enum nl80211_commands cmd, struct nlattr *frame,
872                        struct nlattr *addr, struct nlattr *timed_out,
873                        struct nlattr *freq, struct nlattr *ack,
874                        struct nlattr *cookie)
875 {
876         if (timed_out && addr) {
877                 mlme_timeout_event(drv, cmd, addr);
878                 return;
879         }
880
881         if (frame == NULL) {
882                 wpa_printf(MSG_DEBUG, "nl80211: MLME event %d without frame "
883                            "data", cmd);
884                 return;
885         }
886
887         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d", cmd);
888         wpa_hexdump(MSG_MSGDUMP, "nl80211: MLME event frame",
889                     nla_data(frame), nla_len(frame));
890
891         switch (cmd) {
892         case NL80211_CMD_AUTHENTICATE:
893                 mlme_event_auth(drv, nla_data(frame), nla_len(frame));
894                 break;
895         case NL80211_CMD_ASSOCIATE:
896                 mlme_event_assoc(drv, nla_data(frame), nla_len(frame));
897                 break;
898         case NL80211_CMD_DEAUTHENTICATE:
899                 mlme_event_deauth_disassoc(drv, EVENT_DEAUTH,
900                                            nla_data(frame), nla_len(frame));
901                 break;
902         case NL80211_CMD_DISASSOCIATE:
903                 mlme_event_deauth_disassoc(drv, EVENT_DISASSOC,
904                                            nla_data(frame), nla_len(frame));
905                 break;
906         case NL80211_CMD_FRAME:
907                 mlme_event_mgmt(drv, freq, nla_data(frame), nla_len(frame));
908                 break;
909         case NL80211_CMD_FRAME_TX_STATUS:
910                 mlme_event_action_tx_status(drv, cookie, nla_data(frame),
911                                             nla_len(frame), ack);
912                 break;
913         case NL80211_CMD_UNPROT_DEAUTHENTICATE:
914                 mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DEAUTH,
915                                              nla_data(frame), nla_len(frame));
916                 break;
917         case NL80211_CMD_UNPROT_DISASSOCIATE:
918                 mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DISASSOC,
919                                              nla_data(frame), nla_len(frame));
920                 break;
921         default:
922                 break;
923         }
924 }
925
926
927 static void mlme_event_michael_mic_failure(struct wpa_driver_nl80211_data *drv,
928                                            struct nlattr *tb[])
929 {
930         union wpa_event_data data;
931
932         wpa_printf(MSG_DEBUG, "nl80211: MLME event Michael MIC failure");
933         os_memset(&data, 0, sizeof(data));
934         if (tb[NL80211_ATTR_MAC]) {
935                 wpa_hexdump(MSG_DEBUG, "nl80211: Source MAC address",
936                             nla_data(tb[NL80211_ATTR_MAC]),
937                             nla_len(tb[NL80211_ATTR_MAC]));
938                 data.michael_mic_failure.src = nla_data(tb[NL80211_ATTR_MAC]);
939         }
940         if (tb[NL80211_ATTR_KEY_SEQ]) {
941                 wpa_hexdump(MSG_DEBUG, "nl80211: TSC",
942                             nla_data(tb[NL80211_ATTR_KEY_SEQ]),
943                             nla_len(tb[NL80211_ATTR_KEY_SEQ]));
944         }
945         if (tb[NL80211_ATTR_KEY_TYPE]) {
946                 enum nl80211_key_type key_type =
947                         nla_get_u32(tb[NL80211_ATTR_KEY_TYPE]);
948                 wpa_printf(MSG_DEBUG, "nl80211: Key Type %d", key_type);
949                 if (key_type == NL80211_KEYTYPE_PAIRWISE)
950                         data.michael_mic_failure.unicast = 1;
951         } else
952                 data.michael_mic_failure.unicast = 1;
953
954         if (tb[NL80211_ATTR_KEY_IDX]) {
955                 u8 key_id = nla_get_u8(tb[NL80211_ATTR_KEY_IDX]);
956                 wpa_printf(MSG_DEBUG, "nl80211: Key Id %d", key_id);
957         }
958
959         wpa_supplicant_event(drv->ctx, EVENT_MICHAEL_MIC_FAILURE, &data);
960 }
961
962
963 static void mlme_event_join_ibss(struct wpa_driver_nl80211_data *drv,
964                                  struct nlattr *tb[])
965 {
966         if (tb[NL80211_ATTR_MAC] == NULL) {
967                 wpa_printf(MSG_DEBUG, "nl80211: No address in IBSS joined "
968                            "event");
969                 return;
970         }
971         os_memcpy(drv->bssid, nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
972         drv->associated = 1;
973         wpa_printf(MSG_DEBUG, "nl80211: IBSS " MACSTR " joined",
974                    MAC2STR(drv->bssid));
975
976         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, NULL);
977 }
978
979
980 static void mlme_event_remain_on_channel(struct wpa_driver_nl80211_data *drv,
981                                          int cancel_event, struct nlattr *tb[])
982 {
983         unsigned int freq, chan_type, duration;
984         union wpa_event_data data;
985         u64 cookie;
986
987         if (tb[NL80211_ATTR_WIPHY_FREQ])
988                 freq = nla_get_u32(tb[NL80211_ATTR_WIPHY_FREQ]);
989         else
990                 freq = 0;
991
992         if (tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE])
993                 chan_type = nla_get_u32(tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
994         else
995                 chan_type = 0;
996
997         if (tb[NL80211_ATTR_DURATION])
998                 duration = nla_get_u32(tb[NL80211_ATTR_DURATION]);
999         else
1000                 duration = 0;
1001
1002         if (tb[NL80211_ATTR_COOKIE])
1003                 cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
1004         else
1005                 cookie = 0;
1006
1007         wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel event (cancel=%d "
1008                    "freq=%u channel_type=%u duration=%u cookie=0x%llx (%s))",
1009                    cancel_event, freq, chan_type, duration,
1010                    (long long unsigned int) cookie,
1011                    cookie == drv->remain_on_chan_cookie ? "match" : "unknown");
1012
1013         if (cookie != drv->remain_on_chan_cookie)
1014                 return; /* not for us */
1015
1016         drv->pending_remain_on_chan = !cancel_event;
1017
1018         os_memset(&data, 0, sizeof(data));
1019         data.remain_on_channel.freq = freq;
1020         data.remain_on_channel.duration = duration;
1021         wpa_supplicant_event(drv->ctx, cancel_event ?
1022                              EVENT_CANCEL_REMAIN_ON_CHANNEL :
1023                              EVENT_REMAIN_ON_CHANNEL, &data);
1024 }
1025
1026
1027 static void send_scan_event(struct wpa_driver_nl80211_data *drv, int aborted,
1028                             struct nlattr *tb[])
1029 {
1030         union wpa_event_data event;
1031         struct nlattr *nl;
1032         int rem;
1033         struct scan_info *info;
1034 #define MAX_REPORT_FREQS 50
1035         int freqs[MAX_REPORT_FREQS];
1036         int num_freqs = 0;
1037
1038         os_memset(&event, 0, sizeof(event));
1039         info = &event.scan_info;
1040         info->aborted = aborted;
1041
1042         if (tb[NL80211_ATTR_SCAN_SSIDS]) {
1043                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_SSIDS], rem) {
1044                         struct wpa_driver_scan_ssid *s =
1045                                 &info->ssids[info->num_ssids];
1046                         s->ssid = nla_data(nl);
1047                         s->ssid_len = nla_len(nl);
1048                         info->num_ssids++;
1049                         if (info->num_ssids == WPAS_MAX_SCAN_SSIDS)
1050                                 break;
1051                 }
1052         }
1053         if (tb[NL80211_ATTR_SCAN_FREQUENCIES]) {
1054                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_FREQUENCIES], rem)
1055                 {
1056                         freqs[num_freqs] = nla_get_u32(nl);
1057                         num_freqs++;
1058                         if (num_freqs == MAX_REPORT_FREQS - 1)
1059                                 break;
1060                 }
1061                 info->freqs = freqs;
1062                 info->num_freqs = num_freqs;
1063         }
1064         wpa_supplicant_event(drv->ctx, EVENT_SCAN_RESULTS, &event);
1065 }
1066
1067
1068 static int get_link_signal(struct nl_msg *msg, void *arg)
1069 {
1070         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1071         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1072         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
1073         static struct nla_policy policy[NL80211_STA_INFO_MAX + 1] = {
1074                 [NL80211_STA_INFO_SIGNAL] = { .type = NLA_U8 },
1075         };
1076         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
1077         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
1078                 [NL80211_RATE_INFO_BITRATE] = { .type = NLA_U16 },
1079                 [NL80211_RATE_INFO_MCS] = { .type = NLA_U8 },
1080                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG },
1081                 [NL80211_RATE_INFO_SHORT_GI] = { .type = NLA_FLAG },
1082         };
1083         struct signal_change *sig_change = arg;
1084
1085         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1086                   genlmsg_attrlen(gnlh, 0), NULL);
1087         if (!tb[NL80211_ATTR_STA_INFO] ||
1088             nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
1089                              tb[NL80211_ATTR_STA_INFO], policy))
1090                 return NL_SKIP;
1091         if (!sinfo[NL80211_STA_INFO_SIGNAL])
1092                 return NL_SKIP;
1093
1094         sig_change->current_signal =
1095                 (s8) nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
1096
1097         if (sinfo[NL80211_STA_INFO_TX_BITRATE]) {
1098                 if (nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1099                                      sinfo[NL80211_STA_INFO_TX_BITRATE],
1100                                      rate_policy)) {
1101                         sig_change->current_txrate = 0;
1102                 } else {
1103                         if (rinfo[NL80211_RATE_INFO_BITRATE]) {
1104                                 sig_change->current_txrate =
1105                                         nla_get_u16(rinfo[
1106                                              NL80211_RATE_INFO_BITRATE]) * 100;
1107                         }
1108                 }
1109         }
1110
1111         return NL_SKIP;
1112 }
1113
1114
1115 static int nl80211_get_link_signal(struct wpa_driver_nl80211_data *drv,
1116                                    struct signal_change *sig)
1117 {
1118         struct nl_msg *msg;
1119
1120         sig->current_signal = -9999;
1121         sig->current_txrate = 0;
1122
1123         msg = nlmsg_alloc();
1124         if (!msg)
1125                 return -ENOMEM;
1126
1127         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1128                     0, NL80211_CMD_GET_STATION, 0);
1129
1130         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1131         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
1132
1133         return send_and_recv_msgs(drv, msg, get_link_signal, sig);
1134  nla_put_failure:
1135         return -ENOBUFS;
1136 }
1137
1138
1139 static int get_link_noise(struct nl_msg *msg, void *arg)
1140 {
1141         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1142         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1143         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1144         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1145                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1146                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
1147         };
1148         struct signal_change *sig_change = arg;
1149
1150         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1151                   genlmsg_attrlen(gnlh, 0), NULL);
1152
1153         if (!tb[NL80211_ATTR_SURVEY_INFO]) {
1154                 wpa_printf(MSG_DEBUG, "nl80211: survey data missing!");
1155                 return NL_SKIP;
1156         }
1157
1158         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1159                              tb[NL80211_ATTR_SURVEY_INFO],
1160                              survey_policy)) {
1161                 wpa_printf(MSG_DEBUG, "nl80211: failed to parse nested "
1162                            "attributes!");
1163                 return NL_SKIP;
1164         }
1165
1166         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1167                 return NL_SKIP;
1168
1169         if (nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
1170             sig_change->frequency)
1171                 return NL_SKIP;
1172
1173         if (!sinfo[NL80211_SURVEY_INFO_NOISE])
1174                 return NL_SKIP;
1175
1176         sig_change->current_noise =
1177                 (s8) nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1178
1179         return NL_SKIP;
1180 }
1181
1182
1183 static int nl80211_get_link_noise(struct wpa_driver_nl80211_data *drv,
1184                                   struct signal_change *sig_change)
1185 {
1186         struct nl_msg *msg;
1187
1188         sig_change->current_noise = 9999;
1189         sig_change->frequency = drv->assoc_freq;
1190
1191         msg = nlmsg_alloc();
1192         if (!msg)
1193                 return -ENOMEM;
1194
1195         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1196                     NLM_F_DUMP, NL80211_CMD_GET_SURVEY, 0);
1197
1198         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1199
1200         return send_and_recv_msgs(drv, msg, get_link_noise, sig_change);
1201  nla_put_failure:
1202         return -ENOBUFS;
1203 }
1204
1205
1206 static void nl80211_cqm_event(struct wpa_driver_nl80211_data *drv,
1207                               struct nlattr *tb[])
1208 {
1209         static struct nla_policy cqm_policy[NL80211_ATTR_CQM_MAX + 1] = {
1210                 [NL80211_ATTR_CQM_RSSI_THOLD] = { .type = NLA_U32 },
1211                 [NL80211_ATTR_CQM_RSSI_HYST] = { .type = NLA_U8 },
1212                 [NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] = { .type = NLA_U32 },
1213                 [NL80211_ATTR_CQM_PKT_LOSS_EVENT] = { .type = NLA_U32 },
1214         };
1215         struct nlattr *cqm[NL80211_ATTR_CQM_MAX + 1];
1216         enum nl80211_cqm_rssi_threshold_event event;
1217         union wpa_event_data ed;
1218         struct signal_change sig;
1219         int res;
1220
1221         if (tb[NL80211_ATTR_CQM] == NULL ||
1222             nla_parse_nested(cqm, NL80211_ATTR_CQM_MAX, tb[NL80211_ATTR_CQM],
1223                              cqm_policy)) {
1224                 wpa_printf(MSG_DEBUG, "nl80211: Ignore invalid CQM event");
1225                 return;
1226         }
1227
1228         os_memset(&ed, 0, sizeof(ed));
1229
1230         if (cqm[NL80211_ATTR_CQM_PKT_LOSS_EVENT]) {
1231                 if (!tb[NL80211_ATTR_MAC])
1232                         return;
1233                 os_memcpy(ed.low_ack.addr, nla_data(tb[NL80211_ATTR_MAC]),
1234                           ETH_ALEN);
1235                 wpa_supplicant_event(drv->ctx, EVENT_STATION_LOW_ACK, &ed);
1236                 return;
1237         }
1238
1239         if (cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] == NULL)
1240                 return;
1241         event = nla_get_u32(cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]);
1242
1243         if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH) {
1244                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1245                            "event: RSSI high");
1246                 ed.signal_change.above_threshold = 1;
1247         } else if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW) {
1248                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1249                            "event: RSSI low");
1250                 ed.signal_change.above_threshold = 0;
1251         } else
1252                 return;
1253
1254         res = nl80211_get_link_signal(drv, &sig);
1255         if (res == 0) {
1256                 ed.signal_change.current_signal = sig.current_signal;
1257                 ed.signal_change.current_txrate = sig.current_txrate;
1258                 wpa_printf(MSG_DEBUG, "nl80211: Signal: %d dBm  txrate: %d",
1259                            sig.current_signal, sig.current_txrate);
1260         }
1261
1262         res = nl80211_get_link_noise(drv, &sig);
1263         if (res == 0) {
1264                 ed.signal_change.current_noise = sig.current_noise;
1265                 wpa_printf(MSG_DEBUG, "nl80211: Noise: %d dBm",
1266                            sig.current_noise);
1267         }
1268
1269         wpa_supplicant_event(drv->ctx, EVENT_SIGNAL_CHANGE, &ed);
1270 }
1271
1272
1273 static void nl80211_new_station_event(struct wpa_driver_nl80211_data *drv,
1274                                       struct nlattr **tb)
1275 {
1276         u8 *addr;
1277         union wpa_event_data data;
1278
1279         if (tb[NL80211_ATTR_MAC] == NULL)
1280                 return;
1281         addr = nla_data(tb[NL80211_ATTR_MAC]);
1282         wpa_printf(MSG_DEBUG, "nl80211: New station " MACSTR, MAC2STR(addr));
1283         if (drv->nlmode != NL80211_IFTYPE_ADHOC)
1284                 return;
1285
1286         os_memset(&data, 0, sizeof(data));
1287         os_memcpy(data.ibss_rsn_start.peer, addr, ETH_ALEN);
1288         wpa_supplicant_event(drv->ctx, EVENT_IBSS_RSN_START, &data);
1289 }
1290
1291
1292 static int process_event(struct nl_msg *msg, void *arg)
1293 {
1294         struct wpa_driver_nl80211_data *drv = arg;
1295         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1296         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1297         union wpa_event_data data;
1298
1299         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1300                   genlmsg_attrlen(gnlh, 0), NULL);
1301
1302         if (tb[NL80211_ATTR_IFINDEX]) {
1303                 int ifindex = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
1304                 if (ifindex != drv->ifindex && !have_ifidx(drv, ifindex)) {
1305                         wpa_printf(MSG_DEBUG, "nl80211: Ignored event (cmd=%d)"
1306                                    " for foreign interface (ifindex %d)",
1307                                    gnlh->cmd, ifindex);
1308                         return NL_SKIP;
1309                 }
1310         }
1311
1312         if (drv->ap_scan_as_station &&
1313             (gnlh->cmd == NL80211_CMD_NEW_SCAN_RESULTS ||
1314              gnlh->cmd == NL80211_CMD_SCAN_ABORTED)) {
1315                 wpa_driver_nl80211_set_mode(&drv->first_bss,
1316                                             IEEE80211_MODE_AP);
1317                 drv->ap_scan_as_station = 0;
1318         }
1319
1320         switch (gnlh->cmd) {
1321         case NL80211_CMD_TRIGGER_SCAN:
1322                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger");
1323                 break;
1324         case NL80211_CMD_NEW_SCAN_RESULTS:
1325                 wpa_printf(MSG_DEBUG, "nl80211: New scan results available");
1326                 drv->scan_complete_events = 1;
1327                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
1328                                      drv->ctx);
1329                 send_scan_event(drv, 0, tb);
1330                 break;
1331         case NL80211_CMD_SCAN_ABORTED:
1332                 wpa_printf(MSG_DEBUG, "nl80211: Scan aborted");
1333                 /*
1334                  * Need to indicate that scan results are available in order
1335                  * not to make wpa_supplicant stop its scanning.
1336                  */
1337                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
1338                                      drv->ctx);
1339                 send_scan_event(drv, 1, tb);
1340                 break;
1341         case NL80211_CMD_AUTHENTICATE:
1342         case NL80211_CMD_ASSOCIATE:
1343         case NL80211_CMD_DEAUTHENTICATE:
1344         case NL80211_CMD_DISASSOCIATE:
1345         case NL80211_CMD_FRAME:
1346         case NL80211_CMD_FRAME_TX_STATUS:
1347         case NL80211_CMD_UNPROT_DEAUTHENTICATE:
1348         case NL80211_CMD_UNPROT_DISASSOCIATE:
1349                 mlme_event(drv, gnlh->cmd, tb[NL80211_ATTR_FRAME],
1350                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
1351                            tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
1352                            tb[NL80211_ATTR_COOKIE]);
1353                 break;
1354         case NL80211_CMD_CONNECT:
1355         case NL80211_CMD_ROAM:
1356                 mlme_event_connect(drv, gnlh->cmd,
1357                                    tb[NL80211_ATTR_STATUS_CODE],
1358                                    tb[NL80211_ATTR_MAC],
1359                                    tb[NL80211_ATTR_REQ_IE],
1360                                    tb[NL80211_ATTR_RESP_IE]);
1361                 break;
1362         case NL80211_CMD_DISCONNECT:
1363                 if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1364                         /*
1365                          * Avoid reporting two disassociation events that could
1366                          * confuse the core code.
1367                          */
1368                         wpa_printf(MSG_DEBUG, "nl80211: Ignore disconnect "
1369                                    "event when using userspace SME");
1370                         break;
1371                 }
1372                 drv->associated = 0;
1373                 os_memset(&data, 0, sizeof(data));
1374                 if (tb[NL80211_ATTR_REASON_CODE])
1375                         data.disassoc_info.reason_code =
1376                                 nla_get_u16(tb[NL80211_ATTR_REASON_CODE]);
1377                 wpa_supplicant_event(drv->ctx, EVENT_DISASSOC, &data);
1378                 break;
1379         case NL80211_CMD_MICHAEL_MIC_FAILURE:
1380                 mlme_event_michael_mic_failure(drv, tb);
1381                 break;
1382         case NL80211_CMD_JOIN_IBSS:
1383                 mlme_event_join_ibss(drv, tb);
1384                 break;
1385         case NL80211_CMD_REMAIN_ON_CHANNEL:
1386                 mlme_event_remain_on_channel(drv, 0, tb);
1387                 break;
1388         case NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL:
1389                 mlme_event_remain_on_channel(drv, 1, tb);
1390                 break;
1391         case NL80211_CMD_NOTIFY_CQM:
1392                 nl80211_cqm_event(drv, tb);
1393                 break;
1394         case NL80211_CMD_REG_CHANGE:
1395                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory domain change");
1396                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
1397                                      NULL);
1398                 break;
1399         case NL80211_CMD_REG_BEACON_HINT:
1400                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory beacon hint");
1401                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
1402                                      NULL);
1403                 break;
1404         case NL80211_CMD_NEW_STATION:
1405                 nl80211_new_station_event(drv, tb);
1406                 break;
1407         default:
1408                 wpa_printf(MSG_DEBUG, "nl80211: Ignored unknown event "
1409                            "(cmd=%d)", gnlh->cmd);
1410                 break;
1411         }
1412
1413         return NL_SKIP;
1414 }
1415
1416
1417 static void wpa_driver_nl80211_event_receive(int sock, void *eloop_ctx,
1418                                              void *handle)
1419 {
1420         struct nl_cb *cb;
1421         struct wpa_driver_nl80211_data *drv = eloop_ctx;
1422
1423         wpa_printf(MSG_DEBUG, "nl80211: Event message available");
1424
1425         cb = nl_cb_clone(drv->nl_cb);
1426         if (!cb)
1427                 return;
1428         nl_cb_set(cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, no_seq_check, NULL);
1429         nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, process_event, drv);
1430         nl_recvmsgs(handle, cb);
1431         nl_cb_put(cb);
1432 }
1433
1434
1435 /**
1436  * wpa_driver_nl80211_set_country - ask nl80211 to set the regulatory domain
1437  * @priv: driver_nl80211 private data
1438  * @alpha2_arg: country to which to switch to
1439  * Returns: 0 on success, -1 on failure
1440  *
1441  * This asks nl80211 to set the regulatory domain for given
1442  * country ISO / IEC alpha2.
1443  */
1444 static int wpa_driver_nl80211_set_country(void *priv, const char *alpha2_arg)
1445 {
1446         struct i802_bss *bss = priv;
1447         struct wpa_driver_nl80211_data *drv = bss->drv;
1448         char alpha2[3];
1449         struct nl_msg *msg;
1450
1451         msg = nlmsg_alloc();
1452         if (!msg)
1453                 return -ENOMEM;
1454
1455         alpha2[0] = alpha2_arg[0];
1456         alpha2[1] = alpha2_arg[1];
1457         alpha2[2] = '\0';
1458
1459         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1460                     0, NL80211_CMD_REQ_SET_REG, 0);
1461
1462         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
1463         if (send_and_recv_msgs(drv, msg, NULL, NULL))
1464                 return -EINVAL;
1465         return 0;
1466 nla_put_failure:
1467         return -EINVAL;
1468 }
1469
1470
1471 #ifndef HOSTAPD
1472 struct wiphy_info_data {
1473         int max_scan_ssids;
1474         int ap_supported;
1475         int p2p_supported;
1476         int auth_supported;
1477         int connect_supported;
1478         int offchan_tx_supported;
1479         int max_remain_on_chan;
1480 };
1481
1482
1483 static int wiphy_info_handler(struct nl_msg *msg, void *arg)
1484 {
1485         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1486         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1487         struct wiphy_info_data *info = arg;
1488         int p2p_go_supported = 0, p2p_client_supported = 0;
1489
1490         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1491                   genlmsg_attrlen(gnlh, 0), NULL);
1492
1493         if (tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS])
1494                 info->max_scan_ssids =
1495                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS]);
1496
1497         if (tb[NL80211_ATTR_SUPPORTED_IFTYPES]) {
1498                 struct nlattr *nl_mode;
1499                 int i;
1500                 nla_for_each_nested(nl_mode,
1501                                     tb[NL80211_ATTR_SUPPORTED_IFTYPES], i) {
1502                         switch (nla_type(nl_mode)) {
1503                         case NL80211_IFTYPE_AP:
1504                                 info->ap_supported = 1;
1505                                 break;
1506                         case NL80211_IFTYPE_P2P_GO:
1507                                 p2p_go_supported = 1;
1508                                 break;
1509                         case NL80211_IFTYPE_P2P_CLIENT:
1510                                 p2p_client_supported = 1;
1511                                 break;
1512                         }
1513                 }
1514         }
1515
1516         info->p2p_supported = p2p_go_supported && p2p_client_supported;
1517
1518         if (tb[NL80211_ATTR_SUPPORTED_COMMANDS]) {
1519                 struct nlattr *nl_cmd;
1520                 int i;
1521
1522                 nla_for_each_nested(nl_cmd,
1523                                     tb[NL80211_ATTR_SUPPORTED_COMMANDS], i) {
1524                         u32 cmd = nla_get_u32(nl_cmd);
1525                         if (cmd == NL80211_CMD_AUTHENTICATE)
1526                                 info->auth_supported = 1;
1527                         else if (cmd == NL80211_CMD_CONNECT)
1528                                 info->connect_supported = 1;
1529                 }
1530         }
1531
1532         if (tb[NL80211_ATTR_OFFCHANNEL_TX_OK])
1533                 info->offchan_tx_supported = 1;
1534
1535         if (tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION])
1536                 info->max_remain_on_chan =
1537                         nla_get_u32(tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION]);
1538
1539         return NL_SKIP;
1540 }
1541
1542
1543 static int wpa_driver_nl80211_get_info(struct wpa_driver_nl80211_data *drv,
1544                                        struct wiphy_info_data *info)
1545 {
1546         struct nl_msg *msg;
1547
1548         os_memset(info, 0, sizeof(*info));
1549
1550         /* default to 5000 since early versions of mac80211 don't set it */
1551         info->max_remain_on_chan = 5000;
1552
1553         msg = nlmsg_alloc();
1554         if (!msg)
1555                 return -1;
1556
1557         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1558                     0, NL80211_CMD_GET_WIPHY, 0);
1559
1560         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->first_bss.ifindex);
1561
1562         if (send_and_recv_msgs(drv, msg, wiphy_info_handler, info) == 0)
1563                 return 0;
1564         msg = NULL;
1565 nla_put_failure:
1566         nlmsg_free(msg);
1567         return -1;
1568 }
1569
1570
1571 static int wpa_driver_nl80211_capa(struct wpa_driver_nl80211_data *drv)
1572 {
1573         struct wiphy_info_data info;
1574         if (wpa_driver_nl80211_get_info(drv, &info))
1575                 return -1;
1576         drv->has_capability = 1;
1577         /* For now, assume TKIP, CCMP, WPA, WPA2 are supported */
1578         drv->capa.key_mgmt = WPA_DRIVER_CAPA_KEY_MGMT_WPA |
1579                 WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK |
1580                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2 |
1581                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK;
1582         drv->capa.enc = WPA_DRIVER_CAPA_ENC_WEP40 |
1583                 WPA_DRIVER_CAPA_ENC_WEP104 |
1584                 WPA_DRIVER_CAPA_ENC_TKIP |
1585                 WPA_DRIVER_CAPA_ENC_CCMP;
1586         drv->capa.auth = WPA_DRIVER_AUTH_OPEN |
1587                 WPA_DRIVER_AUTH_SHARED |
1588                 WPA_DRIVER_AUTH_LEAP;
1589
1590         drv->capa.max_scan_ssids = info.max_scan_ssids;
1591         if (info.ap_supported)
1592                 drv->capa.flags |= WPA_DRIVER_FLAGS_AP;
1593
1594         if (info.auth_supported)
1595                 drv->capa.flags |= WPA_DRIVER_FLAGS_SME;
1596         else if (!info.connect_supported) {
1597                 wpa_printf(MSG_INFO, "nl80211: Driver does not support "
1598                            "authentication/association or connect commands");
1599                 return -1;
1600         }
1601
1602         if (info.offchan_tx_supported) {
1603                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based "
1604                            "off-channel TX");
1605                 drv->capa.flags |= WPA_DRIVER_FLAGS_OFFCHANNEL_TX;
1606         }
1607
1608         drv->capa.flags |= WPA_DRIVER_FLAGS_SANE_ERROR_CODES;
1609         drv->capa.flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE;
1610         if (info.p2p_supported)
1611                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CAPABLE;
1612         drv->capa.max_remain_on_chan = info.max_remain_on_chan;
1613
1614         return 0;
1615 }
1616 #endif /* HOSTAPD */
1617
1618
1619 static int wpa_driver_nl80211_init_nl(struct wpa_driver_nl80211_data *drv)
1620 {
1621         int ret;
1622
1623         /* Initialize generic netlink and nl80211 */
1624
1625         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
1626         if (drv->nl_cb == NULL) {
1627                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1628                            "callbacks");
1629                 goto err1;
1630         }
1631
1632         drv->nl_handle = nl80211_handle_alloc(drv->nl_cb);
1633         if (drv->nl_handle == NULL) {
1634                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1635                            "callbacks");
1636                 goto err2;
1637         }
1638
1639         drv->nl_handle_event = nl80211_handle_alloc(drv->nl_cb);
1640         if (drv->nl_handle_event == NULL) {
1641                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1642                            "callbacks (event)");
1643                 goto err2b;
1644         }
1645
1646         if (genl_connect(drv->nl_handle)) {
1647                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
1648                            "netlink");
1649                 goto err3;
1650         }
1651
1652         if (genl_connect(drv->nl_handle_event)) {
1653                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
1654                            "netlink (event)");
1655                 goto err3;
1656         }
1657
1658 #ifdef CONFIG_LIBNL20
1659         if (genl_ctrl_alloc_cache(drv->nl_handle, &drv->nl_cache) < 0) {
1660                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1661                            "netlink cache");
1662                 goto err3;
1663         }
1664         if (genl_ctrl_alloc_cache(drv->nl_handle_event, &drv->nl_cache_event) <
1665             0) {
1666                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1667                            "netlink cache (event)");
1668                 goto err3b;
1669         }
1670 #else /* CONFIG_LIBNL20 */
1671         drv->nl_cache = genl_ctrl_alloc_cache(drv->nl_handle);
1672         if (drv->nl_cache == NULL) {
1673                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1674                            "netlink cache");
1675                 goto err3;
1676         }
1677         drv->nl_cache_event = genl_ctrl_alloc_cache(drv->nl_handle_event);
1678         if (drv->nl_cache_event == NULL) {
1679                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1680                            "netlink cache (event)");
1681                 goto err3b;
1682         }
1683 #endif /* CONFIG_LIBNL20 */
1684
1685         drv->nl80211 = genl_ctrl_search_by_name(drv->nl_cache, "nl80211");
1686         if (drv->nl80211 == NULL) {
1687                 wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
1688                            "found");
1689                 goto err4;
1690         }
1691
1692         ret = nl_get_multicast_id(drv, "nl80211", "scan");
1693         if (ret >= 0)
1694                 ret = nl_socket_add_membership(drv->nl_handle_event, ret);
1695         if (ret < 0) {
1696                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
1697                            "membership for scan events: %d (%s)",
1698                            ret, strerror(-ret));
1699                 goto err4;
1700         }
1701
1702         ret = nl_get_multicast_id(drv, "nl80211", "mlme");
1703         if (ret >= 0)
1704                 ret = nl_socket_add_membership(drv->nl_handle_event, ret);
1705         if (ret < 0) {
1706                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
1707                            "membership for mlme events: %d (%s)",
1708                            ret, strerror(-ret));
1709                 goto err4;
1710         }
1711
1712         ret = nl_get_multicast_id(drv, "nl80211", "regulatory");
1713         if (ret >= 0)
1714                 ret = nl_socket_add_membership(drv->nl_handle_event, ret);
1715         if (ret < 0) {
1716                 wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
1717                            "membership for regulatory events: %d (%s)",
1718                            ret, strerror(-ret));
1719                 /* Continue without regulatory events */
1720         }
1721
1722         eloop_register_read_sock(nl_socket_get_fd(drv->nl_handle_event),
1723                                  wpa_driver_nl80211_event_receive, drv,
1724                                  drv->nl_handle_event);
1725
1726         return 0;
1727
1728 err4:
1729         nl_cache_free(drv->nl_cache_event);
1730 err3b:
1731         nl_cache_free(drv->nl_cache);
1732 err3:
1733         nl80211_handle_destroy(drv->nl_handle_event);
1734 err2b:
1735         nl80211_handle_destroy(drv->nl_handle);
1736 err2:
1737         nl_cb_put(drv->nl_cb);
1738 err1:
1739         return -1;
1740 }
1741
1742
1743 static void wpa_driver_nl80211_rfkill_blocked(void *ctx)
1744 {
1745         wpa_printf(MSG_DEBUG, "nl80211: RFKILL blocked");
1746         /*
1747          * This may be for any interface; use ifdown event to disable
1748          * interface.
1749          */
1750 }
1751
1752
1753 static void wpa_driver_nl80211_rfkill_unblocked(void *ctx)
1754 {
1755         struct wpa_driver_nl80211_data *drv = ctx;
1756         wpa_printf(MSG_DEBUG, "nl80211: RFKILL unblocked");
1757         if (linux_set_iface_flags(drv->ioctl_sock, drv->first_bss.ifname, 1)) {
1758                 wpa_printf(MSG_DEBUG, "nl80211: Could not set interface UP "
1759                            "after rfkill unblock");
1760                 return;
1761         }
1762         /* rtnetlink ifup handler will report interface as enabled */
1763 }
1764
1765
1766 static void nl80211_get_phy_name(struct wpa_driver_nl80211_data *drv)
1767 {
1768         /* Find phy (radio) to which this interface belongs */
1769         char buf[90], *pos;
1770         int f, rv;
1771
1772         drv->phyname[0] = '\0';
1773         snprintf(buf, sizeof(buf) - 1, "/sys/class/net/%s/phy80211/name",
1774                  drv->first_bss.ifname);
1775         f = open(buf, O_RDONLY);
1776         if (f < 0) {
1777                 wpa_printf(MSG_DEBUG, "Could not open file %s: %s",
1778                            buf, strerror(errno));
1779                 return;
1780         }
1781
1782         rv = read(f, drv->phyname, sizeof(drv->phyname) - 1);
1783         close(f);
1784         if (rv < 0) {
1785                 wpa_printf(MSG_DEBUG, "Could not read file %s: %s",
1786                            buf, strerror(errno));
1787                 return;
1788         }
1789
1790         drv->phyname[rv] = '\0';
1791         pos = os_strchr(drv->phyname, '\n');
1792         if (pos)
1793                 *pos = '\0';
1794         wpa_printf(MSG_DEBUG, "nl80211: interface %s in phy %s",
1795                    drv->first_bss.ifname, drv->phyname);
1796 }
1797
1798
1799 /**
1800  * wpa_driver_nl80211_init - Initialize nl80211 driver interface
1801  * @ctx: context to be used when calling wpa_supplicant functions,
1802  * e.g., wpa_supplicant_event()
1803  * @ifname: interface name, e.g., wlan0
1804  * @global_priv: private driver global data from global_init()
1805  * Returns: Pointer to private data, %NULL on failure
1806  */
1807 static void * wpa_driver_nl80211_init(void *ctx, const char *ifname,
1808                                       void *global_priv)
1809 {
1810         struct wpa_driver_nl80211_data *drv;
1811         struct netlink_config *cfg;
1812         struct rfkill_config *rcfg;
1813         struct i802_bss *bss;
1814
1815         drv = os_zalloc(sizeof(*drv));
1816         if (drv == NULL)
1817                 return NULL;
1818         drv->global = global_priv;
1819         if (drv->global)
1820                 dl_list_add(&drv->global->interfaces, &drv->list);
1821         drv->ctx = ctx;
1822         bss = &drv->first_bss;
1823         bss->drv = drv;
1824         os_strlcpy(bss->ifname, ifname, sizeof(bss->ifname));
1825         drv->monitor_ifidx = -1;
1826         drv->monitor_sock = -1;
1827         drv->ioctl_sock = -1;
1828
1829         if (wpa_driver_nl80211_init_nl(drv)) {
1830                 os_free(drv);
1831                 return NULL;
1832         }
1833
1834         nl80211_get_phy_name(drv);
1835
1836         drv->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
1837         if (drv->ioctl_sock < 0) {
1838                 perror("socket(PF_INET,SOCK_DGRAM)");
1839                 goto failed;
1840         }
1841
1842         cfg = os_zalloc(sizeof(*cfg));
1843         if (cfg == NULL)
1844                 goto failed;
1845         cfg->ctx = drv;
1846         cfg->newlink_cb = wpa_driver_nl80211_event_rtm_newlink;
1847         cfg->dellink_cb = wpa_driver_nl80211_event_rtm_dellink;
1848         drv->netlink = netlink_init(cfg);
1849         if (drv->netlink == NULL) {
1850                 os_free(cfg);
1851                 goto failed;
1852         }
1853
1854         rcfg = os_zalloc(sizeof(*rcfg));
1855         if (rcfg == NULL)
1856                 goto failed;
1857         rcfg->ctx = drv;
1858         os_strlcpy(rcfg->ifname, ifname, sizeof(rcfg->ifname));
1859         rcfg->blocked_cb = wpa_driver_nl80211_rfkill_blocked;
1860         rcfg->unblocked_cb = wpa_driver_nl80211_rfkill_unblocked;
1861         drv->rfkill = rfkill_init(rcfg);
1862         if (drv->rfkill == NULL) {
1863                 wpa_printf(MSG_DEBUG, "nl80211: RFKILL status not available");
1864                 os_free(rcfg);
1865         }
1866
1867         if (wpa_driver_nl80211_finish_drv_init(drv))
1868                 goto failed;
1869
1870         return bss;
1871
1872 failed:
1873         rfkill_deinit(drv->rfkill);
1874         netlink_deinit(drv->netlink);
1875         if (drv->ioctl_sock >= 0)
1876                 close(drv->ioctl_sock);
1877
1878         genl_family_put(drv->nl80211);
1879         nl_cache_free(drv->nl_cache);
1880         nl80211_handle_destroy(drv->nl_handle);
1881         nl_cb_put(drv->nl_cb);
1882         eloop_unregister_read_sock(nl_socket_get_fd(drv->nl_handle_event));
1883
1884         os_free(drv);
1885         return NULL;
1886 }
1887
1888
1889 static int nl80211_register_frame(struct wpa_driver_nl80211_data *drv,
1890                                   struct nl_handle *nl_handle,
1891                                   u16 type, const u8 *match, size_t match_len)
1892 {
1893         struct nl_msg *msg;
1894         int ret = -1;
1895
1896         msg = nlmsg_alloc();
1897         if (!msg)
1898                 return -1;
1899
1900         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
1901                     NL80211_CMD_REGISTER_ACTION, 0);
1902
1903         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1904         NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE, type);
1905         NLA_PUT(msg, NL80211_ATTR_FRAME_MATCH, match_len, match);
1906
1907         ret = send_and_recv(drv, nl_handle, msg, NULL, NULL);
1908         msg = NULL;
1909         if (ret) {
1910                 wpa_printf(MSG_DEBUG, "nl80211: Register frame command "
1911                            "failed (type=%u): ret=%d (%s)",
1912                            type, ret, strerror(-ret));
1913                 wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
1914                             match, match_len);
1915                 goto nla_put_failure;
1916         }
1917         ret = 0;
1918 nla_put_failure:
1919         nlmsg_free(msg);
1920         return ret;
1921 }
1922
1923
1924 static int nl80211_register_action_frame(struct wpa_driver_nl80211_data *drv,
1925                                          const u8 *match, size_t match_len)
1926 {
1927         u16 type = (WLAN_FC_TYPE_MGMT << 2) | (WLAN_FC_STYPE_ACTION << 4);
1928         return nl80211_register_frame(drv, drv->nl_handle_event,
1929                                       type, match, match_len);
1930 }
1931
1932
1933 static int nl80211_register_action_frames(struct wpa_driver_nl80211_data *drv)
1934 {
1935 #ifdef CONFIG_P2P
1936         /* GAS Initial Request */
1937         if (nl80211_register_action_frame(drv, (u8 *) "\x04\x0a", 2) < 0)
1938                 return -1;
1939         /* GAS Initial Response */
1940         if (nl80211_register_action_frame(drv, (u8 *) "\x04\x0b", 2) < 0)
1941                 return -1;
1942         /* GAS Comeback Request */
1943         if (nl80211_register_action_frame(drv, (u8 *) "\x04\x0c", 2) < 0)
1944                 return -1;
1945         /* GAS Comeback Response */
1946         if (nl80211_register_action_frame(drv, (u8 *) "\x04\x0d", 2) < 0)
1947                 return -1;
1948         /* P2P Public Action */
1949         if (nl80211_register_action_frame(drv,
1950                                           (u8 *) "\x04\x09\x50\x6f\x9a\x09",
1951                                           6) < 0)
1952                 return -1;
1953         /* P2P Action */
1954         if (nl80211_register_action_frame(drv,
1955                                           (u8 *) "\x7f\x50\x6f\x9a\x09",
1956                                           5) < 0)
1957                 return -1;
1958 #endif /* CONFIG_P2P */
1959 #ifdef CONFIG_IEEE80211W
1960         /* SA Query Response */
1961         if (nl80211_register_action_frame(drv, (u8 *) "\x08\x01", 2) < 0)
1962                 return -1;
1963 #endif /* CONFIG_IEEE80211W */
1964
1965         /* FT Action frames */
1966         if (nl80211_register_action_frame(drv, (u8 *) "\x06", 1) < 0)
1967                 return -1;
1968         else
1969                 drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_FT |
1970                         WPA_DRIVER_CAPA_KEY_MGMT_FT_PSK;
1971
1972         return 0;
1973 }
1974
1975
1976 static void wpa_driver_nl80211_send_rfkill(void *eloop_ctx, void *timeout_ctx)
1977 {
1978         wpa_supplicant_event(timeout_ctx, EVENT_INTERFACE_DISABLED, NULL);
1979 }
1980
1981
1982 static int
1983 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv)
1984 {
1985         struct i802_bss *bss = &drv->first_bss;
1986         int send_rfkill_event = 0;
1987
1988         drv->ifindex = if_nametoindex(bss->ifname);
1989         drv->first_bss.ifindex = drv->ifindex;
1990
1991 #ifndef HOSTAPD
1992         if (wpa_driver_nl80211_set_mode(bss, IEEE80211_MODE_INFRA) < 0) {
1993                 wpa_printf(MSG_DEBUG, "nl80211: Could not configure driver to "
1994                            "use managed mode");
1995         }
1996
1997         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 1)) {
1998                 if (rfkill_is_blocked(drv->rfkill)) {
1999                         wpa_printf(MSG_DEBUG, "nl80211: Could not yet enable "
2000                                    "interface '%s' due to rfkill",
2001                                    bss->ifname);
2002                         drv->if_disabled = 1;
2003                         send_rfkill_event = 1;
2004                 } else {
2005                         wpa_printf(MSG_ERROR, "nl80211: Could not set "
2006                                    "interface '%s' UP", bss->ifname);
2007                         return -1;
2008                 }
2009         }
2010
2011         if (wpa_driver_nl80211_capa(drv))
2012                 return -1;
2013
2014         netlink_send_oper_ifla(drv->netlink, drv->ifindex,
2015                                1, IF_OPER_DORMANT);
2016 #endif /* HOSTAPD */
2017
2018         if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, drv->addr))
2019                 return -1;
2020
2021         if (nl80211_register_action_frames(drv) < 0) {
2022                 wpa_printf(MSG_DEBUG, "nl80211: Failed to register Action "
2023                            "frame processing - ignore for now");
2024                 /*
2025                  * Older kernel versions did not support this, so ignore the
2026                  * error for now. Some functionality may not be available
2027                  * because of this.
2028                  */
2029         }
2030
2031         if (send_rfkill_event) {
2032                 eloop_register_timeout(0, 0, wpa_driver_nl80211_send_rfkill,
2033                                        drv, drv->ctx);
2034         }
2035
2036         return 0;
2037 }
2038
2039
2040 static int wpa_driver_nl80211_del_beacon(struct wpa_driver_nl80211_data *drv)
2041 {
2042         struct nl_msg *msg;
2043
2044         msg = nlmsg_alloc();
2045         if (!msg)
2046                 return -ENOMEM;
2047
2048         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2049                     0, NL80211_CMD_DEL_BEACON, 0);
2050         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2051
2052         return send_and_recv_msgs(drv, msg, NULL, NULL);
2053  nla_put_failure:
2054         return -ENOBUFS;
2055 }
2056
2057
2058 /**
2059  * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
2060  * @priv: Pointer to private nl80211 data from wpa_driver_nl80211_init()
2061  *
2062  * Shut down driver interface and processing of driver events. Free
2063  * private data buffer if one was allocated in wpa_driver_nl80211_init().
2064  */
2065 static void wpa_driver_nl80211_deinit(void *priv)
2066 {
2067         struct i802_bss *bss = priv;
2068         struct wpa_driver_nl80211_data *drv = bss->drv;
2069
2070         if (drv->nl_handle_preq)
2071                 wpa_driver_nl80211_probe_req_report(bss, 0);
2072         if (bss->added_if_into_bridge) {
2073                 if (linux_br_del_if(drv->ioctl_sock, bss->brname, bss->ifname)
2074                     < 0)
2075                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
2076                                    "interface %s from bridge %s: %s",
2077                                    bss->ifname, bss->brname, strerror(errno));
2078         }
2079         if (bss->added_bridge) {
2080                 if (linux_br_del(drv->ioctl_sock, bss->brname) < 0)
2081                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
2082                                    "bridge %s: %s",
2083                                    bss->brname, strerror(errno));
2084         }
2085
2086         nl80211_remove_monitor_interface(drv);
2087
2088         if (drv->nlmode == NL80211_IFTYPE_AP)
2089                 wpa_driver_nl80211_del_beacon(drv);
2090
2091 #ifdef HOSTAPD
2092         if (drv->last_freq_ht) {
2093                 /* Clear HT flags from the driver */
2094                 struct hostapd_freq_params freq;
2095                 os_memset(&freq, 0, sizeof(freq));
2096                 freq.freq = drv->last_freq;
2097                 i802_set_freq(priv, &freq);
2098         }
2099
2100         if (drv->eapol_sock >= 0) {
2101                 eloop_unregister_read_sock(drv->eapol_sock);
2102                 close(drv->eapol_sock);
2103         }
2104
2105         if (drv->if_indices != drv->default_if_indices)
2106                 os_free(drv->if_indices);
2107 #endif /* HOSTAPD */
2108
2109         if (drv->disable_11b_rates)
2110                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
2111
2112         netlink_send_oper_ifla(drv->netlink, drv->ifindex, 0, IF_OPER_UP);
2113         netlink_deinit(drv->netlink);
2114         rfkill_deinit(drv->rfkill);
2115
2116         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
2117
2118         (void) linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 0);
2119         wpa_driver_nl80211_set_mode(bss, IEEE80211_MODE_INFRA);
2120
2121         if (drv->ioctl_sock >= 0)
2122                 close(drv->ioctl_sock);
2123
2124         eloop_unregister_read_sock(nl_socket_get_fd(drv->nl_handle_event));
2125         genl_family_put(drv->nl80211);
2126         nl_cache_free(drv->nl_cache);
2127         nl_cache_free(drv->nl_cache_event);
2128         nl80211_handle_destroy(drv->nl_handle);
2129         nl80211_handle_destroy(drv->nl_handle_event);
2130         nl_cb_put(drv->nl_cb);
2131
2132         os_free(drv->filter_ssids);
2133
2134         if (drv->global)
2135                 dl_list_del(&drv->list);
2136
2137         os_free(drv);
2138 }
2139
2140
2141 /**
2142  * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
2143  * @eloop_ctx: Driver private data
2144  * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
2145  *
2146  * This function can be used as registered timeout when starting a scan to
2147  * generate a scan completed event if the driver does not report this.
2148  */
2149 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
2150 {
2151         struct wpa_driver_nl80211_data *drv = eloop_ctx;
2152         if (drv->ap_scan_as_station) {
2153                 wpa_driver_nl80211_set_mode(&drv->first_bss,
2154                                             IEEE80211_MODE_AP);
2155                 drv->ap_scan_as_station = 0;
2156         }
2157         wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
2158         wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
2159 }
2160
2161
2162 /**
2163  * wpa_driver_nl80211_scan - Request the driver to initiate scan
2164  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
2165  * @params: Scan parameters
2166  * Returns: 0 on success, -1 on failure
2167  */
2168 static int wpa_driver_nl80211_scan(void *priv,
2169                                    struct wpa_driver_scan_params *params)
2170 {
2171         struct i802_bss *bss = priv;
2172         struct wpa_driver_nl80211_data *drv = bss->drv;
2173         int ret = 0, timeout;
2174         struct nl_msg *msg, *ssids, *freqs;
2175         size_t i;
2176
2177         msg = nlmsg_alloc();
2178         ssids = nlmsg_alloc();
2179         freqs = nlmsg_alloc();
2180         if (!msg || !ssids || !freqs) {
2181                 nlmsg_free(msg);
2182                 nlmsg_free(ssids);
2183                 nlmsg_free(freqs);
2184                 return -1;
2185         }
2186
2187         os_free(drv->filter_ssids);
2188         drv->filter_ssids = params->filter_ssids;
2189         params->filter_ssids = NULL;
2190         drv->num_filter_ssids = params->num_filter_ssids;
2191
2192         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
2193                     NL80211_CMD_TRIGGER_SCAN, 0);
2194
2195         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2196
2197         for (i = 0; i < params->num_ssids; i++) {
2198                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan SSID",
2199                                   params->ssids[i].ssid,
2200                                   params->ssids[i].ssid_len);
2201                 NLA_PUT(ssids, i + 1, params->ssids[i].ssid_len,
2202                         params->ssids[i].ssid);
2203         }
2204         if (params->num_ssids)
2205                 nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
2206
2207         if (params->extra_ies) {
2208                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan extra IEs",
2209                                   params->extra_ies, params->extra_ies_len);
2210                 NLA_PUT(msg, NL80211_ATTR_IE, params->extra_ies_len,
2211                         params->extra_ies);
2212         }
2213
2214         if (params->freqs) {
2215                 for (i = 0; params->freqs[i]; i++) {
2216                         wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
2217                                    "MHz", params->freqs[i]);
2218                         NLA_PUT_U32(freqs, i + 1, params->freqs[i]);
2219                 }
2220                 nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs);
2221         }
2222
2223         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2224         msg = NULL;
2225         if (ret) {
2226                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
2227                            "(%s)", ret, strerror(-ret));
2228 #ifdef HOSTAPD
2229                 if (drv->nlmode == NL80211_IFTYPE_AP) {
2230                         /*
2231                          * mac80211 does not allow scan requests in AP mode, so
2232                          * try to do this in station mode.
2233                          */
2234                         if (wpa_driver_nl80211_set_mode(bss,
2235                                                         IEEE80211_MODE_INFRA))
2236                                 goto nla_put_failure;
2237
2238                         if (wpa_driver_nl80211_scan(drv, params)) {
2239                                 wpa_driver_nl80211_set_mode(bss,
2240                                                             IEEE80211_MODE_AP);
2241                                 goto nla_put_failure;
2242                         }
2243
2244                         /* Restore AP mode when processing scan results */
2245                         drv->ap_scan_as_station = 1;
2246                         ret = 0;
2247                 } else
2248                         goto nla_put_failure;
2249 #else /* HOSTAPD */
2250                 goto nla_put_failure;
2251 #endif /* HOSTAPD */
2252         }
2253
2254         /* Not all drivers generate "scan completed" wireless event, so try to
2255          * read results after a timeout. */
2256         timeout = 10;
2257         if (drv->scan_complete_events) {
2258                 /*
2259                  * The driver seems to deliver events to notify when scan is
2260                  * complete, so use longer timeout to avoid race conditions
2261                  * with scanning and following association request.
2262                  */
2263                 timeout = 30;
2264         }
2265         wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
2266                    "seconds", ret, timeout);
2267         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
2268         eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
2269                                drv, drv->ctx);
2270
2271 nla_put_failure:
2272         nlmsg_free(ssids);
2273         nlmsg_free(msg);
2274         nlmsg_free(freqs);
2275         return ret;
2276 }
2277
2278
2279 static const u8 * nl80211_get_ie(const u8 *ies, size_t ies_len, u8 ie)
2280 {
2281         const u8 *end, *pos;
2282
2283         if (ies == NULL)
2284                 return NULL;
2285
2286         pos = ies;
2287         end = ies + ies_len;
2288
2289         while (pos + 1 < end) {
2290                 if (pos + 2 + pos[1] > end)
2291                         break;
2292                 if (pos[0] == ie)
2293                         return pos;
2294                 pos += 2 + pos[1];
2295         }
2296
2297         return NULL;
2298 }
2299
2300
2301 static int nl80211_scan_filtered(struct wpa_driver_nl80211_data *drv,
2302                                  const u8 *ie, size_t ie_len)
2303 {
2304         const u8 *ssid;
2305         size_t i;
2306
2307         if (drv->filter_ssids == NULL)
2308                 return 0;
2309
2310         ssid = nl80211_get_ie(ie, ie_len, WLAN_EID_SSID);
2311         if (ssid == NULL)
2312                 return 1;
2313
2314         for (i = 0; i < drv->num_filter_ssids; i++) {
2315                 if (ssid[1] == drv->filter_ssids[i].ssid_len &&
2316                     os_memcmp(ssid + 2, drv->filter_ssids[i].ssid, ssid[1]) ==
2317                     0)
2318                         return 0;
2319         }
2320
2321         return 1;
2322 }
2323
2324
2325 struct nl80211_bss_info_arg {
2326         struct wpa_driver_nl80211_data *drv;
2327         struct wpa_scan_results *res;
2328 };
2329
2330 static int bss_info_handler(struct nl_msg *msg, void *arg)
2331 {
2332         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2333         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2334         struct nlattr *bss[NL80211_BSS_MAX + 1];
2335         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
2336                 [NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
2337                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
2338                 [NL80211_BSS_TSF] = { .type = NLA_U64 },
2339                 [NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
2340                 [NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
2341                 [NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
2342                 [NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
2343                 [NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
2344                 [NL80211_BSS_STATUS] = { .type = NLA_U32 },
2345                 [NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
2346                 [NL80211_BSS_BEACON_IES] = { .type = NLA_UNSPEC },
2347         };
2348         struct nl80211_bss_info_arg *_arg = arg;
2349         struct wpa_scan_results *res = _arg->res;
2350         struct wpa_scan_res **tmp;
2351         struct wpa_scan_res *r;
2352         const u8 *ie, *beacon_ie;
2353         size_t ie_len, beacon_ie_len;
2354         u8 *pos;
2355
2356         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2357                   genlmsg_attrlen(gnlh, 0), NULL);
2358         if (!tb[NL80211_ATTR_BSS])
2359                 return NL_SKIP;
2360         if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
2361                              bss_policy))
2362                 return NL_SKIP;
2363         if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
2364                 ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2365                 ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2366         } else {
2367                 ie = NULL;
2368                 ie_len = 0;
2369         }
2370         if (bss[NL80211_BSS_BEACON_IES]) {
2371                 beacon_ie = nla_data(bss[NL80211_BSS_BEACON_IES]);
2372                 beacon_ie_len = nla_len(bss[NL80211_BSS_BEACON_IES]);
2373         } else {
2374                 beacon_ie = NULL;
2375                 beacon_ie_len = 0;
2376         }
2377
2378         if (nl80211_scan_filtered(_arg->drv, ie ? ie : beacon_ie,
2379                                   ie ? ie_len : beacon_ie_len))
2380                 return NL_SKIP;
2381
2382         r = os_zalloc(sizeof(*r) + ie_len + beacon_ie_len);
2383         if (r == NULL)
2384                 return NL_SKIP;
2385         if (bss[NL80211_BSS_BSSID])
2386                 os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
2387                           ETH_ALEN);
2388         if (bss[NL80211_BSS_FREQUENCY])
2389                 r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
2390         if (bss[NL80211_BSS_BEACON_INTERVAL])
2391                 r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
2392         if (bss[NL80211_BSS_CAPABILITY])
2393                 r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
2394         r->flags |= WPA_SCAN_NOISE_INVALID;
2395         if (bss[NL80211_BSS_SIGNAL_MBM]) {
2396                 r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
2397                 r->level /= 100; /* mBm to dBm */
2398                 r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
2399         } else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
2400                 r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
2401                 r->flags |= WPA_SCAN_LEVEL_INVALID;
2402         } else
2403                 r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
2404         if (bss[NL80211_BSS_TSF])
2405                 r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
2406         if (bss[NL80211_BSS_SEEN_MS_AGO])
2407                 r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
2408         r->ie_len = ie_len;
2409         pos = (u8 *) (r + 1);
2410         if (ie) {
2411                 os_memcpy(pos, ie, ie_len);
2412                 pos += ie_len;
2413         }
2414         r->beacon_ie_len = beacon_ie_len;
2415         if (beacon_ie)
2416                 os_memcpy(pos, beacon_ie, beacon_ie_len);
2417
2418         if (bss[NL80211_BSS_STATUS]) {
2419                 enum nl80211_bss_status status;
2420                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
2421                 switch (status) {
2422                 case NL80211_BSS_STATUS_AUTHENTICATED:
2423                         r->flags |= WPA_SCAN_AUTHENTICATED;
2424                         break;
2425                 case NL80211_BSS_STATUS_ASSOCIATED:
2426                         r->flags |= WPA_SCAN_ASSOCIATED;
2427                         break;
2428                 default:
2429                         break;
2430                 }
2431         }
2432
2433         tmp = os_realloc(res->res,
2434                          (res->num + 1) * sizeof(struct wpa_scan_res *));
2435         if (tmp == NULL) {
2436                 os_free(r);
2437                 return NL_SKIP;
2438         }
2439         tmp[res->num++] = r;
2440         res->res = tmp;
2441
2442         return NL_SKIP;
2443 }
2444
2445
2446 static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
2447                                  const u8 *addr)
2448 {
2449         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
2450                 wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
2451                            "mismatch (" MACSTR ")", MAC2STR(addr));
2452                 wpa_driver_nl80211_mlme(drv, addr,
2453                                         NL80211_CMD_DEAUTHENTICATE,
2454                                         WLAN_REASON_PREV_AUTH_NOT_VALID, 1);
2455         }
2456 }
2457
2458
2459 static void wpa_driver_nl80211_check_bss_status(
2460         struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
2461 {
2462         size_t i;
2463
2464         for (i = 0; i < res->num; i++) {
2465                 struct wpa_scan_res *r = res->res[i];
2466                 if (r->flags & WPA_SCAN_AUTHENTICATED) {
2467                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
2468                                    "indicates BSS status with " MACSTR
2469                                    " as authenticated",
2470                                    MAC2STR(r->bssid));
2471                         if (drv->nlmode == NL80211_IFTYPE_STATION &&
2472                             os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
2473                             os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
2474                             0) {
2475                                 wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
2476                                            " in local state (auth=" MACSTR
2477                                            " assoc=" MACSTR ")",
2478                                            MAC2STR(drv->auth_bssid),
2479                                            MAC2STR(drv->bssid));
2480                                 clear_state_mismatch(drv, r->bssid);
2481                         }
2482                 }
2483
2484                 if (r->flags & WPA_SCAN_ASSOCIATED) {
2485                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
2486                                    "indicate BSS status with " MACSTR
2487                                    " as associated",
2488                                    MAC2STR(r->bssid));
2489                         if (drv->nlmode == NL80211_IFTYPE_STATION &&
2490                             !drv->associated) {
2491                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
2492                                            "(not associated) does not match "
2493                                            "with BSS state");
2494                                 clear_state_mismatch(drv, r->bssid);
2495                         } else if (drv->nlmode == NL80211_IFTYPE_STATION &&
2496                                    os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
2497                                    0) {
2498                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
2499                                            "(associated with " MACSTR ") does "
2500                                            "not match with BSS state",
2501                                            MAC2STR(drv->bssid));
2502                                 clear_state_mismatch(drv, r->bssid);
2503                                 clear_state_mismatch(drv, drv->bssid);
2504                         }
2505                 }
2506         }
2507 }
2508
2509
2510 static void wpa_scan_results_free(struct wpa_scan_results *res)
2511 {
2512         size_t i;
2513
2514         if (res == NULL)
2515                 return;
2516
2517         for (i = 0; i < res->num; i++)
2518                 os_free(res->res[i]);
2519         os_free(res->res);
2520         os_free(res);
2521 }
2522
2523
2524 static struct wpa_scan_results *
2525 nl80211_get_scan_results(struct wpa_driver_nl80211_data *drv)
2526 {
2527         struct nl_msg *msg;
2528         struct wpa_scan_results *res;
2529         int ret;
2530         struct nl80211_bss_info_arg arg;
2531
2532         res = os_zalloc(sizeof(*res));
2533         if (res == NULL)
2534                 return NULL;
2535         msg = nlmsg_alloc();
2536         if (!msg)
2537                 goto nla_put_failure;
2538
2539         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, NLM_F_DUMP,
2540                     NL80211_CMD_GET_SCAN, 0);
2541         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2542
2543         arg.drv = drv;
2544         arg.res = res;
2545         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
2546         msg = NULL;
2547         if (ret == 0) {
2548                 wpa_printf(MSG_DEBUG, "Received scan results (%lu BSSes)",
2549                            (unsigned long) res->num);
2550                 return res;
2551         }
2552         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
2553                    "(%s)", ret, strerror(-ret));
2554 nla_put_failure:
2555         nlmsg_free(msg);
2556         wpa_scan_results_free(res);
2557         return NULL;
2558 }
2559
2560
2561 /**
2562  * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
2563  * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
2564  * Returns: Scan results on success, -1 on failure
2565  */
2566 static struct wpa_scan_results *
2567 wpa_driver_nl80211_get_scan_results(void *priv)
2568 {
2569         struct i802_bss *bss = priv;
2570         struct wpa_driver_nl80211_data *drv = bss->drv;
2571         struct wpa_scan_results *res;
2572
2573         res = nl80211_get_scan_results(drv);
2574         if (res)
2575                 wpa_driver_nl80211_check_bss_status(drv, res);
2576         return res;
2577 }
2578
2579
2580 static void nl80211_dump_scan(struct wpa_driver_nl80211_data *drv)
2581 {
2582         struct wpa_scan_results *res;
2583         size_t i;
2584
2585         res = nl80211_get_scan_results(drv);
2586         if (res == NULL) {
2587                 wpa_printf(MSG_DEBUG, "nl80211: Failed to get scan results");
2588                 return;
2589         }
2590
2591         wpa_printf(MSG_DEBUG, "nl80211: Scan result dump");
2592         for (i = 0; i < res->num; i++) {
2593                 struct wpa_scan_res *r = res->res[i];
2594                 wpa_printf(MSG_DEBUG, "nl80211: %d/%d " MACSTR "%s%s",
2595                            (int) i, (int) res->num, MAC2STR(r->bssid),
2596                            r->flags & WPA_SCAN_AUTHENTICATED ? " [auth]" : "",
2597                            r->flags & WPA_SCAN_ASSOCIATED ? " [assoc]" : "");
2598         }
2599
2600         wpa_scan_results_free(res);
2601 }
2602
2603
2604 static int wpa_driver_nl80211_set_key(const char *ifname, void *priv,
2605                                       enum wpa_alg alg, const u8 *addr,
2606                                       int key_idx, int set_tx,
2607                                       const u8 *seq, size_t seq_len,
2608                                       const u8 *key, size_t key_len)
2609 {
2610         struct i802_bss *bss = priv;
2611         struct wpa_driver_nl80211_data *drv = bss->drv;
2612         int ifindex = if_nametoindex(ifname);
2613         struct nl_msg *msg;
2614         int ret;
2615
2616         wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
2617                    "set_tx=%d seq_len=%lu key_len=%lu",
2618                    __func__, ifindex, alg, addr, key_idx, set_tx,
2619                    (unsigned long) seq_len, (unsigned long) key_len);
2620
2621         msg = nlmsg_alloc();
2622         if (!msg)
2623                 return -ENOMEM;
2624
2625         if (alg == WPA_ALG_NONE) {
2626                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2627                             0, NL80211_CMD_DEL_KEY, 0);
2628         } else {
2629                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2630                             0, NL80211_CMD_NEW_KEY, 0);
2631                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
2632                 switch (alg) {
2633                 case WPA_ALG_WEP:
2634                         if (key_len == 5)
2635                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2636                                             WLAN_CIPHER_SUITE_WEP40);
2637                         else
2638                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2639                                             WLAN_CIPHER_SUITE_WEP104);
2640                         break;
2641                 case WPA_ALG_TKIP:
2642                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2643                                     WLAN_CIPHER_SUITE_TKIP);
2644                         break;
2645                 case WPA_ALG_CCMP:
2646                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2647                                     WLAN_CIPHER_SUITE_CCMP);
2648                         break;
2649                 case WPA_ALG_IGTK:
2650                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2651                                     WLAN_CIPHER_SUITE_AES_CMAC);
2652                         break;
2653                 default:
2654                         wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
2655                                    "algorithm %d", __func__, alg);
2656                         nlmsg_free(msg);
2657                         return -1;
2658                 }
2659         }
2660
2661         if (seq && seq_len)
2662                 NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
2663
2664         if (addr && !is_broadcast_ether_addr(addr)) {
2665                 wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
2666                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
2667
2668                 if (alg != WPA_ALG_WEP && key_idx && !set_tx) {
2669                         wpa_printf(MSG_DEBUG, "   RSN IBSS RX GTK");
2670                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_TYPE,
2671                                     NL80211_KEYTYPE_GROUP);
2672                 }
2673         } else if (addr && is_broadcast_ether_addr(addr)) {
2674                 struct nl_msg *types;
2675                 int err;
2676                 wpa_printf(MSG_DEBUG, "   broadcast key");
2677                 types = nlmsg_alloc();
2678                 if (!types)
2679                         goto nla_put_failure;
2680                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
2681                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
2682                                      types);
2683                 nlmsg_free(types);
2684                 if (err)
2685                         goto nla_put_failure;
2686         }
2687         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
2688         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
2689
2690         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2691         if ((ret == -ENOENT || ret == -ENOLINK) && alg == WPA_ALG_NONE)
2692                 ret = 0;
2693         if (ret)
2694                 wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
2695                            ret, strerror(-ret));
2696
2697         /*
2698          * If we failed or don't need to set the default TX key (below),
2699          * we're done here.
2700          */
2701         if (ret || !set_tx || alg == WPA_ALG_NONE)
2702                 return ret;
2703         if (drv->nlmode == NL80211_IFTYPE_AP && addr &&
2704             !is_broadcast_ether_addr(addr))
2705                 return ret;
2706
2707         msg = nlmsg_alloc();
2708         if (!msg)
2709                 return -ENOMEM;
2710
2711         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2712                     0, NL80211_CMD_SET_KEY, 0);
2713         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
2714         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
2715         if (alg == WPA_ALG_IGTK)
2716                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
2717         else
2718                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
2719         if (addr && is_broadcast_ether_addr(addr)) {
2720                 struct nl_msg *types;
2721                 int err;
2722                 types = nlmsg_alloc();
2723                 if (!types)
2724                         goto nla_put_failure;
2725                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
2726                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
2727                                      types);
2728                 nlmsg_free(types);
2729                 if (err)
2730                         goto nla_put_failure;
2731         } else if (addr) {
2732                 struct nl_msg *types;
2733                 int err;
2734                 types = nlmsg_alloc();
2735                 if (!types)
2736                         goto nla_put_failure;
2737                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_UNICAST);
2738                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
2739                                      types);
2740                 nlmsg_free(types);
2741                 if (err)
2742                         goto nla_put_failure;
2743         }
2744
2745         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2746         if (ret == -ENOENT)
2747                 ret = 0;
2748         if (ret)
2749                 wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
2750                            "err=%d %s)", ret, strerror(-ret));
2751         return ret;
2752
2753 nla_put_failure:
2754         return -ENOBUFS;
2755 }
2756
2757
2758 static int nl_add_key(struct nl_msg *msg, enum wpa_alg alg,
2759                       int key_idx, int defkey,
2760                       const u8 *seq, size_t seq_len,
2761                       const u8 *key, size_t key_len)
2762 {
2763         struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
2764         if (!key_attr)
2765                 return -1;
2766
2767         if (defkey && alg == WPA_ALG_IGTK)
2768                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
2769         else if (defkey)
2770                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
2771
2772         NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
2773
2774         switch (alg) {
2775         case WPA_ALG_WEP:
2776                 if (key_len == 5)
2777                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2778                                     WLAN_CIPHER_SUITE_WEP40);
2779                 else
2780                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2781                                     WLAN_CIPHER_SUITE_WEP104);
2782                 break;
2783         case WPA_ALG_TKIP:
2784                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_TKIP);
2785                 break;
2786         case WPA_ALG_CCMP:
2787                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_CCMP);
2788                 break;
2789         case WPA_ALG_IGTK:
2790                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2791                             WLAN_CIPHER_SUITE_AES_CMAC);
2792                 break;
2793         default:
2794                 wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
2795                            "algorithm %d", __func__, alg);
2796                 return -1;
2797         }
2798
2799         if (seq && seq_len)
2800                 NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
2801
2802         NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
2803
2804         nla_nest_end(msg, key_attr);
2805
2806         return 0;
2807  nla_put_failure:
2808         return -1;
2809 }
2810
2811
2812 static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
2813                                  struct nl_msg *msg)
2814 {
2815         int i, privacy = 0;
2816         struct nlattr *nl_keys, *nl_key;
2817
2818         for (i = 0; i < 4; i++) {
2819                 if (!params->wep_key[i])
2820                         continue;
2821                 privacy = 1;
2822                 break;
2823         }
2824         if (params->wps == WPS_MODE_PRIVACY)
2825                 privacy = 1;
2826         if (params->pairwise_suite &&
2827             params->pairwise_suite != WPA_CIPHER_NONE)
2828                 privacy = 1;
2829
2830         if (!privacy)
2831                 return 0;
2832
2833         NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
2834
2835         nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
2836         if (!nl_keys)
2837                 goto nla_put_failure;
2838
2839         for (i = 0; i < 4; i++) {
2840                 if (!params->wep_key[i])
2841                         continue;
2842
2843                 nl_key = nla_nest_start(msg, i);
2844                 if (!nl_key)
2845                         goto nla_put_failure;
2846
2847                 NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
2848                         params->wep_key[i]);
2849                 if (params->wep_key_len[i] == 5)
2850                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2851                                     WLAN_CIPHER_SUITE_WEP40);
2852                 else
2853                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2854                                     WLAN_CIPHER_SUITE_WEP104);
2855
2856                 NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
2857
2858                 if (i == params->wep_tx_keyidx)
2859                         NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
2860
2861                 nla_nest_end(msg, nl_key);
2862         }
2863         nla_nest_end(msg, nl_keys);
2864
2865         return 0;
2866
2867 nla_put_failure:
2868         return -ENOBUFS;
2869 }
2870
2871
2872 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
2873                                    const u8 *addr, int cmd, u16 reason_code,
2874                                    int local_state_change)
2875 {
2876         int ret = -1;
2877         struct nl_msg *msg;
2878
2879         msg = nlmsg_alloc();
2880         if (!msg)
2881                 return -1;
2882
2883         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0, cmd, 0);
2884
2885         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2886         NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
2887         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
2888         if (local_state_change)
2889                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
2890
2891         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2892         msg = NULL;
2893         if (ret) {
2894                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
2895                            "(%s)", ret, strerror(-ret));
2896                 goto nla_put_failure;
2897         }
2898         ret = 0;
2899
2900 nla_put_failure:
2901         nlmsg_free(msg);
2902         return ret;
2903 }
2904
2905
2906 static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
2907                                          const u8 *addr, int reason_code)
2908 {
2909         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
2910                    __func__, MAC2STR(addr), reason_code);
2911         drv->associated = 0;
2912         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISCONNECT,
2913                                        reason_code, 0);
2914 }
2915
2916
2917 static int wpa_driver_nl80211_deauthenticate(void *priv, const u8 *addr,
2918                                              int reason_code)
2919 {
2920         struct i802_bss *bss = priv;
2921         struct wpa_driver_nl80211_data *drv = bss->drv;
2922         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
2923                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
2924         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
2925                    __func__, MAC2STR(addr), reason_code);
2926         drv->associated = 0;
2927         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
2928                                        reason_code, 0);
2929 }
2930
2931
2932 static int wpa_driver_nl80211_disassociate(void *priv, const u8 *addr,
2933                                            int reason_code)
2934 {
2935         struct i802_bss *bss = priv;
2936         struct wpa_driver_nl80211_data *drv = bss->drv;
2937         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
2938                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
2939         wpa_printf(MSG_DEBUG, "%s", __func__);
2940         drv->associated = 0;
2941         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISASSOCIATE,
2942                                        reason_code, 0);
2943 }
2944
2945
2946 static int wpa_driver_nl80211_authenticate(
2947         void *priv, struct wpa_driver_auth_params *params)
2948 {
2949         struct i802_bss *bss = priv;
2950         struct wpa_driver_nl80211_data *drv = bss->drv;
2951         int ret = -1, i;
2952         struct nl_msg *msg;
2953         enum nl80211_auth_type type;
2954         int count = 0;
2955
2956         drv->associated = 0;
2957         os_memset(drv->auth_bssid, 0, ETH_ALEN);
2958         /* FIX: IBSS mode */
2959         if (drv->nlmode != NL80211_IFTYPE_STATION &&
2960             wpa_driver_nl80211_set_mode(priv, IEEE80211_MODE_INFRA) < 0)
2961                 return -1;
2962
2963 retry:
2964         msg = nlmsg_alloc();
2965         if (!msg)
2966                 return -1;
2967
2968         wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
2969                    drv->ifindex);
2970
2971         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
2972                     NL80211_CMD_AUTHENTICATE, 0);
2973
2974         for (i = 0; i < 4; i++) {
2975                 if (!params->wep_key[i])
2976                         continue;
2977                 wpa_driver_nl80211_set_key(bss->ifname, priv, WPA_ALG_WEP,
2978                                            NULL, i,
2979                                            i == params->wep_tx_keyidx, NULL, 0,
2980                                            params->wep_key[i],
2981                                            params->wep_key_len[i]);
2982                 if (params->wep_tx_keyidx != i)
2983                         continue;
2984                 if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
2985                                params->wep_key[i], params->wep_key_len[i])) {
2986                         nlmsg_free(msg);
2987                         return -1;
2988                 }
2989         }
2990
2991         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2992         if (params->bssid) {
2993                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
2994                            MAC2STR(params->bssid));
2995                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
2996         }
2997         if (params->freq) {
2998                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
2999                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
3000         }
3001         if (params->ssid) {
3002                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
3003                                   params->ssid, params->ssid_len);
3004                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
3005                         params->ssid);
3006         }
3007         wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
3008         if (params->ie)
3009                 NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
3010         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
3011                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
3012         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
3013                 type = NL80211_AUTHTYPE_SHARED_KEY;
3014         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
3015                 type = NL80211_AUTHTYPE_NETWORK_EAP;
3016         else if (params->auth_alg & WPA_AUTH_ALG_FT)
3017                 type = NL80211_AUTHTYPE_FT;
3018         else
3019                 goto nla_put_failure;
3020         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
3021         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
3022         if (params->local_state_change) {
3023                 wpa_printf(MSG_DEBUG, "  * Local state change only");
3024                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
3025         }
3026
3027         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3028         msg = NULL;
3029         if (ret) {
3030                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
3031                            "(%s)", ret, strerror(-ret));
3032                 count++;
3033                 if (ret == -EALREADY && count == 1 && params->bssid &&
3034                     !params->local_state_change) {
3035                         /*
3036                          * mac80211 does not currently accept new
3037                          * authentication if we are already authenticated. As a
3038                          * workaround, force deauthentication and try again.
3039                          */
3040                         wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
3041                                    "after forced deauthentication");
3042                         wpa_driver_nl80211_deauthenticate(
3043                                 bss, params->bssid,
3044                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
3045                         nlmsg_free(msg);
3046                         goto retry;
3047                 }
3048                 goto nla_put_failure;
3049         }
3050         ret = 0;
3051         wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
3052                    "successfully");
3053
3054 nla_put_failure:
3055         nlmsg_free(msg);
3056         return ret;
3057 }
3058
3059
3060 struct phy_info_arg {
3061         u16 *num_modes;
3062         struct hostapd_hw_modes *modes;
3063 };
3064
3065 static int phy_info_handler(struct nl_msg *msg, void *arg)
3066 {
3067         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
3068         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3069         struct phy_info_arg *phy_info = arg;
3070
3071         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
3072
3073         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
3074         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
3075                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
3076                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
3077                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
3078                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
3079                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
3080                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
3081         };
3082
3083         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
3084         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
3085                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
3086                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
3087         };
3088
3089         struct nlattr *nl_band;
3090         struct nlattr *nl_freq;
3091         struct nlattr *nl_rate;
3092         int rem_band, rem_freq, rem_rate;
3093         struct hostapd_hw_modes *mode;
3094         int idx, mode_is_set;
3095
3096         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3097                   genlmsg_attrlen(gnlh, 0), NULL);
3098
3099         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
3100                 return NL_SKIP;
3101
3102         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
3103                 mode = os_realloc(phy_info->modes, (*phy_info->num_modes + 1) * sizeof(*mode));
3104                 if (!mode)
3105                         return NL_SKIP;
3106                 phy_info->modes = mode;
3107
3108                 mode_is_set = 0;
3109
3110                 mode = &phy_info->modes[*(phy_info->num_modes)];
3111                 memset(mode, 0, sizeof(*mode));
3112                 *(phy_info->num_modes) += 1;
3113
3114                 nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
3115                           nla_len(nl_band), NULL);
3116
3117                 if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
3118                         mode->ht_capab = nla_get_u16(
3119                                 tb_band[NL80211_BAND_ATTR_HT_CAPA]);
3120                 }
3121
3122                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) {
3123                         mode->a_mpdu_params |= nla_get_u8(
3124                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) &
3125                                 0x03;
3126                 }
3127
3128                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) {
3129                         mode->a_mpdu_params |= nla_get_u8(
3130                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) <<
3131                                 2;
3132                 }
3133
3134                 if (tb_band[NL80211_BAND_ATTR_HT_MCS_SET] &&
3135                     nla_len(tb_band[NL80211_BAND_ATTR_HT_MCS_SET])) {
3136                         u8 *mcs;
3137                         mcs = nla_data(tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
3138                         os_memcpy(mode->mcs_set, mcs, 16);
3139                 }
3140
3141                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
3142                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
3143                                   nla_len(nl_freq), freq_policy);
3144                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
3145                                 continue;
3146                         mode->num_channels++;
3147                 }
3148
3149                 mode->channels = os_zalloc(mode->num_channels * sizeof(struct hostapd_channel_data));
3150                 if (!mode->channels)
3151                         return NL_SKIP;
3152
3153                 idx = 0;
3154
3155                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
3156                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
3157                                   nla_len(nl_freq), freq_policy);
3158                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
3159                                 continue;
3160
3161                         mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
3162                         mode->channels[idx].flag = 0;
3163
3164                         if (!mode_is_set) {
3165                                 /* crude heuristic */
3166                                 if (mode->channels[idx].freq < 4000)
3167                                         mode->mode = HOSTAPD_MODE_IEEE80211B;
3168                                 else
3169                                         mode->mode = HOSTAPD_MODE_IEEE80211A;
3170                                 mode_is_set = 1;
3171                         }
3172
3173                         /* crude heuristic */
3174                         if (mode->channels[idx].freq < 4000)
3175                                 if (mode->channels[idx].freq == 2484)
3176                                         mode->channels[idx].chan = 14;
3177                                 else
3178                                         mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
3179                         else
3180                                 mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
3181
3182                         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
3183                                 mode->channels[idx].flag |=
3184                                         HOSTAPD_CHAN_DISABLED;
3185                         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
3186                                 mode->channels[idx].flag |=
3187                                         HOSTAPD_CHAN_PASSIVE_SCAN;
3188                         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
3189                                 mode->channels[idx].flag |=
3190                                         HOSTAPD_CHAN_NO_IBSS;
3191                         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
3192                                 mode->channels[idx].flag |=
3193                                         HOSTAPD_CHAN_RADAR;
3194
3195                         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
3196                             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
3197                                 mode->channels[idx].max_tx_power =
3198                                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
3199
3200                         idx++;
3201                 }
3202
3203                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
3204                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
3205                                   nla_len(nl_rate), rate_policy);
3206                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
3207                                 continue;
3208                         mode->num_rates++;
3209                 }
3210
3211                 mode->rates = os_zalloc(mode->num_rates * sizeof(int));
3212                 if (!mode->rates)
3213                         return NL_SKIP;
3214
3215                 idx = 0;
3216
3217                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
3218                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
3219                                   nla_len(nl_rate), rate_policy);
3220                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
3221                                 continue;
3222                         mode->rates[idx] = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
3223
3224                         /* crude heuristic */
3225                         if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
3226                             mode->rates[idx] > 200)
3227                                 mode->mode = HOSTAPD_MODE_IEEE80211G;
3228
3229                         idx++;
3230                 }
3231         }
3232
3233         return NL_SKIP;
3234 }
3235
3236 static struct hostapd_hw_modes *
3237 wpa_driver_nl80211_add_11b(struct hostapd_hw_modes *modes, u16 *num_modes)
3238 {
3239         u16 m;
3240         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
3241         int i, mode11g_idx = -1;
3242
3243         /* If only 802.11g mode is included, use it to construct matching
3244          * 802.11b mode data. */
3245
3246         for (m = 0; m < *num_modes; m++) {
3247                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
3248                         return modes; /* 802.11b already included */
3249                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
3250                         mode11g_idx = m;
3251         }
3252
3253         if (mode11g_idx < 0)
3254                 return modes; /* 2.4 GHz band not supported at all */
3255
3256         nmodes = os_realloc(modes, (*num_modes + 1) * sizeof(*nmodes));
3257         if (nmodes == NULL)
3258                 return modes; /* Could not add 802.11b mode */
3259
3260         mode = &nmodes[*num_modes];
3261         os_memset(mode, 0, sizeof(*mode));
3262         (*num_modes)++;
3263         modes = nmodes;
3264
3265         mode->mode = HOSTAPD_MODE_IEEE80211B;
3266
3267         mode11g = &modes[mode11g_idx];
3268         mode->num_channels = mode11g->num_channels;
3269         mode->channels = os_malloc(mode11g->num_channels *
3270                                    sizeof(struct hostapd_channel_data));
3271         if (mode->channels == NULL) {
3272                 (*num_modes)--;
3273                 return modes; /* Could not add 802.11b mode */
3274         }
3275         os_memcpy(mode->channels, mode11g->channels,
3276                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
3277
3278         mode->num_rates = 0;
3279         mode->rates = os_malloc(4 * sizeof(int));
3280         if (mode->rates == NULL) {
3281                 os_free(mode->channels);
3282                 (*num_modes)--;
3283                 return modes; /* Could not add 802.11b mode */
3284         }
3285
3286         for (i = 0; i < mode11g->num_rates; i++) {
3287                 if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 &&
3288                     mode11g->rates[i] != 55 && mode11g->rates[i] != 110)
3289                         continue;
3290                 mode->rates[mode->num_rates] = mode11g->rates[i];
3291                 mode->num_rates++;
3292                 if (mode->num_rates == 4)
3293                         break;
3294         }
3295
3296         if (mode->num_rates == 0) {
3297                 os_free(mode->channels);
3298                 os_free(mode->rates);
3299                 (*num_modes)--;
3300                 return modes; /* No 802.11b rates */
3301         }
3302
3303         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
3304                    "information");
3305
3306         return modes;
3307 }
3308
3309
3310 static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start,
3311                                   int end)
3312 {
3313         int c;
3314
3315         for (c = 0; c < mode->num_channels; c++) {
3316                 struct hostapd_channel_data *chan = &mode->channels[c];
3317                 if (chan->freq - 10 >= start && chan->freq + 10 <= end)
3318                         chan->flag |= HOSTAPD_CHAN_HT40;
3319         }
3320 }
3321
3322
3323 static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start,
3324                                       int end)
3325 {
3326         int c;
3327
3328         for (c = 0; c < mode->num_channels; c++) {
3329                 struct hostapd_channel_data *chan = &mode->channels[c];
3330                 if (!(chan->flag & HOSTAPD_CHAN_HT40))
3331                         continue;
3332                 if (chan->freq - 30 >= start && chan->freq - 10 <= end)
3333                         chan->flag |= HOSTAPD_CHAN_HT40MINUS;
3334                 if (chan->freq + 10 >= start && chan->freq + 30 <= end)
3335                         chan->flag |= HOSTAPD_CHAN_HT40PLUS;
3336         }
3337 }
3338
3339
3340 static void nl80211_reg_rule_ht40(struct nlattr *tb[],
3341                                   struct phy_info_arg *results)
3342 {
3343         u32 start, end, max_bw;
3344         u16 m;
3345
3346         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
3347             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
3348             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
3349                 return;
3350
3351         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
3352         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
3353         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
3354
3355         wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz",
3356                    start, end, max_bw);
3357         if (max_bw < 40)
3358                 return;
3359
3360         for (m = 0; m < *results->num_modes; m++) {
3361                 if (!(results->modes[m].ht_capab &
3362                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
3363                         continue;
3364                 nl80211_set_ht40_mode(&results->modes[m], start, end);
3365         }
3366 }
3367
3368
3369 static void nl80211_reg_rule_sec(struct nlattr *tb[],
3370                                  struct phy_info_arg *results)
3371 {
3372         u32 start, end, max_bw;
3373         u16 m;
3374
3375         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
3376             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
3377             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
3378                 return;
3379
3380         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
3381         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
3382         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
3383
3384         if (max_bw < 20)
3385                 return;
3386
3387         for (m = 0; m < *results->num_modes; m++) {
3388                 if (!(results->modes[m].ht_capab &
3389                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
3390                         continue;
3391                 nl80211_set_ht40_mode_sec(&results->modes[m], start, end);
3392         }
3393 }
3394
3395
3396 static int nl80211_get_reg(struct nl_msg *msg, void *arg)
3397 {
3398         struct phy_info_arg *results = arg;
3399         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
3400         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3401         struct nlattr *nl_rule;
3402         struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1];
3403         int rem_rule;
3404         static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
3405                 [NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
3406                 [NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
3407                 [NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
3408                 [NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
3409                 [NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
3410                 [NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
3411         };
3412
3413         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3414                   genlmsg_attrlen(gnlh, 0), NULL);
3415         if (!tb_msg[NL80211_ATTR_REG_ALPHA2] ||
3416             !tb_msg[NL80211_ATTR_REG_RULES]) {
3417                 wpa_printf(MSG_DEBUG, "nl80211: No regulatory information "
3418                            "available");
3419                 return NL_SKIP;
3420         }
3421
3422         wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s",
3423                    (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]));
3424
3425         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
3426         {
3427                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
3428                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
3429                 nl80211_reg_rule_ht40(tb_rule, results);
3430         }
3431
3432         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
3433         {
3434                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
3435                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
3436                 nl80211_reg_rule_sec(tb_rule, results);
3437         }
3438
3439         return NL_SKIP;
3440 }
3441
3442
3443 static int nl80211_set_ht40_flags(struct wpa_driver_nl80211_data *drv,
3444                                   struct phy_info_arg *results)
3445 {
3446         struct nl_msg *msg;
3447
3448         msg = nlmsg_alloc();
3449         if (!msg)
3450                 return -ENOMEM;
3451
3452         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3453                     0, NL80211_CMD_GET_REG, 0);
3454         return send_and_recv_msgs(drv, msg, nl80211_get_reg, results);
3455 }
3456
3457
3458 static struct hostapd_hw_modes *
3459 wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
3460 {
3461         struct i802_bss *bss = priv;
3462         struct wpa_driver_nl80211_data *drv = bss->drv;
3463         struct nl_msg *msg;
3464         struct phy_info_arg result = {
3465                 .num_modes = num_modes,
3466                 .modes = NULL,
3467         };
3468
3469         *num_modes = 0;
3470         *flags = 0;
3471
3472         msg = nlmsg_alloc();
3473         if (!msg)
3474                 return NULL;
3475
3476         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3477                     0, NL80211_CMD_GET_WIPHY, 0);
3478
3479         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3480
3481         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) {
3482                 nl80211_set_ht40_flags(drv, &result);
3483                 return wpa_driver_nl80211_add_11b(result.modes, num_modes);
3484         }
3485  nla_put_failure:
3486         return NULL;
3487 }
3488
3489
3490 static int wpa_driver_nl80211_send_frame(struct wpa_driver_nl80211_data *drv,
3491                                          const void *data, size_t len,
3492                                          int encrypt)
3493 {
3494         __u8 rtap_hdr[] = {
3495                 0x00, 0x00, /* radiotap version */
3496                 0x0e, 0x00, /* radiotap length */
3497                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
3498                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
3499                 0x00,       /* padding */
3500                 0x00, 0x00, /* RX and TX flags to indicate that */
3501                 0x00, 0x00, /* this is the injected frame directly */
3502         };
3503         struct iovec iov[2] = {
3504                 {
3505                         .iov_base = &rtap_hdr,
3506                         .iov_len = sizeof(rtap_hdr),
3507                 },
3508                 {
3509                         .iov_base = (void *) data,
3510                         .iov_len = len,
3511                 }
3512         };
3513         struct msghdr msg = {
3514                 .msg_name = NULL,
3515                 .msg_namelen = 0,
3516                 .msg_iov = iov,
3517                 .msg_iovlen = 2,
3518                 .msg_control = NULL,
3519                 .msg_controllen = 0,
3520                 .msg_flags = 0,
3521         };
3522         int res;
3523
3524         if (encrypt)
3525                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
3526
3527         res = sendmsg(drv->monitor_sock, &msg, 0);
3528         if (res < 0) {
3529                 wpa_printf(MSG_INFO, "nl80211: sendmsg: %s", strerror(errno));
3530                 return -1;
3531         }
3532         return 0;
3533 }
3534
3535
3536 static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
3537                                         size_t data_len)
3538 {
3539         struct i802_bss *bss = priv;
3540         struct wpa_driver_nl80211_data *drv = bss->drv;
3541         struct ieee80211_mgmt *mgmt;
3542         int encrypt = 1;
3543         u16 fc;
3544
3545         mgmt = (struct ieee80211_mgmt *) data;
3546         fc = le_to_host16(mgmt->frame_control);
3547
3548         if (drv->nlmode == NL80211_IFTYPE_STATION &&
3549             WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
3550             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_PROBE_RESP) {
3551                 /*
3552                  * The use of last_mgmt_freq is a bit of a hack,
3553                  * but it works due to the single-threaded nature
3554                  * of wpa_supplicant.
3555                  */
3556                 return nl80211_send_frame_cmd(drv, drv->last_mgmt_freq, 0,
3557                                               data, data_len, NULL);
3558         }
3559
3560         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
3561             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
3562                 /*
3563                  * Only one of the authentication frame types is encrypted.
3564                  * In order for static WEP encryption to work properly (i.e.,
3565                  * to not encrypt the frame), we need to tell mac80211 about
3566                  * the frames that must not be encrypted.
3567                  */
3568                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
3569                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
3570                 if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
3571                         encrypt = 0;
3572         }
3573
3574         return wpa_driver_nl80211_send_frame(drv, data, data_len, encrypt);
3575 }
3576
3577
3578 static int wpa_driver_nl80211_set_beacon(void *priv,
3579                                          const u8 *head, size_t head_len,
3580                                          const u8 *tail, size_t tail_len,
3581                                          int dtim_period, int beacon_int)
3582 {
3583         struct i802_bss *bss = priv;
3584         struct wpa_driver_nl80211_data *drv = bss->drv;
3585         struct nl_msg *msg;
3586         u8 cmd = NL80211_CMD_NEW_BEACON;
3587         int ret;
3588         int beacon_set;
3589         int ifindex = if_nametoindex(bss->ifname);
3590
3591         beacon_set = bss->beacon_set;
3592
3593         msg = nlmsg_alloc();
3594         if (!msg)
3595                 return -ENOMEM;
3596
3597         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
3598                    beacon_set);
3599         if (beacon_set)
3600                 cmd = NL80211_CMD_SET_BEACON;
3601
3602         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3603                     0, cmd, 0);
3604         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, head_len, head);
3605         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, tail_len, tail);
3606         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
3607         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, beacon_int);
3608         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, dtim_period);
3609
3610         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3611         if (ret) {
3612                 wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
3613                            ret, strerror(-ret));
3614         } else {
3615                 bss->beacon_set = 1;
3616         }
3617         return ret;
3618  nla_put_failure:
3619         return -ENOBUFS;
3620 }
3621
3622
3623 static int wpa_driver_nl80211_set_freq(struct wpa_driver_nl80211_data *drv,
3624                                        int freq, int ht_enabled,
3625                                        int sec_channel_offset)
3626 {
3627         struct nl_msg *msg;
3628         int ret;
3629
3630         msg = nlmsg_alloc();
3631         if (!msg)
3632                 return -1;
3633
3634         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
3635                     NL80211_CMD_SET_WIPHY, 0);
3636
3637         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3638         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
3639         if (ht_enabled) {
3640                 switch (sec_channel_offset) {
3641                 case -1:
3642                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3643                                     NL80211_CHAN_HT40MINUS);
3644                         break;
3645                 case 1:
3646                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3647                                     NL80211_CHAN_HT40PLUS);
3648                         break;
3649                 default:
3650                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3651                                     NL80211_CHAN_HT20);
3652                         break;
3653                 }
3654         }
3655
3656         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3657         if (ret == 0)
3658                 return 0;
3659         wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
3660                    "%d (%s)", freq, ret, strerror(-ret));
3661 nla_put_failure:
3662         return -1;
3663 }
3664
3665
3666 static int wpa_driver_nl80211_sta_add(void *priv,
3667                                       struct hostapd_sta_add_params *params)
3668 {
3669         struct i802_bss *bss = priv;
3670         struct wpa_driver_nl80211_data *drv = bss->drv;
3671         struct nl_msg *msg;
3672         int ret = -ENOBUFS;
3673
3674         msg = nlmsg_alloc();
3675         if (!msg)
3676                 return -ENOMEM;
3677
3678         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3679                     0, NL80211_CMD_NEW_STATION, 0);
3680
3681         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
3682         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
3683         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
3684         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
3685                 params->supp_rates);
3686         NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
3687                     params->listen_interval);
3688         if (params->ht_capabilities) {
3689                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
3690                         sizeof(*params->ht_capabilities),
3691                         params->ht_capabilities);
3692         }
3693
3694         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3695         if (ret)
3696                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_NEW_STATION "
3697                            "result: %d (%s)", ret, strerror(-ret));
3698         if (ret == -EEXIST)
3699                 ret = 0;
3700  nla_put_failure:
3701         return ret;
3702 }
3703
3704
3705 static int wpa_driver_nl80211_sta_remove(void *priv, const u8 *addr)
3706 {
3707         struct i802_bss *bss = priv;
3708         struct wpa_driver_nl80211_data *drv = bss->drv;
3709         struct nl_msg *msg;
3710         int ret;
3711
3712         msg = nlmsg_alloc();
3713         if (!msg)
3714                 return -ENOMEM;
3715
3716         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3717                     0, NL80211_CMD_DEL_STATION, 0);
3718
3719         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3720                     if_nametoindex(bss->ifname));
3721         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3722
3723         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3724         if (ret == -ENOENT)
3725                 return 0;
3726         return ret;
3727  nla_put_failure:
3728         return -ENOBUFS;
3729 }
3730
3731
3732 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
3733                                  int ifidx)
3734 {
3735         struct nl_msg *msg;
3736
3737         wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
3738
3739 #ifdef HOSTAPD
3740         /* stop listening for EAPOL on this interface */
3741         del_ifidx(drv, ifidx);
3742 #endif /* HOSTAPD */
3743
3744         msg = nlmsg_alloc();
3745         if (!msg)
3746                 goto nla_put_failure;
3747
3748         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3749                     0, NL80211_CMD_DEL_INTERFACE, 0);
3750         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
3751
3752         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
3753                 return;
3754  nla_put_failure:
3755         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
3756 }
3757
3758
3759 static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
3760                                      const char *ifname,
3761                                      enum nl80211_iftype iftype,
3762                                      const u8 *addr, int wds)
3763 {
3764         struct nl_msg *msg, *flags = NULL;
3765         int ifidx;
3766         int ret = -ENOBUFS;
3767
3768         msg = nlmsg_alloc();
3769         if (!msg)
3770                 return -1;
3771
3772         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3773                     0, NL80211_CMD_NEW_INTERFACE, 0);
3774         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3775         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
3776         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
3777
3778         if (iftype == NL80211_IFTYPE_MONITOR) {
3779                 int err;
3780
3781                 flags = nlmsg_alloc();
3782                 if (!flags)
3783                         goto nla_put_failure;
3784
3785                 NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
3786
3787                 err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
3788
3789                 nlmsg_free(flags);
3790
3791                 if (err)
3792                         goto nla_put_failure;
3793         } else if (wds) {
3794                 NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
3795         }
3796
3797         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3798         if (ret) {
3799  nla_put_failure:
3800                 wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
3801                            ifname, ret, strerror(-ret));
3802                 return ret;
3803         }
3804
3805         ifidx = if_nametoindex(ifname);
3806         wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
3807                    ifname, ifidx);
3808
3809         if (ifidx <= 0)
3810                 return -1;
3811
3812 #ifdef HOSTAPD
3813         /* start listening for EAPOL on this interface */
3814         add_ifidx(drv, ifidx);
3815 #endif /* HOSTAPD */
3816
3817         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
3818             linux_set_ifhwaddr(drv->ioctl_sock, ifname, addr)) {
3819                 nl80211_remove_iface(drv, ifidx);
3820                 return -1;
3821         }
3822
3823         return ifidx;
3824 }
3825
3826
3827 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
3828                                 const char *ifname, enum nl80211_iftype iftype,
3829                                 const u8 *addr, int wds)
3830 {
3831         int ret;
3832
3833         ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds);
3834
3835         /* if error occured and interface exists already */
3836         if (ret == -ENFILE && if_nametoindex(ifname)) {
3837                 wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
3838
3839                 /* Try to remove the interface that was already there. */
3840                 nl80211_remove_iface(drv, if_nametoindex(ifname));
3841
3842                 /* Try to create the interface again */
3843                 ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
3844                                                 wds);
3845         }
3846
3847         if (ret >= 0 && drv->disable_11b_rates)
3848                 nl80211_disable_11b_rates(drv, ret, 1);
3849
3850         return ret;
3851 }
3852
3853
3854 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
3855 {
3856         struct ieee80211_hdr *hdr;
3857         u16 fc;
3858         union wpa_event_data event;
3859
3860         hdr = (struct ieee80211_hdr *) buf;
3861         fc = le_to_host16(hdr->frame_control);
3862
3863         os_memset(&event, 0, sizeof(event));
3864         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
3865         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
3866         event.tx_status.dst = hdr->addr1;
3867         event.tx_status.data = buf;
3868         event.tx_status.data_len = len;
3869         event.tx_status.ack = ok;
3870         wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
3871 }
3872
3873
3874 static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
3875                              u8 *buf, size_t len)
3876 {
3877         union wpa_event_data event;
3878         os_memset(&event, 0, sizeof(event));
3879         event.rx_from_unknown.frame = buf;
3880         event.rx_from_unknown.len = len;
3881         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
3882 }
3883
3884
3885 static void handle_frame(struct wpa_driver_nl80211_data *drv,
3886                          u8 *buf, size_t len, int datarate, int ssi_signal)
3887 {
3888         struct ieee80211_hdr *hdr;
3889         u16 fc;
3890         union wpa_event_data event;
3891
3892         hdr = (struct ieee80211_hdr *) buf;
3893         fc = le_to_host16(hdr->frame_control);
3894
3895         switch (WLAN_FC_GET_TYPE(fc)) {
3896         case WLAN_FC_TYPE_MGMT:
3897                 os_memset(&event, 0, sizeof(event));
3898                 event.rx_mgmt.frame = buf;
3899                 event.rx_mgmt.frame_len = len;
3900                 event.rx_mgmt.datarate = datarate;
3901                 event.rx_mgmt.ssi_signal = ssi_signal;
3902                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
3903                 break;
3904         case WLAN_FC_TYPE_CTRL:
3905                 /* can only get here with PS-Poll frames */
3906                 wpa_printf(MSG_DEBUG, "CTRL");
3907                 from_unknown_sta(drv, buf, len);
3908                 break;
3909         case WLAN_FC_TYPE_DATA:
3910                 from_unknown_sta(drv, buf, len);
3911                 break;
3912         }
3913 }
3914
3915
3916 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
3917 {
3918         struct wpa_driver_nl80211_data *drv = eloop_ctx;
3919         int len;
3920         unsigned char buf[3000];
3921         struct ieee80211_radiotap_iterator iter;
3922         int ret;
3923         int datarate = 0, ssi_signal = 0;
3924         int injected = 0, failed = 0, rxflags = 0;
3925
3926         len = recv(sock, buf, sizeof(buf), 0);
3927         if (len < 0) {
3928                 perror("recv");
3929                 return;
3930         }
3931
3932         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
3933                 printf("received invalid radiotap frame\n");
3934                 return;
3935         }
3936
3937         while (1) {
3938                 ret = ieee80211_radiotap_iterator_next(&iter);
3939                 if (ret == -ENOENT)
3940                         break;
3941                 if (ret) {
3942                         printf("received invalid radiotap frame (%d)\n", ret);
3943                         return;
3944                 }
3945                 switch (iter.this_arg_index) {
3946                 case IEEE80211_RADIOTAP_FLAGS:
3947                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
3948                                 len -= 4;
3949                         break;
3950                 case IEEE80211_RADIOTAP_RX_FLAGS:
3951                         rxflags = 1;
3952                         break;
3953                 case IEEE80211_RADIOTAP_TX_FLAGS:
3954                         injected = 1;
3955                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
3956                                         IEEE80211_RADIOTAP_F_TX_FAIL;
3957                         break;
3958                 case IEEE80211_RADIOTAP_DATA_RETRIES:
3959                         break;
3960                 case IEEE80211_RADIOTAP_CHANNEL:
3961                         /* TODO: convert from freq/flags to channel number */
3962                         break;
3963                 case IEEE80211_RADIOTAP_RATE:
3964                         datarate = *iter.this_arg * 5;
3965                         break;
3966                 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
3967                         ssi_signal = *iter.this_arg;
3968                         break;
3969                 }
3970         }
3971
3972         if (rxflags && injected)
3973                 return;
3974
3975         if (!injected)
3976                 handle_frame(drv, buf + iter.max_length,
3977                              len - iter.max_length, datarate, ssi_signal);
3978         else
3979                 handle_tx_callback(drv->ctx, buf + iter.max_length,
3980                                    len - iter.max_length, !failed);
3981 }
3982
3983
3984 /*
3985  * we post-process the filter code later and rewrite
3986  * this to the offset to the last instruction
3987  */
3988 #define PASS    0xFF
3989 #define FAIL    0xFE
3990
3991 static struct sock_filter msock_filter_insns[] = {
3992         /*
3993          * do a little-endian load of the radiotap length field
3994          */
3995         /* load lower byte into A */
3996         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
3997         /* put it into X (== index register) */
3998         BPF_STMT(BPF_MISC| BPF_TAX, 0),
3999         /* load upper byte into A */
4000         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
4001         /* left-shift it by 8 */
4002         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
4003         /* or with X */
4004         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
4005         /* put result into X */
4006         BPF_STMT(BPF_MISC| BPF_TAX, 0),
4007
4008         /*
4009          * Allow management frames through, this also gives us those
4010          * management frames that we sent ourselves with status
4011          */
4012         /* load the lower byte of the IEEE 802.11 frame control field */
4013         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
4014         /* mask off frame type and version */
4015         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
4016         /* accept frame if it's both 0, fall through otherwise */
4017         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
4018
4019         /*
4020          * TODO: add a bit to radiotap RX flags that indicates
4021          * that the sending station is not associated, then
4022          * add a filter here that filters on our DA and that flag
4023          * to allow us to deauth frames to that bad station.
4024          *
4025          * For now allow all To DS data frames through.
4026          */
4027         /* load the IEEE 802.11 frame control field */
4028         BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
4029         /* mask off frame type, version and DS status */
4030         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
4031         /* accept frame if version 0, type 2 and To DS, fall through otherwise
4032          */
4033         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
4034
4035 #if 0
4036         /*
4037          * drop non-data frames
4038          */
4039         /* load the lower byte of the frame control field */
4040         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
4041         /* mask off QoS bit */
4042         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
4043         /* drop non-data frames */
4044         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
4045 #endif
4046         /* load the upper byte of the frame control field */
4047         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
4048         /* mask off toDS/fromDS */
4049         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
4050         /* accept WDS frames */
4051         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
4052
4053         /*
4054          * add header length to index
4055          */
4056         /* load the lower byte of the frame control field */
4057         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
4058         /* mask off QoS bit */
4059         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
4060         /* right shift it by 6 to give 0 or 2 */
4061         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
4062         /* add data frame header length */
4063         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
4064         /* add index, was start of 802.11 header */
4065         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
4066         /* move to index, now start of LL header */
4067         BPF_STMT(BPF_MISC | BPF_TAX, 0),
4068
4069         /*
4070          * Accept empty data frames, we use those for
4071          * polling activity.
4072          */
4073         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
4074         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
4075
4076         /*
4077          * Accept EAPOL frames
4078          */
4079         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
4080         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
4081         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
4082         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
4083
4084         /* keep these last two statements or change the code below */
4085         /* return 0 == "DROP" */
4086         BPF_STMT(BPF_RET | BPF_K, 0),
4087         /* return ~0 == "keep all" */
4088         BPF_STMT(BPF_RET | BPF_K, ~0),
4089 };
4090
4091 static struct sock_fprog msock_filter = {
4092         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
4093         .filter = msock_filter_insns,
4094 };
4095
4096
4097 static int add_monitor_filter(int s)
4098 {
4099         int idx;
4100
4101         /* rewrite all PASS/FAIL jump offsets */
4102         for (idx = 0; idx < msock_filter.len; idx++) {
4103                 struct sock_filter *insn = &msock_filter_insns[idx];
4104
4105                 if (BPF_CLASS(insn->code) == BPF_JMP) {
4106                         if (insn->code == (BPF_JMP|BPF_JA)) {
4107                                 if (insn->k == PASS)
4108                                         insn->k = msock_filter.len - idx - 2;
4109                                 else if (insn->k == FAIL)
4110                                         insn->k = msock_filter.len - idx - 3;
4111                         }
4112
4113                         if (insn->jt == PASS)
4114                                 insn->jt = msock_filter.len - idx - 2;
4115                         else if (insn->jt == FAIL)
4116                                 insn->jt = msock_filter.len - idx - 3;
4117
4118                         if (insn->jf == PASS)
4119                                 insn->jf = msock_filter.len - idx - 2;
4120                         else if (insn->jf == FAIL)
4121                                 insn->jf = msock_filter.len - idx - 3;
4122                 }
4123         }
4124
4125         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
4126                        &msock_filter, sizeof(msock_filter))) {
4127                 perror("SO_ATTACH_FILTER");
4128                 return -1;
4129         }
4130
4131         return 0;
4132 }
4133
4134
4135 static void nl80211_remove_monitor_interface(
4136         struct wpa_driver_nl80211_data *drv)
4137 {
4138         if (drv->monitor_ifidx >= 0) {
4139                 nl80211_remove_iface(drv, drv->monitor_ifidx);
4140                 drv->monitor_ifidx = -1;
4141         }
4142         if (drv->monitor_sock >= 0) {
4143                 eloop_unregister_read_sock(drv->monitor_sock);
4144                 close(drv->monitor_sock);
4145                 drv->monitor_sock = -1;
4146         }
4147 }
4148
4149
4150 static int
4151 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
4152 {
4153         char buf[IFNAMSIZ];
4154         struct sockaddr_ll ll;
4155         int optval;
4156         socklen_t optlen;
4157
4158         snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss.ifname);
4159         buf[IFNAMSIZ - 1] = '\0';
4160
4161         drv->monitor_ifidx =
4162                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
4163                                      0);
4164
4165         if (drv->monitor_ifidx < 0)
4166                 return -1;
4167
4168         if (linux_set_iface_flags(drv->ioctl_sock, buf, 1))
4169                 goto error;
4170
4171         memset(&ll, 0, sizeof(ll));
4172         ll.sll_family = AF_PACKET;
4173         ll.sll_ifindex = drv->monitor_ifidx;
4174         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
4175         if (drv->monitor_sock < 0) {
4176                 perror("socket[PF_PACKET,SOCK_RAW]");
4177                 goto error;
4178         }
4179
4180         if (add_monitor_filter(drv->monitor_sock)) {
4181                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
4182                            "interface; do filtering in user space");
4183                 /* This works, but will cost in performance. */
4184         }
4185
4186         if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
4187                 perror("monitor socket bind");
4188                 goto error;
4189         }
4190
4191         optlen = sizeof(optval);
4192         optval = 20;
4193         if (setsockopt
4194             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
4195                 perror("Failed to set socket priority");
4196                 goto error;
4197         }
4198
4199         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
4200                                      drv, NULL)) {
4201                 printf("Could not register monitor read socket\n");
4202                 goto error;
4203         }
4204
4205         return 0;
4206  error:
4207         nl80211_remove_monitor_interface(drv);
4208         return -1;
4209 }
4210
4211
4212 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
4213
4214 static int wpa_driver_nl80211_hapd_send_eapol(
4215         void *priv, const u8 *addr, const u8 *data,
4216         size_t data_len, int encrypt, const u8 *own_addr)
4217 {
4218         struct i802_bss *bss = priv;
4219         struct wpa_driver_nl80211_data *drv = bss->drv;
4220         struct ieee80211_hdr *hdr;
4221         size_t len;
4222         u8 *pos;
4223         int res;
4224 #if 0 /* FIX */
4225         int qos = sta->flags & WPA_STA_WMM;
4226 #else
4227         int qos = 0;
4228 #endif
4229
4230         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
4231                 data_len;
4232         hdr = os_zalloc(len);
4233         if (hdr == NULL) {
4234                 printf("malloc() failed for i802_send_data(len=%lu)\n",
4235                        (unsigned long) len);
4236                 return -1;
4237         }
4238
4239         hdr->frame_control =
4240                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
4241         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
4242         if (encrypt)
4243                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
4244 #if 0 /* To be enabled if qos determination is added above */
4245         if (qos) {
4246                 hdr->frame_control |=
4247                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
4248         }
4249 #endif
4250
4251         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
4252         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
4253         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
4254         pos = (u8 *) (hdr + 1);
4255
4256 #if 0 /* To be enabled if qos determination is added above */
4257         if (qos) {
4258                 /* add an empty QoS header if needed */
4259                 pos[0] = 0;
4260                 pos[1] = 0;
4261                 pos += 2;
4262         }
4263 #endif
4264
4265         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
4266         pos += sizeof(rfc1042_header);
4267         WPA_PUT_BE16(pos, ETH_P_PAE);
4268         pos += 2;
4269         memcpy(pos, data, data_len);
4270
4271         res = wpa_driver_nl80211_send_frame(drv, (u8 *) hdr, len, encrypt);
4272         if (res < 0) {
4273                 wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
4274                            "failed: %d (%s)",
4275                            (unsigned long) len, errno, strerror(errno));
4276         }
4277         os_free(hdr);
4278
4279         return res;
4280 }
4281
4282
4283 static u32 sta_flags_nl80211(int flags)
4284 {
4285         u32 f = 0;
4286
4287         if (flags & WPA_STA_AUTHORIZED)
4288                 f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
4289         if (flags & WPA_STA_WMM)
4290                 f |= BIT(NL80211_STA_FLAG_WME);
4291         if (flags & WPA_STA_SHORT_PREAMBLE)
4292                 f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
4293         if (flags & WPA_STA_MFP)
4294                 f |= BIT(NL80211_STA_FLAG_MFP);
4295
4296         return f;
4297 }
4298
4299
4300 static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
4301                                             int total_flags,
4302                                             int flags_or, int flags_and)
4303 {
4304         struct i802_bss *bss = priv;
4305         struct wpa_driver_nl80211_data *drv = bss->drv;
4306         struct nl_msg *msg, *flags = NULL;
4307         struct nl80211_sta_flag_update upd;
4308
4309         msg = nlmsg_alloc();
4310         if (!msg)
4311                 return -ENOMEM;
4312
4313         flags = nlmsg_alloc();
4314         if (!flags) {
4315                 nlmsg_free(msg);
4316                 return -ENOMEM;
4317         }
4318
4319         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4320                     0, NL80211_CMD_SET_STATION, 0);
4321
4322         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
4323                     if_nametoindex(bss->ifname));
4324         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4325
4326         /*
4327          * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
4328          * can be removed eventually.
4329          */
4330         if (total_flags & WPA_STA_AUTHORIZED)
4331                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
4332
4333         if (total_flags & WPA_STA_WMM)
4334                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
4335
4336         if (total_flags & WPA_STA_SHORT_PREAMBLE)
4337                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
4338
4339         if (total_flags & WPA_STA_MFP)
4340                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
4341
4342         if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
4343                 goto nla_put_failure;
4344
4345         os_memset(&upd, 0, sizeof(upd));
4346         upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
4347         upd.set = sta_flags_nl80211(flags_or);
4348         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
4349
4350         nlmsg_free(flags);
4351
4352         return send_and_recv_msgs(drv, msg, NULL, NULL);
4353  nla_put_failure:
4354         nlmsg_free(flags);
4355         return -ENOBUFS;
4356 }
4357
4358
4359 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
4360                                  struct wpa_driver_associate_params *params)
4361 {
4362         if (params->p2p)
4363                 wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
4364                            "group (GO)");
4365         if (wpa_driver_nl80211_set_mode(&drv->first_bss, params->mode) ||
4366             wpa_driver_nl80211_set_freq(drv, params->freq, 0, 0)) {
4367                 nl80211_remove_monitor_interface(drv);
4368                 return -1;
4369         }
4370
4371         /* TODO: setup monitor interface (and add code somewhere to remove this
4372          * when AP mode is stopped; associate with mode != 2 or drv_deinit) */
4373
4374         return 0;
4375 }
4376
4377
4378 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
4379 {
4380         struct nl_msg *msg;
4381         int ret = -1;
4382
4383         msg = nlmsg_alloc();
4384         if (!msg)
4385                 return -1;
4386
4387         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4388                     NL80211_CMD_LEAVE_IBSS, 0);
4389         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4390         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4391         msg = NULL;
4392         if (ret) {
4393                 wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
4394                            "(%s)", ret, strerror(-ret));
4395                 goto nla_put_failure;
4396         }
4397
4398         ret = 0;
4399         wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
4400
4401 nla_put_failure:
4402         nlmsg_free(msg);
4403         return ret;
4404 }
4405
4406
4407 static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
4408                                    struct wpa_driver_associate_params *params)
4409 {
4410         struct nl_msg *msg;
4411         int ret = -1;
4412         int count = 0;
4413
4414         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
4415
4416         if (wpa_driver_nl80211_set_mode(&drv->first_bss, params->mode)) {
4417                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
4418                            "IBSS mode");
4419                 return -1;
4420         }
4421
4422 retry:
4423         msg = nlmsg_alloc();
4424         if (!msg)
4425                 return -1;
4426
4427         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4428                     NL80211_CMD_JOIN_IBSS, 0);
4429         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4430
4431         if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
4432                 goto nla_put_failure;
4433
4434         wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4435                           params->ssid, params->ssid_len);
4436         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4437                 params->ssid);
4438         os_memcpy(drv->ssid, params->ssid, params->ssid_len);
4439         drv->ssid_len = params->ssid_len;
4440
4441         wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4442         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4443
4444         ret = nl80211_set_conn_keys(params, msg);
4445         if (ret)
4446                 goto nla_put_failure;
4447
4448         if (params->wpa_ie) {
4449                 wpa_hexdump(MSG_DEBUG,
4450                             "  * Extra IEs for Beacon/Probe Response frames",
4451                             params->wpa_ie, params->wpa_ie_len);
4452                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
4453                         params->wpa_ie);
4454         }
4455
4456         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4457         msg = NULL;
4458         if (ret) {
4459                 wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
4460                            ret, strerror(-ret));
4461                 count++;
4462                 if (ret == -EALREADY && count == 1) {
4463                         wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
4464                                    "forced leave");
4465                         nl80211_leave_ibss(drv);
4466                         nlmsg_free(msg);
4467                         goto retry;
4468                 }
4469
4470                 goto nla_put_failure;
4471         }
4472         ret = 0;
4473         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
4474
4475 nla_put_failure:
4476         nlmsg_free(msg);
4477         return ret;
4478 }
4479
4480
4481 static int wpa_driver_nl80211_connect(
4482         struct wpa_driver_nl80211_data *drv,
4483         struct wpa_driver_associate_params *params)
4484 {
4485         struct nl_msg *msg;
4486         enum nl80211_auth_type type;
4487         int ret = 0;
4488
4489         msg = nlmsg_alloc();
4490         if (!msg)
4491                 return -1;
4492
4493         wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
4494         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4495                     NL80211_CMD_CONNECT, 0);
4496
4497         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4498         if (params->bssid) {
4499                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4500                            MAC2STR(params->bssid));
4501                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4502         }
4503         if (params->freq) {
4504                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4505                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4506         }
4507         if (params->ssid) {
4508                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4509                                   params->ssid, params->ssid_len);
4510                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4511                         params->ssid);
4512                 if (params->ssid_len > sizeof(drv->ssid))
4513                         goto nla_put_failure;
4514                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
4515                 drv->ssid_len = params->ssid_len;
4516         }
4517         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
4518         if (params->wpa_ie)
4519                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
4520                         params->wpa_ie);
4521
4522         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
4523                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
4524         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
4525                 type = NL80211_AUTHTYPE_SHARED_KEY;
4526         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
4527                 type = NL80211_AUTHTYPE_NETWORK_EAP;
4528         else if (params->auth_alg & WPA_AUTH_ALG_FT)
4529                 type = NL80211_AUTHTYPE_FT;
4530         else
4531                 goto nla_put_failure;
4532
4533         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
4534         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
4535
4536         if (params->wpa_ie && params->wpa_ie_len) {
4537                 enum nl80211_wpa_versions ver;
4538
4539                 if (params->wpa_ie[0] == WLAN_EID_RSN)
4540                         ver = NL80211_WPA_VERSION_2;
4541                 else
4542                         ver = NL80211_WPA_VERSION_1;
4543
4544                 wpa_printf(MSG_DEBUG, "  * WPA Version %d", ver);
4545                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
4546         }
4547
4548         if (params->pairwise_suite != CIPHER_NONE) {
4549                 int cipher;
4550
4551                 switch (params->pairwise_suite) {
4552                 case CIPHER_WEP40:
4553                         cipher = WLAN_CIPHER_SUITE_WEP40;
4554                         break;
4555                 case CIPHER_WEP104:
4556                         cipher = WLAN_CIPHER_SUITE_WEP104;
4557                         break;
4558                 case CIPHER_CCMP:
4559                         cipher = WLAN_CIPHER_SUITE_CCMP;
4560                         break;
4561                 case CIPHER_TKIP:
4562                 default:
4563                         cipher = WLAN_CIPHER_SUITE_TKIP;
4564                         break;
4565                 }
4566                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
4567         }
4568
4569         if (params->group_suite != CIPHER_NONE) {
4570                 int cipher;
4571
4572                 switch (params->group_suite) {
4573                 case CIPHER_WEP40:
4574                         cipher = WLAN_CIPHER_SUITE_WEP40;
4575                         break;
4576                 case CIPHER_WEP104:
4577                         cipher = WLAN_CIPHER_SUITE_WEP104;
4578                         break;
4579                 case CIPHER_CCMP:
4580                         cipher = WLAN_CIPHER_SUITE_CCMP;
4581                         break;
4582                 case CIPHER_TKIP:
4583                 default:
4584                         cipher = WLAN_CIPHER_SUITE_TKIP;
4585                         break;
4586                 }
4587                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
4588         }
4589
4590         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
4591             params->key_mgmt_suite == KEY_MGMT_PSK) {
4592                 int mgmt = WLAN_AKM_SUITE_PSK;
4593
4594                 switch (params->key_mgmt_suite) {
4595                 case KEY_MGMT_802_1X:
4596                         mgmt = WLAN_AKM_SUITE_8021X;
4597                         break;
4598                 case KEY_MGMT_PSK:
4599                 default:
4600                         mgmt = WLAN_AKM_SUITE_PSK;
4601                         break;
4602                 }
4603                 NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
4604         }
4605
4606         ret = nl80211_set_conn_keys(params, msg);
4607         if (ret)
4608                 goto nla_put_failure;
4609
4610         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4611         msg = NULL;
4612         if (ret) {
4613                 wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
4614                            "(%s)", ret, strerror(-ret));
4615                 goto nla_put_failure;
4616         }
4617         ret = 0;
4618         wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
4619
4620 nla_put_failure:
4621         nlmsg_free(msg);
4622         return ret;
4623
4624 }
4625
4626
4627 static int wpa_driver_nl80211_associate(
4628         void *priv, struct wpa_driver_associate_params *params)
4629 {
4630         struct i802_bss *bss = priv;
4631         struct wpa_driver_nl80211_data *drv = bss->drv;
4632         int ret = -1;
4633         struct nl_msg *msg;
4634
4635         if (params->mode == IEEE80211_MODE_AP)
4636                 return wpa_driver_nl80211_ap(drv, params);
4637
4638         if (params->mode == IEEE80211_MODE_IBSS)
4639                 return wpa_driver_nl80211_ibss(drv, params);
4640
4641         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
4642                 if (wpa_driver_nl80211_set_mode(priv, params->mode) < 0)
4643                         return -1;
4644                 return wpa_driver_nl80211_connect(drv, params);
4645         }
4646
4647         drv->associated = 0;
4648
4649         msg = nlmsg_alloc();
4650         if (!msg)
4651                 return -1;
4652
4653         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
4654                    drv->ifindex);
4655         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4656                     NL80211_CMD_ASSOCIATE, 0);
4657
4658         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4659         if (params->bssid) {
4660                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4661                            MAC2STR(params->bssid));
4662                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4663         }
4664         if (params->freq) {
4665                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4666                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4667                 drv->assoc_freq = params->freq;
4668         } else
4669                 drv->assoc_freq = 0;
4670         if (params->ssid) {
4671                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4672                                   params->ssid, params->ssid_len);
4673                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4674                         params->ssid);
4675                 if (params->ssid_len > sizeof(drv->ssid))
4676                         goto nla_put_failure;
4677                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
4678                 drv->ssid_len = params->ssid_len;
4679         }
4680         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
4681         if (params->wpa_ie)
4682                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
4683                         params->wpa_ie);
4684
4685         if (params->pairwise_suite != CIPHER_NONE) {
4686                 int cipher;
4687
4688                 switch (params->pairwise_suite) {
4689                 case CIPHER_WEP40:
4690                         cipher = WLAN_CIPHER_SUITE_WEP40;
4691                         break;
4692                 case CIPHER_WEP104:
4693                         cipher = WLAN_CIPHER_SUITE_WEP104;
4694                         break;
4695                 case CIPHER_CCMP:
4696                         cipher = WLAN_CIPHER_SUITE_CCMP;
4697                         break;
4698                 case CIPHER_TKIP:
4699                 default:
4700                         cipher = WLAN_CIPHER_SUITE_TKIP;
4701                         break;
4702                 }
4703                 wpa_printf(MSG_DEBUG, "  * pairwise=0x%x", cipher);
4704                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
4705         }
4706
4707         if (params->group_suite != CIPHER_NONE) {
4708                 int cipher;
4709
4710                 switch (params->group_suite) {
4711                 case CIPHER_WEP40:
4712                         cipher = WLAN_CIPHER_SUITE_WEP40;
4713                         break;
4714                 case CIPHER_WEP104:
4715                         cipher = WLAN_CIPHER_SUITE_WEP104;
4716                         break;
4717                 case CIPHER_CCMP:
4718                         cipher = WLAN_CIPHER_SUITE_CCMP;
4719                         break;
4720                 case CIPHER_TKIP:
4721                 default:
4722                         cipher = WLAN_CIPHER_SUITE_TKIP;
4723                         break;
4724                 }
4725                 wpa_printf(MSG_DEBUG, "  * group=0x%x", cipher);
4726                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
4727         }
4728
4729 #ifdef CONFIG_IEEE80211W
4730         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
4731                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
4732 #endif /* CONFIG_IEEE80211W */
4733
4734         NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
4735
4736         if (params->prev_bssid) {
4737                 wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
4738                            MAC2STR(params->prev_bssid));
4739                 NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
4740                         params->prev_bssid);
4741         }
4742
4743         if (params->p2p)
4744                 wpa_printf(MSG_DEBUG, "  * P2P group");
4745
4746         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4747         msg = NULL;
4748         if (ret) {
4749                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
4750                            "(%s)", ret, strerror(-ret));
4751                 nl80211_dump_scan(drv);
4752                 goto nla_put_failure;
4753         }
4754         ret = 0;
4755         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
4756                    "successfully");
4757
4758 nla_put_failure:
4759         nlmsg_free(msg);
4760         return ret;
4761 }
4762
4763
4764 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
4765                             int ifindex, int mode)
4766 {
4767         struct nl_msg *msg;
4768         int ret = -ENOBUFS;
4769
4770         msg = nlmsg_alloc();
4771         if (!msg)
4772                 return -ENOMEM;
4773
4774         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4775                     0, NL80211_CMD_SET_INTERFACE, 0);
4776         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4777         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
4778
4779         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4780         if (!ret)
4781                 return 0;
4782 nla_put_failure:
4783         wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
4784                    " %d (%s)", ifindex, mode, ret, strerror(-ret));
4785         return ret;
4786 }
4787
4788
4789 static int wpa_driver_nl80211_set_mode(void *priv, int mode)
4790 {
4791         struct i802_bss *bss = priv;
4792         struct wpa_driver_nl80211_data *drv = bss->drv;
4793         int ret = -1;
4794         int nlmode;
4795         int i;
4796
4797         switch (mode) {
4798         case 0:
4799                 nlmode = NL80211_IFTYPE_STATION;
4800                 break;
4801         case 1:
4802                 nlmode = NL80211_IFTYPE_ADHOC;
4803                 break;
4804         case 2:
4805                 nlmode = NL80211_IFTYPE_AP;
4806                 break;
4807         default:
4808                 return -1;
4809         }
4810
4811         if (nl80211_set_mode(drv, drv->ifindex, nlmode) == 0) {
4812                 drv->nlmode = nlmode;
4813                 ret = 0;
4814                 goto done;
4815         }
4816
4817         if (nlmode == drv->nlmode) {
4818                 wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
4819                            "requested mode - ignore error");
4820                 ret = 0;
4821                 goto done; /* Already in the requested mode */
4822         }
4823
4824         /* mac80211 doesn't allow mode changes while the device is up, so
4825          * take the device down, try to set the mode again, and bring the
4826          * device back up.
4827          */
4828         wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
4829                    "interface down");
4830         for (i = 0; i < 10; i++) {
4831                 if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 0) ==
4832                     0) {
4833                         /* Try to set the mode again while the interface is
4834                          * down */
4835                         ret = nl80211_set_mode(drv, drv->ifindex, nlmode);
4836                         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname,
4837                                                   1))
4838                                 ret = -1;
4839                         if (!ret)
4840                                 break;
4841                 } else
4842                         wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
4843                                    "interface down");
4844                 os_sleep(0, 100000);
4845         }
4846
4847         if (!ret) {
4848                 wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
4849                            "interface is down");
4850                 drv->nlmode = nlmode;
4851         }
4852
4853 done:
4854         if (!ret && nlmode == NL80211_IFTYPE_AP) {
4855                 /* Setup additional AP mode functionality if needed */
4856                 if (drv->monitor_ifidx < 0 &&
4857                     nl80211_create_monitor_interface(drv))
4858                         return -1;
4859         } else if (!ret && nlmode != NL80211_IFTYPE_AP) {
4860                 /* Remove additional AP mode functionality */
4861                 nl80211_remove_monitor_interface(drv);
4862                 bss->beacon_set = 0;
4863         }
4864
4865         if (ret)
4866                 wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
4867                            "from %d failed", nlmode, drv->nlmode);
4868
4869         return ret;
4870 }
4871
4872
4873 static int wpa_driver_nl80211_get_capa(void *priv,
4874                                        struct wpa_driver_capa *capa)
4875 {
4876         struct i802_bss *bss = priv;
4877         struct wpa_driver_nl80211_data *drv = bss->drv;
4878         if (!drv->has_capability)
4879                 return -1;
4880         os_memcpy(capa, &drv->capa, sizeof(*capa));
4881         return 0;
4882 }
4883
4884
4885 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
4886 {
4887         struct i802_bss *bss = priv;
4888         struct wpa_driver_nl80211_data *drv = bss->drv;
4889
4890         wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
4891                    __func__, drv->operstate, state, state ? "UP" : "DORMANT");
4892         drv->operstate = state;
4893         return netlink_send_oper_ifla(drv->netlink, drv->ifindex, -1,
4894                                       state ? IF_OPER_UP : IF_OPER_DORMANT);
4895 }
4896
4897
4898 static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
4899 {
4900         struct i802_bss *bss = priv;
4901         struct wpa_driver_nl80211_data *drv = bss->drv;
4902         struct nl_msg *msg;
4903         struct nl80211_sta_flag_update upd;
4904
4905         msg = nlmsg_alloc();
4906         if (!msg)
4907                 return -ENOMEM;
4908
4909         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4910                     0, NL80211_CMD_SET_STATION, 0);
4911
4912         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
4913                     if_nametoindex(bss->ifname));
4914         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
4915
4916         os_memset(&upd, 0, sizeof(upd));
4917         upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
4918         if (authorized)
4919                 upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
4920         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
4921
4922         return send_and_recv_msgs(drv, msg, NULL, NULL);
4923  nla_put_failure:
4924         return -ENOBUFS;
4925 }
4926
4927
4928 #ifdef HOSTAPD
4929
4930 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
4931 {
4932         int i;
4933         int *old;
4934
4935         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
4936                    ifidx);
4937         for (i = 0; i < drv->num_if_indices; i++) {
4938                 if (drv->if_indices[i] == 0) {
4939                         drv->if_indices[i] = ifidx;
4940                         return;
4941                 }
4942         }
4943
4944         if (drv->if_indices != drv->default_if_indices)
4945                 old = drv->if_indices;
4946         else
4947                 old = NULL;
4948
4949         drv->if_indices = os_realloc(old,
4950                                      sizeof(int) * (drv->num_if_indices + 1));
4951         if (!drv->if_indices) {
4952                 if (!old)
4953                         drv->if_indices = drv->default_if_indices;
4954                 else
4955                         drv->if_indices = old;
4956                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
4957                            "interfaces");
4958                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
4959                 return;
4960         } else if (!old)
4961                 os_memcpy(drv->if_indices, drv->default_if_indices,
4962                           sizeof(drv->default_if_indices));
4963         drv->if_indices[drv->num_if_indices] = ifidx;
4964         drv->num_if_indices++;
4965 }
4966
4967
4968 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
4969 {
4970         int i;
4971
4972         for (i = 0; i < drv->num_if_indices; i++) {
4973                 if (drv->if_indices[i] == ifidx) {
4974                         drv->if_indices[i] = 0;
4975                         break;
4976                 }
4977         }
4978 }
4979
4980
4981 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
4982 {
4983         int i;
4984
4985         for (i = 0; i < drv->num_if_indices; i++)
4986                 if (drv->if_indices[i] == ifidx)
4987                         return 1;
4988
4989         return 0;
4990 }
4991
4992
4993 static inline int min_int(int a, int b)
4994 {
4995         if (a < b)
4996                 return a;
4997         return b;
4998 }
4999
5000
5001 static int get_key_handler(struct nl_msg *msg, void *arg)
5002 {
5003         struct nlattr *tb[NL80211_ATTR_MAX + 1];
5004         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5005
5006         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5007                   genlmsg_attrlen(gnlh, 0), NULL);
5008
5009         /*
5010          * TODO: validate the key index and mac address!
5011          * Otherwise, there's a race condition as soon as
5012          * the kernel starts sending key notifications.
5013          */
5014
5015         if (tb[NL80211_ATTR_KEY_SEQ])
5016                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
5017                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
5018         return NL_SKIP;
5019 }
5020
5021
5022 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
5023                            int idx, u8 *seq)
5024 {
5025         struct i802_bss *bss = priv;
5026         struct wpa_driver_nl80211_data *drv = bss->drv;
5027         struct nl_msg *msg;
5028
5029         msg = nlmsg_alloc();
5030         if (!msg)
5031                 return -ENOMEM;
5032
5033         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5034                     0, NL80211_CMD_GET_KEY, 0);
5035
5036         if (addr)
5037                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5038         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
5039         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
5040
5041         memset(seq, 0, 6);
5042
5043         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
5044  nla_put_failure:
5045         return -ENOBUFS;
5046 }
5047
5048
5049 static int i802_set_rate_sets(void *priv, int *supp_rates, int *basic_rates,
5050                               int mode)
5051 {
5052         struct i802_bss *bss = priv;
5053         struct wpa_driver_nl80211_data *drv = bss->drv;
5054         struct nl_msg *msg;
5055         u8 rates[NL80211_MAX_SUPP_RATES];
5056         u8 rates_len = 0;
5057         int i;
5058
5059         msg = nlmsg_alloc();
5060         if (!msg)
5061                 return -ENOMEM;
5062
5063         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5064                     NL80211_CMD_SET_BSS, 0);
5065
5066         for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0; i++)
5067                 rates[rates_len++] = basic_rates[i] / 5;
5068
5069         NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
5070
5071         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5072
5073         return send_and_recv_msgs(drv, msg, NULL, NULL);
5074  nla_put_failure:
5075         return -ENOBUFS;
5076 }
5077
5078 #endif /* HOSTAPD */
5079
5080
5081 /* Set kernel driver on given frequency (MHz) */
5082 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
5083 {
5084         struct i802_bss *bss = priv;
5085         struct wpa_driver_nl80211_data *drv = bss->drv;
5086         return wpa_driver_nl80211_set_freq(drv, freq->freq, freq->ht_enabled,
5087                                            freq->sec_channel_offset);
5088 }
5089
5090
5091 #ifdef HOSTAPD
5092
5093 static int i802_set_rts(void *priv, int rts)
5094 {
5095         struct i802_bss *bss = priv;
5096         struct wpa_driver_nl80211_data *drv = bss->drv;
5097         struct nl_msg *msg;
5098         int ret = -ENOBUFS;
5099         u32 val;
5100
5101         msg = nlmsg_alloc();
5102         if (!msg)
5103                 return -ENOMEM;
5104
5105         if (rts >= 2347)
5106                 val = (u32) -1;
5107         else
5108                 val = rts;
5109
5110         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5111                     0, NL80211_CMD_SET_WIPHY, 0);
5112         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5113         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
5114
5115         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5116         if (!ret)
5117                 return 0;
5118 nla_put_failure:
5119         wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
5120                    "%d (%s)", rts, ret, strerror(-ret));
5121         return ret;
5122 }
5123
5124
5125 static int i802_set_frag(void *priv, int frag)
5126 {
5127         struct i802_bss *bss = priv;
5128         struct wpa_driver_nl80211_data *drv = bss->drv;
5129         struct nl_msg *msg;
5130         int ret = -ENOBUFS;
5131         u32 val;
5132
5133         msg = nlmsg_alloc();
5134         if (!msg)
5135                 return -ENOMEM;
5136
5137         if (frag >= 2346)
5138                 val = (u32) -1;
5139         else
5140                 val = frag;
5141
5142         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5143                     0, NL80211_CMD_SET_WIPHY, 0);
5144         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5145         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
5146
5147         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5148         if (!ret)
5149                 return 0;
5150 nla_put_failure:
5151         wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
5152                    "%d: %d (%s)", frag, ret, strerror(-ret));
5153         return ret;
5154 }
5155
5156
5157 static int i802_flush(void *priv)
5158 {
5159         struct i802_bss *bss = priv;
5160         struct wpa_driver_nl80211_data *drv = bss->drv;
5161         struct nl_msg *msg;
5162
5163         msg = nlmsg_alloc();
5164         if (!msg)
5165                 return -1;
5166
5167         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5168                     0, NL80211_CMD_DEL_STATION, 0);
5169
5170         /*
5171          * XXX: FIX! this needs to flush all VLANs too
5172          */
5173         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5174                     if_nametoindex(bss->ifname));
5175
5176         return send_and_recv_msgs(drv, msg, NULL, NULL);
5177  nla_put_failure:
5178         return -ENOBUFS;
5179 }
5180
5181
5182 static int get_sta_handler(struct nl_msg *msg, void *arg)
5183 {
5184         struct nlattr *tb[NL80211_ATTR_MAX + 1];
5185         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5186         struct hostap_sta_driver_data *data = arg;
5187         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
5188         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
5189                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
5190                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
5191                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
5192                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
5193                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
5194         };
5195
5196         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5197                   genlmsg_attrlen(gnlh, 0), NULL);
5198
5199         /*
5200          * TODO: validate the interface and mac address!
5201          * Otherwise, there's a race condition as soon as
5202          * the kernel starts sending station notifications.
5203          */
5204
5205         if (!tb[NL80211_ATTR_STA_INFO]) {
5206                 wpa_printf(MSG_DEBUG, "sta stats missing!");
5207                 return NL_SKIP;
5208         }
5209         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
5210                              tb[NL80211_ATTR_STA_INFO],
5211                              stats_policy)) {
5212                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
5213                 return NL_SKIP;
5214         }
5215
5216         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
5217                 data->inactive_msec =
5218                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
5219         if (stats[NL80211_STA_INFO_RX_BYTES])
5220                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
5221         if (stats[NL80211_STA_INFO_TX_BYTES])
5222                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
5223         if (stats[NL80211_STA_INFO_RX_PACKETS])
5224                 data->rx_packets =
5225                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
5226         if (stats[NL80211_STA_INFO_TX_PACKETS])
5227                 data->tx_packets =
5228                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
5229
5230         return NL_SKIP;
5231 }
5232
5233 static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
5234                               const u8 *addr)
5235 {
5236         struct i802_bss *bss = priv;
5237         struct wpa_driver_nl80211_data *drv = bss->drv;
5238         struct nl_msg *msg;
5239
5240         os_memset(data, 0, sizeof(*data));
5241         msg = nlmsg_alloc();
5242         if (!msg)
5243                 return -ENOMEM;
5244
5245         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5246                     0, NL80211_CMD_GET_STATION, 0);
5247
5248         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5249         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5250
5251         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
5252  nla_put_failure:
5253         return -ENOBUFS;
5254 }
5255
5256
5257 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
5258                                     int cw_min, int cw_max, int burst_time)
5259 {
5260         struct i802_bss *bss = priv;
5261         struct wpa_driver_nl80211_data *drv = bss->drv;
5262         struct nl_msg *msg;
5263         struct nlattr *txq, *params;
5264
5265         msg = nlmsg_alloc();
5266         if (!msg)
5267                 return -1;
5268
5269         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5270                     0, NL80211_CMD_SET_WIPHY, 0);
5271
5272         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5273
5274         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
5275         if (!txq)
5276                 goto nla_put_failure;
5277
5278         /* We are only sending parameters for a single TXQ at a time */
5279         params = nla_nest_start(msg, 1);
5280         if (!params)
5281                 goto nla_put_failure;
5282
5283         switch (queue) {
5284         case 0:
5285                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
5286                 break;
5287         case 1:
5288                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
5289                 break;
5290         case 2:
5291                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
5292                 break;
5293         case 3:
5294                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
5295                 break;
5296         }
5297         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
5298          * 32 usec, so need to convert the value here. */
5299         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
5300         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
5301         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
5302         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
5303
5304         nla_nest_end(msg, params);
5305
5306         nla_nest_end(msg, txq);
5307
5308         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
5309                 return 0;
5310  nla_put_failure:
5311         return -1;
5312 }
5313
5314
5315 static int i802_set_bss(void *priv, int cts, int preamble, int slot,
5316                         int ht_opmode)
5317 {
5318         struct i802_bss *bss = priv;
5319         struct wpa_driver_nl80211_data *drv = bss->drv;
5320         struct nl_msg *msg;
5321
5322         msg = nlmsg_alloc();
5323         if (!msg)
5324                 return -ENOMEM;
5325
5326         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5327                     NL80211_CMD_SET_BSS, 0);
5328
5329         if (cts >= 0)
5330                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
5331         if (preamble >= 0)
5332                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
5333         if (slot >= 0)
5334                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
5335         if (ht_opmode >= 0)
5336                 NLA_PUT_U16(msg, NL80211_ATTR_BSS_HT_OPMODE, ht_opmode);
5337         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5338
5339         return send_and_recv_msgs(drv, msg, NULL, NULL);
5340  nla_put_failure:
5341         return -ENOBUFS;
5342 }
5343
5344
5345 static int i802_set_cts_protect(void *priv, int value)
5346 {
5347         return i802_set_bss(priv, value, -1, -1, -1);
5348 }
5349
5350
5351 static int i802_set_preamble(void *priv, int value)
5352 {
5353         return i802_set_bss(priv, -1, value, -1, -1);
5354 }
5355
5356
5357 static int i802_set_short_slot_time(void *priv, int value)
5358 {
5359         return i802_set_bss(priv, -1, -1, value, -1);
5360 }
5361
5362
5363 static int i802_set_sta_vlan(void *priv, const u8 *addr,
5364                              const char *ifname, int vlan_id)
5365 {
5366         struct i802_bss *bss = priv;
5367         struct wpa_driver_nl80211_data *drv = bss->drv;
5368         struct nl_msg *msg;
5369         int ret = -ENOBUFS;
5370
5371         msg = nlmsg_alloc();
5372         if (!msg)
5373                 return -ENOMEM;
5374
5375         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5376                     0, NL80211_CMD_SET_STATION, 0);
5377
5378         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5379                     if_nametoindex(bss->ifname));
5380         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5381         NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
5382                     if_nametoindex(ifname));
5383
5384         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5385         if (ret < 0) {
5386                 wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
5387                            MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
5388                            MAC2STR(addr), ifname, vlan_id, ret,
5389                            strerror(-ret));
5390         }
5391  nla_put_failure:
5392         return ret;
5393 }
5394
5395
5396 static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
5397                             const char *bridge_ifname)
5398 {
5399         struct i802_bss *bss = priv;
5400         struct wpa_driver_nl80211_data *drv = bss->drv;
5401         char name[IFNAMSIZ + 1];
5402
5403         os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
5404         wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
5405                    " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
5406         if (val) {
5407                 if (!if_nametoindex(name)) {
5408                         if (nl80211_create_iface(drv, name,
5409                                                  NL80211_IFTYPE_AP_VLAN,
5410                                                  NULL, 1) < 0)
5411                                 return -1;
5412                         if (bridge_ifname &&
5413                             linux_br_add_if(drv->ioctl_sock, bridge_ifname,
5414                                             name) < 0)
5415                                 return -1;
5416                 }
5417                 linux_set_iface_flags(drv->ioctl_sock, name, 1);
5418                 return i802_set_sta_vlan(priv, addr, name, 0);
5419         } else {
5420                 i802_set_sta_vlan(priv, addr, bss->ifname, 0);
5421                 return wpa_driver_nl80211_if_remove(priv, WPA_IF_AP_VLAN,
5422                                                     name);
5423         }
5424 }
5425
5426
5427 static int i802_set_ht_params(void *priv, const u8 *ht_capab,
5428                               size_t ht_capab_len, const u8 *ht_oper,
5429                               size_t ht_oper_len)
5430 {
5431         if (ht_oper_len >= 6) {
5432                 /* ht opmode uses 16bit in octet 5 & 6 */
5433                 u16 ht_opmode = le_to_host16(((u16 *) ht_oper)[2]);
5434                 return i802_set_bss(priv, -1, -1, -1, ht_opmode);
5435         } else
5436                 return -1;
5437 }
5438
5439
5440 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
5441 {
5442         struct wpa_driver_nl80211_data *drv = eloop_ctx;
5443         struct sockaddr_ll lladdr;
5444         unsigned char buf[3000];
5445         int len;
5446         socklen_t fromlen = sizeof(lladdr);
5447
5448         len = recvfrom(sock, buf, sizeof(buf), 0,
5449                        (struct sockaddr *)&lladdr, &fromlen);
5450         if (len < 0) {
5451                 perror("recv");
5452                 return;
5453         }
5454
5455         if (have_ifidx(drv, lladdr.sll_ifindex))
5456                 drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
5457 }
5458
5459
5460 static int i802_get_inact_sec(void *priv, const u8 *addr)
5461 {
5462         struct hostap_sta_driver_data data;
5463         int ret;
5464
5465         data.inactive_msec = (unsigned long) -1;
5466         ret = i802_read_sta_data(priv, &data, addr);
5467         if (ret || data.inactive_msec == (unsigned long) -1)
5468                 return -1;
5469         return data.inactive_msec / 1000;
5470 }
5471
5472
5473 static int i802_sta_clear_stats(void *priv, const u8 *addr)
5474 {
5475 #if 0
5476         /* TODO */
5477 #endif
5478         return 0;
5479 }
5480
5481 #endif /* HOSTAPD */
5482
5483 #if defined(HOSTAPD) || defined(CONFIG_AP)
5484
5485 static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
5486                            int reason)
5487 {
5488         struct i802_bss *bss = priv;
5489         struct ieee80211_mgmt mgmt;
5490
5491         memset(&mgmt, 0, sizeof(mgmt));
5492         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
5493                                           WLAN_FC_STYPE_DEAUTH);
5494         memcpy(mgmt.da, addr, ETH_ALEN);
5495         memcpy(mgmt.sa, own_addr, ETH_ALEN);
5496         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
5497         mgmt.u.deauth.reason_code = host_to_le16(reason);
5498         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
5499                                             IEEE80211_HDRLEN +
5500                                             sizeof(mgmt.u.deauth));
5501 }
5502
5503
5504 static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
5505                              int reason)
5506 {
5507         struct i802_bss *bss = priv;
5508         struct ieee80211_mgmt mgmt;
5509
5510         memset(&mgmt, 0, sizeof(mgmt));
5511         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
5512                                           WLAN_FC_STYPE_DISASSOC);
5513         memcpy(mgmt.da, addr, ETH_ALEN);
5514         memcpy(mgmt.sa, own_addr, ETH_ALEN);
5515         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
5516         mgmt.u.disassoc.reason_code = host_to_le16(reason);
5517         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
5518                                             IEEE80211_HDRLEN +
5519                                             sizeof(mgmt.u.disassoc));
5520 }
5521
5522 #endif /* HOSTAPD || CONFIG_AP */
5523
5524 #ifdef HOSTAPD
5525
5526 static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
5527                              struct i802_bss *bss,
5528                              const char *brname, const char *ifname)
5529 {
5530         int ifindex;
5531         char in_br[IFNAMSIZ];
5532
5533         os_strlcpy(bss->brname, brname, IFNAMSIZ);
5534         ifindex = if_nametoindex(brname);
5535         if (ifindex == 0) {
5536                 /*
5537                  * Bridge was configured, but the bridge device does
5538                  * not exist. Try to add it now.
5539                  */
5540                 if (linux_br_add(drv->ioctl_sock, brname) < 0) {
5541                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
5542                                    "bridge interface %s: %s",
5543                                    brname, strerror(errno));
5544                         return -1;
5545                 }
5546                 bss->added_bridge = 1;
5547                 add_ifidx(drv, if_nametoindex(brname));
5548         }
5549
5550         if (linux_br_get(in_br, ifname) == 0) {
5551                 if (os_strcmp(in_br, brname) == 0)
5552                         return 0; /* already in the bridge */
5553
5554                 wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
5555                            "bridge %s", ifname, in_br);
5556                 if (linux_br_del_if(drv->ioctl_sock, in_br, ifname) < 0) {
5557                         wpa_printf(MSG_ERROR, "nl80211: Failed to "
5558                                    "remove interface %s from bridge "
5559                                    "%s: %s",
5560                                    ifname, brname, strerror(errno));
5561                         return -1;
5562                 }
5563         }
5564
5565         wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
5566                    ifname, brname);
5567         if (linux_br_add_if(drv->ioctl_sock, brname, ifname) < 0) {
5568                 wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
5569                            "into bridge %s: %s",
5570                            ifname, brname, strerror(errno));
5571                 return -1;
5572         }
5573         bss->added_if_into_bridge = 1;
5574
5575         return 0;
5576 }
5577
5578
5579 static void *i802_init(struct hostapd_data *hapd,
5580                        struct wpa_init_params *params)
5581 {
5582         struct wpa_driver_nl80211_data *drv;
5583         struct i802_bss *bss;
5584         size_t i;
5585         char brname[IFNAMSIZ];
5586         int ifindex, br_ifindex;
5587         int br_added = 0;
5588
5589         bss = wpa_driver_nl80211_init(hapd, params->ifname, NULL);
5590         if (bss == NULL)
5591                 return NULL;
5592
5593         drv = bss->drv;
5594         drv->nlmode = NL80211_IFTYPE_AP;
5595         if (linux_br_get(brname, params->ifname) == 0) {
5596                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
5597                            params->ifname, brname);
5598                 br_ifindex = if_nametoindex(brname);
5599         } else {
5600                 brname[0] = '\0';
5601                 br_ifindex = 0;
5602         }
5603
5604         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
5605         drv->if_indices = drv->default_if_indices;
5606         for (i = 0; i < params->num_bridge; i++) {
5607                 if (params->bridge[i]) {
5608                         ifindex = if_nametoindex(params->bridge[i]);
5609                         if (ifindex)
5610                                 add_ifidx(drv, ifindex);
5611                         if (ifindex == br_ifindex)
5612                                 br_added = 1;
5613                 }
5614         }
5615         if (!br_added && br_ifindex &&
5616             (params->num_bridge == 0 || !params->bridge[0]))
5617                 add_ifidx(drv, br_ifindex);
5618
5619         /* start listening for EAPOL on the default AP interface */
5620         add_ifidx(drv, drv->ifindex);
5621
5622         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 0))
5623                 goto failed;
5624
5625         if (params->bssid) {
5626                 if (linux_set_ifhwaddr(drv->ioctl_sock, bss->ifname,
5627                                        params->bssid))
5628                         goto failed;
5629         }
5630
5631         if (wpa_driver_nl80211_set_mode(bss, IEEE80211_MODE_AP)) {
5632                 wpa_printf(MSG_ERROR, "nl80211: Failed to set interface %s "
5633                            "into AP mode", bss->ifname);
5634                 goto failed;
5635         }
5636
5637         if (params->num_bridge && params->bridge[0] &&
5638             i802_check_bridge(drv, bss, params->bridge[0], params->ifname) < 0)
5639                 goto failed;
5640
5641         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 1))
5642                 goto failed;
5643
5644         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
5645         if (drv->eapol_sock < 0) {
5646                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
5647                 goto failed;
5648         }
5649
5650         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
5651         {
5652                 printf("Could not register read socket for eapol\n");
5653                 goto failed;
5654         }
5655
5656         if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, params->own_addr))
5657                 goto failed;
5658
5659         return bss;
5660
5661 failed:
5662         nl80211_remove_monitor_interface(drv);
5663         rfkill_deinit(drv->rfkill);
5664         netlink_deinit(drv->netlink);
5665         if (drv->ioctl_sock >= 0)
5666                 close(drv->ioctl_sock);
5667
5668         genl_family_put(drv->nl80211);
5669         nl_cache_free(drv->nl_cache);
5670         nl80211_handle_destroy(drv->nl_handle);
5671         nl_cb_put(drv->nl_cb);
5672         eloop_unregister_read_sock(nl_socket_get_fd(drv->nl_handle_event));
5673
5674         os_free(drv);
5675         return NULL;
5676 }
5677
5678
5679 static void i802_deinit(void *priv)
5680 {
5681         wpa_driver_nl80211_deinit(priv);
5682 }
5683
5684 #endif /* HOSTAPD */
5685
5686
5687 static enum nl80211_iftype wpa_driver_nl80211_if_type(
5688         enum wpa_driver_if_type type)
5689 {
5690         switch (type) {
5691         case WPA_IF_STATION:
5692                 return NL80211_IFTYPE_STATION;
5693         case WPA_IF_P2P_CLIENT:
5694         case WPA_IF_P2P_GROUP:
5695                 return NL80211_IFTYPE_P2P_CLIENT;
5696         case WPA_IF_AP_VLAN:
5697                 return NL80211_IFTYPE_AP_VLAN;
5698         case WPA_IF_AP_BSS:
5699                 return NL80211_IFTYPE_AP;
5700         case WPA_IF_P2P_GO:
5701                 return NL80211_IFTYPE_P2P_GO;
5702         }
5703         return -1;
5704 }
5705
5706
5707 #ifdef CONFIG_P2P
5708
5709 static int nl80211_addr_in_use(struct nl80211_global *global, const u8 *addr)
5710 {
5711         struct wpa_driver_nl80211_data *drv;
5712         dl_list_for_each(drv, &global->interfaces,
5713                          struct wpa_driver_nl80211_data, list) {
5714                 if (os_memcmp(addr, drv->addr, ETH_ALEN) == 0)
5715                         return 1;
5716         }
5717         return 0;
5718 }
5719
5720
5721 static int nl80211_p2p_interface_addr(struct wpa_driver_nl80211_data *drv,
5722                                       u8 *new_addr)
5723 {
5724         unsigned int idx;
5725
5726         if (!drv->global)
5727                 return -1;
5728
5729         os_memcpy(new_addr, drv->addr, ETH_ALEN);
5730         for (idx = 0; idx < 64; idx++) {
5731                 new_addr[0] = drv->addr[0] | 0x02;
5732                 new_addr[0] ^= idx << 2;
5733                 if (!nl80211_addr_in_use(drv->global, new_addr))
5734                         break;
5735         }
5736         if (idx == 64)
5737                 return -1;
5738
5739         wpa_printf(MSG_DEBUG, "nl80211: Assigned new P2P Interface Address "
5740                    MACSTR, MAC2STR(new_addr));
5741
5742         return 0;
5743 }
5744
5745 #endif /* CONFIG_P2P */
5746
5747
5748 static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
5749                                      const char *ifname, const u8 *addr,
5750                                      void *bss_ctx, void **drv_priv,
5751                                      char *force_ifname, u8 *if_addr,
5752                                      const char *bridge)
5753 {
5754         struct i802_bss *bss = priv;
5755         struct wpa_driver_nl80211_data *drv = bss->drv;
5756         int ifidx;
5757 #ifdef HOSTAPD
5758         struct i802_bss *new_bss = NULL;
5759
5760         if (type == WPA_IF_AP_BSS) {
5761                 new_bss = os_zalloc(sizeof(*new_bss));
5762                 if (new_bss == NULL)
5763                         return -1;
5764         }
5765 #endif /* HOSTAPD */
5766
5767         if (addr)
5768                 os_memcpy(if_addr, addr, ETH_ALEN);
5769         ifidx = nl80211_create_iface(drv, ifname,
5770                                      wpa_driver_nl80211_if_type(type), addr,
5771                                      0);
5772         if (ifidx < 0) {
5773 #ifdef HOSTAPD
5774                 os_free(new_bss);
5775 #endif /* HOSTAPD */
5776                 return -1;
5777         }
5778
5779         if (!addr &&
5780             linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, if_addr) < 0) {
5781                 nl80211_remove_iface(drv, ifidx);
5782                 return -1;
5783         }
5784
5785 #ifdef CONFIG_P2P
5786         if (!addr &&
5787             (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
5788              type == WPA_IF_P2P_GO)) {
5789                 /* Enforce unique P2P Interface Address */
5790                 u8 new_addr[ETH_ALEN], own_addr[ETH_ALEN];
5791
5792                 if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, own_addr)
5793                     < 0 ||
5794                     linux_get_ifhwaddr(drv->ioctl_sock, ifname, new_addr) < 0)
5795                 {
5796                         nl80211_remove_iface(drv, ifidx);
5797                         return -1;
5798                 }
5799                 if (os_memcmp(own_addr, new_addr, ETH_ALEN) == 0) {
5800                         wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
5801                                    "for P2P group interface");
5802                         if (nl80211_p2p_interface_addr(drv, new_addr) < 0) {
5803                                 nl80211_remove_iface(drv, ifidx);
5804                                 return -1;
5805                         }
5806                         if (linux_set_ifhwaddr(drv->ioctl_sock, ifname,
5807                                                new_addr) < 0) {
5808                                 nl80211_remove_iface(drv, ifidx);
5809                                 return -1;
5810                         }
5811                         os_memcpy(if_addr, new_addr, ETH_ALEN);
5812                 }
5813         }
5814 #endif /* CONFIG_P2P */
5815
5816 #ifdef HOSTAPD
5817         if (bridge &&
5818             i802_check_bridge(drv, new_bss, bridge, ifname) < 0) {
5819                 wpa_printf(MSG_ERROR, "nl80211: Failed to add the new "
5820                            "interface %s to a bridge %s", ifname, bridge);
5821                 nl80211_remove_iface(drv, ifidx);
5822                 os_free(new_bss);
5823                 return -1;
5824         }
5825
5826         if (type == WPA_IF_AP_BSS) {
5827                 if (linux_set_iface_flags(drv->ioctl_sock, ifname, 1)) {
5828                         nl80211_remove_iface(drv, ifidx);
5829                         os_free(new_bss);
5830                         return -1;
5831                 }
5832                 os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
5833                 new_bss->ifindex = ifidx;
5834                 new_bss->drv = drv;
5835                 new_bss->next = drv->first_bss.next;
5836                 drv->first_bss.next = new_bss;
5837                 if (drv_priv)
5838                         *drv_priv = new_bss;
5839         }
5840 #endif /* HOSTAPD */
5841
5842         return 0;
5843 }
5844
5845
5846 static int wpa_driver_nl80211_if_remove(void *priv,
5847                                         enum wpa_driver_if_type type,
5848                                         const char *ifname)
5849 {
5850         struct i802_bss *bss = priv;
5851         struct wpa_driver_nl80211_data *drv = bss->drv;
5852         int ifindex = if_nametoindex(ifname);
5853
5854         wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d",
5855                    __func__, type, ifname, ifindex);
5856         if (ifindex <= 0)
5857                 return -1;
5858
5859 #ifdef HOSTAPD
5860         if (bss->added_if_into_bridge) {
5861                 if (linux_br_del_if(drv->ioctl_sock, bss->brname, bss->ifname)
5862                     < 0)
5863                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
5864                                    "interface %s from bridge %s: %s",
5865                                    bss->ifname, bss->brname, strerror(errno));
5866         }
5867         if (bss->added_bridge) {
5868                 if (linux_br_del(drv->ioctl_sock, bss->brname) < 0)
5869                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
5870                                    "bridge %s: %s",
5871                                    bss->brname, strerror(errno));
5872         }
5873 #endif /* HOSTAPD */
5874
5875         nl80211_remove_iface(drv, ifindex);
5876
5877 #ifdef HOSTAPD
5878         if (type != WPA_IF_AP_BSS)
5879                 return 0;
5880
5881         if (bss != &drv->first_bss) {
5882                 struct i802_bss *tbss;
5883
5884                 for (tbss = &drv->first_bss; tbss; tbss = tbss->next) {
5885                         if (tbss->next == bss) {
5886                                 tbss->next = bss->next;
5887                                 os_free(bss);
5888                                 bss = NULL;
5889                                 break;
5890                         }
5891                 }
5892                 if (bss)
5893                         wpa_printf(MSG_INFO, "nl80211: %s - could not find "
5894                                    "BSS %p in the list", __func__, bss);
5895         }
5896 #endif /* HOSTAPD */
5897
5898         return 0;
5899 }
5900
5901
5902 static int cookie_handler(struct nl_msg *msg, void *arg)
5903 {
5904         struct nlattr *tb[NL80211_ATTR_MAX + 1];
5905         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5906         u64 *cookie = arg;
5907         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5908                   genlmsg_attrlen(gnlh, 0), NULL);
5909         if (tb[NL80211_ATTR_COOKIE])
5910                 *cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
5911         return NL_SKIP;
5912 }
5913
5914
5915 static int nl80211_send_frame_cmd(struct wpa_driver_nl80211_data *drv,
5916                                   unsigned int freq, unsigned int wait,
5917                                   const u8 *buf, size_t buf_len,
5918                                   u64 *cookie_out)
5919 {
5920         struct nl_msg *msg;
5921         u64 cookie;
5922         int ret = -1;
5923
5924         msg = nlmsg_alloc();
5925         if (!msg)
5926                 return -1;
5927
5928         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5929                     NL80211_CMD_FRAME, 0);
5930
5931         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5932         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
5933         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, wait);
5934         NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
5935         NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
5936
5937         cookie = 0;
5938         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
5939         msg = NULL;
5940         if (ret) {
5941                 wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
5942                            "(%s)", ret, strerror(-ret));
5943                 goto nla_put_failure;
5944         }
5945         wpa_printf(MSG_DEBUG, "nl80211: Frame TX command accepted; "
5946                    "cookie 0x%llx", (long long unsigned int) cookie);
5947
5948         if (cookie_out)
5949                 *cookie_out = cookie;
5950
5951 nla_put_failure:
5952         nlmsg_free(msg);
5953         return ret;
5954 }
5955
5956
5957 static int wpa_driver_nl80211_send_action(void *priv, unsigned int freq,
5958                                           unsigned int wait_time,
5959                                           const u8 *dst, const u8 *src,
5960                                           const u8 *bssid,
5961                                           const u8 *data, size_t data_len)
5962 {
5963         struct i802_bss *bss = priv;
5964         struct wpa_driver_nl80211_data *drv = bss->drv;
5965         int ret = -1;
5966         u8 *buf;
5967         struct ieee80211_hdr *hdr;
5968
5969         wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d, "
5970                    "wait=%d ms)", drv->ifindex, wait_time);
5971
5972         buf = os_zalloc(24 + data_len);
5973         if (buf == NULL)
5974                 return ret;
5975         os_memcpy(buf + 24, data, data_len);
5976         hdr = (struct ieee80211_hdr *) buf;
5977         hdr->frame_control =
5978                 IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
5979         os_memcpy(hdr->addr1, dst, ETH_ALEN);
5980         os_memcpy(hdr->addr2, src, ETH_ALEN);
5981         os_memcpy(hdr->addr3, bssid, ETH_ALEN);
5982
5983         if (drv->nlmode == NL80211_IFTYPE_AP)
5984                 ret = wpa_driver_nl80211_send_mlme(priv, buf, 24 + data_len);
5985         else
5986                 ret = nl80211_send_frame_cmd(drv, freq, wait_time, buf,
5987                                              24 + data_len,
5988                                              &drv->send_action_cookie);
5989
5990         os_free(buf);
5991         return ret;
5992 }
5993
5994
5995 static void wpa_driver_nl80211_send_action_cancel_wait(void *priv)
5996 {
5997         struct i802_bss *bss = priv;
5998         struct wpa_driver_nl80211_data *drv = bss->drv;
5999         struct nl_msg *msg;
6000         int ret;
6001
6002         msg = nlmsg_alloc();
6003         if (!msg)
6004                 return;
6005
6006         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6007                     NL80211_CMD_FRAME_WAIT_CANCEL, 0);
6008
6009         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6010         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->send_action_cookie);
6011
6012         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6013         msg = NULL;
6014         if (ret)
6015                 wpa_printf(MSG_DEBUG, "nl80211: wait cancel failed: ret=%d "
6016                            "(%s)", ret, strerror(-ret));
6017
6018  nla_put_failure:
6019         nlmsg_free(msg);
6020 }
6021
6022
6023 static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
6024                                                 unsigned int duration)
6025 {
6026         struct i802_bss *bss = priv;
6027         struct wpa_driver_nl80211_data *drv = bss->drv;
6028         struct nl_msg *msg;
6029         int ret;
6030         u64 cookie;
6031
6032         msg = nlmsg_alloc();
6033         if (!msg)
6034                 return -1;
6035
6036         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6037                     NL80211_CMD_REMAIN_ON_CHANNEL, 0);
6038
6039         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6040         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
6041         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
6042
6043         cookie = 0;
6044         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
6045         if (ret == 0) {
6046                 wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
6047                            "0x%llx for freq=%u MHz duration=%u",
6048                            (long long unsigned int) cookie, freq, duration);
6049                 drv->remain_on_chan_cookie = cookie;
6050                 return 0;
6051         }
6052         wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
6053                    "(freq=%d duration=%u): %d (%s)",
6054                    freq, duration, ret, strerror(-ret));
6055 nla_put_failure:
6056         return -1;
6057 }
6058
6059
6060 static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
6061 {
6062         struct i802_bss *bss = priv;
6063         struct wpa_driver_nl80211_data *drv = bss->drv;
6064         struct nl_msg *msg;
6065         int ret;
6066
6067         if (!drv->pending_remain_on_chan) {
6068                 wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
6069                            "to cancel");
6070                 return -1;
6071         }
6072
6073         wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
6074                    "0x%llx",
6075                    (long long unsigned int) drv->remain_on_chan_cookie);
6076
6077         msg = nlmsg_alloc();
6078         if (!msg)
6079                 return -1;
6080
6081         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6082                     NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL, 0);
6083
6084         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6085         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
6086
6087         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6088         if (ret == 0)
6089                 return 0;
6090         wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
6091                    "%d (%s)", ret, strerror(-ret));
6092 nla_put_failure:
6093         return -1;
6094 }
6095
6096
6097 static int wpa_driver_nl80211_probe_req_report(void *priv, int report)
6098 {
6099         struct i802_bss *bss = priv;
6100         struct wpa_driver_nl80211_data *drv = bss->drv;
6101
6102         if (drv->nlmode != NL80211_IFTYPE_STATION) {
6103                 wpa_printf(MSG_DEBUG, "nl80211: probe_req_report control only "
6104                            "allowed in station mode (iftype=%d)",
6105                            drv->nlmode);
6106                 return -1;
6107         }
6108
6109         if (!report) {
6110                 if (drv->nl_handle_preq) {
6111                         eloop_unregister_read_sock(
6112                                 nl_socket_get_fd(drv->nl_handle_preq));
6113                         nl_cache_free(drv->nl_cache_preq);
6114                         nl80211_handle_destroy(drv->nl_handle_preq);
6115                         drv->nl_handle_preq = NULL;
6116                 }
6117                 return 0;
6118         }
6119
6120         if (drv->nl_handle_preq) {
6121                 wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
6122                            "already on!");
6123                 return 0;
6124         }
6125
6126         drv->nl_handle_preq = nl80211_handle_alloc(drv->nl_cb);
6127         if (drv->nl_handle_preq == NULL) {
6128                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate "
6129                            "netlink callbacks (preq)");
6130                 goto out_err1;
6131         }
6132
6133         if (genl_connect(drv->nl_handle_preq)) {
6134                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to "
6135                            "generic netlink (preq)");
6136                 goto out_err2;
6137                 return -1;
6138         }
6139
6140 #ifdef CONFIG_LIBNL20
6141         if (genl_ctrl_alloc_cache(drv->nl_handle_preq,
6142                                   &drv->nl_cache_preq) < 0) {
6143                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
6144                            "netlink cache (preq)");
6145                 goto out_err2;
6146         }
6147 #else /* CONFIG_LIBNL20 */
6148         drv->nl_cache_preq = genl_ctrl_alloc_cache(drv->nl_handle_preq);
6149         if (drv->nl_cache_preq == NULL) {
6150                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
6151                            "netlink cache (preq)");
6152                 goto out_err2;
6153         }
6154 #endif /* CONFIG_LIBNL20 */
6155
6156         if (nl80211_register_frame(drv, drv->nl_handle_preq,
6157                                    (WLAN_FC_TYPE_MGMT << 2) |
6158                                    (WLAN_FC_STYPE_PROBE_REQ << 4),
6159                                    NULL, 0) < 0) {
6160                 goto out_err3;
6161         }
6162
6163         eloop_register_read_sock(nl_socket_get_fd(drv->nl_handle_preq),
6164                                  wpa_driver_nl80211_event_receive, drv,
6165                                  drv->nl_handle_preq);
6166
6167         return 0;
6168
6169  out_err3:
6170         nl_cache_free(drv->nl_cache_preq);
6171  out_err2:
6172         nl80211_handle_destroy(drv->nl_handle_preq);
6173         drv->nl_handle_preq = NULL;
6174  out_err1:
6175         return -1;
6176 }
6177
6178
6179 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
6180                                      int ifindex, int disabled)
6181 {
6182         struct nl_msg *msg;
6183         struct nlattr *bands, *band;
6184         int ret;
6185
6186         msg = nlmsg_alloc();
6187         if (!msg)
6188                 return -1;
6189
6190         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6191                     NL80211_CMD_SET_TX_BITRATE_MASK, 0);
6192         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
6193
6194         bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
6195         if (!bands)
6196                 goto nla_put_failure;
6197
6198         /*
6199          * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
6200          * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
6201          * rates. All 5 GHz rates are left enabled.
6202          */
6203         band = nla_nest_start(msg, NL80211_BAND_2GHZ);
6204         if (!band)
6205                 goto nla_put_failure;
6206         NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
6207                 "\x0c\x12\x18\x24\x30\x48\x60\x6c");
6208         nla_nest_end(msg, band);
6209
6210         nla_nest_end(msg, bands);
6211
6212         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6213         msg = NULL;
6214         if (ret) {
6215                 wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
6216                            "(%s)", ret, strerror(-ret));
6217         }
6218
6219         return ret;
6220
6221 nla_put_failure:
6222         nlmsg_free(msg);
6223         return -1;
6224 }
6225
6226
6227 static int wpa_driver_nl80211_disable_11b_rates(void *priv, int disabled)
6228 {
6229         struct i802_bss *bss = priv;
6230         struct wpa_driver_nl80211_data *drv = bss->drv;
6231         drv->disable_11b_rates = disabled;
6232         return nl80211_disable_11b_rates(drv, drv->ifindex, disabled);
6233 }
6234
6235
6236 static int wpa_driver_nl80211_deinit_ap(void *priv)
6237 {
6238         struct i802_bss *bss = priv;
6239         struct wpa_driver_nl80211_data *drv = bss->drv;
6240         if (drv->nlmode != NL80211_IFTYPE_AP)
6241                 return -1;
6242         wpa_driver_nl80211_del_beacon(drv);
6243         return wpa_driver_nl80211_set_mode(priv, IEEE80211_MODE_INFRA);
6244 }
6245
6246
6247 static void wpa_driver_nl80211_resume(void *priv)
6248 {
6249         struct i802_bss *bss = priv;
6250         struct wpa_driver_nl80211_data *drv = bss->drv;
6251         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 1)) {
6252                 wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on "
6253                            "resume event");
6254         }
6255 }
6256
6257
6258 static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
6259                                   const u8 *ies, size_t ies_len)
6260 {
6261         struct i802_bss *bss = priv;
6262         struct wpa_driver_nl80211_data *drv = bss->drv;
6263         int ret;
6264         u8 *data, *pos;
6265         size_t data_len;
6266         u8 own_addr[ETH_ALEN];
6267
6268         if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, own_addr) < 0)
6269                 return -1;
6270
6271         if (action != 1) {
6272                 wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
6273                            "action %d", action);
6274                 return -1;
6275         }
6276
6277         /*
6278          * Action frame payload:
6279          * Category[1] = 6 (Fast BSS Transition)
6280          * Action[1] = 1 (Fast BSS Transition Request)
6281          * STA Address
6282          * Target AP Address
6283          * FT IEs
6284          */
6285
6286         data_len = 2 + 2 * ETH_ALEN + ies_len;
6287         data = os_malloc(data_len);
6288         if (data == NULL)
6289                 return -1;
6290         pos = data;
6291         *pos++ = 0x06; /* FT Action category */
6292         *pos++ = action;
6293         os_memcpy(pos, own_addr, ETH_ALEN);
6294         pos += ETH_ALEN;
6295         os_memcpy(pos, target_ap, ETH_ALEN);
6296         pos += ETH_ALEN;
6297         os_memcpy(pos, ies, ies_len);
6298
6299         ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, 0,
6300                                              drv->bssid, own_addr, drv->bssid,
6301                                              data, data_len);
6302         os_free(data);
6303
6304         return ret;
6305 }
6306
6307
6308 static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
6309 {
6310         struct i802_bss *bss = priv;
6311         struct wpa_driver_nl80211_data *drv = bss->drv;
6312         struct nl_msg *msg, *cqm = NULL;
6313
6314         wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
6315                    "hysteresis=%d", threshold, hysteresis);
6316
6317         msg = nlmsg_alloc();
6318         if (!msg)
6319                 return -1;
6320
6321         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
6322                     0, NL80211_CMD_SET_CQM, 0);
6323
6324         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
6325
6326         cqm = nlmsg_alloc();
6327         if (cqm == NULL)
6328                 return -1;
6329
6330         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
6331         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
6332         nla_put_nested(msg, NL80211_ATTR_CQM, cqm);
6333
6334         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
6335                 return 0;
6336         msg = NULL;
6337
6338 nla_put_failure:
6339         if (cqm)
6340                 nlmsg_free(cqm);
6341         nlmsg_free(msg);
6342         return -1;
6343 }
6344
6345
6346 static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
6347                               int encrypt)
6348 {
6349         struct i802_bss *bss = priv;
6350         struct wpa_driver_nl80211_data *drv = bss->drv;
6351         return wpa_driver_nl80211_send_frame(drv, data, data_len, encrypt);
6352 }
6353
6354
6355 static int nl80211_set_intra_bss(void *priv, int enabled)
6356 {
6357         struct i802_bss *bss = priv;
6358         struct wpa_driver_nl80211_data *drv = bss->drv;
6359         struct nl_msg *msg;
6360
6361         msg = nlmsg_alloc();
6362         if (!msg)
6363                 return -ENOMEM;
6364
6365         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6366                     NL80211_CMD_SET_BSS, 0);
6367
6368         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
6369         NLA_PUT_U8(msg, NL80211_ATTR_AP_ISOLATE, !enabled);
6370
6371         return send_and_recv_msgs(drv, msg, NULL, NULL);
6372  nla_put_failure:
6373         return -ENOBUFS;
6374 }
6375
6376
6377 static int nl80211_set_param(void *priv, const char *param)
6378 {
6379         wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
6380         if (param == NULL)
6381                 return 0;
6382
6383 #ifdef CONFIG_P2P
6384         if (os_strstr(param, "use_p2p_group_interface=1")) {
6385                 struct i802_bss *bss = priv;
6386                 struct wpa_driver_nl80211_data *drv = bss->drv;
6387
6388                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
6389                            "interface");
6390                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
6391                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
6392         }
6393 #endif /* CONFIG_P2P */
6394
6395         return 0;
6396 }
6397
6398
6399 static void * nl80211_global_init(void)
6400 {
6401         struct nl80211_global *global;
6402         global = os_zalloc(sizeof(*global));
6403         if (global == NULL)
6404                 return NULL;
6405         dl_list_init(&global->interfaces);
6406         return global;
6407 }
6408
6409
6410 static void nl80211_global_deinit(void *priv)
6411 {
6412         struct nl80211_global *global = priv;
6413         if (global == NULL)
6414                 return;
6415         if (!dl_list_empty(&global->interfaces)) {
6416                 wpa_printf(MSG_ERROR, "nl80211: %u interface(s) remain at "
6417                            "nl80211_global_deinit",
6418                            dl_list_len(&global->interfaces));
6419         }
6420         os_free(global);
6421 }
6422
6423
6424 static const char * nl80211_get_radio_name(void *priv)
6425 {
6426         struct i802_bss *bss = priv;
6427         struct wpa_driver_nl80211_data *drv = bss->drv;
6428         return drv->phyname;
6429 }
6430
6431
6432 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
6433         .name = "nl80211",
6434         .desc = "Linux nl80211/cfg80211",
6435         .get_bssid = wpa_driver_nl80211_get_bssid,
6436         .get_ssid = wpa_driver_nl80211_get_ssid,
6437         .set_key = wpa_driver_nl80211_set_key,
6438         .scan2 = wpa_driver_nl80211_scan,
6439         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
6440         .deauthenticate = wpa_driver_nl80211_deauthenticate,
6441         .disassociate = wpa_driver_nl80211_disassociate,
6442         .authenticate = wpa_driver_nl80211_authenticate,
6443         .associate = wpa_driver_nl80211_associate,
6444         .global_init = nl80211_global_init,
6445         .global_deinit = nl80211_global_deinit,
6446         .init2 = wpa_driver_nl80211_init,
6447         .deinit = wpa_driver_nl80211_deinit,
6448         .get_capa = wpa_driver_nl80211_get_capa,
6449         .set_operstate = wpa_driver_nl80211_set_operstate,
6450         .set_supp_port = wpa_driver_nl80211_set_supp_port,
6451         .set_country = wpa_driver_nl80211_set_country,
6452         .set_beacon = wpa_driver_nl80211_set_beacon,
6453         .if_add = wpa_driver_nl80211_if_add,
6454         .if_remove = wpa_driver_nl80211_if_remove,
6455         .send_mlme = wpa_driver_nl80211_send_mlme,
6456         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
6457         .sta_add = wpa_driver_nl80211_sta_add,
6458         .sta_remove = wpa_driver_nl80211_sta_remove,
6459         .hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
6460         .sta_set_flags = wpa_driver_nl80211_sta_set_flags,
6461 #ifdef HOSTAPD
6462         .hapd_init = i802_init,
6463         .hapd_deinit = i802_deinit,
6464         .get_seqnum = i802_get_seqnum,
6465         .flush = i802_flush,
6466         .read_sta_data = i802_read_sta_data,
6467         .get_inact_sec = i802_get_inact_sec,
6468         .sta_clear_stats = i802_sta_clear_stats,
6469         .set_rts = i802_set_rts,
6470         .set_frag = i802_set_frag,
6471         .set_rate_sets = i802_set_rate_sets,
6472         .set_cts_protect = i802_set_cts_protect,
6473         .set_preamble = i802_set_preamble,
6474         .set_short_slot_time = i802_set_short_slot_time,
6475         .set_tx_queue_params = i802_set_tx_queue_params,
6476         .set_sta_vlan = i802_set_sta_vlan,
6477         .set_wds_sta = i802_set_wds_sta,
6478         .set_ht_params = i802_set_ht_params,
6479 #endif /* HOSTAPD */
6480 #if defined(HOSTAPD) || defined(CONFIG_AP)
6481         .sta_deauth = i802_sta_deauth,
6482         .sta_disassoc = i802_sta_disassoc,
6483 #endif /* HOSTAPD || CONFIG_AP */
6484         .set_freq = i802_set_freq,
6485         .send_action = wpa_driver_nl80211_send_action,
6486         .send_action_cancel_wait = wpa_driver_nl80211_send_action_cancel_wait,
6487         .remain_on_channel = wpa_driver_nl80211_remain_on_channel,
6488         .cancel_remain_on_channel =
6489         wpa_driver_nl80211_cancel_remain_on_channel,
6490         .probe_req_report = wpa_driver_nl80211_probe_req_report,
6491         .disable_11b_rates = wpa_driver_nl80211_disable_11b_rates,
6492         .deinit_ap = wpa_driver_nl80211_deinit_ap,
6493         .resume = wpa_driver_nl80211_resume,
6494         .send_ft_action = nl80211_send_ft_action,
6495         .signal_monitor = nl80211_signal_monitor,
6496         .send_frame = nl80211_send_frame,
6497         .set_intra_bss = nl80211_set_intra_bss,
6498         .set_param = nl80211_set_param,
6499         .get_radio_name = nl80211_get_radio_name,
6500 };