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