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