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