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