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