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