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