nl80211: Add driver flag for firmware-based BSS selection
[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         int firmware_roam;
1692 };
1693
1694
1695 static int wiphy_info_handler(struct nl_msg *msg, void *arg)
1696 {
1697         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1698         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1699         struct wiphy_info_data *info = arg;
1700         int p2p_go_supported = 0, p2p_client_supported = 0;
1701         static struct nla_policy
1702         iface_combination_policy[NUM_NL80211_IFACE_COMB] = {
1703                 [NL80211_IFACE_COMB_LIMITS] = { .type = NLA_NESTED },
1704                 [NL80211_IFACE_COMB_MAXNUM] = { .type = NLA_U32 },
1705                 [NL80211_IFACE_COMB_STA_AP_BI_MATCH] = { .type = NLA_FLAG },
1706                 [NL80211_IFACE_COMB_NUM_CHANNELS] = { .type = NLA_U32 },
1707         },
1708         iface_limit_policy[NUM_NL80211_IFACE_LIMIT] = {
1709                 [NL80211_IFACE_LIMIT_TYPES] = { .type = NLA_NESTED },
1710                 [NL80211_IFACE_LIMIT_MAX] = { .type = NLA_U32 },
1711         };
1712
1713         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1714                   genlmsg_attrlen(gnlh, 0), NULL);
1715
1716         if (tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS])
1717                 info->max_scan_ssids =
1718                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS]);
1719
1720         if (tb[NL80211_ATTR_SUPPORTED_IFTYPES]) {
1721                 struct nlattr *nl_mode;
1722                 int i;
1723                 nla_for_each_nested(nl_mode,
1724                                     tb[NL80211_ATTR_SUPPORTED_IFTYPES], i) {
1725                         switch (nla_type(nl_mode)) {
1726                         case NL80211_IFTYPE_AP:
1727                                 info->ap_supported = 1;
1728                                 break;
1729                         case NL80211_IFTYPE_P2P_GO:
1730                                 p2p_go_supported = 1;
1731                                 break;
1732                         case NL80211_IFTYPE_P2P_CLIENT:
1733                                 p2p_client_supported = 1;
1734                                 break;
1735                         }
1736                 }
1737         }
1738
1739         if (tb[NL80211_ATTR_INTERFACE_COMBINATIONS]) {
1740                 struct nlattr *nl_combi;
1741                 int rem_combi;
1742
1743                 nla_for_each_nested(nl_combi,
1744                                     tb[NL80211_ATTR_INTERFACE_COMBINATIONS],
1745                                     rem_combi) {
1746                         struct nlattr *tb_comb[NUM_NL80211_IFACE_COMB];
1747                         struct nlattr *tb_limit[NUM_NL80211_IFACE_LIMIT];
1748                         struct nlattr *nl_limit, *nl_mode;
1749                         int err, rem_limit, rem_mode;
1750                         int combination_has_p2p = 0, combination_has_mgd = 0;
1751
1752                         err = nla_parse_nested(tb_comb, MAX_NL80211_IFACE_COMB,
1753                                                nl_combi,
1754                                                iface_combination_policy);
1755                         if (err || !tb_comb[NL80211_IFACE_COMB_LIMITS] ||
1756                             !tb_comb[NL80211_IFACE_COMB_MAXNUM] ||
1757                             !tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS])
1758                                 goto broken_combination;
1759
1760                         nla_for_each_nested(nl_limit,
1761                                             tb_comb[NL80211_IFACE_COMB_LIMITS],
1762                                             rem_limit) {
1763                                 err = nla_parse_nested(tb_limit,
1764                                                        MAX_NL80211_IFACE_LIMIT,
1765                                                        nl_limit,
1766                                                        iface_limit_policy);
1767                                 if (err ||
1768                                     !tb_limit[NL80211_IFACE_LIMIT_TYPES])
1769                                         goto broken_combination;
1770
1771                                 nla_for_each_nested(
1772                                         nl_mode,
1773                                         tb_limit[NL80211_IFACE_LIMIT_TYPES],
1774                                         rem_mode) {
1775                                         int ift = nla_type(nl_mode);
1776                                         if (ift == NL80211_IFTYPE_P2P_GO ||
1777                                             ift == NL80211_IFTYPE_P2P_CLIENT)
1778                                                 combination_has_p2p = 1;
1779                                         if (ift == NL80211_IFTYPE_STATION)
1780                                                 combination_has_mgd = 1;
1781                                 }
1782                                 if (combination_has_p2p && combination_has_mgd)
1783                                         break;
1784                         }
1785
1786                         if (combination_has_p2p && combination_has_mgd) {
1787                                 info->p2p_concurrent = 1;
1788                                 break;
1789                         }
1790
1791 broken_combination:
1792                         ;
1793                 }
1794         }
1795
1796         info->p2p_supported = p2p_go_supported && p2p_client_supported;
1797
1798         if (tb[NL80211_ATTR_SUPPORTED_COMMANDS]) {
1799                 struct nlattr *nl_cmd;
1800                 int i;
1801
1802                 nla_for_each_nested(nl_cmd,
1803                                     tb[NL80211_ATTR_SUPPORTED_COMMANDS], i) {
1804                         u32 cmd = nla_get_u32(nl_cmd);
1805                         if (cmd == NL80211_CMD_AUTHENTICATE)
1806                                 info->auth_supported = 1;
1807                         else if (cmd == NL80211_CMD_CONNECT)
1808                                 info->connect_supported = 1;
1809                 }
1810         }
1811
1812         if (tb[NL80211_ATTR_OFFCHANNEL_TX_OK])
1813                 info->offchan_tx_supported = 1;
1814
1815         if (tb[NL80211_ATTR_ROAM_SUPPORT])
1816                 info->firmware_roam = 1;
1817
1818         if (tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION])
1819                 info->max_remain_on_chan =
1820                         nla_get_u32(tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION]);
1821
1822         return NL_SKIP;
1823 }
1824
1825
1826 static int wpa_driver_nl80211_get_info(struct wpa_driver_nl80211_data *drv,
1827                                        struct wiphy_info_data *info)
1828 {
1829         struct nl_msg *msg;
1830
1831         os_memset(info, 0, sizeof(*info));
1832
1833         /* default to 5000 since early versions of mac80211 don't set it */
1834         info->max_remain_on_chan = 5000;
1835
1836         msg = nlmsg_alloc();
1837         if (!msg)
1838                 return -1;
1839
1840         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1841                     0, NL80211_CMD_GET_WIPHY, 0);
1842
1843         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->first_bss.ifindex);
1844
1845         if (send_and_recv_msgs(drv, msg, wiphy_info_handler, info) == 0)
1846                 return 0;
1847         msg = NULL;
1848 nla_put_failure:
1849         nlmsg_free(msg);
1850         return -1;
1851 }
1852
1853
1854 static int wpa_driver_nl80211_capa(struct wpa_driver_nl80211_data *drv)
1855 {
1856         struct wiphy_info_data info;
1857         if (wpa_driver_nl80211_get_info(drv, &info))
1858                 return -1;
1859         drv->has_capability = 1;
1860         /* For now, assume TKIP, CCMP, WPA, WPA2 are supported */
1861         drv->capa.key_mgmt = WPA_DRIVER_CAPA_KEY_MGMT_WPA |
1862                 WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK |
1863                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2 |
1864                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK;
1865         drv->capa.enc = WPA_DRIVER_CAPA_ENC_WEP40 |
1866                 WPA_DRIVER_CAPA_ENC_WEP104 |
1867                 WPA_DRIVER_CAPA_ENC_TKIP |
1868                 WPA_DRIVER_CAPA_ENC_CCMP;
1869         drv->capa.auth = WPA_DRIVER_AUTH_OPEN |
1870                 WPA_DRIVER_AUTH_SHARED |
1871                 WPA_DRIVER_AUTH_LEAP;
1872
1873         drv->capa.max_scan_ssids = info.max_scan_ssids;
1874         if (info.ap_supported)
1875                 drv->capa.flags |= WPA_DRIVER_FLAGS_AP;
1876
1877         if (info.auth_supported)
1878                 drv->capa.flags |= WPA_DRIVER_FLAGS_SME;
1879         else if (!info.connect_supported) {
1880                 wpa_printf(MSG_INFO, "nl80211: Driver does not support "
1881                            "authentication/association or connect commands");
1882                 return -1;
1883         }
1884
1885         if (info.offchan_tx_supported) {
1886                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based "
1887                            "off-channel TX");
1888                 drv->capa.flags |= WPA_DRIVER_FLAGS_OFFCHANNEL_TX;
1889         }
1890
1891         if (info.firmware_roam) {
1892                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based roaming");
1893                 drv->capa.flags |= WPA_DRIVER_FLAGS_BSS_SELECTION;
1894         }
1895
1896         drv->capa.flags |= WPA_DRIVER_FLAGS_SANE_ERROR_CODES;
1897         drv->capa.flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE;
1898         if (info.p2p_supported)
1899                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CAPABLE;
1900         if (info.p2p_concurrent) {
1901                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
1902                            "interface (driver advertised support)");
1903                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
1904                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
1905         }
1906         drv->capa.flags |= WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
1907         drv->capa.flags |= WPA_DRIVER_FLAGS_DEAUTH_TX_STATUS;
1908         drv->capa.max_remain_on_chan = info.max_remain_on_chan;
1909
1910         return 0;
1911 }
1912
1913
1914 static int wpa_driver_nl80211_init_nl(struct wpa_driver_nl80211_data *drv)
1915 {
1916         int ret;
1917
1918         /* Initialize generic netlink and nl80211 */
1919
1920         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
1921         if (drv->nl_cb == NULL) {
1922                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1923                            "callbacks");
1924                 goto err1;
1925         }
1926
1927         drv->nl_handle = nl80211_handle_alloc(drv->nl_cb);
1928         if (drv->nl_handle == NULL) {
1929                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1930                            "callbacks");
1931                 goto err2;
1932         }
1933
1934         drv->nl_handle_event = nl80211_handle_alloc(drv->nl_cb);
1935         if (drv->nl_handle_event == NULL) {
1936                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1937                            "callbacks (event)");
1938                 goto err2b;
1939         }
1940
1941         if (genl_connect(drv->nl_handle)) {
1942                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
1943                            "netlink");
1944                 goto err3;
1945         }
1946
1947         if (genl_connect(drv->nl_handle_event)) {
1948                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
1949                            "netlink (event)");
1950                 goto err3;
1951         }
1952
1953 #ifdef CONFIG_LIBNL20
1954         if (genl_ctrl_alloc_cache(drv->nl_handle, &drv->nl_cache) < 0) {
1955                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1956                            "netlink cache");
1957                 goto err3;
1958         }
1959         if (genl_ctrl_alloc_cache(drv->nl_handle_event, &drv->nl_cache_event) <
1960             0) {
1961                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1962                            "netlink cache (event)");
1963                 goto err3b;
1964         }
1965 #else /* CONFIG_LIBNL20 */
1966         drv->nl_cache = genl_ctrl_alloc_cache(drv->nl_handle);
1967         if (drv->nl_cache == NULL) {
1968                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1969                            "netlink cache");
1970                 goto err3;
1971         }
1972         drv->nl_cache_event = genl_ctrl_alloc_cache(drv->nl_handle_event);
1973         if (drv->nl_cache_event == NULL) {
1974                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1975                            "netlink cache (event)");
1976                 goto err3b;
1977         }
1978 #endif /* CONFIG_LIBNL20 */
1979
1980         drv->nl80211 = genl_ctrl_search_by_name(drv->nl_cache, "nl80211");
1981         if (drv->nl80211 == NULL) {
1982                 wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
1983                            "found");
1984                 goto err4;
1985         }
1986
1987         ret = nl_get_multicast_id(drv, "nl80211", "scan");
1988         if (ret >= 0)
1989                 ret = nl_socket_add_membership(drv->nl_handle_event, ret);
1990         if (ret < 0) {
1991                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
1992                            "membership for scan events: %d (%s)",
1993                            ret, strerror(-ret));
1994                 goto err4;
1995         }
1996
1997         ret = nl_get_multicast_id(drv, "nl80211", "mlme");
1998         if (ret >= 0)
1999                 ret = nl_socket_add_membership(drv->nl_handle_event, ret);
2000         if (ret < 0) {
2001                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
2002                            "membership for mlme events: %d (%s)",
2003                            ret, strerror(-ret));
2004                 goto err4;
2005         }
2006
2007         ret = nl_get_multicast_id(drv, "nl80211", "regulatory");
2008         if (ret >= 0)
2009                 ret = nl_socket_add_membership(drv->nl_handle_event, ret);
2010         if (ret < 0) {
2011                 wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
2012                            "membership for regulatory events: %d (%s)",
2013                            ret, strerror(-ret));
2014                 /* Continue without regulatory events */
2015         }
2016
2017         eloop_register_read_sock(nl_socket_get_fd(drv->nl_handle_event),
2018                                  wpa_driver_nl80211_event_receive, drv,
2019                                  drv->nl_handle_event);
2020
2021         return 0;
2022
2023 err4:
2024         nl_cache_free(drv->nl_cache_event);
2025 err3b:
2026         nl_cache_free(drv->nl_cache);
2027 err3:
2028         nl80211_handle_destroy(drv->nl_handle_event);
2029 err2b:
2030         nl80211_handle_destroy(drv->nl_handle);
2031 err2:
2032         nl_cb_put(drv->nl_cb);
2033 err1:
2034         return -1;
2035 }
2036
2037
2038 static void wpa_driver_nl80211_rfkill_blocked(void *ctx)
2039 {
2040         wpa_printf(MSG_DEBUG, "nl80211: RFKILL blocked");
2041         /*
2042          * This may be for any interface; use ifdown event to disable
2043          * interface.
2044          */
2045 }
2046
2047
2048 static void wpa_driver_nl80211_rfkill_unblocked(void *ctx)
2049 {
2050         struct wpa_driver_nl80211_data *drv = ctx;
2051         wpa_printf(MSG_DEBUG, "nl80211: RFKILL unblocked");
2052         if (linux_set_iface_flags(drv->ioctl_sock, drv->first_bss.ifname, 1)) {
2053                 wpa_printf(MSG_DEBUG, "nl80211: Could not set interface UP "
2054                            "after rfkill unblock");
2055                 return;
2056         }
2057         /* rtnetlink ifup handler will report interface as enabled */
2058 }
2059
2060
2061 static void nl80211_get_phy_name(struct wpa_driver_nl80211_data *drv)
2062 {
2063         /* Find phy (radio) to which this interface belongs */
2064         char buf[90], *pos;
2065         int f, rv;
2066
2067         drv->phyname[0] = '\0';
2068         snprintf(buf, sizeof(buf) - 1, "/sys/class/net/%s/phy80211/name",
2069                  drv->first_bss.ifname);
2070         f = open(buf, O_RDONLY);
2071         if (f < 0) {
2072                 wpa_printf(MSG_DEBUG, "Could not open file %s: %s",
2073                            buf, strerror(errno));
2074                 return;
2075         }
2076
2077         rv = read(f, drv->phyname, sizeof(drv->phyname) - 1);
2078         close(f);
2079         if (rv < 0) {
2080                 wpa_printf(MSG_DEBUG, "Could not read file %s: %s",
2081                            buf, strerror(errno));
2082                 return;
2083         }
2084
2085         drv->phyname[rv] = '\0';
2086         pos = os_strchr(drv->phyname, '\n');
2087         if (pos)
2088                 *pos = '\0';
2089         wpa_printf(MSG_DEBUG, "nl80211: interface %s in phy %s",
2090                    drv->first_bss.ifname, drv->phyname);
2091 }
2092
2093
2094 #ifdef CONFIG_AP
2095 static void nl80211_l2_read(void *ctx, const u8 *src_addr, const u8 *buf,
2096                             size_t len)
2097 {
2098         wpa_printf(MSG_DEBUG, "nl80211: l2_packet read %u",
2099                    (unsigned int) len);
2100 }
2101 #endif /* CONFIG_AP */
2102
2103
2104 /**
2105  * wpa_driver_nl80211_init - Initialize nl80211 driver interface
2106  * @ctx: context to be used when calling wpa_supplicant functions,
2107  * e.g., wpa_supplicant_event()
2108  * @ifname: interface name, e.g., wlan0
2109  * @global_priv: private driver global data from global_init()
2110  * Returns: Pointer to private data, %NULL on failure
2111  */
2112 static void * wpa_driver_nl80211_init(void *ctx, const char *ifname,
2113                                       void *global_priv)
2114 {
2115         struct wpa_driver_nl80211_data *drv;
2116         struct netlink_config *cfg;
2117         struct rfkill_config *rcfg;
2118         struct i802_bss *bss;
2119
2120         drv = os_zalloc(sizeof(*drv));
2121         if (drv == NULL)
2122                 return NULL;
2123         drv->global = global_priv;
2124         drv->ctx = ctx;
2125         bss = &drv->first_bss;
2126         bss->drv = drv;
2127         os_strlcpy(bss->ifname, ifname, sizeof(bss->ifname));
2128         drv->monitor_ifidx = -1;
2129         drv->monitor_sock = -1;
2130         drv->ioctl_sock = -1;
2131         drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
2132
2133         if (wpa_driver_nl80211_init_nl(drv)) {
2134                 os_free(drv);
2135                 return NULL;
2136         }
2137
2138         nl80211_get_phy_name(drv);
2139
2140         drv->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
2141         if (drv->ioctl_sock < 0) {
2142                 perror("socket(PF_INET,SOCK_DGRAM)");
2143                 goto failed;
2144         }
2145
2146         cfg = os_zalloc(sizeof(*cfg));
2147         if (cfg == NULL)
2148                 goto failed;
2149         cfg->ctx = drv;
2150         cfg->newlink_cb = wpa_driver_nl80211_event_rtm_newlink;
2151         cfg->dellink_cb = wpa_driver_nl80211_event_rtm_dellink;
2152         drv->netlink = netlink_init(cfg);
2153         if (drv->netlink == NULL) {
2154                 os_free(cfg);
2155                 goto failed;
2156         }
2157
2158         rcfg = os_zalloc(sizeof(*rcfg));
2159         if (rcfg == NULL)
2160                 goto failed;
2161         rcfg->ctx = drv;
2162         os_strlcpy(rcfg->ifname, ifname, sizeof(rcfg->ifname));
2163         rcfg->blocked_cb = wpa_driver_nl80211_rfkill_blocked;
2164         rcfg->unblocked_cb = wpa_driver_nl80211_rfkill_unblocked;
2165         drv->rfkill = rfkill_init(rcfg);
2166         if (drv->rfkill == NULL) {
2167                 wpa_printf(MSG_DEBUG, "nl80211: RFKILL status not available");
2168                 os_free(rcfg);
2169         }
2170
2171         if (wpa_driver_nl80211_finish_drv_init(drv))
2172                 goto failed;
2173
2174 #ifdef CONFIG_AP
2175         drv->l2 = l2_packet_init(ifname, NULL, ETH_P_EAPOL,
2176                                  nl80211_l2_read, drv, 0);
2177 #endif /* CONFIG_AP */
2178
2179         if (drv->global)
2180                 dl_list_add(&drv->global->interfaces, &drv->list);
2181
2182         return bss;
2183
2184 failed:
2185         rfkill_deinit(drv->rfkill);
2186         netlink_deinit(drv->netlink);
2187         if (drv->ioctl_sock >= 0)
2188                 close(drv->ioctl_sock);
2189
2190         genl_family_put(drv->nl80211);
2191         nl_cache_free(drv->nl_cache);
2192         nl80211_handle_destroy(drv->nl_handle);
2193         nl_cb_put(drv->nl_cb);
2194         eloop_unregister_read_sock(nl_socket_get_fd(drv->nl_handle_event));
2195
2196         os_free(drv);
2197         return NULL;
2198 }
2199
2200
2201 static int nl80211_register_frame(struct wpa_driver_nl80211_data *drv,
2202                                   struct nl_handle *nl_handle,
2203                                   u16 type, const u8 *match, size_t match_len)
2204 {
2205         struct nl_msg *msg;
2206         int ret = -1;
2207
2208         msg = nlmsg_alloc();
2209         if (!msg)
2210                 return -1;
2211
2212         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
2213                     NL80211_CMD_REGISTER_ACTION, 0);
2214
2215         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2216         NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE, type);
2217         NLA_PUT(msg, NL80211_ATTR_FRAME_MATCH, match_len, match);
2218
2219         ret = send_and_recv(drv, nl_handle, msg, NULL, NULL);
2220         msg = NULL;
2221         if (ret) {
2222                 wpa_printf(MSG_DEBUG, "nl80211: Register frame command "
2223                            "failed (type=%u): ret=%d (%s)",
2224                            type, ret, strerror(-ret));
2225                 wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
2226                             match, match_len);
2227                 goto nla_put_failure;
2228         }
2229         ret = 0;
2230 nla_put_failure:
2231         nlmsg_free(msg);
2232         return ret;
2233 }
2234
2235
2236 static int nl80211_register_action_frame(struct wpa_driver_nl80211_data *drv,
2237                                          const u8 *match, size_t match_len)
2238 {
2239         u16 type = (WLAN_FC_TYPE_MGMT << 2) | (WLAN_FC_STYPE_ACTION << 4);
2240         return nl80211_register_frame(drv, drv->nl_handle_event,
2241                                       type, match, match_len);
2242 }
2243
2244
2245 static int nl80211_register_action_frames(struct wpa_driver_nl80211_data *drv)
2246 {
2247 #ifdef CONFIG_P2P
2248         /* GAS Initial Request */
2249         if (nl80211_register_action_frame(drv, (u8 *) "\x04\x0a", 2) < 0)
2250                 return -1;
2251         /* GAS Initial Response */
2252         if (nl80211_register_action_frame(drv, (u8 *) "\x04\x0b", 2) < 0)
2253                 return -1;
2254         /* GAS Comeback Request */
2255         if (nl80211_register_action_frame(drv, (u8 *) "\x04\x0c", 2) < 0)
2256                 return -1;
2257         /* GAS Comeback Response */
2258         if (nl80211_register_action_frame(drv, (u8 *) "\x04\x0d", 2) < 0)
2259                 return -1;
2260         /* P2P Public Action */
2261         if (nl80211_register_action_frame(drv,
2262                                           (u8 *) "\x04\x09\x50\x6f\x9a\x09",
2263                                           6) < 0)
2264                 return -1;
2265         /* P2P Action */
2266         if (nl80211_register_action_frame(drv,
2267                                           (u8 *) "\x7f\x50\x6f\x9a\x09",
2268                                           5) < 0)
2269                 return -1;
2270 #endif /* CONFIG_P2P */
2271 #ifdef CONFIG_IEEE80211W
2272         /* SA Query Response */
2273         if (nl80211_register_action_frame(drv, (u8 *) "\x08\x01", 2) < 0)
2274                 return -1;
2275 #endif /* CONFIG_IEEE80211W */
2276
2277         /* FT Action frames */
2278         if (nl80211_register_action_frame(drv, (u8 *) "\x06", 1) < 0)
2279                 return -1;
2280         else
2281                 drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_FT |
2282                         WPA_DRIVER_CAPA_KEY_MGMT_FT_PSK;
2283
2284         return 0;
2285 }
2286
2287
2288 static void wpa_driver_nl80211_send_rfkill(void *eloop_ctx, void *timeout_ctx)
2289 {
2290         wpa_supplicant_event(timeout_ctx, EVENT_INTERFACE_DISABLED, NULL);
2291 }
2292
2293
2294 static int
2295 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv)
2296 {
2297         struct i802_bss *bss = &drv->first_bss;
2298         int send_rfkill_event = 0;
2299
2300         drv->ifindex = if_nametoindex(bss->ifname);
2301         drv->first_bss.ifindex = drv->ifindex;
2302
2303 #ifndef HOSTAPD
2304         /*
2305          * Make sure the interface starts up in station mode unless this is a
2306          * dynamically added interface (e.g., P2P) that was already configured
2307          * with proper iftype.
2308          */
2309         if ((drv->global == NULL ||
2310              drv->ifindex != drv->global->if_add_ifindex) &&
2311             wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION) < 0) {
2312                 wpa_printf(MSG_DEBUG, "nl80211: Could not configure driver to "
2313                            "use managed mode");
2314         }
2315
2316         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 1)) {
2317                 if (rfkill_is_blocked(drv->rfkill)) {
2318                         wpa_printf(MSG_DEBUG, "nl80211: Could not yet enable "
2319                                    "interface '%s' due to rfkill",
2320                                    bss->ifname);
2321                         drv->if_disabled = 1;
2322                         send_rfkill_event = 1;
2323                 } else {
2324                         wpa_printf(MSG_ERROR, "nl80211: Could not set "
2325                                    "interface '%s' UP", bss->ifname);
2326                         return -1;
2327                 }
2328         }
2329
2330         netlink_send_oper_ifla(drv->netlink, drv->ifindex,
2331                                1, IF_OPER_DORMANT);
2332 #endif /* HOSTAPD */
2333
2334         if (wpa_driver_nl80211_capa(drv))
2335                 return -1;
2336
2337         if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, drv->addr))
2338                 return -1;
2339
2340         if (nl80211_register_action_frames(drv) < 0) {
2341                 wpa_printf(MSG_DEBUG, "nl80211: Failed to register Action "
2342                            "frame processing - ignore for now");
2343                 /*
2344                  * Older kernel versions did not support this, so ignore the
2345                  * error for now. Some functionality may not be available
2346                  * because of this.
2347                  */
2348         }
2349
2350         if (send_rfkill_event) {
2351                 eloop_register_timeout(0, 0, wpa_driver_nl80211_send_rfkill,
2352                                        drv, drv->ctx);
2353         }
2354
2355         return 0;
2356 }
2357
2358
2359 static int wpa_driver_nl80211_del_beacon(struct wpa_driver_nl80211_data *drv)
2360 {
2361         struct nl_msg *msg;
2362
2363         msg = nlmsg_alloc();
2364         if (!msg)
2365                 return -ENOMEM;
2366
2367         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2368                     0, NL80211_CMD_DEL_BEACON, 0);
2369         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2370
2371         return send_and_recv_msgs(drv, msg, NULL, NULL);
2372  nla_put_failure:
2373         return -ENOBUFS;
2374 }
2375
2376
2377 /**
2378  * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
2379  * @priv: Pointer to private nl80211 data from wpa_driver_nl80211_init()
2380  *
2381  * Shut down driver interface and processing of driver events. Free
2382  * private data buffer if one was allocated in wpa_driver_nl80211_init().
2383  */
2384 static void wpa_driver_nl80211_deinit(void *priv)
2385 {
2386         struct i802_bss *bss = priv;
2387         struct wpa_driver_nl80211_data *drv = bss->drv;
2388
2389 #ifdef CONFIG_AP
2390         if (drv->l2)
2391                 l2_packet_deinit(drv->l2);
2392 #endif /* CONFIG_AP */
2393
2394         if (drv->nl_handle_preq)
2395                 wpa_driver_nl80211_probe_req_report(bss, 0);
2396         if (bss->added_if_into_bridge) {
2397                 if (linux_br_del_if(drv->ioctl_sock, bss->brname, bss->ifname)
2398                     < 0)
2399                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
2400                                    "interface %s from bridge %s: %s",
2401                                    bss->ifname, bss->brname, strerror(errno));
2402         }
2403         if (bss->added_bridge) {
2404                 if (linux_br_del(drv->ioctl_sock, bss->brname) < 0)
2405                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
2406                                    "bridge %s: %s",
2407                                    bss->brname, strerror(errno));
2408         }
2409
2410         nl80211_remove_monitor_interface(drv);
2411
2412         if (is_ap_interface(drv->nlmode))
2413                 wpa_driver_nl80211_del_beacon(drv);
2414
2415 #ifdef HOSTAPD
2416         if (drv->last_freq_ht) {
2417                 /* Clear HT flags from the driver */
2418                 struct hostapd_freq_params freq;
2419                 os_memset(&freq, 0, sizeof(freq));
2420                 freq.freq = drv->last_freq;
2421                 i802_set_freq(priv, &freq);
2422         }
2423
2424         if (drv->eapol_sock >= 0) {
2425                 eloop_unregister_read_sock(drv->eapol_sock);
2426                 close(drv->eapol_sock);
2427         }
2428
2429         if (drv->if_indices != drv->default_if_indices)
2430                 os_free(drv->if_indices);
2431 #endif /* HOSTAPD */
2432
2433         if (drv->disable_11b_rates)
2434                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
2435
2436         netlink_send_oper_ifla(drv->netlink, drv->ifindex, 0, IF_OPER_UP);
2437         netlink_deinit(drv->netlink);
2438         rfkill_deinit(drv->rfkill);
2439
2440         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
2441
2442         (void) linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 0);
2443         wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION);
2444
2445         if (drv->ioctl_sock >= 0)
2446                 close(drv->ioctl_sock);
2447
2448         eloop_unregister_read_sock(nl_socket_get_fd(drv->nl_handle_event));
2449         genl_family_put(drv->nl80211);
2450         nl_cache_free(drv->nl_cache);
2451         nl_cache_free(drv->nl_cache_event);
2452         nl80211_handle_destroy(drv->nl_handle);
2453         nl80211_handle_destroy(drv->nl_handle_event);
2454         nl_cb_put(drv->nl_cb);
2455
2456         os_free(drv->filter_ssids);
2457
2458         if (drv->global)
2459                 dl_list_del(&drv->list);
2460
2461         os_free(drv);
2462 }
2463
2464
2465 /**
2466  * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
2467  * @eloop_ctx: Driver private data
2468  * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
2469  *
2470  * This function can be used as registered timeout when starting a scan to
2471  * generate a scan completed event if the driver does not report this.
2472  */
2473 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
2474 {
2475         struct wpa_driver_nl80211_data *drv = eloop_ctx;
2476         if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED) {
2477                 wpa_driver_nl80211_set_mode(&drv->first_bss,
2478                                             drv->ap_scan_as_station);
2479                 drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
2480         }
2481         wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
2482         wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
2483 }
2484
2485
2486 /**
2487  * wpa_driver_nl80211_scan - Request the driver to initiate scan
2488  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
2489  * @params: Scan parameters
2490  * Returns: 0 on success, -1 on failure
2491  */
2492 static int wpa_driver_nl80211_scan(void *priv,
2493                                    struct wpa_driver_scan_params *params)
2494 {
2495         struct i802_bss *bss = priv;
2496         struct wpa_driver_nl80211_data *drv = bss->drv;
2497         int ret = 0, timeout;
2498         struct nl_msg *msg, *ssids, *freqs, *rates;
2499         size_t i;
2500
2501         msg = nlmsg_alloc();
2502         ssids = nlmsg_alloc();
2503         freqs = nlmsg_alloc();
2504         rates = nlmsg_alloc();
2505         if (!msg || !ssids || !freqs || !rates) {
2506                 nlmsg_free(msg);
2507                 nlmsg_free(ssids);
2508                 nlmsg_free(freqs);
2509                 nlmsg_free(rates);
2510                 return -1;
2511         }
2512
2513         os_free(drv->filter_ssids);
2514         drv->filter_ssids = params->filter_ssids;
2515         params->filter_ssids = NULL;
2516         drv->num_filter_ssids = params->num_filter_ssids;
2517
2518         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
2519                     NL80211_CMD_TRIGGER_SCAN, 0);
2520
2521         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2522
2523         for (i = 0; i < params->num_ssids; i++) {
2524                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan SSID",
2525                                   params->ssids[i].ssid,
2526                                   params->ssids[i].ssid_len);
2527                 NLA_PUT(ssids, i + 1, params->ssids[i].ssid_len,
2528                         params->ssids[i].ssid);
2529         }
2530         if (params->num_ssids)
2531                 nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
2532
2533         if (params->extra_ies) {
2534                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan extra IEs",
2535                                   params->extra_ies, params->extra_ies_len);
2536                 NLA_PUT(msg, NL80211_ATTR_IE, params->extra_ies_len,
2537                         params->extra_ies);
2538         }
2539
2540         if (params->freqs) {
2541                 for (i = 0; params->freqs[i]; i++) {
2542                         wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
2543                                    "MHz", params->freqs[i]);
2544                         NLA_PUT_U32(freqs, i + 1, params->freqs[i]);
2545                 }
2546                 nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs);
2547         }
2548
2549         if (params->p2p_probe) {
2550                 /*
2551                  * Remove 2.4 GHz rates 1, 2, 5.5, 11 Mbps from supported rates
2552                  * by masking out everything else apart from the OFDM rates 6,
2553                  * 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS rates. All 5 GHz
2554                  * rates are left enabled.
2555                  */
2556                 NLA_PUT(rates, NL80211_BAND_2GHZ, 8,
2557                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
2558                 nla_put_nested(msg, NL80211_ATTR_SCAN_SUPP_RATES, rates);
2559         }
2560
2561         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2562         msg = NULL;
2563         if (ret) {
2564                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
2565                            "(%s)", ret, strerror(-ret));
2566 #ifdef HOSTAPD
2567                 if (is_ap_interface(drv->nlmode)) {
2568                         /*
2569                          * mac80211 does not allow scan requests in AP mode, so
2570                          * try to do this in station mode.
2571                          */
2572                         if (wpa_driver_nl80211_set_mode(
2573                                     bss, NL80211_IFTYPE_STATION))
2574                                 goto nla_put_failure;
2575
2576                         if (wpa_driver_nl80211_scan(drv, params)) {
2577                                 wpa_driver_nl80211_set_mode(bss, drv->nlmode);
2578                                 goto nla_put_failure;
2579                         }
2580
2581                         /* Restore AP mode when processing scan results */
2582                         drv->ap_scan_as_station = drv->nlmode;
2583                         ret = 0;
2584                 } else
2585                         goto nla_put_failure;
2586 #else /* HOSTAPD */
2587                 goto nla_put_failure;
2588 #endif /* HOSTAPD */
2589         }
2590
2591         /* Not all drivers generate "scan completed" wireless event, so try to
2592          * read results after a timeout. */
2593         timeout = 10;
2594         if (drv->scan_complete_events) {
2595                 /*
2596                  * The driver seems to deliver events to notify when scan is
2597                  * complete, so use longer timeout to avoid race conditions
2598                  * with scanning and following association request.
2599                  */
2600                 timeout = 30;
2601         }
2602         wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
2603                    "seconds", ret, timeout);
2604         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
2605         eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
2606                                drv, drv->ctx);
2607
2608 nla_put_failure:
2609         nlmsg_free(ssids);
2610         nlmsg_free(msg);
2611         nlmsg_free(freqs);
2612         nlmsg_free(rates);
2613         return ret;
2614 }
2615
2616
2617 static const u8 * nl80211_get_ie(const u8 *ies, size_t ies_len, u8 ie)
2618 {
2619         const u8 *end, *pos;
2620
2621         if (ies == NULL)
2622                 return NULL;
2623
2624         pos = ies;
2625         end = ies + ies_len;
2626
2627         while (pos + 1 < end) {
2628                 if (pos + 2 + pos[1] > end)
2629                         break;
2630                 if (pos[0] == ie)
2631                         return pos;
2632                 pos += 2 + pos[1];
2633         }
2634
2635         return NULL;
2636 }
2637
2638
2639 static int nl80211_scan_filtered(struct wpa_driver_nl80211_data *drv,
2640                                  const u8 *ie, size_t ie_len)
2641 {
2642         const u8 *ssid;
2643         size_t i;
2644
2645         if (drv->filter_ssids == NULL)
2646                 return 0;
2647
2648         ssid = nl80211_get_ie(ie, ie_len, WLAN_EID_SSID);
2649         if (ssid == NULL)
2650                 return 1;
2651
2652         for (i = 0; i < drv->num_filter_ssids; i++) {
2653                 if (ssid[1] == drv->filter_ssids[i].ssid_len &&
2654                     os_memcmp(ssid + 2, drv->filter_ssids[i].ssid, ssid[1]) ==
2655                     0)
2656                         return 0;
2657         }
2658
2659         return 1;
2660 }
2661
2662
2663 static int bss_info_handler(struct nl_msg *msg, void *arg)
2664 {
2665         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2666         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2667         struct nlattr *bss[NL80211_BSS_MAX + 1];
2668         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
2669                 [NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
2670                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
2671                 [NL80211_BSS_TSF] = { .type = NLA_U64 },
2672                 [NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
2673                 [NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
2674                 [NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
2675                 [NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
2676                 [NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
2677                 [NL80211_BSS_STATUS] = { .type = NLA_U32 },
2678                 [NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
2679                 [NL80211_BSS_BEACON_IES] = { .type = NLA_UNSPEC },
2680         };
2681         struct nl80211_bss_info_arg *_arg = arg;
2682         struct wpa_scan_results *res = _arg->res;
2683         struct wpa_scan_res **tmp;
2684         struct wpa_scan_res *r;
2685         const u8 *ie, *beacon_ie;
2686         size_t ie_len, beacon_ie_len;
2687         u8 *pos;
2688         size_t i;
2689
2690         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2691                   genlmsg_attrlen(gnlh, 0), NULL);
2692         if (!tb[NL80211_ATTR_BSS])
2693                 return NL_SKIP;
2694         if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
2695                              bss_policy))
2696                 return NL_SKIP;
2697         if (bss[NL80211_BSS_STATUS]) {
2698                 enum nl80211_bss_status status;
2699                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
2700                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
2701                     bss[NL80211_BSS_FREQUENCY]) {
2702                         _arg->assoc_freq =
2703                                 nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
2704                         wpa_printf(MSG_DEBUG, "nl80211: Associated on %u MHz",
2705                                    _arg->assoc_freq);
2706                 }
2707                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
2708                     bss[NL80211_BSS_BSSID]) {
2709                         os_memcpy(_arg->assoc_bssid,
2710                                   nla_data(bss[NL80211_BSS_BSSID]), ETH_ALEN);
2711                         wpa_printf(MSG_DEBUG, "nl80211: Associated with "
2712                                    MACSTR, MAC2STR(_arg->assoc_bssid));
2713                 }
2714         }
2715         if (!res)
2716                 return NL_SKIP;
2717         if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
2718                 ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2719                 ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2720         } else {
2721                 ie = NULL;
2722                 ie_len = 0;
2723         }
2724         if (bss[NL80211_BSS_BEACON_IES]) {
2725                 beacon_ie = nla_data(bss[NL80211_BSS_BEACON_IES]);
2726                 beacon_ie_len = nla_len(bss[NL80211_BSS_BEACON_IES]);
2727         } else {
2728                 beacon_ie = NULL;
2729                 beacon_ie_len = 0;
2730         }
2731
2732         if (nl80211_scan_filtered(_arg->drv, ie ? ie : beacon_ie,
2733                                   ie ? ie_len : beacon_ie_len))
2734                 return NL_SKIP;
2735
2736         r = os_zalloc(sizeof(*r) + ie_len + beacon_ie_len);
2737         if (r == NULL)
2738                 return NL_SKIP;
2739         if (bss[NL80211_BSS_BSSID])
2740                 os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
2741                           ETH_ALEN);
2742         if (bss[NL80211_BSS_FREQUENCY])
2743                 r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
2744         if (bss[NL80211_BSS_BEACON_INTERVAL])
2745                 r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
2746         if (bss[NL80211_BSS_CAPABILITY])
2747                 r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
2748         r->flags |= WPA_SCAN_NOISE_INVALID;
2749         if (bss[NL80211_BSS_SIGNAL_MBM]) {
2750                 r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
2751                 r->level /= 100; /* mBm to dBm */
2752                 r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
2753         } else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
2754                 r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
2755                 r->flags |= WPA_SCAN_LEVEL_INVALID;
2756         } else
2757                 r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
2758         if (bss[NL80211_BSS_TSF])
2759                 r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
2760         if (bss[NL80211_BSS_SEEN_MS_AGO])
2761                 r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
2762         r->ie_len = ie_len;
2763         pos = (u8 *) (r + 1);
2764         if (ie) {
2765                 os_memcpy(pos, ie, ie_len);
2766                 pos += ie_len;
2767         }
2768         r->beacon_ie_len = beacon_ie_len;
2769         if (beacon_ie)
2770                 os_memcpy(pos, beacon_ie, beacon_ie_len);
2771
2772         if (bss[NL80211_BSS_STATUS]) {
2773                 enum nl80211_bss_status status;
2774                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
2775                 switch (status) {
2776                 case NL80211_BSS_STATUS_AUTHENTICATED:
2777                         r->flags |= WPA_SCAN_AUTHENTICATED;
2778                         break;
2779                 case NL80211_BSS_STATUS_ASSOCIATED:
2780                         r->flags |= WPA_SCAN_ASSOCIATED;
2781                         break;
2782                 default:
2783                         break;
2784                 }
2785         }
2786
2787         /*
2788          * cfg80211 maintains separate BSS table entries for APs if the same
2789          * BSSID,SSID pair is seen on multiple channels. wpa_supplicant does
2790          * not use frequency as a separate key in the BSS table, so filter out
2791          * duplicated entries. Prefer associated BSS entry in such a case in
2792          * order to get the correct frequency into the BSS table.
2793          */
2794         for (i = 0; i < res->num; i++) {
2795                 const u8 *s1, *s2;
2796                 if (os_memcmp(res->res[i]->bssid, r->bssid, ETH_ALEN) != 0)
2797                         continue;
2798
2799                 s1 = nl80211_get_ie((u8 *) (res->res[i] + 1),
2800                                     res->res[i]->ie_len, WLAN_EID_SSID);
2801                 s2 = nl80211_get_ie((u8 *) (r + 1), r->ie_len, WLAN_EID_SSID);
2802                 if (s1 == NULL || s2 == NULL || s1[1] != s2[1] ||
2803                     os_memcmp(s1, s2, 2 + s1[1]) != 0)
2804                         continue;
2805
2806                 /* Same BSSID,SSID was already included in scan results */
2807                 wpa_printf(MSG_DEBUG, "nl80211: Remove duplicated scan result "
2808                            "for " MACSTR, MAC2STR(r->bssid));
2809
2810                 if ((r->flags & WPA_SCAN_ASSOCIATED) &&
2811                     !(res->res[i]->flags & WPA_SCAN_ASSOCIATED)) {
2812                         os_free(res->res[i]);
2813                         res->res[i] = r;
2814                 } else
2815                         os_free(r);
2816                 return NL_SKIP;
2817         }
2818
2819         tmp = os_realloc(res->res,
2820                          (res->num + 1) * sizeof(struct wpa_scan_res *));
2821         if (tmp == NULL) {
2822                 os_free(r);
2823                 return NL_SKIP;
2824         }
2825         tmp[res->num++] = r;
2826         res->res = tmp;
2827
2828         return NL_SKIP;
2829 }
2830
2831
2832 static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
2833                                  const u8 *addr)
2834 {
2835         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
2836                 wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
2837                            "mismatch (" MACSTR ")", MAC2STR(addr));
2838                 wpa_driver_nl80211_mlme(drv, addr,
2839                                         NL80211_CMD_DEAUTHENTICATE,
2840                                         WLAN_REASON_PREV_AUTH_NOT_VALID, 1);
2841         }
2842 }
2843
2844
2845 static void wpa_driver_nl80211_check_bss_status(
2846         struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
2847 {
2848         size_t i;
2849
2850         for (i = 0; i < res->num; i++) {
2851                 struct wpa_scan_res *r = res->res[i];
2852                 if (r->flags & WPA_SCAN_AUTHENTICATED) {
2853                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
2854                                    "indicates BSS status with " MACSTR
2855                                    " as authenticated",
2856                                    MAC2STR(r->bssid));
2857                         if (is_sta_interface(drv->nlmode) &&
2858                             os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
2859                             os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
2860                             0) {
2861                                 wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
2862                                            " in local state (auth=" MACSTR
2863                                            " assoc=" MACSTR ")",
2864                                            MAC2STR(drv->auth_bssid),
2865                                            MAC2STR(drv->bssid));
2866                                 clear_state_mismatch(drv, r->bssid);
2867                         }
2868                 }
2869
2870                 if (r->flags & WPA_SCAN_ASSOCIATED) {
2871                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
2872                                    "indicate BSS status with " MACSTR
2873                                    " as associated",
2874                                    MAC2STR(r->bssid));
2875                         if (is_sta_interface(drv->nlmode) &&
2876                             !drv->associated) {
2877                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
2878                                            "(not associated) does not match "
2879                                            "with BSS state");
2880                                 clear_state_mismatch(drv, r->bssid);
2881                         } else if (is_sta_interface(drv->nlmode) &&
2882                                    os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
2883                                    0) {
2884                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
2885                                            "(associated with " MACSTR ") does "
2886                                            "not match with BSS state",
2887                                            MAC2STR(drv->bssid));
2888                                 clear_state_mismatch(drv, r->bssid);
2889                                 clear_state_mismatch(drv, drv->bssid);
2890                         }
2891                 }
2892         }
2893 }
2894
2895
2896 static void wpa_scan_results_free(struct wpa_scan_results *res)
2897 {
2898         size_t i;
2899
2900         if (res == NULL)
2901                 return;
2902
2903         for (i = 0; i < res->num; i++)
2904                 os_free(res->res[i]);
2905         os_free(res->res);
2906         os_free(res);
2907 }
2908
2909
2910 static struct wpa_scan_results *
2911 nl80211_get_scan_results(struct wpa_driver_nl80211_data *drv)
2912 {
2913         struct nl_msg *msg;
2914         struct wpa_scan_results *res;
2915         int ret;
2916         struct nl80211_bss_info_arg arg;
2917
2918         res = os_zalloc(sizeof(*res));
2919         if (res == NULL)
2920                 return NULL;
2921         msg = nlmsg_alloc();
2922         if (!msg)
2923                 goto nla_put_failure;
2924
2925         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, NLM_F_DUMP,
2926                     NL80211_CMD_GET_SCAN, 0);
2927         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2928
2929         arg.drv = drv;
2930         arg.res = res;
2931         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
2932         msg = NULL;
2933         if (ret == 0) {
2934                 wpa_printf(MSG_DEBUG, "Received scan results (%lu BSSes)",
2935                            (unsigned long) res->num);
2936                 return res;
2937         }
2938         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
2939                    "(%s)", ret, strerror(-ret));
2940 nla_put_failure:
2941         nlmsg_free(msg);
2942         wpa_scan_results_free(res);
2943         return NULL;
2944 }
2945
2946
2947 /**
2948  * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
2949  * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
2950  * Returns: Scan results on success, -1 on failure
2951  */
2952 static struct wpa_scan_results *
2953 wpa_driver_nl80211_get_scan_results(void *priv)
2954 {
2955         struct i802_bss *bss = priv;
2956         struct wpa_driver_nl80211_data *drv = bss->drv;
2957         struct wpa_scan_results *res;
2958
2959         res = nl80211_get_scan_results(drv);
2960         if (res)
2961                 wpa_driver_nl80211_check_bss_status(drv, res);
2962         return res;
2963 }
2964
2965
2966 static void nl80211_dump_scan(struct wpa_driver_nl80211_data *drv)
2967 {
2968         struct wpa_scan_results *res;
2969         size_t i;
2970
2971         res = nl80211_get_scan_results(drv);
2972         if (res == NULL) {
2973                 wpa_printf(MSG_DEBUG, "nl80211: Failed to get scan results");
2974                 return;
2975         }
2976
2977         wpa_printf(MSG_DEBUG, "nl80211: Scan result dump");
2978         for (i = 0; i < res->num; i++) {
2979                 struct wpa_scan_res *r = res->res[i];
2980                 wpa_printf(MSG_DEBUG, "nl80211: %d/%d " MACSTR "%s%s",
2981                            (int) i, (int) res->num, MAC2STR(r->bssid),
2982                            r->flags & WPA_SCAN_AUTHENTICATED ? " [auth]" : "",
2983                            r->flags & WPA_SCAN_ASSOCIATED ? " [assoc]" : "");
2984         }
2985
2986         wpa_scan_results_free(res);
2987 }
2988
2989
2990 static int wpa_driver_nl80211_set_key(const char *ifname, void *priv,
2991                                       enum wpa_alg alg, const u8 *addr,
2992                                       int key_idx, int set_tx,
2993                                       const u8 *seq, size_t seq_len,
2994                                       const u8 *key, size_t key_len)
2995 {
2996         struct i802_bss *bss = priv;
2997         struct wpa_driver_nl80211_data *drv = bss->drv;
2998         int ifindex = if_nametoindex(ifname);
2999         struct nl_msg *msg;
3000         int ret;
3001
3002         wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
3003                    "set_tx=%d seq_len=%lu key_len=%lu",
3004                    __func__, ifindex, alg, addr, key_idx, set_tx,
3005                    (unsigned long) seq_len, (unsigned long) key_len);
3006
3007         msg = nlmsg_alloc();
3008         if (!msg)
3009                 return -ENOMEM;
3010
3011         if (alg == WPA_ALG_NONE) {
3012                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3013                             0, NL80211_CMD_DEL_KEY, 0);
3014         } else {
3015                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3016                             0, NL80211_CMD_NEW_KEY, 0);
3017                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
3018                 switch (alg) {
3019                 case WPA_ALG_WEP:
3020                         if (key_len == 5)
3021                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
3022                                             WLAN_CIPHER_SUITE_WEP40);
3023                         else
3024                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
3025                                             WLAN_CIPHER_SUITE_WEP104);
3026                         break;
3027                 case WPA_ALG_TKIP:
3028                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
3029                                     WLAN_CIPHER_SUITE_TKIP);
3030                         break;
3031                 case WPA_ALG_CCMP:
3032                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
3033                                     WLAN_CIPHER_SUITE_CCMP);
3034                         break;
3035                 case WPA_ALG_IGTK:
3036                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
3037                                     WLAN_CIPHER_SUITE_AES_CMAC);
3038                         break;
3039                 default:
3040                         wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
3041                                    "algorithm %d", __func__, alg);
3042                         nlmsg_free(msg);
3043                         return -1;
3044                 }
3045         }
3046
3047         if (seq && seq_len)
3048                 NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
3049
3050         if (addr && !is_broadcast_ether_addr(addr)) {
3051                 wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
3052                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3053
3054                 if (alg != WPA_ALG_WEP && key_idx && !set_tx) {
3055                         wpa_printf(MSG_DEBUG, "   RSN IBSS RX GTK");
3056                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_TYPE,
3057                                     NL80211_KEYTYPE_GROUP);
3058                 }
3059         } else if (addr && is_broadcast_ether_addr(addr)) {
3060                 struct nl_msg *types;
3061                 int err;
3062                 wpa_printf(MSG_DEBUG, "   broadcast key");
3063                 types = nlmsg_alloc();
3064                 if (!types)
3065                         goto nla_put_failure;
3066                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
3067                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
3068                                      types);
3069                 nlmsg_free(types);
3070                 if (err)
3071                         goto nla_put_failure;
3072         }
3073         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
3074         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
3075
3076         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3077         if ((ret == -ENOENT || ret == -ENOLINK) && alg == WPA_ALG_NONE)
3078                 ret = 0;
3079         if (ret)
3080                 wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
3081                            ret, strerror(-ret));
3082
3083         /*
3084          * If we failed or don't need to set the default TX key (below),
3085          * we're done here.
3086          */
3087         if (ret || !set_tx || alg == WPA_ALG_NONE)
3088                 return ret;
3089         if (is_ap_interface(drv->nlmode) && addr &&
3090             !is_broadcast_ether_addr(addr))
3091                 return ret;
3092
3093         msg = nlmsg_alloc();
3094         if (!msg)
3095                 return -ENOMEM;
3096
3097         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3098                     0, NL80211_CMD_SET_KEY, 0);
3099         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
3100         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
3101         if (alg == WPA_ALG_IGTK)
3102                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
3103         else
3104                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
3105         if (addr && is_broadcast_ether_addr(addr)) {
3106                 struct nl_msg *types;
3107                 int err;
3108                 types = nlmsg_alloc();
3109                 if (!types)
3110                         goto nla_put_failure;
3111                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
3112                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
3113                                      types);
3114                 nlmsg_free(types);
3115                 if (err)
3116                         goto nla_put_failure;
3117         } else if (addr) {
3118                 struct nl_msg *types;
3119                 int err;
3120                 types = nlmsg_alloc();
3121                 if (!types)
3122                         goto nla_put_failure;
3123                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_UNICAST);
3124                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
3125                                      types);
3126                 nlmsg_free(types);
3127                 if (err)
3128                         goto nla_put_failure;
3129         }
3130
3131         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3132         if (ret == -ENOENT)
3133                 ret = 0;
3134         if (ret)
3135                 wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
3136                            "err=%d %s)", ret, strerror(-ret));
3137         return ret;
3138
3139 nla_put_failure:
3140         return -ENOBUFS;
3141 }
3142
3143
3144 static int nl_add_key(struct nl_msg *msg, enum wpa_alg alg,
3145                       int key_idx, int defkey,
3146                       const u8 *seq, size_t seq_len,
3147                       const u8 *key, size_t key_len)
3148 {
3149         struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
3150         if (!key_attr)
3151                 return -1;
3152
3153         if (defkey && alg == WPA_ALG_IGTK)
3154                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
3155         else if (defkey)
3156                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
3157
3158         NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
3159
3160         switch (alg) {
3161         case WPA_ALG_WEP:
3162                 if (key_len == 5)
3163                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
3164                                     WLAN_CIPHER_SUITE_WEP40);
3165                 else
3166                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
3167                                     WLAN_CIPHER_SUITE_WEP104);
3168                 break;
3169         case WPA_ALG_TKIP:
3170                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_TKIP);
3171                 break;
3172         case WPA_ALG_CCMP:
3173                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_CCMP);
3174                 break;
3175         case WPA_ALG_IGTK:
3176                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
3177                             WLAN_CIPHER_SUITE_AES_CMAC);
3178                 break;
3179         default:
3180                 wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
3181                            "algorithm %d", __func__, alg);
3182                 return -1;
3183         }
3184
3185         if (seq && seq_len)
3186                 NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
3187
3188         NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
3189
3190         nla_nest_end(msg, key_attr);
3191
3192         return 0;
3193  nla_put_failure:
3194         return -1;
3195 }
3196
3197
3198 static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
3199                                  struct nl_msg *msg)
3200 {
3201         int i, privacy = 0;
3202         struct nlattr *nl_keys, *nl_key;
3203
3204         for (i = 0; i < 4; i++) {
3205                 if (!params->wep_key[i])
3206                         continue;
3207                 privacy = 1;
3208                 break;
3209         }
3210         if (params->wps == WPS_MODE_PRIVACY)
3211                 privacy = 1;
3212         if (params->pairwise_suite &&
3213             params->pairwise_suite != WPA_CIPHER_NONE)
3214                 privacy = 1;
3215
3216         if (!privacy)
3217                 return 0;
3218
3219         NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
3220
3221         nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
3222         if (!nl_keys)
3223                 goto nla_put_failure;
3224
3225         for (i = 0; i < 4; i++) {
3226                 if (!params->wep_key[i])
3227                         continue;
3228
3229                 nl_key = nla_nest_start(msg, i);
3230                 if (!nl_key)
3231                         goto nla_put_failure;
3232
3233                 NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
3234                         params->wep_key[i]);
3235                 if (params->wep_key_len[i] == 5)
3236                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
3237                                     WLAN_CIPHER_SUITE_WEP40);
3238                 else
3239                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
3240                                     WLAN_CIPHER_SUITE_WEP104);
3241
3242                 NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
3243
3244                 if (i == params->wep_tx_keyidx)
3245                         NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
3246
3247                 nla_nest_end(msg, nl_key);
3248         }
3249         nla_nest_end(msg, nl_keys);
3250
3251         return 0;
3252
3253 nla_put_failure:
3254         return -ENOBUFS;
3255 }
3256
3257
3258 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
3259                                    const u8 *addr, int cmd, u16 reason_code,
3260                                    int local_state_change)
3261 {
3262         int ret = -1;
3263         struct nl_msg *msg;
3264
3265         msg = nlmsg_alloc();
3266         if (!msg)
3267                 return -1;
3268
3269         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0, cmd, 0);
3270
3271         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3272         NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
3273         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3274         if (local_state_change)
3275                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
3276
3277         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3278         msg = NULL;
3279         if (ret) {
3280                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
3281                            "(%s)", ret, strerror(-ret));
3282                 goto nla_put_failure;
3283         }
3284         ret = 0;
3285
3286 nla_put_failure:
3287         nlmsg_free(msg);
3288         return ret;
3289 }
3290
3291
3292 static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
3293                                          const u8 *addr, int reason_code)
3294 {
3295         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
3296                    __func__, MAC2STR(addr), reason_code);
3297         drv->associated = 0;
3298         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISCONNECT,
3299                                        reason_code, 0);
3300 }
3301
3302
3303 static int wpa_driver_nl80211_deauthenticate(void *priv, const u8 *addr,
3304                                              int reason_code)
3305 {
3306         struct i802_bss *bss = priv;
3307         struct wpa_driver_nl80211_data *drv = bss->drv;
3308         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
3309                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
3310         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
3311                    __func__, MAC2STR(addr), reason_code);
3312         drv->associated = 0;
3313         if (drv->nlmode == NL80211_IFTYPE_ADHOC)
3314                 return nl80211_leave_ibss(drv);
3315         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
3316                                        reason_code, 0);
3317 }
3318
3319
3320 static int wpa_driver_nl80211_disassociate(void *priv, const u8 *addr,
3321                                            int reason_code)
3322 {
3323         struct i802_bss *bss = priv;
3324         struct wpa_driver_nl80211_data *drv = bss->drv;
3325         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
3326                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
3327         wpa_printf(MSG_DEBUG, "%s", __func__);
3328         drv->associated = 0;
3329         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISASSOCIATE,
3330                                        reason_code, 0);
3331 }
3332
3333
3334 static int wpa_driver_nl80211_authenticate(
3335         void *priv, struct wpa_driver_auth_params *params)
3336 {
3337         struct i802_bss *bss = priv;
3338         struct wpa_driver_nl80211_data *drv = bss->drv;
3339         int ret = -1, i;
3340         struct nl_msg *msg;
3341         enum nl80211_auth_type type;
3342         enum nl80211_iftype nlmode;
3343         int count = 0;
3344
3345         drv->associated = 0;
3346         os_memset(drv->auth_bssid, 0, ETH_ALEN);
3347         /* FIX: IBSS mode */
3348         nlmode = params->p2p ?
3349                 NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
3350         if (drv->nlmode != nlmode &&
3351             wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
3352                 return -1;
3353
3354 retry:
3355         msg = nlmsg_alloc();
3356         if (!msg)
3357                 return -1;
3358
3359         wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
3360                    drv->ifindex);
3361
3362         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
3363                     NL80211_CMD_AUTHENTICATE, 0);
3364
3365         for (i = 0; i < 4; i++) {
3366                 if (!params->wep_key[i])
3367                         continue;
3368                 wpa_driver_nl80211_set_key(bss->ifname, priv, WPA_ALG_WEP,
3369                                            NULL, i,
3370                                            i == params->wep_tx_keyidx, NULL, 0,
3371                                            params->wep_key[i],
3372                                            params->wep_key_len[i]);
3373                 if (params->wep_tx_keyidx != i)
3374                         continue;
3375                 if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
3376                                params->wep_key[i], params->wep_key_len[i])) {
3377                         nlmsg_free(msg);
3378                         return -1;
3379                 }
3380         }
3381
3382         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3383         if (params->bssid) {
3384                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
3385                            MAC2STR(params->bssid));
3386                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
3387         }
3388         if (params->freq) {
3389                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
3390                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
3391         }
3392         if (params->ssid) {
3393                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
3394                                   params->ssid, params->ssid_len);
3395                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
3396                         params->ssid);
3397         }
3398         wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
3399         if (params->ie)
3400                 NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
3401         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
3402                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
3403         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
3404                 type = NL80211_AUTHTYPE_SHARED_KEY;
3405         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
3406                 type = NL80211_AUTHTYPE_NETWORK_EAP;
3407         else if (params->auth_alg & WPA_AUTH_ALG_FT)
3408                 type = NL80211_AUTHTYPE_FT;
3409         else
3410                 goto nla_put_failure;
3411         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
3412         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
3413         if (params->local_state_change) {
3414                 wpa_printf(MSG_DEBUG, "  * Local state change only");
3415                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
3416         }
3417
3418         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3419         msg = NULL;
3420         if (ret) {
3421                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
3422                            "(%s)", ret, strerror(-ret));
3423                 count++;
3424                 if (ret == -EALREADY && count == 1 && params->bssid &&
3425                     !params->local_state_change) {
3426                         /*
3427                          * mac80211 does not currently accept new
3428                          * authentication if we are already authenticated. As a
3429                          * workaround, force deauthentication and try again.
3430                          */
3431                         wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
3432                                    "after forced deauthentication");
3433                         wpa_driver_nl80211_deauthenticate(
3434                                 bss, params->bssid,
3435                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
3436                         nlmsg_free(msg);
3437                         goto retry;
3438                 }
3439                 goto nla_put_failure;
3440         }
3441         ret = 0;
3442         wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
3443                    "successfully");
3444
3445 nla_put_failure:
3446         nlmsg_free(msg);
3447         return ret;
3448 }
3449
3450
3451 struct phy_info_arg {
3452         u16 *num_modes;
3453         struct hostapd_hw_modes *modes;
3454 };
3455
3456 static int phy_info_handler(struct nl_msg *msg, void *arg)
3457 {
3458         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
3459         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3460         struct phy_info_arg *phy_info = arg;
3461
3462         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
3463
3464         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
3465         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
3466                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
3467                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
3468                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
3469                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
3470                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
3471                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
3472         };
3473
3474         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
3475         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
3476                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
3477                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
3478         };
3479
3480         struct nlattr *nl_band;
3481         struct nlattr *nl_freq;
3482         struct nlattr *nl_rate;
3483         int rem_band, rem_freq, rem_rate;
3484         struct hostapd_hw_modes *mode;
3485         int idx, mode_is_set;
3486
3487         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3488                   genlmsg_attrlen(gnlh, 0), NULL);
3489
3490         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
3491                 return NL_SKIP;
3492
3493         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
3494                 mode = os_realloc(phy_info->modes, (*phy_info->num_modes + 1) * sizeof(*mode));
3495                 if (!mode)
3496                         return NL_SKIP;
3497                 phy_info->modes = mode;
3498
3499                 mode_is_set = 0;
3500
3501                 mode = &phy_info->modes[*(phy_info->num_modes)];
3502                 memset(mode, 0, sizeof(*mode));
3503                 *(phy_info->num_modes) += 1;
3504
3505                 nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
3506                           nla_len(nl_band), NULL);
3507
3508                 if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
3509                         mode->ht_capab = nla_get_u16(
3510                                 tb_band[NL80211_BAND_ATTR_HT_CAPA]);
3511                 }
3512
3513                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) {
3514                         mode->a_mpdu_params |= nla_get_u8(
3515                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) &
3516                                 0x03;
3517                 }
3518
3519                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) {
3520                         mode->a_mpdu_params |= nla_get_u8(
3521                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) <<
3522                                 2;
3523                 }
3524
3525                 if (tb_band[NL80211_BAND_ATTR_HT_MCS_SET] &&
3526                     nla_len(tb_band[NL80211_BAND_ATTR_HT_MCS_SET])) {
3527                         u8 *mcs;
3528                         mcs = nla_data(tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
3529                         os_memcpy(mode->mcs_set, mcs, 16);
3530                 }
3531
3532                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
3533                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
3534                                   nla_len(nl_freq), freq_policy);
3535                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
3536                                 continue;
3537                         mode->num_channels++;
3538                 }
3539
3540                 mode->channels = os_zalloc(mode->num_channels * sizeof(struct hostapd_channel_data));
3541                 if (!mode->channels)
3542                         return NL_SKIP;
3543
3544                 idx = 0;
3545
3546                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
3547                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
3548                                   nla_len(nl_freq), freq_policy);
3549                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
3550                                 continue;
3551
3552                         mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
3553                         mode->channels[idx].flag = 0;
3554
3555                         if (!mode_is_set) {
3556                                 /* crude heuristic */
3557                                 if (mode->channels[idx].freq < 4000)
3558                                         mode->mode = HOSTAPD_MODE_IEEE80211B;
3559                                 else
3560                                         mode->mode = HOSTAPD_MODE_IEEE80211A;
3561                                 mode_is_set = 1;
3562                         }
3563
3564                         /* crude heuristic */
3565                         if (mode->channels[idx].freq < 4000)
3566                                 if (mode->channels[idx].freq == 2484)
3567                                         mode->channels[idx].chan = 14;
3568                                 else
3569                                         mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
3570                         else
3571                                 mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
3572
3573                         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
3574                                 mode->channels[idx].flag |=
3575                                         HOSTAPD_CHAN_DISABLED;
3576                         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
3577                                 mode->channels[idx].flag |=
3578                                         HOSTAPD_CHAN_PASSIVE_SCAN;
3579                         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
3580                                 mode->channels[idx].flag |=
3581                                         HOSTAPD_CHAN_NO_IBSS;
3582                         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
3583                                 mode->channels[idx].flag |=
3584                                         HOSTAPD_CHAN_RADAR;
3585
3586                         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
3587                             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
3588                                 mode->channels[idx].max_tx_power =
3589                                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
3590
3591                         idx++;
3592                 }
3593
3594                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
3595                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
3596                                   nla_len(nl_rate), rate_policy);
3597                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
3598                                 continue;
3599                         mode->num_rates++;
3600                 }
3601
3602                 mode->rates = os_zalloc(mode->num_rates * sizeof(int));
3603                 if (!mode->rates)
3604                         return NL_SKIP;
3605
3606                 idx = 0;
3607
3608                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
3609                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
3610                                   nla_len(nl_rate), rate_policy);
3611                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
3612                                 continue;
3613                         mode->rates[idx] = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
3614
3615                         /* crude heuristic */
3616                         if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
3617                             mode->rates[idx] > 200)
3618                                 mode->mode = HOSTAPD_MODE_IEEE80211G;
3619
3620                         idx++;
3621                 }
3622         }
3623
3624         return NL_SKIP;
3625 }
3626
3627 static struct hostapd_hw_modes *
3628 wpa_driver_nl80211_add_11b(struct hostapd_hw_modes *modes, u16 *num_modes)
3629 {
3630         u16 m;
3631         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
3632         int i, mode11g_idx = -1;
3633
3634         /* If only 802.11g mode is included, use it to construct matching
3635          * 802.11b mode data. */
3636
3637         for (m = 0; m < *num_modes; m++) {
3638                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
3639                         return modes; /* 802.11b already included */
3640                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
3641                         mode11g_idx = m;
3642         }
3643
3644         if (mode11g_idx < 0)
3645                 return modes; /* 2.4 GHz band not supported at all */
3646
3647         nmodes = os_realloc(modes, (*num_modes + 1) * sizeof(*nmodes));
3648         if (nmodes == NULL)
3649                 return modes; /* Could not add 802.11b mode */
3650
3651         mode = &nmodes[*num_modes];
3652         os_memset(mode, 0, sizeof(*mode));
3653         (*num_modes)++;
3654         modes = nmodes;
3655
3656         mode->mode = HOSTAPD_MODE_IEEE80211B;
3657
3658         mode11g = &modes[mode11g_idx];
3659         mode->num_channels = mode11g->num_channels;
3660         mode->channels = os_malloc(mode11g->num_channels *
3661                                    sizeof(struct hostapd_channel_data));
3662         if (mode->channels == NULL) {
3663                 (*num_modes)--;
3664                 return modes; /* Could not add 802.11b mode */
3665         }
3666         os_memcpy(mode->channels, mode11g->channels,
3667                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
3668
3669         mode->num_rates = 0;
3670         mode->rates = os_malloc(4 * sizeof(int));
3671         if (mode->rates == NULL) {
3672                 os_free(mode->channels);
3673                 (*num_modes)--;
3674                 return modes; /* Could not add 802.11b mode */
3675         }
3676
3677         for (i = 0; i < mode11g->num_rates; i++) {
3678                 if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 &&
3679                     mode11g->rates[i] != 55 && mode11g->rates[i] != 110)
3680                         continue;
3681                 mode->rates[mode->num_rates] = mode11g->rates[i];
3682                 mode->num_rates++;
3683                 if (mode->num_rates == 4)
3684                         break;
3685         }
3686
3687         if (mode->num_rates == 0) {
3688                 os_free(mode->channels);
3689                 os_free(mode->rates);
3690                 (*num_modes)--;
3691                 return modes; /* No 802.11b rates */
3692         }
3693
3694         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
3695                    "information");
3696
3697         return modes;
3698 }
3699
3700
3701 static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start,
3702                                   int end)
3703 {
3704         int c;
3705
3706         for (c = 0; c < mode->num_channels; c++) {
3707                 struct hostapd_channel_data *chan = &mode->channels[c];
3708                 if (chan->freq - 10 >= start && chan->freq + 10 <= end)
3709                         chan->flag |= HOSTAPD_CHAN_HT40;
3710         }
3711 }
3712
3713
3714 static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start,
3715                                       int end)
3716 {
3717         int c;
3718
3719         for (c = 0; c < mode->num_channels; c++) {
3720                 struct hostapd_channel_data *chan = &mode->channels[c];
3721                 if (!(chan->flag & HOSTAPD_CHAN_HT40))
3722                         continue;
3723                 if (chan->freq - 30 >= start && chan->freq - 10 <= end)
3724                         chan->flag |= HOSTAPD_CHAN_HT40MINUS;
3725                 if (chan->freq + 10 >= start && chan->freq + 30 <= end)
3726                         chan->flag |= HOSTAPD_CHAN_HT40PLUS;
3727         }
3728 }
3729
3730
3731 static void nl80211_reg_rule_ht40(struct nlattr *tb[],
3732                                   struct phy_info_arg *results)
3733 {
3734         u32 start, end, max_bw;
3735         u16 m;
3736
3737         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
3738             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
3739             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
3740                 return;
3741
3742         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
3743         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
3744         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
3745
3746         wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz",
3747                    start, end, max_bw);
3748         if (max_bw < 40)
3749                 return;
3750
3751         for (m = 0; m < *results->num_modes; m++) {
3752                 if (!(results->modes[m].ht_capab &
3753                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
3754                         continue;
3755                 nl80211_set_ht40_mode(&results->modes[m], start, end);
3756         }
3757 }
3758
3759
3760 static void nl80211_reg_rule_sec(struct nlattr *tb[],
3761                                  struct phy_info_arg *results)
3762 {
3763         u32 start, end, max_bw;
3764         u16 m;
3765
3766         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
3767             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
3768             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
3769                 return;
3770
3771         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
3772         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
3773         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
3774
3775         if (max_bw < 20)
3776                 return;
3777
3778         for (m = 0; m < *results->num_modes; m++) {
3779                 if (!(results->modes[m].ht_capab &
3780                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
3781                         continue;
3782                 nl80211_set_ht40_mode_sec(&results->modes[m], start, end);
3783         }
3784 }
3785
3786
3787 static int nl80211_get_reg(struct nl_msg *msg, void *arg)
3788 {
3789         struct phy_info_arg *results = arg;
3790         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
3791         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3792         struct nlattr *nl_rule;
3793         struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1];
3794         int rem_rule;
3795         static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
3796                 [NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
3797                 [NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
3798                 [NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
3799                 [NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
3800                 [NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
3801                 [NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
3802         };
3803
3804         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3805                   genlmsg_attrlen(gnlh, 0), NULL);
3806         if (!tb_msg[NL80211_ATTR_REG_ALPHA2] ||
3807             !tb_msg[NL80211_ATTR_REG_RULES]) {
3808                 wpa_printf(MSG_DEBUG, "nl80211: No regulatory information "
3809                            "available");
3810                 return NL_SKIP;
3811         }
3812
3813         wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s",
3814                    (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]));
3815
3816         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
3817         {
3818                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
3819                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
3820                 nl80211_reg_rule_ht40(tb_rule, results);
3821         }
3822
3823         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
3824         {
3825                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
3826                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
3827                 nl80211_reg_rule_sec(tb_rule, results);
3828         }
3829
3830         return NL_SKIP;
3831 }
3832
3833
3834 static int nl80211_set_ht40_flags(struct wpa_driver_nl80211_data *drv,
3835                                   struct phy_info_arg *results)
3836 {
3837         struct nl_msg *msg;
3838
3839         msg = nlmsg_alloc();
3840         if (!msg)
3841                 return -ENOMEM;
3842
3843         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3844                     0, NL80211_CMD_GET_REG, 0);
3845         return send_and_recv_msgs(drv, msg, nl80211_get_reg, results);
3846 }
3847
3848
3849 static struct hostapd_hw_modes *
3850 wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
3851 {
3852         struct i802_bss *bss = priv;
3853         struct wpa_driver_nl80211_data *drv = bss->drv;
3854         struct nl_msg *msg;
3855         struct phy_info_arg result = {
3856                 .num_modes = num_modes,
3857                 .modes = NULL,
3858         };
3859
3860         *num_modes = 0;
3861         *flags = 0;
3862
3863         msg = nlmsg_alloc();
3864         if (!msg)
3865                 return NULL;
3866
3867         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3868                     0, NL80211_CMD_GET_WIPHY, 0);
3869
3870         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3871
3872         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) {
3873                 nl80211_set_ht40_flags(drv, &result);
3874                 return wpa_driver_nl80211_add_11b(result.modes, num_modes);
3875         }
3876  nla_put_failure:
3877         return NULL;
3878 }
3879
3880
3881 static int wpa_driver_nl80211_send_frame(struct wpa_driver_nl80211_data *drv,
3882                                          const void *data, size_t len,
3883                                          int encrypt)
3884 {
3885         __u8 rtap_hdr[] = {
3886                 0x00, 0x00, /* radiotap version */
3887                 0x0e, 0x00, /* radiotap length */
3888                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
3889                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
3890                 0x00,       /* padding */
3891                 0x00, 0x00, /* RX and TX flags to indicate that */
3892                 0x00, 0x00, /* this is the injected frame directly */
3893         };
3894         struct iovec iov[2] = {
3895                 {
3896                         .iov_base = &rtap_hdr,
3897                         .iov_len = sizeof(rtap_hdr),
3898                 },
3899                 {
3900                         .iov_base = (void *) data,
3901                         .iov_len = len,
3902                 }
3903         };
3904         struct msghdr msg = {
3905                 .msg_name = NULL,
3906                 .msg_namelen = 0,
3907                 .msg_iov = iov,
3908                 .msg_iovlen = 2,
3909                 .msg_control = NULL,
3910                 .msg_controllen = 0,
3911                 .msg_flags = 0,
3912         };
3913         int res;
3914
3915         if (encrypt)
3916                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
3917
3918         if (drv->monitor_sock < 0) {
3919                 wpa_printf(MSG_DEBUG, "nl80211: No monitor socket available "
3920                            "for %s", __func__);
3921                 return -1;
3922         }
3923
3924         res = sendmsg(drv->monitor_sock, &msg, 0);
3925         if (res < 0) {
3926                 wpa_printf(MSG_INFO, "nl80211: sendmsg: %s", strerror(errno));
3927                 return -1;
3928         }
3929         return 0;
3930 }
3931
3932
3933 static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
3934                                         size_t data_len)
3935 {
3936         struct i802_bss *bss = priv;
3937         struct wpa_driver_nl80211_data *drv = bss->drv;
3938         struct ieee80211_mgmt *mgmt;
3939         int encrypt = 1;
3940         u16 fc;
3941
3942         mgmt = (struct ieee80211_mgmt *) data;
3943         fc = le_to_host16(mgmt->frame_control);
3944
3945         if (is_sta_interface(drv->nlmode) &&
3946             WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
3947             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_PROBE_RESP) {
3948                 /*
3949                  * The use of last_mgmt_freq is a bit of a hack,
3950                  * but it works due to the single-threaded nature
3951                  * of wpa_supplicant.
3952                  */
3953                 return nl80211_send_frame_cmd(drv, drv->last_mgmt_freq, 0,
3954                                               data, data_len, NULL);
3955         }
3956
3957         if (drv->no_monitor_iface_capab && is_ap_interface(drv->nlmode)) {
3958                 return nl80211_send_frame_cmd(drv, drv->ap_oper_freq, 0,
3959                                               data, data_len, NULL);
3960         }
3961
3962         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
3963             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
3964                 /*
3965                  * Only one of the authentication frame types is encrypted.
3966                  * In order for static WEP encryption to work properly (i.e.,
3967                  * to not encrypt the frame), we need to tell mac80211 about
3968                  * the frames that must not be encrypted.
3969                  */
3970                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
3971                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
3972                 if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
3973                         encrypt = 0;
3974         }
3975
3976         return wpa_driver_nl80211_send_frame(drv, data, data_len, encrypt);
3977 }
3978
3979
3980 static int wpa_driver_nl80211_set_ap(void *priv,
3981                                      struct wpa_driver_ap_params *params)
3982 {
3983         struct i802_bss *bss = priv;
3984         struct wpa_driver_nl80211_data *drv = bss->drv;
3985         struct nl_msg *msg;
3986         u8 cmd = NL80211_CMD_NEW_BEACON;
3987         int ret;
3988         int beacon_set;
3989         int ifindex = if_nametoindex(bss->ifname);
3990         int num_suites;
3991         u32 suites[10];
3992         u32 ver;
3993
3994         beacon_set = bss->beacon_set;
3995
3996         msg = nlmsg_alloc();
3997         if (!msg)
3998                 return -ENOMEM;
3999
4000         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
4001                    beacon_set);
4002         if (beacon_set)
4003                 cmd = NL80211_CMD_SET_BEACON;
4004
4005         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4006                     0, cmd, 0);
4007         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, params->head_len, params->head);
4008         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, params->tail_len, params->tail);
4009         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4010         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, params->beacon_int);
4011         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, params->dtim_period);
4012         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4013                 params->ssid);
4014         switch (params->hide_ssid) {
4015         case NO_SSID_HIDING:
4016                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
4017                             NL80211_HIDDEN_SSID_NOT_IN_USE);
4018                 break;
4019         case HIDDEN_SSID_ZERO_LEN:
4020                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
4021                             NL80211_HIDDEN_SSID_ZERO_LEN);
4022                 break;
4023         case HIDDEN_SSID_ZERO_CONTENTS:
4024                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
4025                             NL80211_HIDDEN_SSID_ZERO_CONTENTS);
4026                 break;
4027         }
4028         if (params->privacy)
4029                 NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
4030         if ((params->auth_algs & (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) ==
4031             (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) {
4032                 /* Leave out the attribute */
4033         } else if (params->auth_algs & WPA_AUTH_ALG_SHARED)
4034                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
4035                             NL80211_AUTHTYPE_SHARED_KEY);
4036         else
4037                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
4038                             NL80211_AUTHTYPE_OPEN_SYSTEM);
4039
4040         ver = 0;
4041         if (params->wpa_version & WPA_PROTO_WPA)
4042                 ver |= NL80211_WPA_VERSION_1;
4043         if (params->wpa_version & WPA_PROTO_RSN)
4044                 ver |= NL80211_WPA_VERSION_2;
4045         if (ver)
4046                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
4047
4048         num_suites = 0;
4049         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X)
4050                 suites[num_suites++] = WLAN_AKM_SUITE_8021X;
4051         if (params->key_mgmt_suites & WPA_KEY_MGMT_PSK)
4052                 suites[num_suites++] = WLAN_AKM_SUITE_PSK;
4053         if (num_suites) {
4054                 NLA_PUT(msg, NL80211_ATTR_AKM_SUITES,
4055                         num_suites * sizeof(u32), suites);
4056         }
4057
4058         num_suites = 0;
4059         if (params->pairwise_ciphers & WPA_CIPHER_CCMP)
4060                 suites[num_suites++] = WLAN_CIPHER_SUITE_CCMP;
4061         if (params->pairwise_ciphers & WPA_CIPHER_TKIP)
4062                 suites[num_suites++] = WLAN_CIPHER_SUITE_TKIP;
4063         if (params->pairwise_ciphers & WPA_CIPHER_WEP104)
4064                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP104;
4065         if (params->pairwise_ciphers & WPA_CIPHER_WEP40)
4066                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP40;
4067         if (num_suites) {
4068                 NLA_PUT(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE,
4069                         num_suites * sizeof(u32), suites);
4070         }
4071
4072         switch (params->group_cipher) {
4073         case WPA_CIPHER_CCMP:
4074                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
4075                             WLAN_CIPHER_SUITE_CCMP);
4076                 break;
4077         case WPA_CIPHER_TKIP:
4078                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
4079                             WLAN_CIPHER_SUITE_TKIP);
4080                 break;
4081         case WPA_CIPHER_WEP104:
4082                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
4083                             WLAN_CIPHER_SUITE_WEP104);
4084                 break;
4085         case WPA_CIPHER_WEP40:
4086                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
4087                             WLAN_CIPHER_SUITE_WEP40);
4088                 break;
4089         }
4090
4091         if (params->beacon_ies) {
4092                 NLA_PUT(msg, NL80211_ATTR_IE, wpabuf_len(params->beacon_ies),
4093                         wpabuf_head(params->beacon_ies));
4094         }
4095         if (params->proberesp_ies) {
4096                 NLA_PUT(msg, NL80211_ATTR_IE_PROBE_RESP,
4097                         wpabuf_len(params->proberesp_ies),
4098                         wpabuf_head(params->proberesp_ies));
4099         }
4100         if (params->assocresp_ies) {
4101                 NLA_PUT(msg, NL80211_ATTR_IE_ASSOC_RESP,
4102                         wpabuf_len(params->assocresp_ies),
4103                         wpabuf_head(params->assocresp_ies));
4104         }
4105
4106         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4107         if (ret) {
4108                 wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
4109                            ret, strerror(-ret));
4110         } else {
4111                 bss->beacon_set = 1;
4112         }
4113         return ret;
4114  nla_put_failure:
4115         return -ENOBUFS;
4116 }
4117
4118
4119 static int wpa_driver_nl80211_set_freq(struct wpa_driver_nl80211_data *drv,
4120                                        int freq, int ht_enabled,
4121                                        int sec_channel_offset)
4122 {
4123         struct nl_msg *msg;
4124         int ret;
4125
4126         msg = nlmsg_alloc();
4127         if (!msg)
4128                 return -1;
4129
4130         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4131                     NL80211_CMD_SET_WIPHY, 0);
4132
4133         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4134         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
4135         if (ht_enabled) {
4136                 switch (sec_channel_offset) {
4137                 case -1:
4138                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
4139                                     NL80211_CHAN_HT40MINUS);
4140                         break;
4141                 case 1:
4142                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
4143                                     NL80211_CHAN_HT40PLUS);
4144                         break;
4145                 default:
4146                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
4147                                     NL80211_CHAN_HT20);
4148                         break;
4149                 }
4150         }
4151
4152         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4153         if (ret == 0)
4154                 return 0;
4155         wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
4156                    "%d (%s)", freq, ret, strerror(-ret));
4157 nla_put_failure:
4158         return -1;
4159 }
4160
4161
4162 static u32 sta_flags_nl80211(int flags)
4163 {
4164         u32 f = 0;
4165
4166         if (flags & WPA_STA_AUTHORIZED)
4167                 f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
4168         if (flags & WPA_STA_WMM)
4169                 f |= BIT(NL80211_STA_FLAG_WME);
4170         if (flags & WPA_STA_SHORT_PREAMBLE)
4171                 f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
4172         if (flags & WPA_STA_MFP)
4173                 f |= BIT(NL80211_STA_FLAG_MFP);
4174
4175         return f;
4176 }
4177
4178
4179 static int wpa_driver_nl80211_sta_add(void *priv,
4180                                       struct hostapd_sta_add_params *params)
4181 {
4182         struct i802_bss *bss = priv;
4183         struct wpa_driver_nl80211_data *drv = bss->drv;
4184         struct nl_msg *msg;
4185         struct nl80211_sta_flag_update upd;
4186         int ret = -ENOBUFS;
4187
4188         msg = nlmsg_alloc();
4189         if (!msg)
4190                 return -ENOMEM;
4191
4192         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4193                     0, NL80211_CMD_NEW_STATION, 0);
4194
4195         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
4196         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
4197         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
4198         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
4199                 params->supp_rates);
4200         NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
4201                     params->listen_interval);
4202         if (params->ht_capabilities) {
4203                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
4204                         sizeof(*params->ht_capabilities),
4205                         params->ht_capabilities);
4206         }
4207
4208         os_memset(&upd, 0, sizeof(upd));
4209         upd.mask = sta_flags_nl80211(params->flags);
4210         upd.set = upd.mask;
4211         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
4212
4213         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4214         if (ret)
4215                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_NEW_STATION "
4216                            "result: %d (%s)", ret, strerror(-ret));
4217         if (ret == -EEXIST)
4218                 ret = 0;
4219  nla_put_failure:
4220         return ret;
4221 }
4222
4223
4224 static int wpa_driver_nl80211_sta_remove(void *priv, const u8 *addr)
4225 {
4226         struct i802_bss *bss = priv;
4227         struct wpa_driver_nl80211_data *drv = bss->drv;
4228         struct nl_msg *msg;
4229         int ret;
4230
4231         msg = nlmsg_alloc();
4232         if (!msg)
4233                 return -ENOMEM;
4234
4235         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4236                     0, NL80211_CMD_DEL_STATION, 0);
4237
4238         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
4239                     if_nametoindex(bss->ifname));
4240         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4241
4242         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4243         if (ret == -ENOENT)
4244                 return 0;
4245         return ret;
4246  nla_put_failure:
4247         return -ENOBUFS;
4248 }
4249
4250
4251 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
4252                                  int ifidx)
4253 {
4254         struct nl_msg *msg;
4255
4256         wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
4257
4258 #ifdef HOSTAPD
4259         /* stop listening for EAPOL on this interface */
4260         del_ifidx(drv, ifidx);
4261 #endif /* HOSTAPD */
4262
4263         msg = nlmsg_alloc();
4264         if (!msg)
4265                 goto nla_put_failure;
4266
4267         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4268                     0, NL80211_CMD_DEL_INTERFACE, 0);
4269         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
4270
4271         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
4272                 return;
4273  nla_put_failure:
4274         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
4275 }
4276
4277
4278 static const char * nl80211_iftype_str(enum nl80211_iftype mode)
4279 {
4280         switch (mode) {
4281         case NL80211_IFTYPE_ADHOC:
4282                 return "ADHOC";
4283         case NL80211_IFTYPE_STATION:
4284                 return "STATION";
4285         case NL80211_IFTYPE_AP:
4286                 return "AP";
4287         case NL80211_IFTYPE_MONITOR:
4288                 return "MONITOR";
4289         case NL80211_IFTYPE_P2P_CLIENT:
4290                 return "P2P_CLIENT";
4291         case NL80211_IFTYPE_P2P_GO:
4292                 return "P2P_GO";
4293         default:
4294                 return "unknown";
4295         }
4296 }
4297
4298
4299 static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
4300                                      const char *ifname,
4301                                      enum nl80211_iftype iftype,
4302                                      const u8 *addr, int wds)
4303 {
4304         struct nl_msg *msg, *flags = NULL;
4305         int ifidx;
4306         int ret = -ENOBUFS;
4307
4308         wpa_printf(MSG_DEBUG, "nl80211: Create interface iftype %d (%s)",
4309                    iftype, nl80211_iftype_str(iftype));
4310
4311         msg = nlmsg_alloc();
4312         if (!msg)
4313                 return -1;
4314
4315         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4316                     0, NL80211_CMD_NEW_INTERFACE, 0);
4317         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4318         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
4319         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
4320
4321         if (iftype == NL80211_IFTYPE_MONITOR) {
4322                 int err;
4323
4324                 flags = nlmsg_alloc();
4325                 if (!flags)
4326                         goto nla_put_failure;
4327
4328                 NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
4329
4330                 err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
4331
4332                 nlmsg_free(flags);
4333
4334                 if (err)
4335                         goto nla_put_failure;
4336         } else if (wds) {
4337                 NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
4338         }
4339
4340         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4341         if (ret) {
4342  nla_put_failure:
4343                 wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
4344                            ifname, ret, strerror(-ret));
4345                 return ret;
4346         }
4347
4348         ifidx = if_nametoindex(ifname);
4349         wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
4350                    ifname, ifidx);
4351
4352         if (ifidx <= 0)
4353                 return -1;
4354
4355 #ifdef HOSTAPD
4356         /* start listening for EAPOL on this interface */
4357         add_ifidx(drv, ifidx);
4358 #endif /* HOSTAPD */
4359
4360         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
4361             linux_set_ifhwaddr(drv->ioctl_sock, ifname, addr)) {
4362                 nl80211_remove_iface(drv, ifidx);
4363                 return -1;
4364         }
4365
4366         return ifidx;
4367 }
4368
4369
4370 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
4371                                 const char *ifname, enum nl80211_iftype iftype,
4372                                 const u8 *addr, int wds)
4373 {
4374         int ret;
4375
4376         ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds);
4377
4378         /* if error occurred and interface exists already */
4379         if (ret == -ENFILE && if_nametoindex(ifname)) {
4380                 wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
4381
4382                 /* Try to remove the interface that was already there. */
4383                 nl80211_remove_iface(drv, if_nametoindex(ifname));
4384
4385                 /* Try to create the interface again */
4386                 ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
4387                                                 wds);
4388         }
4389
4390         if (ret >= 0 && drv->disable_11b_rates)
4391                 nl80211_disable_11b_rates(drv, ret, 1);
4392
4393         return ret;
4394 }
4395
4396
4397 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
4398 {
4399         struct ieee80211_hdr *hdr;
4400         u16 fc;
4401         union wpa_event_data event;
4402
4403         hdr = (struct ieee80211_hdr *) buf;
4404         fc = le_to_host16(hdr->frame_control);
4405
4406         os_memset(&event, 0, sizeof(event));
4407         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
4408         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
4409         event.tx_status.dst = hdr->addr1;
4410         event.tx_status.data = buf;
4411         event.tx_status.data_len = len;
4412         event.tx_status.ack = ok;
4413         wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
4414 }
4415
4416
4417 static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
4418                              u8 *buf, size_t len)
4419 {
4420         union wpa_event_data event;
4421         os_memset(&event, 0, sizeof(event));
4422         event.rx_from_unknown.frame = buf;
4423         event.rx_from_unknown.len = len;
4424         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
4425 }
4426
4427
4428 static void handle_frame(struct wpa_driver_nl80211_data *drv,
4429                          u8 *buf, size_t len, int datarate, int ssi_signal)
4430 {
4431         struct ieee80211_hdr *hdr;
4432         u16 fc;
4433         union wpa_event_data event;
4434
4435         hdr = (struct ieee80211_hdr *) buf;
4436         fc = le_to_host16(hdr->frame_control);
4437
4438         switch (WLAN_FC_GET_TYPE(fc)) {
4439         case WLAN_FC_TYPE_MGMT:
4440                 os_memset(&event, 0, sizeof(event));
4441                 event.rx_mgmt.frame = buf;
4442                 event.rx_mgmt.frame_len = len;
4443                 event.rx_mgmt.datarate = datarate;
4444                 event.rx_mgmt.ssi_signal = ssi_signal;
4445                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
4446                 break;
4447         case WLAN_FC_TYPE_CTRL:
4448                 /* can only get here with PS-Poll frames */
4449                 wpa_printf(MSG_DEBUG, "CTRL");
4450                 from_unknown_sta(drv, buf, len);
4451                 break;
4452         case WLAN_FC_TYPE_DATA:
4453                 from_unknown_sta(drv, buf, len);
4454                 break;
4455         }
4456 }
4457
4458
4459 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
4460 {
4461         struct wpa_driver_nl80211_data *drv = eloop_ctx;
4462         int len;
4463         unsigned char buf[3000];
4464         struct ieee80211_radiotap_iterator iter;
4465         int ret;
4466         int datarate = 0, ssi_signal = 0;
4467         int injected = 0, failed = 0, rxflags = 0;
4468
4469         len = recv(sock, buf, sizeof(buf), 0);
4470         if (len < 0) {
4471                 perror("recv");
4472                 return;
4473         }
4474
4475         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
4476                 printf("received invalid radiotap frame\n");
4477                 return;
4478         }
4479
4480         while (1) {
4481                 ret = ieee80211_radiotap_iterator_next(&iter);
4482                 if (ret == -ENOENT)
4483                         break;
4484                 if (ret) {
4485                         printf("received invalid radiotap frame (%d)\n", ret);
4486                         return;
4487                 }
4488                 switch (iter.this_arg_index) {
4489                 case IEEE80211_RADIOTAP_FLAGS:
4490                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
4491                                 len -= 4;
4492                         break;
4493                 case IEEE80211_RADIOTAP_RX_FLAGS:
4494                         rxflags = 1;
4495                         break;
4496                 case IEEE80211_RADIOTAP_TX_FLAGS:
4497                         injected = 1;
4498                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
4499                                         IEEE80211_RADIOTAP_F_TX_FAIL;
4500                         break;
4501                 case IEEE80211_RADIOTAP_DATA_RETRIES:
4502                         break;
4503                 case IEEE80211_RADIOTAP_CHANNEL:
4504                         /* TODO: convert from freq/flags to channel number */
4505                         break;
4506                 case IEEE80211_RADIOTAP_RATE:
4507                         datarate = *iter.this_arg * 5;
4508                         break;
4509                 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
4510                         ssi_signal = *iter.this_arg;
4511                         break;
4512                 }
4513         }
4514
4515         if (rxflags && injected)
4516                 return;
4517
4518         if (!injected)
4519                 handle_frame(drv, buf + iter.max_length,
4520                              len - iter.max_length, datarate, ssi_signal);
4521         else
4522                 handle_tx_callback(drv->ctx, buf + iter.max_length,
4523                                    len - iter.max_length, !failed);
4524 }
4525
4526
4527 /*
4528  * we post-process the filter code later and rewrite
4529  * this to the offset to the last instruction
4530  */
4531 #define PASS    0xFF
4532 #define FAIL    0xFE
4533
4534 static struct sock_filter msock_filter_insns[] = {
4535         /*
4536          * do a little-endian load of the radiotap length field
4537          */
4538         /* load lower byte into A */
4539         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
4540         /* put it into X (== index register) */
4541         BPF_STMT(BPF_MISC| BPF_TAX, 0),
4542         /* load upper byte into A */
4543         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
4544         /* left-shift it by 8 */
4545         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
4546         /* or with X */
4547         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
4548         /* put result into X */
4549         BPF_STMT(BPF_MISC| BPF_TAX, 0),
4550
4551         /*
4552          * Allow management frames through, this also gives us those
4553          * management frames that we sent ourselves with status
4554          */
4555         /* load the lower byte of the IEEE 802.11 frame control field */
4556         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
4557         /* mask off frame type and version */
4558         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
4559         /* accept frame if it's both 0, fall through otherwise */
4560         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
4561
4562         /*
4563          * TODO: add a bit to radiotap RX flags that indicates
4564          * that the sending station is not associated, then
4565          * add a filter here that filters on our DA and that flag
4566          * to allow us to deauth frames to that bad station.
4567          *
4568          * For now allow all To DS data frames through.
4569          */
4570         /* load the IEEE 802.11 frame control field */
4571         BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
4572         /* mask off frame type, version and DS status */
4573         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
4574         /* accept frame if version 0, type 2 and To DS, fall through otherwise
4575          */
4576         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
4577
4578 #if 0
4579         /*
4580          * drop non-data frames
4581          */
4582         /* load the lower byte of the frame control field */
4583         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
4584         /* mask off QoS bit */
4585         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
4586         /* drop non-data frames */
4587         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
4588 #endif
4589         /* load the upper byte of the frame control field */
4590         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
4591         /* mask off toDS/fromDS */
4592         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
4593         /* accept WDS frames */
4594         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
4595
4596         /*
4597          * add header length to index
4598          */
4599         /* load the lower byte of the frame control field */
4600         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
4601         /* mask off QoS bit */
4602         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
4603         /* right shift it by 6 to give 0 or 2 */
4604         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
4605         /* add data frame header length */
4606         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
4607         /* add index, was start of 802.11 header */
4608         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
4609         /* move to index, now start of LL header */
4610         BPF_STMT(BPF_MISC | BPF_TAX, 0),
4611
4612         /*
4613          * Accept empty data frames, we use those for
4614          * polling activity.
4615          */
4616         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
4617         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
4618
4619         /*
4620          * Accept EAPOL frames
4621          */
4622         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
4623         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
4624         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
4625         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
4626
4627         /* keep these last two statements or change the code below */
4628         /* return 0 == "DROP" */
4629         BPF_STMT(BPF_RET | BPF_K, 0),
4630         /* return ~0 == "keep all" */
4631         BPF_STMT(BPF_RET | BPF_K, ~0),
4632 };
4633
4634 static struct sock_fprog msock_filter = {
4635         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
4636         .filter = msock_filter_insns,
4637 };
4638
4639
4640 static int add_monitor_filter(int s)
4641 {
4642         int idx;
4643
4644         /* rewrite all PASS/FAIL jump offsets */
4645         for (idx = 0; idx < msock_filter.len; idx++) {
4646                 struct sock_filter *insn = &msock_filter_insns[idx];
4647
4648                 if (BPF_CLASS(insn->code) == BPF_JMP) {
4649                         if (insn->code == (BPF_JMP|BPF_JA)) {
4650                                 if (insn->k == PASS)
4651                                         insn->k = msock_filter.len - idx - 2;
4652                                 else if (insn->k == FAIL)
4653                                         insn->k = msock_filter.len - idx - 3;
4654                         }
4655
4656                         if (insn->jt == PASS)
4657                                 insn->jt = msock_filter.len - idx - 2;
4658                         else if (insn->jt == FAIL)
4659                                 insn->jt = msock_filter.len - idx - 3;
4660
4661                         if (insn->jf == PASS)
4662                                 insn->jf = msock_filter.len - idx - 2;
4663                         else if (insn->jf == FAIL)
4664                                 insn->jf = msock_filter.len - idx - 3;
4665                 }
4666         }
4667
4668         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
4669                        &msock_filter, sizeof(msock_filter))) {
4670                 perror("SO_ATTACH_FILTER");
4671                 return -1;
4672         }
4673
4674         return 0;
4675 }
4676
4677
4678 static void nl80211_remove_monitor_interface(
4679         struct wpa_driver_nl80211_data *drv)
4680 {
4681         if (drv->monitor_ifidx >= 0) {
4682                 nl80211_remove_iface(drv, drv->monitor_ifidx);
4683                 drv->monitor_ifidx = -1;
4684         }
4685         if (drv->monitor_sock >= 0) {
4686                 eloop_unregister_read_sock(drv->monitor_sock);
4687                 close(drv->monitor_sock);
4688                 drv->monitor_sock = -1;
4689         }
4690 }
4691
4692
4693 static int
4694 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
4695 {
4696         char buf[IFNAMSIZ];
4697         struct sockaddr_ll ll;
4698         int optval;
4699         socklen_t optlen;
4700
4701         snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss.ifname);
4702         buf[IFNAMSIZ - 1] = '\0';
4703
4704         drv->monitor_ifidx =
4705                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
4706                                      0);
4707
4708         if (drv->monitor_ifidx == -EOPNOTSUPP) {
4709                 wpa_printf(MSG_DEBUG, "nl80211: Driver does not support "
4710                            "monitor interface type - try to run without it");
4711                 drv->no_monitor_iface_capab = 1;
4712         }
4713
4714         if (drv->monitor_ifidx < 0)
4715                 return -1;
4716
4717         if (linux_set_iface_flags(drv->ioctl_sock, buf, 1))
4718                 goto error;
4719
4720         memset(&ll, 0, sizeof(ll));
4721         ll.sll_family = AF_PACKET;
4722         ll.sll_ifindex = drv->monitor_ifidx;
4723         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
4724         if (drv->monitor_sock < 0) {
4725                 perror("socket[PF_PACKET,SOCK_RAW]");
4726                 goto error;
4727         }
4728
4729         if (add_monitor_filter(drv->monitor_sock)) {
4730                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
4731                            "interface; do filtering in user space");
4732                 /* This works, but will cost in performance. */
4733         }
4734
4735         if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
4736                 perror("monitor socket bind");
4737                 goto error;
4738         }
4739
4740         optlen = sizeof(optval);
4741         optval = 20;
4742         if (setsockopt
4743             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
4744                 perror("Failed to set socket priority");
4745                 goto error;
4746         }
4747
4748         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
4749                                      drv, NULL)) {
4750                 printf("Could not register monitor read socket\n");
4751                 goto error;
4752         }
4753
4754         return 0;
4755  error:
4756         nl80211_remove_monitor_interface(drv);
4757         return -1;
4758 }
4759
4760
4761 #ifdef CONFIG_AP
4762 static int nl80211_send_eapol_data(struct i802_bss *bss,
4763                                    const u8 *addr, const u8 *data,
4764                                    size_t data_len, const u8 *own_addr)
4765 {
4766         if (bss->drv->l2 == NULL) {
4767                 wpa_printf(MSG_DEBUG, "nl80211: No l2_packet to send EAPOL");
4768                 return -1;
4769         }
4770
4771         if (l2_packet_send(bss->drv->l2, addr, ETH_P_EAPOL, data, data_len) <
4772             0)
4773                 return -1;
4774         return 0;
4775 }
4776 #endif /* CONFIG_AP */
4777
4778
4779 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
4780
4781 static int wpa_driver_nl80211_hapd_send_eapol(
4782         void *priv, const u8 *addr, const u8 *data,
4783         size_t data_len, int encrypt, const u8 *own_addr, u32 flags)
4784 {
4785         struct i802_bss *bss = priv;
4786         struct wpa_driver_nl80211_data *drv = bss->drv;
4787         struct ieee80211_hdr *hdr;
4788         size_t len;
4789         u8 *pos;
4790         int res;
4791         int qos = flags & WPA_STA_WMM;
4792
4793 #ifdef CONFIG_AP
4794         if (drv->no_monitor_iface_capab)
4795                 return nl80211_send_eapol_data(bss, addr, data, data_len,
4796                                                own_addr);
4797 #endif /* CONFIG_AP */
4798
4799         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
4800                 data_len;
4801         hdr = os_zalloc(len);
4802         if (hdr == NULL) {
4803                 printf("malloc() failed for i802_send_data(len=%lu)\n",
4804                        (unsigned long) len);
4805                 return -1;
4806         }
4807
4808         hdr->frame_control =
4809                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
4810         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
4811         if (encrypt)
4812                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
4813         if (qos) {
4814                 hdr->frame_control |=
4815                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
4816         }
4817
4818         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
4819         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
4820         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
4821         pos = (u8 *) (hdr + 1);
4822
4823         if (qos) {
4824                 /* add an empty QoS header if needed */
4825                 pos[0] = 0;
4826                 pos[1] = 0;
4827                 pos += 2;
4828         }
4829
4830         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
4831         pos += sizeof(rfc1042_header);
4832         WPA_PUT_BE16(pos, ETH_P_PAE);
4833         pos += 2;
4834         memcpy(pos, data, data_len);
4835
4836         res = wpa_driver_nl80211_send_frame(drv, (u8 *) hdr, len, encrypt);
4837         if (res < 0) {
4838                 wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
4839                            "failed: %d (%s)",
4840                            (unsigned long) len, errno, strerror(errno));
4841         }
4842         os_free(hdr);
4843
4844         return res;
4845 }
4846
4847
4848 static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
4849                                             int total_flags,
4850                                             int flags_or, int flags_and)
4851 {
4852         struct i802_bss *bss = priv;
4853         struct wpa_driver_nl80211_data *drv = bss->drv;
4854         struct nl_msg *msg, *flags = NULL;
4855         struct nl80211_sta_flag_update upd;
4856
4857         msg = nlmsg_alloc();
4858         if (!msg)
4859                 return -ENOMEM;
4860
4861         flags = nlmsg_alloc();
4862         if (!flags) {
4863                 nlmsg_free(msg);
4864                 return -ENOMEM;
4865         }
4866
4867         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4868                     0, NL80211_CMD_SET_STATION, 0);
4869
4870         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
4871                     if_nametoindex(bss->ifname));
4872         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4873
4874         /*
4875          * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
4876          * can be removed eventually.
4877          */
4878         if (total_flags & WPA_STA_AUTHORIZED)
4879                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
4880
4881         if (total_flags & WPA_STA_WMM)
4882                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
4883
4884         if (total_flags & WPA_STA_SHORT_PREAMBLE)
4885                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
4886
4887         if (total_flags & WPA_STA_MFP)
4888                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
4889
4890         if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
4891                 goto nla_put_failure;
4892
4893         os_memset(&upd, 0, sizeof(upd));
4894         upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
4895         upd.set = sta_flags_nl80211(flags_or);
4896         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
4897
4898         nlmsg_free(flags);
4899
4900         return send_and_recv_msgs(drv, msg, NULL, NULL);
4901  nla_put_failure:
4902         nlmsg_free(flags);
4903         return -ENOBUFS;
4904 }
4905
4906
4907 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
4908                                  struct wpa_driver_associate_params *params)
4909 {
4910         enum nl80211_iftype nlmode;
4911
4912         if (params->p2p) {
4913                 wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
4914                            "group (GO)");
4915                 nlmode = NL80211_IFTYPE_P2P_GO;
4916         } else
4917                 nlmode = NL80211_IFTYPE_AP;
4918
4919         if (wpa_driver_nl80211_set_mode(&drv->first_bss, nlmode) ||
4920             wpa_driver_nl80211_set_freq(drv, params->freq, 0, 0)) {
4921                 nl80211_remove_monitor_interface(drv);
4922                 return -1;
4923         }
4924
4925         if (drv->no_monitor_iface_capab) {
4926                 if (wpa_driver_nl80211_probe_req_report(&drv->first_bss, 1) < 0)
4927                 {
4928                         wpa_printf(MSG_DEBUG, "nl80211: Failed to enable "
4929                                    "Probe Request frame reporting in AP mode");
4930                         /* Try to survive without this */
4931                 }
4932         }
4933
4934         drv->ap_oper_freq = params->freq;
4935
4936         return 0;
4937 }
4938
4939
4940 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
4941 {
4942         struct nl_msg *msg;
4943         int ret = -1;
4944
4945         msg = nlmsg_alloc();
4946         if (!msg)
4947                 return -1;
4948
4949         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4950                     NL80211_CMD_LEAVE_IBSS, 0);
4951         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4952         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4953         msg = NULL;
4954         if (ret) {
4955                 wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
4956                            "(%s)", ret, strerror(-ret));
4957                 goto nla_put_failure;
4958         }
4959
4960         ret = 0;
4961         wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
4962
4963 nla_put_failure:
4964         nlmsg_free(msg);
4965         return ret;
4966 }
4967
4968
4969 static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
4970                                    struct wpa_driver_associate_params *params)
4971 {
4972         struct nl_msg *msg;
4973         int ret = -1;
4974         int count = 0;
4975
4976         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
4977
4978         if (wpa_driver_nl80211_set_mode(&drv->first_bss,
4979                                         NL80211_IFTYPE_ADHOC)) {
4980                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
4981                            "IBSS mode");
4982                 return -1;
4983         }
4984
4985 retry:
4986         msg = nlmsg_alloc();
4987         if (!msg)
4988                 return -1;
4989
4990         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4991                     NL80211_CMD_JOIN_IBSS, 0);
4992         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4993
4994         if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
4995                 goto nla_put_failure;
4996
4997         wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4998                           params->ssid, params->ssid_len);
4999         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
5000                 params->ssid);
5001         os_memcpy(drv->ssid, params->ssid, params->ssid_len);
5002         drv->ssid_len = params->ssid_len;
5003
5004         wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
5005         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
5006
5007         ret = nl80211_set_conn_keys(params, msg);
5008         if (ret)
5009                 goto nla_put_failure;
5010
5011         if (params->wpa_ie) {
5012                 wpa_hexdump(MSG_DEBUG,
5013                             "  * Extra IEs for Beacon/Probe Response frames",
5014                             params->wpa_ie, params->wpa_ie_len);
5015                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
5016                         params->wpa_ie);
5017         }
5018
5019         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5020         msg = NULL;
5021         if (ret) {
5022                 wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
5023                            ret, strerror(-ret));
5024                 count++;
5025                 if (ret == -EALREADY && count == 1) {
5026                         wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
5027                                    "forced leave");
5028                         nl80211_leave_ibss(drv);
5029                         nlmsg_free(msg);
5030                         goto retry;
5031                 }
5032
5033                 goto nla_put_failure;
5034         }
5035         ret = 0;
5036         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
5037
5038 nla_put_failure:
5039         nlmsg_free(msg);
5040         return ret;
5041 }
5042
5043
5044 static unsigned int nl80211_get_assoc_bssid(struct wpa_driver_nl80211_data *drv,
5045                                             u8 *bssid)
5046 {
5047         struct nl_msg *msg;
5048         int ret;
5049         struct nl80211_bss_info_arg arg;
5050
5051         os_memset(&arg, 0, sizeof(arg));
5052         msg = nlmsg_alloc();
5053         if (!msg)
5054                 goto nla_put_failure;
5055
5056         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, NLM_F_DUMP,
5057                     NL80211_CMD_GET_SCAN, 0);
5058         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5059
5060         arg.drv = drv;
5061         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
5062         msg = NULL;
5063         if (ret == 0) {
5064                 if (is_zero_ether_addr(arg.assoc_bssid))
5065                         return -ENOTCONN;
5066                 os_memcpy(bssid, arg.assoc_bssid, ETH_ALEN);
5067                 return 0;
5068         }
5069         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
5070                    "(%s)", ret, strerror(-ret));
5071 nla_put_failure:
5072         nlmsg_free(msg);
5073         return drv->assoc_freq;
5074 }
5075
5076
5077 static int nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
5078                               const u8 *bssid)
5079 {
5080         u8 addr[ETH_ALEN];
5081
5082         if (bssid == NULL) {
5083                 int res = nl80211_get_assoc_bssid(drv, addr);
5084                 if (res)
5085                         return res;
5086                 bssid = addr;
5087         }
5088
5089         return wpa_driver_nl80211_disconnect(drv, bssid,
5090                                              WLAN_REASON_PREV_AUTH_NOT_VALID);
5091 }
5092
5093
5094 static int wpa_driver_nl80211_connect(
5095         struct wpa_driver_nl80211_data *drv,
5096         struct wpa_driver_associate_params *params)
5097 {
5098         struct nl_msg *msg;
5099         enum nl80211_auth_type type;
5100         int ret = 0;
5101         int algs;
5102
5103         msg = nlmsg_alloc();
5104         if (!msg)
5105                 return -1;
5106
5107         wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
5108         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5109                     NL80211_CMD_CONNECT, 0);
5110
5111         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5112         if (params->bssid) {
5113                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
5114                            MAC2STR(params->bssid));
5115                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
5116         }
5117         if (params->freq) {
5118                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
5119                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
5120         }
5121         if (params->ssid) {
5122                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
5123                                   params->ssid, params->ssid_len);
5124                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
5125                         params->ssid);
5126                 if (params->ssid_len > sizeof(drv->ssid))
5127                         goto nla_put_failure;
5128                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
5129                 drv->ssid_len = params->ssid_len;
5130         }
5131         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
5132         if (params->wpa_ie)
5133                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
5134                         params->wpa_ie);
5135
5136         algs = 0;
5137         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
5138                 algs++;
5139         if (params->auth_alg & WPA_AUTH_ALG_SHARED)
5140                 algs++;
5141         if (params->auth_alg & WPA_AUTH_ALG_LEAP)
5142                 algs++;
5143         if (algs > 1) {
5144                 wpa_printf(MSG_DEBUG, "  * Leave out Auth Type for automatic "
5145                            "selection");
5146                 goto skip_auth_type;
5147         }
5148
5149         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
5150                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
5151         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
5152                 type = NL80211_AUTHTYPE_SHARED_KEY;
5153         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
5154                 type = NL80211_AUTHTYPE_NETWORK_EAP;
5155         else if (params->auth_alg & WPA_AUTH_ALG_FT)
5156                 type = NL80211_AUTHTYPE_FT;
5157         else
5158                 goto nla_put_failure;
5159
5160         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
5161         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
5162
5163 skip_auth_type:
5164         if (params->wpa_proto) {
5165                 enum nl80211_wpa_versions ver = 0;
5166
5167                 if (params->wpa_proto & WPA_PROTO_WPA)
5168                         ver |= NL80211_WPA_VERSION_1;
5169                 if (params->wpa_proto & WPA_PROTO_RSN)
5170                         ver |= NL80211_WPA_VERSION_2;
5171
5172                 wpa_printf(MSG_DEBUG, "  * WPA Versions 0x%x", ver);
5173                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
5174         }
5175
5176         if (params->pairwise_suite != CIPHER_NONE) {
5177                 int cipher;
5178
5179                 switch (params->pairwise_suite) {
5180                 case CIPHER_WEP40:
5181                         cipher = WLAN_CIPHER_SUITE_WEP40;
5182                         break;
5183                 case CIPHER_WEP104:
5184                         cipher = WLAN_CIPHER_SUITE_WEP104;
5185                         break;
5186                 case CIPHER_CCMP:
5187                         cipher = WLAN_CIPHER_SUITE_CCMP;
5188                         break;
5189                 case CIPHER_TKIP:
5190                 default:
5191                         cipher = WLAN_CIPHER_SUITE_TKIP;
5192                         break;
5193                 }
5194                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
5195         }
5196
5197         if (params->group_suite != CIPHER_NONE) {
5198                 int cipher;
5199
5200                 switch (params->group_suite) {
5201                 case CIPHER_WEP40:
5202                         cipher = WLAN_CIPHER_SUITE_WEP40;
5203                         break;
5204                 case CIPHER_WEP104:
5205                         cipher = WLAN_CIPHER_SUITE_WEP104;
5206                         break;
5207                 case CIPHER_CCMP:
5208                         cipher = WLAN_CIPHER_SUITE_CCMP;
5209                         break;
5210                 case CIPHER_TKIP:
5211                 default:
5212                         cipher = WLAN_CIPHER_SUITE_TKIP;
5213                         break;
5214                 }
5215                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
5216         }
5217
5218         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
5219             params->key_mgmt_suite == KEY_MGMT_PSK) {
5220                 int mgmt = WLAN_AKM_SUITE_PSK;
5221
5222                 switch (params->key_mgmt_suite) {
5223                 case KEY_MGMT_802_1X:
5224                         mgmt = WLAN_AKM_SUITE_8021X;
5225                         break;
5226                 case KEY_MGMT_PSK:
5227                 default:
5228                         mgmt = WLAN_AKM_SUITE_PSK;
5229                         break;
5230                 }
5231                 NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
5232         }
5233
5234         ret = nl80211_set_conn_keys(params, msg);
5235         if (ret)
5236                 goto nla_put_failure;
5237
5238         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5239         msg = NULL;
5240         if (ret) {
5241                 wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
5242                            "(%s)", ret, strerror(-ret));
5243                 /*
5244                  * cfg80211 does not currently accept new connection if we are
5245                  * already connected. As a workaround, force disconnection and
5246                  * try again once the driver indicates it completed
5247                  * disconnection.
5248                  */
5249                 if (ret == -EALREADY)
5250                         nl80211_disconnect(drv, params->bssid);
5251                 goto nla_put_failure;
5252         }
5253         ret = 0;
5254         wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
5255
5256 nla_put_failure:
5257         nlmsg_free(msg);
5258         return ret;
5259
5260 }
5261
5262
5263 static int wpa_driver_nl80211_associate(
5264         void *priv, struct wpa_driver_associate_params *params)
5265 {
5266         struct i802_bss *bss = priv;
5267         struct wpa_driver_nl80211_data *drv = bss->drv;
5268         int ret = -1;
5269         struct nl_msg *msg;
5270
5271         if (params->mode == IEEE80211_MODE_AP)
5272                 return wpa_driver_nl80211_ap(drv, params);
5273
5274         if (params->mode == IEEE80211_MODE_IBSS)
5275                 return wpa_driver_nl80211_ibss(drv, params);
5276
5277         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
5278                 enum nl80211_iftype nlmode = params->p2p ?
5279                         NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
5280
5281                 if (wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
5282                         return -1;
5283                 return wpa_driver_nl80211_connect(drv, params);
5284         }
5285
5286         drv->associated = 0;
5287
5288         msg = nlmsg_alloc();
5289         if (!msg)
5290                 return -1;
5291
5292         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
5293                    drv->ifindex);
5294         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5295                     NL80211_CMD_ASSOCIATE, 0);
5296
5297         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5298         if (params->bssid) {
5299                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
5300                            MAC2STR(params->bssid));
5301                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
5302         }
5303         if (params->freq) {
5304                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
5305                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
5306                 drv->assoc_freq = params->freq;
5307         } else
5308                 drv->assoc_freq = 0;
5309         if (params->ssid) {
5310                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
5311                                   params->ssid, params->ssid_len);
5312                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
5313                         params->ssid);
5314                 if (params->ssid_len > sizeof(drv->ssid))
5315                         goto nla_put_failure;
5316                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
5317                 drv->ssid_len = params->ssid_len;
5318         }
5319         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
5320         if (params->wpa_ie)
5321                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
5322                         params->wpa_ie);
5323
5324         if (params->pairwise_suite != CIPHER_NONE) {
5325                 int cipher;
5326
5327                 switch (params->pairwise_suite) {
5328                 case CIPHER_WEP40:
5329                         cipher = WLAN_CIPHER_SUITE_WEP40;
5330                         break;
5331                 case CIPHER_WEP104:
5332                         cipher = WLAN_CIPHER_SUITE_WEP104;
5333                         break;
5334                 case CIPHER_CCMP:
5335                         cipher = WLAN_CIPHER_SUITE_CCMP;
5336                         break;
5337                 case CIPHER_TKIP:
5338                 default:
5339                         cipher = WLAN_CIPHER_SUITE_TKIP;
5340                         break;
5341                 }
5342                 wpa_printf(MSG_DEBUG, "  * pairwise=0x%x", cipher);
5343                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
5344         }
5345
5346         if (params->group_suite != CIPHER_NONE) {
5347                 int cipher;
5348
5349                 switch (params->group_suite) {
5350                 case CIPHER_WEP40:
5351                         cipher = WLAN_CIPHER_SUITE_WEP40;
5352                         break;
5353                 case CIPHER_WEP104:
5354                         cipher = WLAN_CIPHER_SUITE_WEP104;
5355                         break;
5356                 case CIPHER_CCMP:
5357                         cipher = WLAN_CIPHER_SUITE_CCMP;
5358                         break;
5359                 case CIPHER_TKIP:
5360                 default:
5361                         cipher = WLAN_CIPHER_SUITE_TKIP;
5362                         break;
5363                 }
5364                 wpa_printf(MSG_DEBUG, "  * group=0x%x", cipher);
5365                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
5366         }
5367
5368 #ifdef CONFIG_IEEE80211W
5369         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
5370                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
5371 #endif /* CONFIG_IEEE80211W */
5372
5373         NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
5374
5375         if (params->prev_bssid) {
5376                 wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
5377                            MAC2STR(params->prev_bssid));
5378                 NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
5379                         params->prev_bssid);
5380         }
5381
5382         if (params->p2p)
5383                 wpa_printf(MSG_DEBUG, "  * P2P group");
5384
5385         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5386         msg = NULL;
5387         if (ret) {
5388                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
5389                            "(%s)", ret, strerror(-ret));
5390                 nl80211_dump_scan(drv);
5391                 goto nla_put_failure;
5392         }
5393         ret = 0;
5394         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
5395                    "successfully");
5396
5397 nla_put_failure:
5398         nlmsg_free(msg);
5399         return ret;
5400 }
5401
5402
5403 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
5404                             int ifindex, enum nl80211_iftype mode)
5405 {
5406         struct nl_msg *msg;
5407         int ret = -ENOBUFS;
5408
5409         wpa_printf(MSG_DEBUG, "nl80211: Set mode ifindex %d iftype %d (%s)",
5410                    ifindex, mode, nl80211_iftype_str(mode));
5411
5412         msg = nlmsg_alloc();
5413         if (!msg)
5414                 return -ENOMEM;
5415
5416         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5417                     0, NL80211_CMD_SET_INTERFACE, 0);
5418         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
5419         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
5420
5421         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5422         if (!ret)
5423                 return 0;
5424 nla_put_failure:
5425         wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
5426                    " %d (%s)", ifindex, mode, ret, strerror(-ret));
5427         return ret;
5428 }
5429
5430
5431 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
5432                                        enum nl80211_iftype nlmode)
5433 {
5434         struct wpa_driver_nl80211_data *drv = bss->drv;
5435         int ret = -1;
5436         int i;
5437         int was_ap = is_ap_interface(drv->nlmode);
5438
5439         if (nl80211_set_mode(drv, drv->ifindex, nlmode) == 0) {
5440                 drv->nlmode = nlmode;
5441                 ret = 0;
5442                 goto done;
5443         }
5444
5445         if (nlmode == drv->nlmode) {
5446                 wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
5447                            "requested mode - ignore error");
5448                 ret = 0;
5449                 goto done; /* Already in the requested mode */
5450         }
5451
5452         /* mac80211 doesn't allow mode changes while the device is up, so
5453          * take the device down, try to set the mode again, and bring the
5454          * device back up.
5455          */
5456         wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
5457                    "interface down");
5458         for (i = 0; i < 10; i++) {
5459                 if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 0) ==
5460                     0) {
5461                         /* Try to set the mode again while the interface is
5462                          * down */
5463                         ret = nl80211_set_mode(drv, drv->ifindex, nlmode);
5464                         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname,
5465                                                   1))
5466                                 ret = -1;
5467                         if (!ret)
5468                                 break;
5469                 } else
5470                         wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
5471                                    "interface down");
5472                 os_sleep(0, 100000);
5473         }
5474
5475         if (!ret) {
5476                 wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
5477                            "interface is down");
5478                 drv->nlmode = nlmode;
5479                 drv->ignore_if_down_event = 1;
5480         }
5481
5482 done:
5483         if (!ret && is_ap_interface(nlmode)) {
5484                 /* Setup additional AP mode functionality if needed */
5485                 if (!drv->no_monitor_iface_capab && drv->monitor_ifidx < 0 &&
5486                     nl80211_create_monitor_interface(drv) &&
5487                     !drv->no_monitor_iface_capab)
5488                         return -1;
5489         } else if (!ret && !is_ap_interface(nlmode)) {
5490                 /* Remove additional AP mode functionality */
5491                 if (was_ap && drv->no_monitor_iface_capab)
5492                         wpa_driver_nl80211_probe_req_report(bss, 0);
5493                 nl80211_remove_monitor_interface(drv);
5494                 bss->beacon_set = 0;
5495         }
5496
5497         if (ret)
5498                 wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
5499                            "from %d failed", nlmode, drv->nlmode);
5500
5501         return ret;
5502 }
5503
5504
5505 static int wpa_driver_nl80211_get_capa(void *priv,
5506                                        struct wpa_driver_capa *capa)
5507 {
5508         struct i802_bss *bss = priv;
5509         struct wpa_driver_nl80211_data *drv = bss->drv;
5510         if (!drv->has_capability)
5511                 return -1;
5512         os_memcpy(capa, &drv->capa, sizeof(*capa));
5513         return 0;
5514 }
5515
5516
5517 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
5518 {
5519         struct i802_bss *bss = priv;
5520         struct wpa_driver_nl80211_data *drv = bss->drv;
5521
5522         wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
5523                    __func__, drv->operstate, state, state ? "UP" : "DORMANT");
5524         drv->operstate = state;
5525         return netlink_send_oper_ifla(drv->netlink, drv->ifindex, -1,
5526                                       state ? IF_OPER_UP : IF_OPER_DORMANT);
5527 }
5528
5529
5530 static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
5531 {
5532         struct i802_bss *bss = priv;
5533         struct wpa_driver_nl80211_data *drv = bss->drv;
5534         struct nl_msg *msg;
5535         struct nl80211_sta_flag_update upd;
5536
5537         msg = nlmsg_alloc();
5538         if (!msg)
5539                 return -ENOMEM;
5540
5541         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5542                     0, NL80211_CMD_SET_STATION, 0);
5543
5544         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5545                     if_nametoindex(bss->ifname));
5546         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
5547
5548         os_memset(&upd, 0, sizeof(upd));
5549         upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
5550         if (authorized)
5551                 upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
5552         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
5553
5554         return send_and_recv_msgs(drv, msg, NULL, NULL);
5555  nla_put_failure:
5556         return -ENOBUFS;
5557 }
5558
5559
5560 /* Set kernel driver on given frequency (MHz) */
5561 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
5562 {
5563         struct i802_bss *bss = priv;
5564         struct wpa_driver_nl80211_data *drv = bss->drv;
5565         return wpa_driver_nl80211_set_freq(drv, freq->freq, freq->ht_enabled,
5566                                            freq->sec_channel_offset);
5567 }
5568
5569
5570 #if defined(HOSTAPD) || defined(CONFIG_AP)
5571
5572 static inline int min_int(int a, int b)
5573 {
5574         if (a < b)
5575                 return a;
5576         return b;
5577 }
5578
5579
5580 static int get_key_handler(struct nl_msg *msg, void *arg)
5581 {
5582         struct nlattr *tb[NL80211_ATTR_MAX + 1];
5583         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5584
5585         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5586                   genlmsg_attrlen(gnlh, 0), NULL);
5587
5588         /*
5589          * TODO: validate the key index and mac address!
5590          * Otherwise, there's a race condition as soon as
5591          * the kernel starts sending key notifications.
5592          */
5593
5594         if (tb[NL80211_ATTR_KEY_SEQ])
5595                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
5596                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
5597         return NL_SKIP;
5598 }
5599
5600
5601 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
5602                            int idx, u8 *seq)
5603 {
5604         struct i802_bss *bss = priv;
5605         struct wpa_driver_nl80211_data *drv = bss->drv;
5606         struct nl_msg *msg;
5607
5608         msg = nlmsg_alloc();
5609         if (!msg)
5610                 return -ENOMEM;
5611
5612         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5613                     0, NL80211_CMD_GET_KEY, 0);
5614
5615         if (addr)
5616                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5617         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
5618         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
5619
5620         memset(seq, 0, 6);
5621
5622         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
5623  nla_put_failure:
5624         return -ENOBUFS;
5625 }
5626
5627
5628 static int i802_set_rate_sets(void *priv, int *supp_rates, int *basic_rates,
5629                               int mode)
5630 {
5631         struct i802_bss *bss = priv;
5632         struct wpa_driver_nl80211_data *drv = bss->drv;
5633         struct nl_msg *msg;
5634         u8 rates[NL80211_MAX_SUPP_RATES];
5635         u8 rates_len = 0;
5636         int i;
5637
5638         msg = nlmsg_alloc();
5639         if (!msg)
5640                 return -ENOMEM;
5641
5642         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5643                     NL80211_CMD_SET_BSS, 0);
5644
5645         for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0; i++)
5646                 rates[rates_len++] = basic_rates[i] / 5;
5647
5648         NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
5649
5650         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5651
5652         return send_and_recv_msgs(drv, msg, NULL, NULL);
5653  nla_put_failure:
5654         return -ENOBUFS;
5655 }
5656
5657
5658 static int i802_set_rts(void *priv, int rts)
5659 {
5660         struct i802_bss *bss = priv;
5661         struct wpa_driver_nl80211_data *drv = bss->drv;
5662         struct nl_msg *msg;
5663         int ret = -ENOBUFS;
5664         u32 val;
5665
5666         msg = nlmsg_alloc();
5667         if (!msg)
5668                 return -ENOMEM;
5669
5670         if (rts >= 2347)
5671                 val = (u32) -1;
5672         else
5673                 val = rts;
5674
5675         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5676                     0, NL80211_CMD_SET_WIPHY, 0);
5677         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5678         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
5679
5680         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5681         if (!ret)
5682                 return 0;
5683 nla_put_failure:
5684         wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
5685                    "%d (%s)", rts, ret, strerror(-ret));
5686         return ret;
5687 }
5688
5689
5690 static int i802_set_frag(void *priv, int frag)
5691 {
5692         struct i802_bss *bss = priv;
5693         struct wpa_driver_nl80211_data *drv = bss->drv;
5694         struct nl_msg *msg;
5695         int ret = -ENOBUFS;
5696         u32 val;
5697
5698         msg = nlmsg_alloc();
5699         if (!msg)
5700                 return -ENOMEM;
5701
5702         if (frag >= 2346)
5703                 val = (u32) -1;
5704         else
5705                 val = frag;
5706
5707         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5708                     0, NL80211_CMD_SET_WIPHY, 0);
5709         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5710         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
5711
5712         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5713         if (!ret)
5714                 return 0;
5715 nla_put_failure:
5716         wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
5717                    "%d: %d (%s)", frag, ret, strerror(-ret));
5718         return ret;
5719 }
5720
5721
5722 static int i802_flush(void *priv)
5723 {
5724         struct i802_bss *bss = priv;
5725         struct wpa_driver_nl80211_data *drv = bss->drv;
5726         struct nl_msg *msg;
5727
5728         msg = nlmsg_alloc();
5729         if (!msg)
5730                 return -1;
5731
5732         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5733                     0, NL80211_CMD_DEL_STATION, 0);
5734
5735         /*
5736          * XXX: FIX! this needs to flush all VLANs too
5737          */
5738         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5739                     if_nametoindex(bss->ifname));
5740
5741         return send_and_recv_msgs(drv, msg, NULL, NULL);
5742  nla_put_failure:
5743         return -ENOBUFS;
5744 }
5745
5746
5747 static int get_sta_handler(struct nl_msg *msg, void *arg)
5748 {
5749         struct nlattr *tb[NL80211_ATTR_MAX + 1];
5750         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5751         struct hostap_sta_driver_data *data = arg;
5752         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
5753         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
5754                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
5755                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
5756                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
5757                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
5758                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
5759         };
5760
5761         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5762                   genlmsg_attrlen(gnlh, 0), NULL);
5763
5764         /*
5765          * TODO: validate the interface and mac address!
5766          * Otherwise, there's a race condition as soon as
5767          * the kernel starts sending station notifications.
5768          */
5769
5770         if (!tb[NL80211_ATTR_STA_INFO]) {
5771                 wpa_printf(MSG_DEBUG, "sta stats missing!");
5772                 return NL_SKIP;
5773         }
5774         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
5775                              tb[NL80211_ATTR_STA_INFO],
5776                              stats_policy)) {
5777                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
5778                 return NL_SKIP;
5779         }
5780
5781         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
5782                 data->inactive_msec =
5783                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
5784         if (stats[NL80211_STA_INFO_RX_BYTES])
5785                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
5786         if (stats[NL80211_STA_INFO_TX_BYTES])
5787                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
5788         if (stats[NL80211_STA_INFO_RX_PACKETS])
5789                 data->rx_packets =
5790                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
5791         if (stats[NL80211_STA_INFO_TX_PACKETS])
5792                 data->tx_packets =
5793                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
5794
5795         return NL_SKIP;
5796 }
5797
5798 static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
5799                               const u8 *addr)
5800 {
5801         struct i802_bss *bss = priv;
5802         struct wpa_driver_nl80211_data *drv = bss->drv;
5803         struct nl_msg *msg;
5804
5805         os_memset(data, 0, sizeof(*data));
5806         msg = nlmsg_alloc();
5807         if (!msg)
5808                 return -ENOMEM;
5809
5810         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5811                     0, NL80211_CMD_GET_STATION, 0);
5812
5813         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5814         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5815
5816         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
5817  nla_put_failure:
5818         return -ENOBUFS;
5819 }
5820
5821
5822 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
5823                                     int cw_min, int cw_max, int burst_time)
5824 {
5825         struct i802_bss *bss = priv;
5826         struct wpa_driver_nl80211_data *drv = bss->drv;
5827         struct nl_msg *msg;
5828         struct nlattr *txq, *params;
5829
5830         msg = nlmsg_alloc();
5831         if (!msg)
5832                 return -1;
5833
5834         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5835                     0, NL80211_CMD_SET_WIPHY, 0);
5836
5837         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5838
5839         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
5840         if (!txq)
5841                 goto nla_put_failure;
5842
5843         /* We are only sending parameters for a single TXQ at a time */
5844         params = nla_nest_start(msg, 1);
5845         if (!params)
5846                 goto nla_put_failure;
5847
5848         switch (queue) {
5849         case 0:
5850                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
5851                 break;
5852         case 1:
5853                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
5854                 break;
5855         case 2:
5856                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
5857                 break;
5858         case 3:
5859                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
5860                 break;
5861         }
5862         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
5863          * 32 usec, so need to convert the value here. */
5864         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
5865         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
5866         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
5867         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
5868
5869         nla_nest_end(msg, params);
5870
5871         nla_nest_end(msg, txq);
5872
5873         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
5874                 return 0;
5875  nla_put_failure:
5876         return -1;
5877 }
5878
5879
5880 static int i802_set_bss(void *priv, int cts, int preamble, int slot,
5881                         int ht_opmode)
5882 {
5883         struct i802_bss *bss = priv;
5884         struct wpa_driver_nl80211_data *drv = bss->drv;
5885         struct nl_msg *msg;
5886
5887         msg = nlmsg_alloc();
5888         if (!msg)
5889                 return -ENOMEM;
5890
5891         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5892                     NL80211_CMD_SET_BSS, 0);
5893
5894         if (cts >= 0)
5895                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
5896         if (preamble >= 0)
5897                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
5898         if (slot >= 0)
5899                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
5900         if (ht_opmode >= 0)
5901                 NLA_PUT_U16(msg, NL80211_ATTR_BSS_HT_OPMODE, ht_opmode);
5902         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5903
5904         return send_and_recv_msgs(drv, msg, NULL, NULL);
5905  nla_put_failure:
5906         return -ENOBUFS;
5907 }
5908
5909
5910 static int i802_set_cts_protect(void *priv, int value)
5911 {
5912         return i802_set_bss(priv, value, -1, -1, -1);
5913 }
5914
5915
5916 static int i802_set_preamble(void *priv, int value)
5917 {
5918         return i802_set_bss(priv, -1, value, -1, -1);
5919 }
5920
5921
5922 static int i802_set_short_slot_time(void *priv, int value)
5923 {
5924         return i802_set_bss(priv, -1, -1, value, -1);
5925 }
5926
5927
5928 static int i802_set_sta_vlan(void *priv, const u8 *addr,
5929                              const char *ifname, int vlan_id)
5930 {
5931         struct i802_bss *bss = priv;
5932         struct wpa_driver_nl80211_data *drv = bss->drv;
5933         struct nl_msg *msg;
5934         int ret = -ENOBUFS;
5935
5936         msg = nlmsg_alloc();
5937         if (!msg)
5938                 return -ENOMEM;
5939
5940         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5941                     0, NL80211_CMD_SET_STATION, 0);
5942
5943         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5944                     if_nametoindex(bss->ifname));
5945         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5946         NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
5947                     if_nametoindex(ifname));
5948
5949         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5950         if (ret < 0) {
5951                 wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
5952                            MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
5953                            MAC2STR(addr), ifname, vlan_id, ret,
5954                            strerror(-ret));
5955         }
5956  nla_put_failure:
5957         return ret;
5958 }
5959
5960
5961 static int i802_set_ht_params(void *priv, const u8 *ht_capab,
5962                               size_t ht_capab_len, const u8 *ht_oper,
5963                               size_t ht_oper_len)
5964 {
5965         if (ht_oper_len >= 6) {
5966                 /* ht opmode uses 16bit in octet 5 & 6 */
5967                 u16 ht_opmode = le_to_host16(((u16 *) ht_oper)[2]);
5968                 return i802_set_bss(priv, -1, -1, -1, ht_opmode);
5969         } else
5970                 return -1;
5971 }
5972
5973
5974 static int i802_get_inact_sec(void *priv, const u8 *addr)
5975 {
5976         struct hostap_sta_driver_data data;
5977         int ret;
5978
5979         data.inactive_msec = (unsigned long) -1;
5980         ret = i802_read_sta_data(priv, &data, addr);
5981         if (ret || data.inactive_msec == (unsigned long) -1)
5982                 return -1;
5983         return data.inactive_msec / 1000;
5984 }
5985
5986
5987 static int i802_sta_clear_stats(void *priv, const u8 *addr)
5988 {
5989 #if 0
5990         /* TODO */
5991 #endif
5992         return 0;
5993 }
5994
5995
5996 static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
5997                            int reason)
5998 {
5999         struct i802_bss *bss = priv;
6000         struct ieee80211_mgmt mgmt;
6001
6002         memset(&mgmt, 0, sizeof(mgmt));
6003         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
6004                                           WLAN_FC_STYPE_DEAUTH);
6005         memcpy(mgmt.da, addr, ETH_ALEN);
6006         memcpy(mgmt.sa, own_addr, ETH_ALEN);
6007         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
6008         mgmt.u.deauth.reason_code = host_to_le16(reason);
6009         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
6010                                             IEEE80211_HDRLEN +
6011                                             sizeof(mgmt.u.deauth));
6012 }
6013
6014
6015 static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
6016                              int reason)
6017 {
6018         struct i802_bss *bss = priv;
6019         struct ieee80211_mgmt mgmt;
6020
6021         memset(&mgmt, 0, sizeof(mgmt));
6022         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
6023                                           WLAN_FC_STYPE_DISASSOC);
6024         memcpy(mgmt.da, addr, ETH_ALEN);
6025         memcpy(mgmt.sa, own_addr, ETH_ALEN);
6026         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
6027         mgmt.u.disassoc.reason_code = host_to_le16(reason);
6028         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
6029                                             IEEE80211_HDRLEN +
6030                                             sizeof(mgmt.u.disassoc));
6031 }
6032
6033 #endif /* HOSTAPD || CONFIG_AP */
6034
6035 #ifdef HOSTAPD
6036
6037 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
6038 {
6039         int i;
6040         int *old;
6041
6042         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
6043                    ifidx);
6044         for (i = 0; i < drv->num_if_indices; i++) {
6045                 if (drv->if_indices[i] == 0) {
6046                         drv->if_indices[i] = ifidx;
6047                         return;
6048                 }
6049         }
6050
6051         if (drv->if_indices != drv->default_if_indices)
6052                 old = drv->if_indices;
6053         else
6054                 old = NULL;
6055
6056         drv->if_indices = os_realloc(old,
6057                                      sizeof(int) * (drv->num_if_indices + 1));
6058         if (!drv->if_indices) {
6059                 if (!old)
6060                         drv->if_indices = drv->default_if_indices;
6061                 else
6062                         drv->if_indices = old;
6063                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
6064                            "interfaces");
6065                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
6066                 return;
6067         } else if (!old)
6068                 os_memcpy(drv->if_indices, drv->default_if_indices,
6069                           sizeof(drv->default_if_indices));
6070         drv->if_indices[drv->num_if_indices] = ifidx;
6071         drv->num_if_indices++;
6072 }
6073
6074
6075 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
6076 {
6077         int i;
6078
6079         for (i = 0; i < drv->num_if_indices; i++) {
6080                 if (drv->if_indices[i] == ifidx) {
6081                         drv->if_indices[i] = 0;
6082                         break;
6083                 }
6084         }
6085 }
6086
6087
6088 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
6089 {
6090         int i;
6091
6092         for (i = 0; i < drv->num_if_indices; i++)
6093                 if (drv->if_indices[i] == ifidx)
6094                         return 1;
6095
6096         return 0;
6097 }
6098
6099
6100 static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
6101                             const char *bridge_ifname)
6102 {
6103         struct i802_bss *bss = priv;
6104         struct wpa_driver_nl80211_data *drv = bss->drv;
6105         char name[IFNAMSIZ + 1];
6106
6107         os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
6108         wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
6109                    " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
6110         if (val) {
6111                 if (!if_nametoindex(name)) {
6112                         if (nl80211_create_iface(drv, name,
6113                                                  NL80211_IFTYPE_AP_VLAN,
6114                                                  NULL, 1) < 0)
6115                                 return -1;
6116                         if (bridge_ifname &&
6117                             linux_br_add_if(drv->ioctl_sock, bridge_ifname,
6118                                             name) < 0)
6119                                 return -1;
6120                 }
6121                 linux_set_iface_flags(drv->ioctl_sock, name, 1);
6122                 return i802_set_sta_vlan(priv, addr, name, 0);
6123         } else {
6124                 i802_set_sta_vlan(priv, addr, bss->ifname, 0);
6125                 return wpa_driver_nl80211_if_remove(priv, WPA_IF_AP_VLAN,
6126                                                     name);
6127         }
6128 }
6129
6130
6131 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
6132 {
6133         struct wpa_driver_nl80211_data *drv = eloop_ctx;
6134         struct sockaddr_ll lladdr;
6135         unsigned char buf[3000];
6136         int len;
6137         socklen_t fromlen = sizeof(lladdr);
6138
6139         len = recvfrom(sock, buf, sizeof(buf), 0,
6140                        (struct sockaddr *)&lladdr, &fromlen);
6141         if (len < 0) {
6142                 perror("recv");
6143                 return;
6144         }
6145
6146         if (have_ifidx(drv, lladdr.sll_ifindex))
6147                 drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
6148 }
6149
6150
6151 static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
6152                              struct i802_bss *bss,
6153                              const char *brname, const char *ifname)
6154 {
6155         int ifindex;
6156         char in_br[IFNAMSIZ];
6157
6158         os_strlcpy(bss->brname, brname, IFNAMSIZ);
6159         ifindex = if_nametoindex(brname);
6160         if (ifindex == 0) {
6161                 /*
6162                  * Bridge was configured, but the bridge device does
6163                  * not exist. Try to add it now.
6164                  */
6165                 if (linux_br_add(drv->ioctl_sock, brname) < 0) {
6166                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
6167                                    "bridge interface %s: %s",
6168                                    brname, strerror(errno));
6169                         return -1;
6170                 }
6171                 bss->added_bridge = 1;
6172                 add_ifidx(drv, if_nametoindex(brname));
6173         }
6174
6175         if (linux_br_get(in_br, ifname) == 0) {
6176                 if (os_strcmp(in_br, brname) == 0)
6177                         return 0; /* already in the bridge */
6178
6179                 wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
6180                            "bridge %s", ifname, in_br);
6181                 if (linux_br_del_if(drv->ioctl_sock, in_br, ifname) < 0) {
6182                         wpa_printf(MSG_ERROR, "nl80211: Failed to "
6183                                    "remove interface %s from bridge "
6184                                    "%s: %s",
6185                                    ifname, brname, strerror(errno));
6186                         return -1;
6187                 }
6188         }
6189
6190         wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
6191                    ifname, brname);
6192         if (linux_br_add_if(drv->ioctl_sock, brname, ifname) < 0) {
6193                 wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
6194                            "into bridge %s: %s",
6195                            ifname, brname, strerror(errno));
6196                 return -1;
6197         }
6198         bss->added_if_into_bridge = 1;
6199
6200         return 0;
6201 }
6202
6203
6204 static void *i802_init(struct hostapd_data *hapd,
6205                        struct wpa_init_params *params)
6206 {
6207         struct wpa_driver_nl80211_data *drv;
6208         struct i802_bss *bss;
6209         size_t i;
6210         char brname[IFNAMSIZ];
6211         int ifindex, br_ifindex;
6212         int br_added = 0;
6213
6214         bss = wpa_driver_nl80211_init(hapd, params->ifname, NULL);
6215         if (bss == NULL)
6216                 return NULL;
6217
6218         drv = bss->drv;
6219         drv->nlmode = NL80211_IFTYPE_AP;
6220         if (linux_br_get(brname, params->ifname) == 0) {
6221                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
6222                            params->ifname, brname);
6223                 br_ifindex = if_nametoindex(brname);
6224         } else {
6225                 brname[0] = '\0';
6226                 br_ifindex = 0;
6227         }
6228
6229         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
6230         drv->if_indices = drv->default_if_indices;
6231         for (i = 0; i < params->num_bridge; i++) {
6232                 if (params->bridge[i]) {
6233                         ifindex = if_nametoindex(params->bridge[i]);
6234                         if (ifindex)
6235                                 add_ifidx(drv, ifindex);
6236                         if (ifindex == br_ifindex)
6237                                 br_added = 1;
6238                 }
6239         }
6240         if (!br_added && br_ifindex &&
6241             (params->num_bridge == 0 || !params->bridge[0]))
6242                 add_ifidx(drv, br_ifindex);
6243
6244         /* start listening for EAPOL on the default AP interface */
6245         add_ifidx(drv, drv->ifindex);
6246
6247         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 0))
6248                 goto failed;
6249
6250         if (params->bssid) {
6251                 if (linux_set_ifhwaddr(drv->ioctl_sock, bss->ifname,
6252                                        params->bssid))
6253                         goto failed;
6254         }
6255
6256         if (wpa_driver_nl80211_set_mode(bss, drv->nlmode)) {
6257                 wpa_printf(MSG_ERROR, "nl80211: Failed to set interface %s "
6258                            "into AP mode", bss->ifname);
6259                 goto failed;
6260         }
6261
6262         if (params->num_bridge && params->bridge[0] &&
6263             i802_check_bridge(drv, bss, params->bridge[0], params->ifname) < 0)
6264                 goto failed;
6265
6266         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 1))
6267                 goto failed;
6268
6269         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
6270         if (drv->eapol_sock < 0) {
6271                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
6272                 goto failed;
6273         }
6274
6275         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
6276         {
6277                 printf("Could not register read socket for eapol\n");
6278                 goto failed;
6279         }
6280
6281         if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, params->own_addr))
6282                 goto failed;
6283
6284         return bss;
6285
6286 failed:
6287         nl80211_remove_monitor_interface(drv);
6288         rfkill_deinit(drv->rfkill);
6289         netlink_deinit(drv->netlink);
6290         if (drv->ioctl_sock >= 0)
6291                 close(drv->ioctl_sock);
6292
6293         genl_family_put(drv->nl80211);
6294         nl_cache_free(drv->nl_cache);
6295         nl80211_handle_destroy(drv->nl_handle);
6296         nl_cb_put(drv->nl_cb);
6297         eloop_unregister_read_sock(nl_socket_get_fd(drv->nl_handle_event));
6298
6299         os_free(drv);
6300         return NULL;
6301 }
6302
6303
6304 static void i802_deinit(void *priv)
6305 {
6306         wpa_driver_nl80211_deinit(priv);
6307 }
6308
6309 #endif /* HOSTAPD */
6310
6311
6312 static enum nl80211_iftype wpa_driver_nl80211_if_type(
6313         enum wpa_driver_if_type type)
6314 {
6315         switch (type) {
6316         case WPA_IF_STATION:
6317                 return NL80211_IFTYPE_STATION;
6318         case WPA_IF_P2P_CLIENT:
6319         case WPA_IF_P2P_GROUP:
6320                 return NL80211_IFTYPE_P2P_CLIENT;
6321         case WPA_IF_AP_VLAN:
6322                 return NL80211_IFTYPE_AP_VLAN;
6323         case WPA_IF_AP_BSS:
6324                 return NL80211_IFTYPE_AP;
6325         case WPA_IF_P2P_GO:
6326                 return NL80211_IFTYPE_P2P_GO;
6327         }
6328         return -1;
6329 }
6330
6331
6332 #ifdef CONFIG_P2P
6333
6334 static int nl80211_addr_in_use(struct nl80211_global *global, const u8 *addr)
6335 {
6336         struct wpa_driver_nl80211_data *drv;
6337         dl_list_for_each(drv, &global->interfaces,
6338                          struct wpa_driver_nl80211_data, list) {
6339                 if (os_memcmp(addr, drv->addr, ETH_ALEN) == 0)
6340                         return 1;
6341         }
6342         return 0;
6343 }
6344
6345
6346 static int nl80211_p2p_interface_addr(struct wpa_driver_nl80211_data *drv,
6347                                       u8 *new_addr)
6348 {
6349         unsigned int idx;
6350
6351         if (!drv->global)
6352                 return -1;
6353
6354         os_memcpy(new_addr, drv->addr, ETH_ALEN);
6355         for (idx = 0; idx < 64; idx++) {
6356                 new_addr[0] = drv->addr[0] | 0x02;
6357                 new_addr[0] ^= idx << 2;
6358                 if (!nl80211_addr_in_use(drv->global, new_addr))
6359                         break;
6360         }
6361         if (idx == 64)
6362                 return -1;
6363
6364         wpa_printf(MSG_DEBUG, "nl80211: Assigned new P2P Interface Address "
6365                    MACSTR, MAC2STR(new_addr));
6366
6367         return 0;
6368 }
6369
6370 #endif /* CONFIG_P2P */
6371
6372
6373 static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
6374                                      const char *ifname, const u8 *addr,
6375                                      void *bss_ctx, void **drv_priv,
6376                                      char *force_ifname, u8 *if_addr,
6377                                      const char *bridge)
6378 {
6379         struct i802_bss *bss = priv;
6380         struct wpa_driver_nl80211_data *drv = bss->drv;
6381         int ifidx;
6382 #ifdef HOSTAPD
6383         struct i802_bss *new_bss = NULL;
6384
6385         if (type == WPA_IF_AP_BSS) {
6386                 new_bss = os_zalloc(sizeof(*new_bss));
6387                 if (new_bss == NULL)
6388                         return -1;
6389         }
6390 #endif /* HOSTAPD */
6391
6392         if (addr)
6393                 os_memcpy(if_addr, addr, ETH_ALEN);
6394         ifidx = nl80211_create_iface(drv, ifname,
6395                                      wpa_driver_nl80211_if_type(type), addr,
6396                                      0);
6397         if (ifidx < 0) {
6398 #ifdef HOSTAPD
6399                 os_free(new_bss);
6400 #endif /* HOSTAPD */
6401                 return -1;
6402         }
6403
6404         if (!addr &&
6405             linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, if_addr) < 0) {
6406                 nl80211_remove_iface(drv, ifidx);
6407                 return -1;
6408         }
6409
6410 #ifdef CONFIG_P2P
6411         if (!addr &&
6412             (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
6413              type == WPA_IF_P2P_GO)) {
6414                 /* Enforce unique P2P Interface Address */
6415                 u8 new_addr[ETH_ALEN], own_addr[ETH_ALEN];
6416
6417                 if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, own_addr)
6418                     < 0 ||
6419                     linux_get_ifhwaddr(drv->ioctl_sock, ifname, new_addr) < 0)
6420                 {
6421                         nl80211_remove_iface(drv, ifidx);
6422                         return -1;
6423                 }
6424                 if (os_memcmp(own_addr, new_addr, ETH_ALEN) == 0) {
6425                         wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
6426                                    "for P2P group interface");
6427                         if (nl80211_p2p_interface_addr(drv, new_addr) < 0) {
6428                                 nl80211_remove_iface(drv, ifidx);
6429                                 return -1;
6430                         }
6431                         if (linux_set_ifhwaddr(drv->ioctl_sock, ifname,
6432                                                new_addr) < 0) {
6433                                 nl80211_remove_iface(drv, ifidx);
6434                                 return -1;
6435                         }
6436                 }
6437                 os_memcpy(if_addr, new_addr, ETH_ALEN);
6438         }
6439 #endif /* CONFIG_P2P */
6440
6441 #ifdef HOSTAPD
6442         if (bridge &&
6443             i802_check_bridge(drv, new_bss, bridge, ifname) < 0) {
6444                 wpa_printf(MSG_ERROR, "nl80211: Failed to add the new "
6445                            "interface %s to a bridge %s", ifname, bridge);
6446                 nl80211_remove_iface(drv, ifidx);
6447                 os_free(new_bss);
6448                 return -1;
6449         }
6450
6451         if (type == WPA_IF_AP_BSS) {
6452                 if (linux_set_iface_flags(drv->ioctl_sock, ifname, 1)) {
6453                         nl80211_remove_iface(drv, ifidx);
6454                         os_free(new_bss);
6455                         return -1;
6456                 }
6457                 os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
6458                 new_bss->ifindex = ifidx;
6459                 new_bss->drv = drv;
6460                 new_bss->next = drv->first_bss.next;
6461                 drv->first_bss.next = new_bss;
6462                 if (drv_priv)
6463                         *drv_priv = new_bss;
6464         }
6465 #endif /* HOSTAPD */
6466
6467         if (drv->global)
6468                 drv->global->if_add_ifindex = ifidx;
6469
6470         return 0;
6471 }
6472
6473
6474 static int wpa_driver_nl80211_if_remove(void *priv,
6475                                         enum wpa_driver_if_type type,
6476                                         const char *ifname)
6477 {
6478         struct i802_bss *bss = priv;
6479         struct wpa_driver_nl80211_data *drv = bss->drv;
6480         int ifindex = if_nametoindex(ifname);
6481
6482         wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d",
6483                    __func__, type, ifname, ifindex);
6484         if (ifindex <= 0)
6485                 return -1;
6486
6487 #ifdef HOSTAPD
6488         if (bss->added_if_into_bridge) {
6489                 if (linux_br_del_if(drv->ioctl_sock, bss->brname, bss->ifname)
6490                     < 0)
6491                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
6492                                    "interface %s from bridge %s: %s",
6493                                    bss->ifname, bss->brname, strerror(errno));
6494         }
6495         if (bss->added_bridge) {
6496                 if (linux_br_del(drv->ioctl_sock, bss->brname) < 0)
6497                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
6498                                    "bridge %s: %s",
6499                                    bss->brname, strerror(errno));
6500         }
6501 #endif /* HOSTAPD */
6502
6503         nl80211_remove_iface(drv, ifindex);
6504
6505 #ifdef HOSTAPD
6506         if (type != WPA_IF_AP_BSS)
6507                 return 0;
6508
6509         if (bss != &drv->first_bss) {
6510                 struct i802_bss *tbss;
6511
6512                 for (tbss = &drv->first_bss; tbss; tbss = tbss->next) {
6513                         if (tbss->next == bss) {
6514                                 tbss->next = bss->next;
6515                                 os_free(bss);
6516                                 bss = NULL;
6517                                 break;
6518                         }
6519                 }
6520                 if (bss)
6521                         wpa_printf(MSG_INFO, "nl80211: %s - could not find "
6522                                    "BSS %p in the list", __func__, bss);
6523         }
6524 #endif /* HOSTAPD */
6525
6526         return 0;
6527 }
6528
6529
6530 static int cookie_handler(struct nl_msg *msg, void *arg)
6531 {
6532         struct nlattr *tb[NL80211_ATTR_MAX + 1];
6533         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
6534         u64 *cookie = arg;
6535         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
6536                   genlmsg_attrlen(gnlh, 0), NULL);
6537         if (tb[NL80211_ATTR_COOKIE])
6538                 *cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
6539         return NL_SKIP;
6540 }
6541
6542
6543 static int nl80211_send_frame_cmd(struct wpa_driver_nl80211_data *drv,
6544                                   unsigned int freq, unsigned int wait,
6545                                   const u8 *buf, size_t buf_len,
6546                                   u64 *cookie_out)
6547 {
6548         struct nl_msg *msg;
6549         u64 cookie;
6550         int ret = -1;
6551
6552         msg = nlmsg_alloc();
6553         if (!msg)
6554                 return -1;
6555
6556         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6557                     NL80211_CMD_FRAME, 0);
6558
6559         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6560         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
6561         if (wait)
6562                 NLA_PUT_U32(msg, NL80211_ATTR_DURATION, wait);
6563         NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
6564         NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
6565
6566         cookie = 0;
6567         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
6568         msg = NULL;
6569         if (ret) {
6570                 wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
6571                            "(%s) (freq=%u wait=%u)", ret, strerror(-ret),
6572                            freq, wait);
6573                 goto nla_put_failure;
6574         }
6575         wpa_printf(MSG_DEBUG, "nl80211: Frame TX command accepted; "
6576                    "cookie 0x%llx", (long long unsigned int) cookie);
6577
6578         if (cookie_out)
6579                 *cookie_out = cookie;
6580
6581 nla_put_failure:
6582         nlmsg_free(msg);
6583         return ret;
6584 }
6585
6586
6587 static int wpa_driver_nl80211_send_action(void *priv, unsigned int freq,
6588                                           unsigned int wait_time,
6589                                           const u8 *dst, const u8 *src,
6590                                           const u8 *bssid,
6591                                           const u8 *data, size_t data_len)
6592 {
6593         struct i802_bss *bss = priv;
6594         struct wpa_driver_nl80211_data *drv = bss->drv;
6595         int ret = -1;
6596         u8 *buf;
6597         struct ieee80211_hdr *hdr;
6598
6599         wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d, "
6600                    "wait=%d ms)", drv->ifindex, wait_time);
6601
6602         buf = os_zalloc(24 + data_len);
6603         if (buf == NULL)
6604                 return ret;
6605         os_memcpy(buf + 24, data, data_len);
6606         hdr = (struct ieee80211_hdr *) buf;
6607         hdr->frame_control =
6608                 IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
6609         os_memcpy(hdr->addr1, dst, ETH_ALEN);
6610         os_memcpy(hdr->addr2, src, ETH_ALEN);
6611         os_memcpy(hdr->addr3, bssid, ETH_ALEN);
6612
6613         if (is_ap_interface(drv->nlmode))
6614                 ret = wpa_driver_nl80211_send_mlme(priv, buf, 24 + data_len);
6615         else
6616                 ret = nl80211_send_frame_cmd(drv, freq, wait_time, buf,
6617                                              24 + data_len,
6618                                              &drv->send_action_cookie);
6619
6620         os_free(buf);
6621         return ret;
6622 }
6623
6624
6625 static void wpa_driver_nl80211_send_action_cancel_wait(void *priv)
6626 {
6627         struct i802_bss *bss = priv;
6628         struct wpa_driver_nl80211_data *drv = bss->drv;
6629         struct nl_msg *msg;
6630         int ret;
6631
6632         msg = nlmsg_alloc();
6633         if (!msg)
6634                 return;
6635
6636         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6637                     NL80211_CMD_FRAME_WAIT_CANCEL, 0);
6638
6639         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6640         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->send_action_cookie);
6641
6642         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6643         msg = NULL;
6644         if (ret)
6645                 wpa_printf(MSG_DEBUG, "nl80211: wait cancel failed: ret=%d "
6646                            "(%s)", ret, strerror(-ret));
6647
6648  nla_put_failure:
6649         nlmsg_free(msg);
6650 }
6651
6652
6653 static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
6654                                                 unsigned int duration)
6655 {
6656         struct i802_bss *bss = priv;
6657         struct wpa_driver_nl80211_data *drv = bss->drv;
6658         struct nl_msg *msg;
6659         int ret;
6660         u64 cookie;
6661
6662         msg = nlmsg_alloc();
6663         if (!msg)
6664                 return -1;
6665
6666         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6667                     NL80211_CMD_REMAIN_ON_CHANNEL, 0);
6668
6669         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6670         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
6671         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
6672
6673         cookie = 0;
6674         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
6675         if (ret == 0) {
6676                 wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
6677                            "0x%llx for freq=%u MHz duration=%u",
6678                            (long long unsigned int) cookie, freq, duration);
6679                 drv->remain_on_chan_cookie = cookie;
6680                 drv->pending_remain_on_chan = 1;
6681                 return 0;
6682         }
6683         wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
6684                    "(freq=%d duration=%u): %d (%s)",
6685                    freq, duration, ret, strerror(-ret));
6686 nla_put_failure:
6687         return -1;
6688 }
6689
6690
6691 static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
6692 {
6693         struct i802_bss *bss = priv;
6694         struct wpa_driver_nl80211_data *drv = bss->drv;
6695         struct nl_msg *msg;
6696         int ret;
6697
6698         if (!drv->pending_remain_on_chan) {
6699                 wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
6700                            "to cancel");
6701                 return -1;
6702         }
6703
6704         wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
6705                    "0x%llx",
6706                    (long long unsigned int) drv->remain_on_chan_cookie);
6707
6708         msg = nlmsg_alloc();
6709         if (!msg)
6710                 return -1;
6711
6712         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6713                     NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL, 0);
6714
6715         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6716         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
6717
6718         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6719         if (ret == 0)
6720                 return 0;
6721         wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
6722                    "%d (%s)", ret, strerror(-ret));
6723 nla_put_failure:
6724         return -1;
6725 }
6726
6727
6728 static int wpa_driver_nl80211_probe_req_report(void *priv, int report)
6729 {
6730         struct i802_bss *bss = priv;
6731         struct wpa_driver_nl80211_data *drv = bss->drv;
6732
6733         if (!report) {
6734                 if (drv->nl_handle_preq) {
6735                         eloop_unregister_read_sock(
6736                                 nl_socket_get_fd(drv->nl_handle_preq));
6737                         nl_cache_free(drv->nl_cache_preq);
6738                         nl80211_handle_destroy(drv->nl_handle_preq);
6739                         drv->nl_handle_preq = NULL;
6740                 }
6741                 return 0;
6742         }
6743
6744         if (drv->nl_handle_preq) {
6745                 wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
6746                            "already on!");
6747                 return 0;
6748         }
6749
6750         drv->nl_handle_preq = nl80211_handle_alloc(drv->nl_cb);
6751         if (drv->nl_handle_preq == NULL) {
6752                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate "
6753                            "netlink callbacks (preq)");
6754                 goto out_err1;
6755         }
6756
6757         if (genl_connect(drv->nl_handle_preq)) {
6758                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to "
6759                            "generic netlink (preq)");
6760                 goto out_err2;
6761                 return -1;
6762         }
6763
6764 #ifdef CONFIG_LIBNL20
6765         if (genl_ctrl_alloc_cache(drv->nl_handle_preq,
6766                                   &drv->nl_cache_preq) < 0) {
6767                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
6768                            "netlink cache (preq)");
6769                 goto out_err2;
6770         }
6771 #else /* CONFIG_LIBNL20 */
6772         drv->nl_cache_preq = genl_ctrl_alloc_cache(drv->nl_handle_preq);
6773         if (drv->nl_cache_preq == NULL) {
6774                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
6775                            "netlink cache (preq)");
6776                 goto out_err2;
6777         }
6778 #endif /* CONFIG_LIBNL20 */
6779
6780         if (nl80211_register_frame(drv, drv->nl_handle_preq,
6781                                    (WLAN_FC_TYPE_MGMT << 2) |
6782                                    (WLAN_FC_STYPE_PROBE_REQ << 4),
6783                                    NULL, 0) < 0) {
6784                 goto out_err3;
6785         }
6786
6787         eloop_register_read_sock(nl_socket_get_fd(drv->nl_handle_preq),
6788                                  wpa_driver_nl80211_event_receive, drv,
6789                                  drv->nl_handle_preq);
6790
6791         return 0;
6792
6793  out_err3:
6794         nl_cache_free(drv->nl_cache_preq);
6795  out_err2:
6796         nl80211_handle_destroy(drv->nl_handle_preq);
6797         drv->nl_handle_preq = NULL;
6798  out_err1:
6799         return -1;
6800 }
6801
6802
6803 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
6804                                      int ifindex, int disabled)
6805 {
6806         struct nl_msg *msg;
6807         struct nlattr *bands, *band;
6808         int ret;
6809
6810         msg = nlmsg_alloc();
6811         if (!msg)
6812                 return -1;
6813
6814         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6815                     NL80211_CMD_SET_TX_BITRATE_MASK, 0);
6816         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
6817
6818         bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
6819         if (!bands)
6820                 goto nla_put_failure;
6821
6822         /*
6823          * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
6824          * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
6825          * rates. All 5 GHz rates are left enabled.
6826          */
6827         band = nla_nest_start(msg, NL80211_BAND_2GHZ);
6828         if (!band)
6829                 goto nla_put_failure;
6830         NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
6831                 "\x0c\x12\x18\x24\x30\x48\x60\x6c");
6832         nla_nest_end(msg, band);
6833
6834         nla_nest_end(msg, bands);
6835
6836         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6837         msg = NULL;
6838         if (ret) {
6839                 wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
6840                            "(%s)", ret, strerror(-ret));
6841         }
6842
6843         return ret;
6844
6845 nla_put_failure:
6846         nlmsg_free(msg);
6847         return -1;
6848 }
6849
6850
6851 static int wpa_driver_nl80211_disable_11b_rates(void *priv, int disabled)
6852 {
6853         struct i802_bss *bss = priv;
6854         struct wpa_driver_nl80211_data *drv = bss->drv;
6855         drv->disable_11b_rates = disabled;
6856         return nl80211_disable_11b_rates(drv, drv->ifindex, disabled);
6857 }
6858
6859
6860 static int wpa_driver_nl80211_deinit_ap(void *priv)
6861 {
6862         struct i802_bss *bss = priv;
6863         struct wpa_driver_nl80211_data *drv = bss->drv;
6864         if (!is_ap_interface(drv->nlmode))
6865                 return -1;
6866         wpa_driver_nl80211_del_beacon(drv);
6867         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
6868 }
6869
6870
6871 static void wpa_driver_nl80211_resume(void *priv)
6872 {
6873         struct i802_bss *bss = priv;
6874         struct wpa_driver_nl80211_data *drv = bss->drv;
6875         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 1)) {
6876                 wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on "
6877                            "resume event");
6878         }
6879 }
6880
6881
6882 static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
6883                                   const u8 *ies, size_t ies_len)
6884 {
6885         struct i802_bss *bss = priv;
6886         struct wpa_driver_nl80211_data *drv = bss->drv;
6887         int ret;
6888         u8 *data, *pos;
6889         size_t data_len;
6890         u8 own_addr[ETH_ALEN];
6891
6892         if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, own_addr) < 0)
6893                 return -1;
6894
6895         if (action != 1) {
6896                 wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
6897                            "action %d", action);
6898                 return -1;
6899         }
6900
6901         /*
6902          * Action frame payload:
6903          * Category[1] = 6 (Fast BSS Transition)
6904          * Action[1] = 1 (Fast BSS Transition Request)
6905          * STA Address
6906          * Target AP Address
6907          * FT IEs
6908          */
6909
6910         data_len = 2 + 2 * ETH_ALEN + ies_len;
6911         data = os_malloc(data_len);
6912         if (data == NULL)
6913                 return -1;
6914         pos = data;
6915         *pos++ = 0x06; /* FT Action category */
6916         *pos++ = action;
6917         os_memcpy(pos, own_addr, ETH_ALEN);
6918         pos += ETH_ALEN;
6919         os_memcpy(pos, target_ap, ETH_ALEN);
6920         pos += ETH_ALEN;
6921         os_memcpy(pos, ies, ies_len);
6922
6923         ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, 0,
6924                                              drv->bssid, own_addr, drv->bssid,
6925                                              data, data_len);
6926         os_free(data);
6927
6928         return ret;
6929 }
6930
6931
6932 static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
6933 {
6934         struct i802_bss *bss = priv;
6935         struct wpa_driver_nl80211_data *drv = bss->drv;
6936         struct nl_msg *msg, *cqm = NULL;
6937
6938         wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
6939                    "hysteresis=%d", threshold, hysteresis);
6940
6941         msg = nlmsg_alloc();
6942         if (!msg)
6943                 return -1;
6944
6945         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
6946                     0, NL80211_CMD_SET_CQM, 0);
6947
6948         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
6949
6950         cqm = nlmsg_alloc();
6951         if (cqm == NULL)
6952                 return -1;
6953
6954         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
6955         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
6956         nla_put_nested(msg, NL80211_ATTR_CQM, cqm);
6957
6958         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
6959                 return 0;
6960         msg = NULL;
6961
6962 nla_put_failure:
6963         if (cqm)
6964                 nlmsg_free(cqm);
6965         nlmsg_free(msg);
6966         return -1;
6967 }
6968
6969
6970 static int nl80211_signal_poll(void *priv, struct wpa_signal_info *si)
6971 {
6972         struct i802_bss *bss = priv;
6973         struct wpa_driver_nl80211_data *drv = bss->drv;
6974         int res;
6975
6976         os_memset(si, 0, sizeof(*si));
6977         res = nl80211_get_link_signal(drv, si);
6978         if (res != 0)
6979                 return res;
6980
6981         return nl80211_get_link_noise(drv, si);
6982 }
6983
6984
6985 static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
6986                               int encrypt)
6987 {
6988         struct i802_bss *bss = priv;
6989         struct wpa_driver_nl80211_data *drv = bss->drv;
6990         return wpa_driver_nl80211_send_frame(drv, data, data_len, encrypt);
6991 }
6992
6993
6994 static int nl80211_set_intra_bss(void *priv, int enabled)
6995 {
6996         struct i802_bss *bss = priv;
6997         struct wpa_driver_nl80211_data *drv = bss->drv;
6998         struct nl_msg *msg;
6999
7000         msg = nlmsg_alloc();
7001         if (!msg)
7002                 return -ENOMEM;
7003
7004         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
7005                     NL80211_CMD_SET_BSS, 0);
7006
7007         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7008         NLA_PUT_U8(msg, NL80211_ATTR_AP_ISOLATE, !enabled);
7009
7010         return send_and_recv_msgs(drv, msg, NULL, NULL);
7011  nla_put_failure:
7012         return -ENOBUFS;
7013 }
7014
7015
7016 static int nl80211_set_param(void *priv, const char *param)
7017 {
7018         wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
7019         if (param == NULL)
7020                 return 0;
7021
7022 #ifdef CONFIG_P2P
7023         if (os_strstr(param, "use_p2p_group_interface=1")) {
7024                 struct i802_bss *bss = priv;
7025                 struct wpa_driver_nl80211_data *drv = bss->drv;
7026
7027                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
7028                            "interface");
7029                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
7030                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
7031         }
7032 #endif /* CONFIG_P2P */
7033
7034         return 0;
7035 }
7036
7037
7038 static void * nl80211_global_init(void)
7039 {
7040         struct nl80211_global *global;
7041         global = os_zalloc(sizeof(*global));
7042         if (global == NULL)
7043                 return NULL;
7044         dl_list_init(&global->interfaces);
7045         global->if_add_ifindex = -1;
7046         return global;
7047 }
7048
7049
7050 static void nl80211_global_deinit(void *priv)
7051 {
7052         struct nl80211_global *global = priv;
7053         if (global == NULL)
7054                 return;
7055         if (!dl_list_empty(&global->interfaces)) {
7056                 wpa_printf(MSG_ERROR, "nl80211: %u interface(s) remain at "
7057                            "nl80211_global_deinit",
7058                            dl_list_len(&global->interfaces));
7059         }
7060         os_free(global);
7061 }
7062
7063
7064 static const char * nl80211_get_radio_name(void *priv)
7065 {
7066         struct i802_bss *bss = priv;
7067         struct wpa_driver_nl80211_data *drv = bss->drv;
7068         return drv->phyname;
7069 }
7070
7071
7072 static int nl80211_pmkid(struct i802_bss *bss, int cmd, const u8 *bssid,
7073                          const u8 *pmkid)
7074 {
7075         struct nl_msg *msg;
7076
7077         msg = nlmsg_alloc();
7078         if (!msg)
7079                 return -ENOMEM;
7080
7081         genlmsg_put(msg, 0, 0, genl_family_get_id(bss->drv->nl80211), 0, 0,
7082                     cmd, 0);
7083
7084         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7085         if (pmkid)
7086                 NLA_PUT(msg, NL80211_ATTR_PMKID, 16, pmkid);
7087         if (bssid)
7088                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
7089
7090         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
7091  nla_put_failure:
7092         return -ENOBUFS;
7093 }
7094
7095
7096 static int nl80211_add_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
7097 {
7098         struct i802_bss *bss = priv;
7099         wpa_printf(MSG_DEBUG, "nl80211: Add PMKID for " MACSTR, MAC2STR(bssid));
7100         return nl80211_pmkid(bss, NL80211_CMD_SET_PMKSA, bssid, pmkid);
7101 }
7102
7103
7104 static int nl80211_remove_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
7105 {
7106         struct i802_bss *bss = priv;
7107         wpa_printf(MSG_DEBUG, "nl80211: Delete PMKID for " MACSTR,
7108                    MAC2STR(bssid));
7109         return nl80211_pmkid(bss, NL80211_CMD_DEL_PMKSA, bssid, pmkid);
7110 }
7111
7112
7113 static int nl80211_flush_pmkid(void *priv)
7114 {
7115         struct i802_bss *bss = priv;
7116         wpa_printf(MSG_DEBUG, "nl80211: Flush PMKIDs");
7117         return nl80211_pmkid(bss, NL80211_CMD_FLUSH_PMKSA, NULL, NULL);
7118 }
7119
7120
7121 static void nl80211_set_rekey_info(void *priv, const u8 *kek, const u8 *kck,
7122                                    const u8 *replay_ctr)
7123 {
7124         struct i802_bss *bss = priv;
7125         struct wpa_driver_nl80211_data *drv = bss->drv;
7126         struct nlattr *replay_nested;
7127         struct nl_msg *msg;
7128
7129         msg = nlmsg_alloc();
7130         if (!msg)
7131                 return;
7132
7133         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
7134                     NL80211_CMD_SET_REKEY_OFFLOAD, 0);
7135
7136         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
7137
7138         replay_nested = nla_nest_start(msg, NL80211_ATTR_REKEY_DATA);
7139         if (!replay_nested)
7140                 goto nla_put_failure;
7141
7142         NLA_PUT(msg, NL80211_REKEY_DATA_KEK, NL80211_KEK_LEN, kek);
7143         NLA_PUT(msg, NL80211_REKEY_DATA_KCK, NL80211_KCK_LEN, kck);
7144         NLA_PUT(msg, NL80211_REKEY_DATA_REPLAY_CTR, NL80211_REPLAY_CTR_LEN,
7145                 replay_ctr);
7146
7147         nla_nest_end(msg, replay_nested);
7148
7149         send_and_recv_msgs(drv, msg, NULL, NULL);
7150         return;
7151  nla_put_failure:
7152         nlmsg_free(msg);
7153 }
7154
7155
7156 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
7157         .name = "nl80211",
7158         .desc = "Linux nl80211/cfg80211",
7159         .get_bssid = wpa_driver_nl80211_get_bssid,
7160         .get_ssid = wpa_driver_nl80211_get_ssid,
7161         .set_key = wpa_driver_nl80211_set_key,
7162         .scan2 = wpa_driver_nl80211_scan,
7163         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
7164         .deauthenticate = wpa_driver_nl80211_deauthenticate,
7165         .disassociate = wpa_driver_nl80211_disassociate,
7166         .authenticate = wpa_driver_nl80211_authenticate,
7167         .associate = wpa_driver_nl80211_associate,
7168         .global_init = nl80211_global_init,
7169         .global_deinit = nl80211_global_deinit,
7170         .init2 = wpa_driver_nl80211_init,
7171         .deinit = wpa_driver_nl80211_deinit,
7172         .get_capa = wpa_driver_nl80211_get_capa,
7173         .set_operstate = wpa_driver_nl80211_set_operstate,
7174         .set_supp_port = wpa_driver_nl80211_set_supp_port,
7175         .set_country = wpa_driver_nl80211_set_country,
7176         .set_ap = wpa_driver_nl80211_set_ap,
7177         .if_add = wpa_driver_nl80211_if_add,
7178         .if_remove = wpa_driver_nl80211_if_remove,
7179         .send_mlme = wpa_driver_nl80211_send_mlme,
7180         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
7181         .sta_add = wpa_driver_nl80211_sta_add,
7182         .sta_remove = wpa_driver_nl80211_sta_remove,
7183         .hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
7184         .sta_set_flags = wpa_driver_nl80211_sta_set_flags,
7185 #ifdef HOSTAPD
7186         .hapd_init = i802_init,
7187         .hapd_deinit = i802_deinit,
7188         .set_wds_sta = i802_set_wds_sta,
7189 #endif /* HOSTAPD */
7190 #if defined(HOSTAPD) || defined(CONFIG_AP)
7191         .get_seqnum = i802_get_seqnum,
7192         .flush = i802_flush,
7193         .read_sta_data = i802_read_sta_data,
7194         .get_inact_sec = i802_get_inact_sec,
7195         .sta_clear_stats = i802_sta_clear_stats,
7196         .set_rts = i802_set_rts,
7197         .set_frag = i802_set_frag,
7198         .set_cts_protect = i802_set_cts_protect,
7199         .set_preamble = i802_set_preamble,
7200         .set_short_slot_time = i802_set_short_slot_time,
7201         .set_tx_queue_params = i802_set_tx_queue_params,
7202         .set_sta_vlan = i802_set_sta_vlan,
7203         .set_ht_params = i802_set_ht_params,
7204         .set_rate_sets = i802_set_rate_sets,
7205         .sta_deauth = i802_sta_deauth,
7206         .sta_disassoc = i802_sta_disassoc,
7207 #endif /* HOSTAPD || CONFIG_AP */
7208         .set_freq = i802_set_freq,
7209         .send_action = wpa_driver_nl80211_send_action,
7210         .send_action_cancel_wait = wpa_driver_nl80211_send_action_cancel_wait,
7211         .remain_on_channel = wpa_driver_nl80211_remain_on_channel,
7212         .cancel_remain_on_channel =
7213         wpa_driver_nl80211_cancel_remain_on_channel,
7214         .probe_req_report = wpa_driver_nl80211_probe_req_report,
7215         .disable_11b_rates = wpa_driver_nl80211_disable_11b_rates,
7216         .deinit_ap = wpa_driver_nl80211_deinit_ap,
7217         .resume = wpa_driver_nl80211_resume,
7218         .send_ft_action = nl80211_send_ft_action,
7219         .signal_monitor = nl80211_signal_monitor,
7220         .signal_poll = nl80211_signal_poll,
7221         .send_frame = nl80211_send_frame,
7222         .set_intra_bss = nl80211_set_intra_bss,
7223         .set_param = nl80211_set_param,
7224         .get_radio_name = nl80211_get_radio_name,
7225         .add_pmkid = nl80211_add_pmkid,
7226         .remove_pmkid = nl80211_remove_pmkid,
7227         .flush_pmkid = nl80211_flush_pmkid,
7228         .set_rekey_info = nl80211_set_rekey_info,
7229 };