]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - build-utilities/hostap.git/blob - src/drivers/driver_nl80211.c
nl80211: Fix NL80211_CMD_FRAME to not try offchannel without driver support
[build-utilities/hostap.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  */
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 <linux/errqueue.h>
32 #include "nl80211_copy.h"
34 #include "common.h"
35 #include "eloop.h"
36 #include "utils/list.h"
37 #include "common/ieee802_11_defs.h"
38 #include "common/ieee802_11_common.h"
39 #include "l2_packet/l2_packet.h"
40 #include "netlink.h"
41 #include "linux_ioctl.h"
42 #include "radiotap.h"
43 #include "radiotap_iter.h"
44 #include "rfkill.h"
45 #include "driver.h"
47 #ifndef SO_WIFI_STATUS
48 # if defined(__sparc__)
49 #  define SO_WIFI_STATUS        0x0025
50 # elif defined(__parisc__)
51 #  define SO_WIFI_STATUS        0x4022
52 # else
53 #  define SO_WIFI_STATUS        41
54 # endif
56 # define SCM_WIFI_STATUS        SO_WIFI_STATUS
57 #endif
59 #ifndef SO_EE_ORIGIN_TXSTATUS
60 #define SO_EE_ORIGIN_TXSTATUS   4
61 #endif
63 #ifndef PACKET_TX_TIMESTAMP
64 #define PACKET_TX_TIMESTAMP     16
65 #endif
67 #ifdef ANDROID
68 #include "android_drv.h"
69 #endif /* ANDROID */
70 #ifdef CONFIG_LIBNL20
71 /* libnl 2.0 compatibility code */
72 #define nl_handle nl_sock
73 #define nl80211_handle_alloc nl_socket_alloc_cb
74 #define nl80211_handle_destroy nl_socket_free
75 #else
76 /*
77  * libnl 1.1 has a bug, it tries to allocate socket numbers densely
78  * but when you free a socket again it will mess up its bitmap and
79  * and use the wrong number the next time it needs a socket ID.
80  * Therefore, we wrap the handle alloc/destroy and add our own pid
81  * accounting.
82  */
83 static uint32_t port_bitmap[32] = { 0 };
85 static struct nl_handle *nl80211_handle_alloc(void *cb)
86 {
87         struct nl_handle *handle;
88         uint32_t pid = getpid() & 0x3FFFFF;
89         int i;
91         handle = nl_handle_alloc_cb(cb);
93         for (i = 0; i < 1024; i++) {
94                 if (port_bitmap[i / 32] & (1 << (i % 32)))
95                         continue;
96                 port_bitmap[i / 32] |= 1 << (i % 32);
97                 pid += i << 22;
98                 break;
99         }
101         nl_socket_set_local_port(handle, pid);
103         return handle;
106 static void nl80211_handle_destroy(struct nl_handle *handle)
108         uint32_t port = nl_socket_get_local_port(handle);
110         port >>= 22;
111         port_bitmap[port / 32] &= ~(1 << (port % 32));
113         nl_handle_destroy(handle);
115 #endif /* CONFIG_LIBNL20 */
118 static struct nl_handle * nl_create_handle(struct nl_cb *cb, const char *dbg)
120         struct nl_handle *handle;
122         handle = nl80211_handle_alloc(cb);
123         if (handle == NULL) {
124                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
125                            "callbacks (%s)", dbg);
126                 return NULL;
127         }
129         if (genl_connect(handle)) {
130                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
131                            "netlink (%s)", dbg);
132                 nl80211_handle_destroy(handle);
133                 return NULL;
134         }
136         return handle;
140 static void nl_destroy_handles(struct nl_handle **handle)
142         if (*handle == NULL)
143                 return;
144         nl80211_handle_destroy(*handle);
145         *handle = NULL;
149 #ifndef IFF_LOWER_UP
150 #define IFF_LOWER_UP   0x10000         /* driver signals L1 up         */
151 #endif
152 #ifndef IFF_DORMANT
153 #define IFF_DORMANT    0x20000         /* driver signals dormant       */
154 #endif
156 #ifndef IF_OPER_DORMANT
157 #define IF_OPER_DORMANT 5
158 #endif
159 #ifndef IF_OPER_UP
160 #define IF_OPER_UP 6
161 #endif
163 struct nl80211_global {
164         struct dl_list interfaces;
165         int if_add_ifindex;
166         struct netlink_data *netlink;
167         struct nl_cb *nl_cb;
168         struct nl_handle *nl;
169         int nl80211_id;
170         int ioctl_sock; /* socket for ioctl() use */
172         struct nl_handle *nl_event;
173 };
175 struct nl80211_wiphy_data {
176         struct dl_list list;
177         struct dl_list bsss;
178         struct dl_list drvs;
180         struct nl_handle *nl_beacons;
181         struct nl_cb *nl_cb;
183         int wiphy_idx;
184 };
186 static void nl80211_global_deinit(void *priv);
187 static void wpa_driver_nl80211_deinit(void *priv);
189 struct i802_bss {
190         struct wpa_driver_nl80211_data *drv;
191         struct i802_bss *next;
192         int ifindex;
193         char ifname[IFNAMSIZ + 1];
194         char brname[IFNAMSIZ];
195         unsigned int beacon_set:1;
196         unsigned int added_if_into_bridge:1;
197         unsigned int added_bridge:1;
199         u8 addr[ETH_ALEN];
201         int freq;
203         struct nl_handle *nl_preq, *nl_mgmt;
204         struct nl_cb *nl_cb;
206         struct nl80211_wiphy_data *wiphy_data;
207         struct dl_list wiphy_list;
208 };
210 struct wpa_driver_nl80211_data {
211         struct nl80211_global *global;
212         struct dl_list list;
213         struct dl_list wiphy_list;
214         char phyname[32];
215         void *ctx;
216         int ifindex;
217         int if_removed;
218         int if_disabled;
219         int ignore_if_down_event;
220         struct rfkill_data *rfkill;
221         struct wpa_driver_capa capa;
222         int has_capability;
224         int operstate;
226         int scan_complete_events;
228         struct nl_cb *nl_cb;
230         u8 auth_bssid[ETH_ALEN];
231         u8 bssid[ETH_ALEN];
232         int associated;
233         u8 ssid[32];
234         size_t ssid_len;
235         enum nl80211_iftype nlmode;
236         enum nl80211_iftype ap_scan_as_station;
237         unsigned int assoc_freq;
239         int monitor_sock;
240         int monitor_ifidx;
241         int monitor_refcount;
243         unsigned int disabled_11b_rates:1;
244         unsigned int pending_remain_on_chan:1;
245         unsigned int in_interface_list:1;
246         unsigned int device_ap_sme:1;
247         unsigned int poll_command_supported:1;
248         unsigned int data_tx_status:1;
249         unsigned int scan_for_auth:1;
250         unsigned int retry_auth:1;
251         unsigned int use_monitor:1;
253         u64 remain_on_chan_cookie;
254         u64 send_action_cookie;
256         unsigned int last_mgmt_freq;
258         struct wpa_driver_scan_filter *filter_ssids;
259         size_t num_filter_ssids;
261         struct i802_bss first_bss;
263         int eapol_tx_sock;
265 #ifdef HOSTAPD
266         int eapol_sock; /* socket for EAPOL frames */
268         int default_if_indices[16];
269         int *if_indices;
270         int num_if_indices;
272         int last_freq;
273         int last_freq_ht;
274 #endif /* HOSTAPD */
276         /* From failed authentication command */
277         int auth_freq;
278         u8 auth_bssid_[ETH_ALEN];
279         u8 auth_ssid[32];
280         size_t auth_ssid_len;
281         int auth_alg;
282         u8 *auth_ie;
283         size_t auth_ie_len;
284         u8 auth_wep_key[4][16];
285         size_t auth_wep_key_len[4];
286         int auth_wep_tx_keyidx;
287         int auth_local_state_change;
288         int auth_p2p;
289 };
292 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx,
293                                             void *timeout_ctx);
294 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
295                                        enum nl80211_iftype nlmode);
296 static int
297 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv);
298 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
299                                    const u8 *addr, int cmd, u16 reason_code,
300                                    int local_state_change);
301 static void nl80211_remove_monitor_interface(
302         struct wpa_driver_nl80211_data *drv);
303 static int nl80211_send_frame_cmd(struct i802_bss *bss,
304                                   unsigned int freq, unsigned int wait,
305                                   const u8 *buf, size_t buf_len, u64 *cookie,
306                                   int no_cck, int no_ack, int offchanok);
307 static int wpa_driver_nl80211_probe_req_report(void *priv, int report);
308 #ifdef ANDROID
309 static int android_pno_start(struct i802_bss *bss,
310                              struct wpa_driver_scan_params *params);
311 static int android_pno_stop(struct i802_bss *bss);
312 #endif /* ANDROID */
314 #ifdef HOSTAPD
315 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
316 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
317 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
318 static int wpa_driver_nl80211_if_remove(void *priv,
319                                         enum wpa_driver_if_type type,
320                                         const char *ifname);
321 #else /* HOSTAPD */
322 static inline void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
326 static inline void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
330 static inline int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
332         return 0;
334 #endif /* HOSTAPD */
336 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq);
337 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
338                                      int ifindex, int disabled);
340 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv);
341 static int wpa_driver_nl80211_authenticate_retry(
342         struct wpa_driver_nl80211_data *drv);
345 static int is_ap_interface(enum nl80211_iftype nlmode)
347         return (nlmode == NL80211_IFTYPE_AP ||
348                 nlmode == NL80211_IFTYPE_P2P_GO);
352 static int is_sta_interface(enum nl80211_iftype nlmode)
354         return (nlmode == NL80211_IFTYPE_STATION ||
355                 nlmode == NL80211_IFTYPE_P2P_CLIENT);
359 static int is_p2p_interface(enum nl80211_iftype nlmode)
361         return (nlmode == NL80211_IFTYPE_P2P_CLIENT ||
362                 nlmode == NL80211_IFTYPE_P2P_GO);
366 struct nl80211_bss_info_arg {
367         struct wpa_driver_nl80211_data *drv;
368         struct wpa_scan_results *res;
369         unsigned int assoc_freq;
370         u8 assoc_bssid[ETH_ALEN];
371 };
373 static int bss_info_handler(struct nl_msg *msg, void *arg);
376 /* nl80211 code */
377 static int ack_handler(struct nl_msg *msg, void *arg)
379         int *err = arg;
380         *err = 0;
381         return NL_STOP;
384 static int finish_handler(struct nl_msg *msg, void *arg)
386         int *ret = arg;
387         *ret = 0;
388         return NL_SKIP;
391 static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err,
392                          void *arg)
394         int *ret = arg;
395         *ret = err->error;
396         return NL_SKIP;
400 static int no_seq_check(struct nl_msg *msg, void *arg)
402         return NL_OK;
406 static int send_and_recv(struct nl80211_global *global,
407                          struct nl_handle *nl_handle, struct nl_msg *msg,
408                          int (*valid_handler)(struct nl_msg *, void *),
409                          void *valid_data)
411         struct nl_cb *cb;
412         int err = -ENOMEM;
414         cb = nl_cb_clone(global->nl_cb);
415         if (!cb)
416                 goto out;
418         err = nl_send_auto_complete(nl_handle, msg);
419         if (err < 0)
420                 goto out;
422         err = 1;
424         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
425         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
426         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
428         if (valid_handler)
429                 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM,
430                           valid_handler, valid_data);
432         while (err > 0)
433                 nl_recvmsgs(nl_handle, cb);
434  out:
435         nl_cb_put(cb);
436         nlmsg_free(msg);
437         return err;
441 static int send_and_recv_msgs_global(struct nl80211_global *global,
442                                      struct nl_msg *msg,
443                                      int (*valid_handler)(struct nl_msg *, void *),
444                                      void *valid_data)
446         return send_and_recv(global, global->nl, msg, valid_handler,
447                              valid_data);
451 static int send_and_recv_msgs(struct wpa_driver_nl80211_data *drv,
452                               struct nl_msg *msg,
453                               int (*valid_handler)(struct nl_msg *, void *),
454                               void *valid_data)
456         return send_and_recv(drv->global, drv->global->nl, msg,
457                              valid_handler, valid_data);
461 struct family_data {
462         const char *group;
463         int id;
464 };
467 static int family_handler(struct nl_msg *msg, void *arg)
469         struct family_data *res = arg;
470         struct nlattr *tb[CTRL_ATTR_MAX + 1];
471         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
472         struct nlattr *mcgrp;
473         int i;
475         nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
476                   genlmsg_attrlen(gnlh, 0), NULL);
477         if (!tb[CTRL_ATTR_MCAST_GROUPS])
478                 return NL_SKIP;
480         nla_for_each_nested(mcgrp, tb[CTRL_ATTR_MCAST_GROUPS], i) {
481                 struct nlattr *tb2[CTRL_ATTR_MCAST_GRP_MAX + 1];
482                 nla_parse(tb2, CTRL_ATTR_MCAST_GRP_MAX, nla_data(mcgrp),
483                           nla_len(mcgrp), NULL);
484                 if (!tb2[CTRL_ATTR_MCAST_GRP_NAME] ||
485                     !tb2[CTRL_ATTR_MCAST_GRP_ID] ||
486                     os_strncmp(nla_data(tb2[CTRL_ATTR_MCAST_GRP_NAME]),
487                                res->group,
488                                nla_len(tb2[CTRL_ATTR_MCAST_GRP_NAME])) != 0)
489                         continue;
490                 res->id = nla_get_u32(tb2[CTRL_ATTR_MCAST_GRP_ID]);
491                 break;
492         };
494         return NL_SKIP;
498 static int nl_get_multicast_id(struct nl80211_global *global,
499                                const char *family, const char *group)
501         struct nl_msg *msg;
502         int ret = -1;
503         struct family_data res = { group, -ENOENT };
505         msg = nlmsg_alloc();
506         if (!msg)
507                 return -ENOMEM;
508         genlmsg_put(msg, 0, 0, genl_ctrl_resolve(global->nl, "nlctrl"),
509                     0, 0, CTRL_CMD_GETFAMILY, 0);
510         NLA_PUT_STRING(msg, CTRL_ATTR_FAMILY_NAME, family);
512         ret = send_and_recv_msgs_global(global, msg, family_handler, &res);
513         msg = NULL;
514         if (ret == 0)
515                 ret = res.id;
517 nla_put_failure:
518         nlmsg_free(msg);
519         return ret;
523 static void * nl80211_cmd(struct wpa_driver_nl80211_data *drv,
524                           struct nl_msg *msg, int flags, uint8_t cmd)
526         return genlmsg_put(msg, 0, 0, drv->global->nl80211_id,
527                            0, flags, cmd, 0);
531 struct wiphy_idx_data {
532         int wiphy_idx;
533 };
536 static int netdev_info_handler(struct nl_msg *msg, void *arg)
538         struct nlattr *tb[NL80211_ATTR_MAX + 1];
539         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
540         struct wiphy_idx_data *info = arg;
542         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
543                   genlmsg_attrlen(gnlh, 0), NULL);
545         if (tb[NL80211_ATTR_WIPHY])
546                 info->wiphy_idx = nla_get_u32(tb[NL80211_ATTR_WIPHY]);
548         return NL_SKIP;
552 static int nl80211_get_wiphy_index(struct i802_bss *bss)
554         struct nl_msg *msg;
555         struct wiphy_idx_data data = {
556                 .wiphy_idx = -1,
557         };
559         msg = nlmsg_alloc();
560         if (!msg)
561                 return -1;
563         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_GET_INTERFACE);
565         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
567         if (send_and_recv_msgs(bss->drv, msg, netdev_info_handler, &data) == 0)
568                 return data.wiphy_idx;
569         msg = NULL;
570 nla_put_failure:
571         nlmsg_free(msg);
572         return -1;
576 static int nl80211_register_beacons(struct wpa_driver_nl80211_data *drv,
577                                     struct nl80211_wiphy_data *w)
579         struct nl_msg *msg;
580         int ret = -1;
582         msg = nlmsg_alloc();
583         if (!msg)
584                 return -1;
586         nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_BEACONS);
588         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, w->wiphy_idx);
590         ret = send_and_recv(drv->global, w->nl_beacons, msg, NULL, NULL);
591         msg = NULL;
592         if (ret) {
593                 wpa_printf(MSG_DEBUG, "nl80211: Register beacons command "
594                            "failed: ret=%d (%s)",
595                            ret, strerror(-ret));
596                 goto nla_put_failure;
597         }
598         ret = 0;
599 nla_put_failure:
600         nlmsg_free(msg);
601         return ret;
605 static void nl80211_recv_beacons(int sock, void *eloop_ctx, void *handle)
607         struct nl80211_wiphy_data *w = eloop_ctx;
609         wpa_printf(MSG_DEBUG, "nl80211: Beacon event message available");
611         nl_recvmsgs(handle, w->nl_cb);
615 static int process_beacon_event(struct nl_msg *msg, void *arg)
617         struct nl80211_wiphy_data *w = arg;
618         struct wpa_driver_nl80211_data *drv;
619         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
620         struct nlattr *tb[NL80211_ATTR_MAX + 1];
621         union wpa_event_data event;
623         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
624                   genlmsg_attrlen(gnlh, 0), NULL);
626         if (gnlh->cmd != NL80211_CMD_FRAME) {
627                 wpa_printf(MSG_DEBUG, "nl80211: Unexpected beacon event? (%d)",
628                            gnlh->cmd);
629                 return NL_SKIP;
630         }
632         if (!tb[NL80211_ATTR_FRAME])
633                 return NL_SKIP;
635         dl_list_for_each(drv, &w->drvs, struct wpa_driver_nl80211_data,
636                          wiphy_list) {
637                 os_memset(&event, 0, sizeof(event));
638                 event.rx_mgmt.frame = nla_data(tb[NL80211_ATTR_FRAME]);
639                 event.rx_mgmt.frame_len = nla_len(tb[NL80211_ATTR_FRAME]);
640                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
641         }
643         return NL_SKIP;
647 static struct nl80211_wiphy_data *
648 nl80211_get_wiphy_data_ap(struct i802_bss *bss)
650         static DEFINE_DL_LIST(nl80211_wiphys);
651         struct nl80211_wiphy_data *w;
652         int wiphy_idx, found = 0;
653         struct i802_bss *tmp_bss;
655         if (bss->wiphy_data != NULL)
656                 return bss->wiphy_data;
658         wiphy_idx = nl80211_get_wiphy_index(bss);
660         dl_list_for_each(w, &nl80211_wiphys, struct nl80211_wiphy_data, list) {
661                 if (w->wiphy_idx == wiphy_idx)
662                         goto add;
663         }
665         /* alloc new one */
666         w = os_zalloc(sizeof(*w));
667         if (w == NULL)
668                 return NULL;
669         w->wiphy_idx = wiphy_idx;
670         dl_list_init(&w->bsss);
671         dl_list_init(&w->drvs);
673         w->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
674         if (!w->nl_cb) {
675                 os_free(w);
676                 return NULL;
677         }
678         nl_cb_set(w->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, no_seq_check, NULL);
679         nl_cb_set(w->nl_cb, NL_CB_VALID, NL_CB_CUSTOM, process_beacon_event,
680                   w);
682         w->nl_beacons = nl_create_handle(bss->drv->global->nl_cb,
683                                          "wiphy beacons");
684         if (w->nl_beacons == NULL) {
685                 os_free(w);
686                 return NULL;
687         }
689         if (nl80211_register_beacons(bss->drv, w)) {
690                 nl_destroy_handles(&w->nl_beacons);
691                 os_free(w);
692                 return NULL;
693         }
695         eloop_register_read_sock(nl_socket_get_fd(w->nl_beacons),
696                                  nl80211_recv_beacons, w, w->nl_beacons);
698         dl_list_add(&nl80211_wiphys, &w->list);
700 add:
701         /* drv entry for this bss already there? */
702         dl_list_for_each(tmp_bss, &w->bsss, struct i802_bss, wiphy_list) {
703                 if (tmp_bss->drv == bss->drv) {
704                         found = 1;
705                         break;
706                 }
707         }
708         /* if not add it */
709         if (!found)
710                 dl_list_add(&w->drvs, &bss->drv->wiphy_list);
712         dl_list_add(&w->bsss, &bss->wiphy_list);
713         bss->wiphy_data = w;
714         return w;
718 static void nl80211_put_wiphy_data_ap(struct i802_bss *bss)
720         struct nl80211_wiphy_data *w = bss->wiphy_data;
721         struct i802_bss *tmp_bss;
722         int found = 0;
724         if (w == NULL)
725                 return;
726         bss->wiphy_data = NULL;
727         dl_list_del(&bss->wiphy_list);
729         /* still any for this drv present? */
730         dl_list_for_each(tmp_bss, &w->bsss, struct i802_bss, wiphy_list) {
731                 if (tmp_bss->drv == bss->drv) {
732                         found = 1;
733                         break;
734                 }
735         }
736         /* if not remove it */
737         if (!found)
738                 dl_list_del(&bss->drv->wiphy_list);
740         if (!dl_list_empty(&w->bsss))
741                 return;
743         eloop_unregister_read_sock(nl_socket_get_fd(w->nl_beacons));
745         nl_cb_put(w->nl_cb);
746         nl_destroy_handles(&w->nl_beacons);
747         dl_list_del(&w->list);
748         os_free(w);
752 static int wpa_driver_nl80211_get_bssid(void *priv, u8 *bssid)
754         struct i802_bss *bss = priv;
755         struct wpa_driver_nl80211_data *drv = bss->drv;
756         if (!drv->associated)
757                 return -1;
758         os_memcpy(bssid, drv->bssid, ETH_ALEN);
759         return 0;
763 static int wpa_driver_nl80211_get_ssid(void *priv, u8 *ssid)
765         struct i802_bss *bss = priv;
766         struct wpa_driver_nl80211_data *drv = bss->drv;
767         if (!drv->associated)
768                 return -1;
769         os_memcpy(ssid, drv->ssid, drv->ssid_len);
770         return drv->ssid_len;
774 static void wpa_driver_nl80211_event_link(struct wpa_driver_nl80211_data *drv,
775                                           char *buf, size_t len, int del)
777         union wpa_event_data event;
779         os_memset(&event, 0, sizeof(event));
780         if (len > sizeof(event.interface_status.ifname))
781                 len = sizeof(event.interface_status.ifname) - 1;
782         os_memcpy(event.interface_status.ifname, buf, len);
783         event.interface_status.ievent = del ? EVENT_INTERFACE_REMOVED :
784                 EVENT_INTERFACE_ADDED;
786         wpa_printf(MSG_DEBUG, "RTM_%sLINK, IFLA_IFNAME: Interface '%s' %s",
787                    del ? "DEL" : "NEW",
788                    event.interface_status.ifname,
789                    del ? "removed" : "added");
791         if (os_strcmp(drv->first_bss.ifname, event.interface_status.ifname) == 0) {
792                 if (del)
793                         drv->if_removed = 1;
794                 else
795                         drv->if_removed = 0;
796         }
798         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_STATUS, &event);
802 static int wpa_driver_nl80211_own_ifname(struct wpa_driver_nl80211_data *drv,
803                                          u8 *buf, size_t len)
805         int attrlen, rta_len;
806         struct rtattr *attr;
808         attrlen = len;
809         attr = (struct rtattr *) buf;
811         rta_len = RTA_ALIGN(sizeof(struct rtattr));
812         while (RTA_OK(attr, attrlen)) {
813                 if (attr->rta_type == IFLA_IFNAME) {
814                         if (os_strcmp(((char *) attr) + rta_len, drv->first_bss.ifname)
815                             == 0)
816                                 return 1;
817                         else
818                                 break;
819                 }
820                 attr = RTA_NEXT(attr, attrlen);
821         }
823         return 0;
827 static int wpa_driver_nl80211_own_ifindex(struct wpa_driver_nl80211_data *drv,
828                                           int ifindex, u8 *buf, size_t len)
830         if (drv->ifindex == ifindex)
831                 return 1;
833         if (drv->if_removed && wpa_driver_nl80211_own_ifname(drv, buf, len)) {
834                 drv->first_bss.ifindex = if_nametoindex(drv->first_bss.ifname);
835                 wpa_printf(MSG_DEBUG, "nl80211: Update ifindex for a removed "
836                            "interface");
837                 wpa_driver_nl80211_finish_drv_init(drv);
838                 return 1;
839         }
841         return 0;
845 static struct wpa_driver_nl80211_data *
846 nl80211_find_drv(struct nl80211_global *global, int idx, u8 *buf, size_t len)
848         struct wpa_driver_nl80211_data *drv;
849         dl_list_for_each(drv, &global->interfaces,
850                          struct wpa_driver_nl80211_data, list) {
851                 if (wpa_driver_nl80211_own_ifindex(drv, idx, buf, len) ||
852                     have_ifidx(drv, idx))
853                         return drv;
854         }
855         return NULL;
859 static void wpa_driver_nl80211_event_rtm_newlink(void *ctx,
860                                                  struct ifinfomsg *ifi,
861                                                  u8 *buf, size_t len)
863         struct nl80211_global *global = ctx;
864         struct wpa_driver_nl80211_data *drv;
865         int attrlen, rta_len;
866         struct rtattr *attr;
867         u32 brid = 0;
868         char namebuf[IFNAMSIZ];
870         drv = nl80211_find_drv(global, ifi->ifi_index, buf, len);
871         if (!drv) {
872                 wpa_printf(MSG_DEBUG, "nl80211: Ignore event for foreign "
873                            "ifindex %d", ifi->ifi_index);
874                 return;
875         }
877         wpa_printf(MSG_DEBUG, "RTM_NEWLINK: operstate=%d ifi_flags=0x%x "
878                    "(%s%s%s%s)",
879                    drv->operstate, ifi->ifi_flags,
880                    (ifi->ifi_flags & IFF_UP) ? "[UP]" : "",
881                    (ifi->ifi_flags & IFF_RUNNING) ? "[RUNNING]" : "",
882                    (ifi->ifi_flags & IFF_LOWER_UP) ? "[LOWER_UP]" : "",
883                    (ifi->ifi_flags & IFF_DORMANT) ? "[DORMANT]" : "");
885         if (!drv->if_disabled && !(ifi->ifi_flags & IFF_UP)) {
886                 if (if_indextoname(ifi->ifi_index, namebuf) &&
887                     linux_iface_up(drv->global->ioctl_sock,
888                                    drv->first_bss.ifname) > 0) {
889                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface down "
890                                    "event since interface %s is up", namebuf);
891                         return;
892                 }
893                 wpa_printf(MSG_DEBUG, "nl80211: Interface down");
894                 if (drv->ignore_if_down_event) {
895                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface down "
896                                    "event generated by mode change");
897                         drv->ignore_if_down_event = 0;
898                 } else {
899                         drv->if_disabled = 1;
900                         wpa_supplicant_event(drv->ctx,
901                                              EVENT_INTERFACE_DISABLED, NULL);
902                 }
903         }
905         if (drv->if_disabled && (ifi->ifi_flags & IFF_UP)) {
906                 if (if_indextoname(ifi->ifi_index, namebuf) &&
907                     linux_iface_up(drv->global->ioctl_sock,
908                                    drv->first_bss.ifname) == 0) {
909                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
910                                    "event since interface %s is down",
911                                    namebuf);
912                 } else {
913                         wpa_printf(MSG_DEBUG, "nl80211: Interface up");
914                         drv->if_disabled = 0;
915                         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_ENABLED,
916                                              NULL);
917                 }
918         }
920         /*
921          * Some drivers send the association event before the operup event--in
922          * this case, lifting operstate in wpa_driver_nl80211_set_operstate()
923          * fails. This will hit us when wpa_supplicant does not need to do
924          * IEEE 802.1X authentication
925          */
926         if (drv->operstate == 1 &&
927             (ifi->ifi_flags & (IFF_LOWER_UP | IFF_DORMANT)) == IFF_LOWER_UP &&
928             !(ifi->ifi_flags & IFF_RUNNING))
929                 netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
930                                        -1, IF_OPER_UP);
932         attrlen = len;
933         attr = (struct rtattr *) buf;
934         rta_len = RTA_ALIGN(sizeof(struct rtattr));
935         while (RTA_OK(attr, attrlen)) {
936                 if (attr->rta_type == IFLA_IFNAME) {
937                         wpa_driver_nl80211_event_link(
938                                 drv,
939                                 ((char *) attr) + rta_len,
940                                 attr->rta_len - rta_len, 0);
941                 } else if (attr->rta_type == IFLA_MASTER)
942                         brid = nla_get_u32((struct nlattr *) attr);
943                 attr = RTA_NEXT(attr, attrlen);
944         }
946         if (ifi->ifi_family == AF_BRIDGE && brid) {
947                 /* device has been added to bridge */
948                 if_indextoname(brid, namebuf);
949                 wpa_printf(MSG_DEBUG, "nl80211: Add ifindex %u for bridge %s",
950                            brid, namebuf);
951                 add_ifidx(drv, brid);
952         }
956 static void wpa_driver_nl80211_event_rtm_dellink(void *ctx,
957                                                  struct ifinfomsg *ifi,
958                                                  u8 *buf, size_t len)
960         struct nl80211_global *global = ctx;
961         struct wpa_driver_nl80211_data *drv;
962         int attrlen, rta_len;
963         struct rtattr *attr;
964         u32 brid = 0;
966         drv = nl80211_find_drv(global, ifi->ifi_index, buf, len);
967         if (!drv) {
968                 wpa_printf(MSG_DEBUG, "nl80211: Ignore dellink event for "
969                            "foreign ifindex %d", ifi->ifi_index);
970                 return;
971         }
973         attrlen = len;
974         attr = (struct rtattr *) buf;
976         rta_len = RTA_ALIGN(sizeof(struct rtattr));
977         while (RTA_OK(attr, attrlen)) {
978                 if (attr->rta_type == IFLA_IFNAME) {
979                         wpa_driver_nl80211_event_link(
980                                 drv,
981                                 ((char *) attr) + rta_len,
982                                 attr->rta_len - rta_len, 1);
983                 } else if (attr->rta_type == IFLA_MASTER)
984                         brid = nla_get_u32((struct nlattr *) attr);
985                 attr = RTA_NEXT(attr, attrlen);
986         }
988         if (ifi->ifi_family == AF_BRIDGE && brid) {
989                 /* device has been removed from bridge */
990                 char namebuf[IFNAMSIZ];
991                 if_indextoname(brid, namebuf);
992                 wpa_printf(MSG_DEBUG, "nl80211: Remove ifindex %u for bridge "
993                            "%s", brid, namebuf);
994                 del_ifidx(drv, brid);
995         }
999 static void mlme_event_auth(struct wpa_driver_nl80211_data *drv,
1000                             const u8 *frame, size_t len)
1002         const struct ieee80211_mgmt *mgmt;
1003         union wpa_event_data event;
1005         mgmt = (const struct ieee80211_mgmt *) frame;
1006         if (len < 24 + sizeof(mgmt->u.auth)) {
1007                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1008                            "frame");
1009                 return;
1010         }
1012         os_memcpy(drv->auth_bssid, mgmt->sa, ETH_ALEN);
1013         os_memset(&event, 0, sizeof(event));
1014         os_memcpy(event.auth.peer, mgmt->sa, ETH_ALEN);
1015         event.auth.auth_type = le_to_host16(mgmt->u.auth.auth_alg);
1016         event.auth.status_code = le_to_host16(mgmt->u.auth.status_code);
1017         if (len > 24 + sizeof(mgmt->u.auth)) {
1018                 event.auth.ies = mgmt->u.auth.variable;
1019                 event.auth.ies_len = len - 24 - sizeof(mgmt->u.auth);
1020         }
1022         wpa_supplicant_event(drv->ctx, EVENT_AUTH, &event);
1026 static unsigned int nl80211_get_assoc_freq(struct wpa_driver_nl80211_data *drv)
1028         struct nl_msg *msg;
1029         int ret;
1030         struct nl80211_bss_info_arg arg;
1032         os_memset(&arg, 0, sizeof(arg));
1033         msg = nlmsg_alloc();
1034         if (!msg)
1035                 goto nla_put_failure;
1037         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
1038         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1040         arg.drv = drv;
1041         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
1042         msg = NULL;
1043         if (ret == 0) {
1044                 wpa_printf(MSG_DEBUG, "nl80211: Operating frequency for the "
1045                            "associated BSS from scan results: %u MHz",
1046                            arg.assoc_freq);
1047                 return arg.assoc_freq ? arg.assoc_freq : drv->assoc_freq;
1048         }
1049         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
1050                    "(%s)", ret, strerror(-ret));
1051 nla_put_failure:
1052         nlmsg_free(msg);
1053         return drv->assoc_freq;
1057 static void mlme_event_assoc(struct wpa_driver_nl80211_data *drv,
1058                             const u8 *frame, size_t len)
1060         const struct ieee80211_mgmt *mgmt;
1061         union wpa_event_data event;
1062         u16 status;
1064         mgmt = (const struct ieee80211_mgmt *) frame;
1065         if (len < 24 + sizeof(mgmt->u.assoc_resp)) {
1066                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1067                            "frame");
1068                 return;
1069         }
1071         status = le_to_host16(mgmt->u.assoc_resp.status_code);
1072         if (status != WLAN_STATUS_SUCCESS) {
1073                 os_memset(&event, 0, sizeof(event));
1074                 event.assoc_reject.bssid = mgmt->bssid;
1075                 if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
1076                         event.assoc_reject.resp_ies =
1077                                 (u8 *) mgmt->u.assoc_resp.variable;
1078                         event.assoc_reject.resp_ies_len =
1079                                 len - 24 - sizeof(mgmt->u.assoc_resp);
1080                 }
1081                 event.assoc_reject.status_code = status;
1083                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
1084                 return;
1085         }
1087         drv->associated = 1;
1088         os_memcpy(drv->bssid, mgmt->sa, ETH_ALEN);
1090         os_memset(&event, 0, sizeof(event));
1091         if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
1092                 event.assoc_info.resp_ies = (u8 *) mgmt->u.assoc_resp.variable;
1093                 event.assoc_info.resp_ies_len =
1094                         len - 24 - sizeof(mgmt->u.assoc_resp);
1095         }
1097         event.assoc_info.freq = drv->assoc_freq;
1099         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
1103 static void mlme_event_connect(struct wpa_driver_nl80211_data *drv,
1104                                enum nl80211_commands cmd, struct nlattr *status,
1105                                struct nlattr *addr, struct nlattr *req_ie,
1106                                struct nlattr *resp_ie)
1108         union wpa_event_data event;
1110         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1111                 /*
1112                  * Avoid reporting two association events that would confuse
1113                  * the core code.
1114                  */
1115                 wpa_printf(MSG_DEBUG, "nl80211: Ignore connect event (cmd=%d) "
1116                            "when using userspace SME", cmd);
1117                 return;
1118         }
1120         os_memset(&event, 0, sizeof(event));
1121         if (cmd == NL80211_CMD_CONNECT &&
1122             nla_get_u16(status) != WLAN_STATUS_SUCCESS) {
1123                 if (addr)
1124                         event.assoc_reject.bssid = nla_data(addr);
1125                 if (resp_ie) {
1126                         event.assoc_reject.resp_ies = nla_data(resp_ie);
1127                         event.assoc_reject.resp_ies_len = nla_len(resp_ie);
1128                 }
1129                 event.assoc_reject.status_code = nla_get_u16(status);
1130                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
1131                 return;
1132         }
1134         drv->associated = 1;
1135         if (addr)
1136                 os_memcpy(drv->bssid, nla_data(addr), ETH_ALEN);
1138         if (req_ie) {
1139                 event.assoc_info.req_ies = nla_data(req_ie);
1140                 event.assoc_info.req_ies_len = nla_len(req_ie);
1141         }
1142         if (resp_ie) {
1143                 event.assoc_info.resp_ies = nla_data(resp_ie);
1144                 event.assoc_info.resp_ies_len = nla_len(resp_ie);
1145         }
1147         event.assoc_info.freq = nl80211_get_assoc_freq(drv);
1149         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
1153 static void mlme_event_disconnect(struct wpa_driver_nl80211_data *drv,
1154                                   struct nlattr *reason, struct nlattr *addr)
1156         union wpa_event_data data;
1158         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1159                 /*
1160                  * Avoid reporting two disassociation events that could
1161                  * confuse the core code.
1162                  */
1163                 wpa_printf(MSG_DEBUG, "nl80211: Ignore disconnect "
1164                            "event when using userspace SME");
1165                 return;
1166         }
1168         drv->associated = 0;
1169         os_memset(&data, 0, sizeof(data));
1170         if (reason)
1171                 data.disassoc_info.reason_code = nla_get_u16(reason);
1172         wpa_supplicant_event(drv->ctx, EVENT_DISASSOC, &data);
1176 static void mlme_timeout_event(struct wpa_driver_nl80211_data *drv,
1177                                enum nl80211_commands cmd, struct nlattr *addr)
1179         union wpa_event_data event;
1180         enum wpa_event_type ev;
1182         if (nla_len(addr) != ETH_ALEN)
1183                 return;
1185         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d; timeout with " MACSTR,
1186                    cmd, MAC2STR((u8 *) nla_data(addr)));
1188         if (cmd == NL80211_CMD_AUTHENTICATE)
1189                 ev = EVENT_AUTH_TIMED_OUT;
1190         else if (cmd == NL80211_CMD_ASSOCIATE)
1191                 ev = EVENT_ASSOC_TIMED_OUT;
1192         else
1193                 return;
1195         os_memset(&event, 0, sizeof(event));
1196         os_memcpy(event.timeout_event.addr, nla_data(addr), ETH_ALEN);
1197         wpa_supplicant_event(drv->ctx, ev, &event);
1201 static void mlme_event_mgmt(struct wpa_driver_nl80211_data *drv,
1202                             struct nlattr *freq, const u8 *frame, size_t len)
1204         const struct ieee80211_mgmt *mgmt;
1205         union wpa_event_data event;
1206         u16 fc, stype;
1208         mgmt = (const struct ieee80211_mgmt *) frame;
1209         if (len < 24) {
1210                 wpa_printf(MSG_DEBUG, "nl80211: Too short action frame");
1211                 return;
1212         }
1214         fc = le_to_host16(mgmt->frame_control);
1215         stype = WLAN_FC_GET_STYPE(fc);
1217         os_memset(&event, 0, sizeof(event));
1218         if (freq) {
1219                 event.rx_action.freq = nla_get_u32(freq);
1220                 drv->last_mgmt_freq = event.rx_action.freq;
1221         }
1222         if (stype == WLAN_FC_STYPE_ACTION) {
1223                 event.rx_action.da = mgmt->da;
1224                 event.rx_action.sa = mgmt->sa;
1225                 event.rx_action.bssid = mgmt->bssid;
1226                 event.rx_action.category = mgmt->u.action.category;
1227                 event.rx_action.data = &mgmt->u.action.category + 1;
1228                 event.rx_action.len = frame + len - event.rx_action.data;
1229                 wpa_supplicant_event(drv->ctx, EVENT_RX_ACTION, &event);
1230         } else {
1231                 event.rx_mgmt.frame = frame;
1232                 event.rx_mgmt.frame_len = len;
1233                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
1234         }
1238 static void mlme_event_mgmt_tx_status(struct wpa_driver_nl80211_data *drv,
1239                                       struct nlattr *cookie, const u8 *frame,
1240                                       size_t len, struct nlattr *ack)
1242         union wpa_event_data event;
1243         const struct ieee80211_hdr *hdr;
1244         u16 fc;
1246         if (!is_ap_interface(drv->nlmode)) {
1247                 u64 cookie_val;
1249                 if (!cookie)
1250                         return;
1252                 cookie_val = nla_get_u64(cookie);
1253                 wpa_printf(MSG_DEBUG, "nl80211: Action TX status:"
1254                            " cookie=0%llx%s (ack=%d)",
1255                            (long long unsigned int) cookie_val,
1256                            cookie_val == drv->send_action_cookie ?
1257                            " (match)" : " (unknown)", ack != NULL);
1258                 if (cookie_val != drv->send_action_cookie)
1259                         return;
1260         }
1262         hdr = (const struct ieee80211_hdr *) frame;
1263         fc = le_to_host16(hdr->frame_control);
1265         os_memset(&event, 0, sizeof(event));
1266         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
1267         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
1268         event.tx_status.dst = hdr->addr1;
1269         event.tx_status.data = frame;
1270         event.tx_status.data_len = len;
1271         event.tx_status.ack = ack != NULL;
1272         wpa_supplicant_event(drv->ctx, EVENT_TX_STATUS, &event);
1276 static void mlme_event_deauth_disassoc(struct wpa_driver_nl80211_data *drv,
1277                                        enum wpa_event_type type,
1278                                        const u8 *frame, size_t len)
1280         const struct ieee80211_mgmt *mgmt;
1281         union wpa_event_data event;
1282         const u8 *bssid = NULL;
1283         u16 reason_code = 0;
1285         mgmt = (const struct ieee80211_mgmt *) frame;
1286         if (len >= 24) {
1287                 bssid = mgmt->bssid;
1289                 if (drv->associated != 0 &&
1290                     os_memcmp(bssid, drv->bssid, ETH_ALEN) != 0 &&
1291                     os_memcmp(bssid, drv->auth_bssid, ETH_ALEN) != 0) {
1292                         /*
1293                          * We have presumably received this deauth as a
1294                          * response to a clear_state_mismatch() outgoing
1295                          * deauth.  Don't let it take us offline!
1296                          */
1297                         wpa_printf(MSG_DEBUG, "nl80211: Deauth received "
1298                                    "from Unknown BSSID " MACSTR " -- ignoring",
1299                                    MAC2STR(bssid));
1300                         return;
1301                 }
1302         }
1304         drv->associated = 0;
1305         os_memset(&event, 0, sizeof(event));
1307         /* Note: Same offset for Reason Code in both frame subtypes */
1308         if (len >= 24 + sizeof(mgmt->u.deauth))
1309                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
1311         if (type == EVENT_DISASSOC) {
1312                 event.disassoc_info.addr = bssid;
1313                 event.disassoc_info.reason_code = reason_code;
1314                 if (frame + len > mgmt->u.disassoc.variable) {
1315                         event.disassoc_info.ie = mgmt->u.disassoc.variable;
1316                         event.disassoc_info.ie_len = frame + len -
1317                                 mgmt->u.disassoc.variable;
1318                 }
1319         } else {
1320                 event.deauth_info.addr = bssid;
1321                 event.deauth_info.reason_code = reason_code;
1322                 if (frame + len > mgmt->u.deauth.variable) {
1323                         event.deauth_info.ie = mgmt->u.deauth.variable;
1324                         event.deauth_info.ie_len = frame + len -
1325                                 mgmt->u.deauth.variable;
1326                 }
1327         }
1329         wpa_supplicant_event(drv->ctx, type, &event);
1333 static void mlme_event_unprot_disconnect(struct wpa_driver_nl80211_data *drv,
1334                                          enum wpa_event_type type,
1335                                          const u8 *frame, size_t len)
1337         const struct ieee80211_mgmt *mgmt;
1338         union wpa_event_data event;
1339         u16 reason_code = 0;
1341         if (len < 24)
1342                 return;
1344         mgmt = (const struct ieee80211_mgmt *) frame;
1346         os_memset(&event, 0, sizeof(event));
1347         /* Note: Same offset for Reason Code in both frame subtypes */
1348         if (len >= 24 + sizeof(mgmt->u.deauth))
1349                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
1351         if (type == EVENT_UNPROT_DISASSOC) {
1352                 event.unprot_disassoc.sa = mgmt->sa;
1353                 event.unprot_disassoc.da = mgmt->da;
1354                 event.unprot_disassoc.reason_code = reason_code;
1355         } else {
1356                 event.unprot_deauth.sa = mgmt->sa;
1357                 event.unprot_deauth.da = mgmt->da;
1358                 event.unprot_deauth.reason_code = reason_code;
1359         }
1361         wpa_supplicant_event(drv->ctx, type, &event);
1365 static void mlme_event(struct wpa_driver_nl80211_data *drv,
1366                        enum nl80211_commands cmd, struct nlattr *frame,
1367                        struct nlattr *addr, struct nlattr *timed_out,
1368                        struct nlattr *freq, struct nlattr *ack,
1369                        struct nlattr *cookie)
1371         if (timed_out && addr) {
1372                 mlme_timeout_event(drv, cmd, addr);
1373                 return;
1374         }
1376         if (frame == NULL) {
1377                 wpa_printf(MSG_DEBUG, "nl80211: MLME event %d without frame "
1378                            "data", cmd);
1379                 return;
1380         }
1382         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d", cmd);
1383         wpa_hexdump(MSG_MSGDUMP, "nl80211: MLME event frame",
1384                     nla_data(frame), nla_len(frame));
1386         switch (cmd) {
1387         case NL80211_CMD_AUTHENTICATE:
1388                 mlme_event_auth(drv, nla_data(frame), nla_len(frame));
1389                 break;
1390         case NL80211_CMD_ASSOCIATE:
1391                 mlme_event_assoc(drv, nla_data(frame), nla_len(frame));
1392                 break;
1393         case NL80211_CMD_DEAUTHENTICATE:
1394                 mlme_event_deauth_disassoc(drv, EVENT_DEAUTH,
1395                                            nla_data(frame), nla_len(frame));
1396                 break;
1397         case NL80211_CMD_DISASSOCIATE:
1398                 mlme_event_deauth_disassoc(drv, EVENT_DISASSOC,
1399                                            nla_data(frame), nla_len(frame));
1400                 break;
1401         case NL80211_CMD_FRAME:
1402                 mlme_event_mgmt(drv, freq, nla_data(frame), nla_len(frame));
1403                 break;
1404         case NL80211_CMD_FRAME_TX_STATUS:
1405                 mlme_event_mgmt_tx_status(drv, cookie, nla_data(frame),
1406                                           nla_len(frame), ack);
1407                 break;
1408         case NL80211_CMD_UNPROT_DEAUTHENTICATE:
1409                 mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DEAUTH,
1410                                              nla_data(frame), nla_len(frame));
1411                 break;
1412         case NL80211_CMD_UNPROT_DISASSOCIATE:
1413                 mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DISASSOC,
1414                                              nla_data(frame), nla_len(frame));
1415                 break;
1416         default:
1417                 break;
1418         }
1422 static void mlme_event_michael_mic_failure(struct wpa_driver_nl80211_data *drv,
1423                                            struct nlattr *tb[])
1425         union wpa_event_data data;
1427         wpa_printf(MSG_DEBUG, "nl80211: MLME event Michael MIC failure");
1428         os_memset(&data, 0, sizeof(data));
1429         if (tb[NL80211_ATTR_MAC]) {
1430                 wpa_hexdump(MSG_DEBUG, "nl80211: Source MAC address",
1431                             nla_data(tb[NL80211_ATTR_MAC]),
1432                             nla_len(tb[NL80211_ATTR_MAC]));
1433                 data.michael_mic_failure.src = nla_data(tb[NL80211_ATTR_MAC]);
1434         }
1435         if (tb[NL80211_ATTR_KEY_SEQ]) {
1436                 wpa_hexdump(MSG_DEBUG, "nl80211: TSC",
1437                             nla_data(tb[NL80211_ATTR_KEY_SEQ]),
1438                             nla_len(tb[NL80211_ATTR_KEY_SEQ]));
1439         }
1440         if (tb[NL80211_ATTR_KEY_TYPE]) {
1441                 enum nl80211_key_type key_type =
1442                         nla_get_u32(tb[NL80211_ATTR_KEY_TYPE]);
1443                 wpa_printf(MSG_DEBUG, "nl80211: Key Type %d", key_type);
1444                 if (key_type == NL80211_KEYTYPE_PAIRWISE)
1445                         data.michael_mic_failure.unicast = 1;
1446         } else
1447                 data.michael_mic_failure.unicast = 1;
1449         if (tb[NL80211_ATTR_KEY_IDX]) {
1450                 u8 key_id = nla_get_u8(tb[NL80211_ATTR_KEY_IDX]);
1451                 wpa_printf(MSG_DEBUG, "nl80211: Key Id %d", key_id);
1452         }
1454         wpa_supplicant_event(drv->ctx, EVENT_MICHAEL_MIC_FAILURE, &data);
1458 static void mlme_event_join_ibss(struct wpa_driver_nl80211_data *drv,
1459                                  struct nlattr *tb[])
1461         if (tb[NL80211_ATTR_MAC] == NULL) {
1462                 wpa_printf(MSG_DEBUG, "nl80211: No address in IBSS joined "
1463                            "event");
1464                 return;
1465         }
1466         os_memcpy(drv->bssid, nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
1467         drv->associated = 1;
1468         wpa_printf(MSG_DEBUG, "nl80211: IBSS " MACSTR " joined",
1469                    MAC2STR(drv->bssid));
1471         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, NULL);
1475 static void mlme_event_remain_on_channel(struct wpa_driver_nl80211_data *drv,
1476                                          int cancel_event, struct nlattr *tb[])
1478         unsigned int freq, chan_type, duration;
1479         union wpa_event_data data;
1480         u64 cookie;
1482         if (tb[NL80211_ATTR_WIPHY_FREQ])
1483                 freq = nla_get_u32(tb[NL80211_ATTR_WIPHY_FREQ]);
1484         else
1485                 freq = 0;
1487         if (tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE])
1488                 chan_type = nla_get_u32(tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
1489         else
1490                 chan_type = 0;
1492         if (tb[NL80211_ATTR_DURATION])
1493                 duration = nla_get_u32(tb[NL80211_ATTR_DURATION]);
1494         else
1495                 duration = 0;
1497         if (tb[NL80211_ATTR_COOKIE])
1498                 cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
1499         else
1500                 cookie = 0;
1502         wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel event (cancel=%d "
1503                    "freq=%u channel_type=%u duration=%u cookie=0x%llx (%s))",
1504                    cancel_event, freq, chan_type, duration,
1505                    (long long unsigned int) cookie,
1506                    cookie == drv->remain_on_chan_cookie ? "match" : "unknown");
1508         if (cookie != drv->remain_on_chan_cookie)
1509                 return; /* not for us */
1511         if (cancel_event)
1512                 drv->pending_remain_on_chan = 0;
1514         os_memset(&data, 0, sizeof(data));
1515         data.remain_on_channel.freq = freq;
1516         data.remain_on_channel.duration = duration;
1517         wpa_supplicant_event(drv->ctx, cancel_event ?
1518                              EVENT_CANCEL_REMAIN_ON_CHANNEL :
1519                              EVENT_REMAIN_ON_CHANNEL, &data);
1523 static void send_scan_event(struct wpa_driver_nl80211_data *drv, int aborted,
1524                             struct nlattr *tb[])
1526         union wpa_event_data event;
1527         struct nlattr *nl;
1528         int rem;
1529         struct scan_info *info;
1530 #define MAX_REPORT_FREQS 50
1531         int freqs[MAX_REPORT_FREQS];
1532         int num_freqs = 0;
1534         if (drv->scan_for_auth) {
1535                 drv->scan_for_auth = 0;
1536                 wpa_printf(MSG_DEBUG, "nl80211: Scan results for missing "
1537                            "cfg80211 BSS entry");
1538                 wpa_driver_nl80211_authenticate_retry(drv);
1539                 return;
1540         }
1542         os_memset(&event, 0, sizeof(event));
1543         info = &event.scan_info;
1544         info->aborted = aborted;
1546         if (tb[NL80211_ATTR_SCAN_SSIDS]) {
1547                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_SSIDS], rem) {
1548                         struct wpa_driver_scan_ssid *s =
1549                                 &info->ssids[info->num_ssids];
1550                         s->ssid = nla_data(nl);
1551                         s->ssid_len = nla_len(nl);
1552                         info->num_ssids++;
1553                         if (info->num_ssids == WPAS_MAX_SCAN_SSIDS)
1554                                 break;
1555                 }
1556         }
1557         if (tb[NL80211_ATTR_SCAN_FREQUENCIES]) {
1558                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_FREQUENCIES], rem)
1559                 {
1560                         freqs[num_freqs] = nla_get_u32(nl);
1561                         num_freqs++;
1562                         if (num_freqs == MAX_REPORT_FREQS - 1)
1563                                 break;
1564                 }
1565                 info->freqs = freqs;
1566                 info->num_freqs = num_freqs;
1567         }
1568         wpa_supplicant_event(drv->ctx, EVENT_SCAN_RESULTS, &event);
1572 static int get_link_signal(struct nl_msg *msg, void *arg)
1574         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1575         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1576         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
1577         static struct nla_policy policy[NL80211_STA_INFO_MAX + 1] = {
1578                 [NL80211_STA_INFO_SIGNAL] = { .type = NLA_U8 },
1579         };
1580         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
1581         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
1582                 [NL80211_RATE_INFO_BITRATE] = { .type = NLA_U16 },
1583                 [NL80211_RATE_INFO_MCS] = { .type = NLA_U8 },
1584                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG },
1585                 [NL80211_RATE_INFO_SHORT_GI] = { .type = NLA_FLAG },
1586         };
1587         struct wpa_signal_info *sig_change = arg;
1589         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1590                   genlmsg_attrlen(gnlh, 0), NULL);
1591         if (!tb[NL80211_ATTR_STA_INFO] ||
1592             nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
1593                              tb[NL80211_ATTR_STA_INFO], policy))
1594                 return NL_SKIP;
1595         if (!sinfo[NL80211_STA_INFO_SIGNAL])
1596                 return NL_SKIP;
1598         sig_change->current_signal =
1599                 (s8) nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
1601         if (sinfo[NL80211_STA_INFO_TX_BITRATE]) {
1602                 if (nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1603                                      sinfo[NL80211_STA_INFO_TX_BITRATE],
1604                                      rate_policy)) {
1605                         sig_change->current_txrate = 0;
1606                 } else {
1607                         if (rinfo[NL80211_RATE_INFO_BITRATE]) {
1608                                 sig_change->current_txrate =
1609                                         nla_get_u16(rinfo[
1610                                              NL80211_RATE_INFO_BITRATE]) * 100;
1611                         }
1612                 }
1613         }
1615         return NL_SKIP;
1619 static int nl80211_get_link_signal(struct wpa_driver_nl80211_data *drv,
1620                                    struct wpa_signal_info *sig)
1622         struct nl_msg *msg;
1624         sig->current_signal = -9999;
1625         sig->current_txrate = 0;
1627         msg = nlmsg_alloc();
1628         if (!msg)
1629                 return -ENOMEM;
1631         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
1633         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1634         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
1636         return send_and_recv_msgs(drv, msg, get_link_signal, sig);
1637  nla_put_failure:
1638         nlmsg_free(msg);
1639         return -ENOBUFS;
1643 static int get_link_noise(struct nl_msg *msg, void *arg)
1645         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1646         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1647         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1648         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1649                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1650                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
1651         };
1652         struct wpa_signal_info *sig_change = arg;
1654         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1655                   genlmsg_attrlen(gnlh, 0), NULL);
1657         if (!tb[NL80211_ATTR_SURVEY_INFO]) {
1658                 wpa_printf(MSG_DEBUG, "nl80211: survey data missing!");
1659                 return NL_SKIP;
1660         }
1662         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1663                              tb[NL80211_ATTR_SURVEY_INFO],
1664                              survey_policy)) {
1665                 wpa_printf(MSG_DEBUG, "nl80211: failed to parse nested "
1666                            "attributes!");
1667                 return NL_SKIP;
1668         }
1670         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1671                 return NL_SKIP;
1673         if (nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
1674             sig_change->frequency)
1675                 return NL_SKIP;
1677         if (!sinfo[NL80211_SURVEY_INFO_NOISE])
1678                 return NL_SKIP;
1680         sig_change->current_noise =
1681                 (s8) nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1683         return NL_SKIP;
1687 static int nl80211_get_link_noise(struct wpa_driver_nl80211_data *drv,
1688                                   struct wpa_signal_info *sig_change)
1690         struct nl_msg *msg;
1692         sig_change->current_noise = 9999;
1693         sig_change->frequency = drv->assoc_freq;
1695         msg = nlmsg_alloc();
1696         if (!msg)
1697                 return -ENOMEM;
1699         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
1701         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1703         return send_and_recv_msgs(drv, msg, get_link_noise, sig_change);
1704  nla_put_failure:
1705         nlmsg_free(msg);
1706         return -ENOBUFS;
1710 static int get_noise_for_scan_results(struct nl_msg *msg, void *arg)
1712         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1713         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1714         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1715         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1716                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1717                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
1718         };
1719         struct wpa_scan_results *scan_results = arg;
1720         struct wpa_scan_res *scan_res;
1721         size_t i;
1723         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1724                   genlmsg_attrlen(gnlh, 0), NULL);
1726         if (!tb[NL80211_ATTR_SURVEY_INFO]) {
1727                 wpa_printf(MSG_DEBUG, "nl80211: Survey data missing");
1728                 return NL_SKIP;
1729         }
1731         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1732                              tb[NL80211_ATTR_SURVEY_INFO],
1733                              survey_policy)) {
1734                 wpa_printf(MSG_DEBUG, "nl80211: Failed to parse nested "
1735                            "attributes");
1736                 return NL_SKIP;
1737         }
1739         if (!sinfo[NL80211_SURVEY_INFO_NOISE])
1740                 return NL_SKIP;
1742         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1743                 return NL_SKIP;
1745         for (i = 0; i < scan_results->num; ++i) {
1746                 scan_res = scan_results->res[i];
1747                 if (!scan_res)
1748                         continue;
1749                 if ((int) nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
1750                     scan_res->freq)
1751                         continue;
1752                 if (!(scan_res->flags & WPA_SCAN_NOISE_INVALID))
1753                         continue;
1754                 scan_res->noise = (s8)
1755                         nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1756                 scan_res->flags &= ~WPA_SCAN_NOISE_INVALID;
1757         }
1759         return NL_SKIP;
1763 static int nl80211_get_noise_for_scan_results(
1764         struct wpa_driver_nl80211_data *drv,
1765         struct wpa_scan_results *scan_res)
1767         struct nl_msg *msg;
1769         msg = nlmsg_alloc();
1770         if (!msg)
1771                 return -ENOMEM;
1773         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
1775         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1777         return send_and_recv_msgs(drv, msg, get_noise_for_scan_results,
1778                                   scan_res);
1779  nla_put_failure:
1780         nlmsg_free(msg);
1781         return -ENOBUFS;
1785 static void nl80211_cqm_event(struct wpa_driver_nl80211_data *drv,
1786                               struct nlattr *tb[])
1788         static struct nla_policy cqm_policy[NL80211_ATTR_CQM_MAX + 1] = {
1789                 [NL80211_ATTR_CQM_RSSI_THOLD] = { .type = NLA_U32 },
1790                 [NL80211_ATTR_CQM_RSSI_HYST] = { .type = NLA_U8 },
1791                 [NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] = { .type = NLA_U32 },
1792                 [NL80211_ATTR_CQM_PKT_LOSS_EVENT] = { .type = NLA_U32 },
1793         };
1794         struct nlattr *cqm[NL80211_ATTR_CQM_MAX + 1];
1795         enum nl80211_cqm_rssi_threshold_event event;
1796         union wpa_event_data ed;
1797         struct wpa_signal_info sig;
1798         int res;
1800         if (tb[NL80211_ATTR_CQM] == NULL ||
1801             nla_parse_nested(cqm, NL80211_ATTR_CQM_MAX, tb[NL80211_ATTR_CQM],
1802                              cqm_policy)) {
1803                 wpa_printf(MSG_DEBUG, "nl80211: Ignore invalid CQM event");
1804                 return;
1805         }
1807         os_memset(&ed, 0, sizeof(ed));
1809         if (cqm[NL80211_ATTR_CQM_PKT_LOSS_EVENT]) {
1810                 if (!tb[NL80211_ATTR_MAC])
1811                         return;
1812                 os_memcpy(ed.low_ack.addr, nla_data(tb[NL80211_ATTR_MAC]),
1813                           ETH_ALEN);
1814                 wpa_supplicant_event(drv->ctx, EVENT_STATION_LOW_ACK, &ed);
1815                 return;
1816         }
1818         if (cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] == NULL)
1819                 return;
1820         event = nla_get_u32(cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]);
1822         if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH) {
1823                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1824                            "event: RSSI high");
1825                 ed.signal_change.above_threshold = 1;
1826         } else if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW) {
1827                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1828                            "event: RSSI low");
1829                 ed.signal_change.above_threshold = 0;
1830         } else
1831                 return;
1833         res = nl80211_get_link_signal(drv, &sig);
1834         if (res == 0) {
1835                 ed.signal_change.current_signal = sig.current_signal;
1836                 ed.signal_change.current_txrate = sig.current_txrate;
1837                 wpa_printf(MSG_DEBUG, "nl80211: Signal: %d dBm  txrate: %d",
1838                            sig.current_signal, sig.current_txrate);
1839         }
1841         res = nl80211_get_link_noise(drv, &sig);
1842         if (res == 0) {
1843                 ed.signal_change.current_noise = sig.current_noise;
1844                 wpa_printf(MSG_DEBUG, "nl80211: Noise: %d dBm",
1845                            sig.current_noise);
1846         }
1848         wpa_supplicant_event(drv->ctx, EVENT_SIGNAL_CHANGE, &ed);
1852 static void nl80211_new_station_event(struct wpa_driver_nl80211_data *drv,
1853                                       struct nlattr **tb)
1855         u8 *addr;
1856         union wpa_event_data data;
1858         if (tb[NL80211_ATTR_MAC] == NULL)
1859                 return;
1860         addr = nla_data(tb[NL80211_ATTR_MAC]);
1861         wpa_printf(MSG_DEBUG, "nl80211: New station " MACSTR, MAC2STR(addr));
1863         if (is_ap_interface(drv->nlmode) && drv->device_ap_sme) {
1864                 u8 *ies = NULL;
1865                 size_t ies_len = 0;
1866                 if (tb[NL80211_ATTR_IE]) {
1867                         ies = nla_data(tb[NL80211_ATTR_IE]);
1868                         ies_len = nla_len(tb[NL80211_ATTR_IE]);
1869                 }
1870                 wpa_hexdump(MSG_DEBUG, "nl80211: Assoc Req IEs", ies, ies_len);
1871                 drv_event_assoc(drv->ctx, addr, ies, ies_len, 0);
1872                 return;
1873         }
1875         if (drv->nlmode != NL80211_IFTYPE_ADHOC)
1876                 return;
1878         os_memset(&data, 0, sizeof(data));
1879         os_memcpy(data.ibss_rsn_start.peer, addr, ETH_ALEN);
1880         wpa_supplicant_event(drv->ctx, EVENT_IBSS_RSN_START, &data);
1884 static void nl80211_del_station_event(struct wpa_driver_nl80211_data *drv,
1885                                       struct nlattr **tb)
1887         u8 *addr;
1888         union wpa_event_data data;
1890         if (tb[NL80211_ATTR_MAC] == NULL)
1891                 return;
1892         addr = nla_data(tb[NL80211_ATTR_MAC]);
1893         wpa_printf(MSG_DEBUG, "nl80211: Delete station " MACSTR,
1894                    MAC2STR(addr));
1896         if (is_ap_interface(drv->nlmode) && drv->device_ap_sme) {
1897                 drv_event_disassoc(drv->ctx, addr);
1898                 return;
1899         }
1901         if (drv->nlmode != NL80211_IFTYPE_ADHOC)
1902                 return;
1904         os_memset(&data, 0, sizeof(data));
1905         os_memcpy(data.ibss_peer_lost.peer, addr, ETH_ALEN);
1906         wpa_supplicant_event(drv->ctx, EVENT_IBSS_PEER_LOST, &data);
1910 static void nl80211_rekey_offload_event(struct wpa_driver_nl80211_data *drv,
1911                                         struct nlattr **tb)
1913         struct nlattr *rekey_info[NUM_NL80211_REKEY_DATA];
1914         static struct nla_policy rekey_policy[NUM_NL80211_REKEY_DATA] = {
1915                 [NL80211_REKEY_DATA_KEK] = {
1916                         .minlen = NL80211_KEK_LEN,
1917                         .maxlen = NL80211_KEK_LEN,
1918                 },
1919                 [NL80211_REKEY_DATA_KCK] = {
1920                         .minlen = NL80211_KCK_LEN,
1921                         .maxlen = NL80211_KCK_LEN,
1922                 },
1923                 [NL80211_REKEY_DATA_REPLAY_CTR] = {
1924                         .minlen = NL80211_REPLAY_CTR_LEN,
1925                         .maxlen = NL80211_REPLAY_CTR_LEN,
1926                 },
1927         };
1928         union wpa_event_data data;
1930         if (!tb[NL80211_ATTR_MAC])
1931                 return;
1932         if (!tb[NL80211_ATTR_REKEY_DATA])
1933                 return;
1934         if (nla_parse_nested(rekey_info, MAX_NL80211_REKEY_DATA,
1935                              tb[NL80211_ATTR_REKEY_DATA], rekey_policy))
1936                 return;
1937         if (!rekey_info[NL80211_REKEY_DATA_REPLAY_CTR])
1938                 return;
1940         os_memset(&data, 0, sizeof(data));
1941         data.driver_gtk_rekey.bssid = nla_data(tb[NL80211_ATTR_MAC]);
1942         wpa_printf(MSG_DEBUG, "nl80211: Rekey offload event for BSSID " MACSTR,
1943                    MAC2STR(data.driver_gtk_rekey.bssid));
1944         data.driver_gtk_rekey.replay_ctr =
1945                 nla_data(rekey_info[NL80211_REKEY_DATA_REPLAY_CTR]);
1946         wpa_hexdump(MSG_DEBUG, "nl80211: Rekey offload - Replay Counter",
1947                     data.driver_gtk_rekey.replay_ctr, NL80211_REPLAY_CTR_LEN);
1948         wpa_supplicant_event(drv->ctx, EVENT_DRIVER_GTK_REKEY, &data);
1952 static void nl80211_pmksa_candidate_event(struct wpa_driver_nl80211_data *drv,
1953                                           struct nlattr **tb)
1955         struct nlattr *cand[NUM_NL80211_PMKSA_CANDIDATE];
1956         static struct nla_policy cand_policy[NUM_NL80211_PMKSA_CANDIDATE] = {
1957                 [NL80211_PMKSA_CANDIDATE_INDEX] = { .type = NLA_U32 },
1958                 [NL80211_PMKSA_CANDIDATE_BSSID] = {
1959                         .minlen = ETH_ALEN,
1960                         .maxlen = ETH_ALEN,
1961                 },
1962                 [NL80211_PMKSA_CANDIDATE_PREAUTH] = { .type = NLA_FLAG },
1963         };
1964         union wpa_event_data data;
1966         if (!tb[NL80211_ATTR_PMKSA_CANDIDATE])
1967                 return;
1968         if (nla_parse_nested(cand, MAX_NL80211_PMKSA_CANDIDATE,
1969                              tb[NL80211_ATTR_PMKSA_CANDIDATE], cand_policy))
1970                 return;
1971         if (!cand[NL80211_PMKSA_CANDIDATE_INDEX] ||
1972             !cand[NL80211_PMKSA_CANDIDATE_BSSID])
1973                 return;
1975         os_memset(&data, 0, sizeof(data));
1976         os_memcpy(data.pmkid_candidate.bssid,
1977                   nla_data(cand[NL80211_PMKSA_CANDIDATE_BSSID]), ETH_ALEN);
1978         data.pmkid_candidate.index =
1979                 nla_get_u32(cand[NL80211_PMKSA_CANDIDATE_INDEX]);
1980         data.pmkid_candidate.preauth =
1981                 cand[NL80211_PMKSA_CANDIDATE_PREAUTH] != NULL;
1982         wpa_supplicant_event(drv->ctx, EVENT_PMKID_CANDIDATE, &data);
1986 static void nl80211_client_probe_event(struct wpa_driver_nl80211_data *drv,
1987                                        struct nlattr **tb)
1989         union wpa_event_data data;
1991         if (!tb[NL80211_ATTR_MAC] || !tb[NL80211_ATTR_ACK])
1992                 return;
1994         os_memset(&data, 0, sizeof(data));
1995         os_memcpy(data.client_poll.addr,
1996                   nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
1998         wpa_supplicant_event(drv->ctx, EVENT_DRIVER_CLIENT_POLL_OK, &data);
2002 static void nl80211_spurious_frame(struct i802_bss *bss, struct nlattr **tb,
2003                                    int wds)
2005         struct wpa_driver_nl80211_data *drv = bss->drv;
2006         union wpa_event_data event;
2008         if (!tb[NL80211_ATTR_MAC])
2009                 return;
2011         os_memset(&event, 0, sizeof(event));
2012         event.rx_from_unknown.bssid = bss->addr;
2013         event.rx_from_unknown.addr = nla_data(tb[NL80211_ATTR_MAC]);
2014         event.rx_from_unknown.wds = wds;
2016         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
2020 static void do_process_drv_event(struct wpa_driver_nl80211_data *drv,
2021                                  int cmd, struct nlattr **tb)
2023         if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED &&
2024             (cmd == NL80211_CMD_NEW_SCAN_RESULTS ||
2025              cmd == NL80211_CMD_SCAN_ABORTED)) {
2026                 wpa_driver_nl80211_set_mode(&drv->first_bss,
2027                                             drv->ap_scan_as_station);
2028                 drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
2029         }
2031         switch (cmd) {
2032         case NL80211_CMD_TRIGGER_SCAN:
2033                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger");
2034                 break;
2035         case NL80211_CMD_START_SCHED_SCAN:
2036                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan started");
2037                 break;
2038         case NL80211_CMD_SCHED_SCAN_STOPPED:
2039                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan stopped");
2040                 wpa_supplicant_event(drv->ctx, EVENT_SCHED_SCAN_STOPPED, NULL);
2041                 break;
2042         case NL80211_CMD_NEW_SCAN_RESULTS:
2043                 wpa_printf(MSG_DEBUG, "nl80211: New scan results available");
2044                 drv->scan_complete_events = 1;
2045                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
2046                                      drv->ctx);
2047                 send_scan_event(drv, 0, tb);
2048                 break;
2049         case NL80211_CMD_SCHED_SCAN_RESULTS:
2050                 wpa_printf(MSG_DEBUG,
2051                            "nl80211: New sched scan results available");
2052                 send_scan_event(drv, 0, tb);
2053                 break;
2054         case NL80211_CMD_SCAN_ABORTED:
2055                 wpa_printf(MSG_DEBUG, "nl80211: Scan aborted");
2056                 /*
2057                  * Need to indicate that scan results are available in order
2058                  * not to make wpa_supplicant stop its scanning.
2059                  */
2060                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
2061                                      drv->ctx);
2062                 send_scan_event(drv, 1, tb);
2063                 break;
2064         case NL80211_CMD_AUTHENTICATE:
2065         case NL80211_CMD_ASSOCIATE:
2066         case NL80211_CMD_DEAUTHENTICATE:
2067         case NL80211_CMD_DISASSOCIATE:
2068         case NL80211_CMD_FRAME_TX_STATUS:
2069         case NL80211_CMD_UNPROT_DEAUTHENTICATE:
2070         case NL80211_CMD_UNPROT_DISASSOCIATE:
2071                 mlme_event(drv, cmd, tb[NL80211_ATTR_FRAME],
2072                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
2073                            tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
2074                            tb[NL80211_ATTR_COOKIE]);
2075                 break;
2076         case NL80211_CMD_CONNECT:
2077         case NL80211_CMD_ROAM:
2078                 mlme_event_connect(drv, cmd,
2079                                    tb[NL80211_ATTR_STATUS_CODE],
2080                                    tb[NL80211_ATTR_MAC],
2081                                    tb[NL80211_ATTR_REQ_IE],
2082                                    tb[NL80211_ATTR_RESP_IE]);
2083                 break;
2084         case NL80211_CMD_DISCONNECT:
2085                 mlme_event_disconnect(drv, tb[NL80211_ATTR_REASON_CODE],
2086                                       tb[NL80211_ATTR_MAC]);
2087                 break;
2088         case NL80211_CMD_MICHAEL_MIC_FAILURE:
2089                 mlme_event_michael_mic_failure(drv, tb);
2090                 break;
2091         case NL80211_CMD_JOIN_IBSS:
2092                 mlme_event_join_ibss(drv, tb);
2093                 break;
2094         case NL80211_CMD_REMAIN_ON_CHANNEL:
2095                 mlme_event_remain_on_channel(drv, 0, tb);
2096                 break;
2097         case NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL:
2098                 mlme_event_remain_on_channel(drv, 1, tb);
2099                 break;
2100         case NL80211_CMD_NOTIFY_CQM:
2101                 nl80211_cqm_event(drv, tb);
2102                 break;
2103         case NL80211_CMD_REG_CHANGE:
2104                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory domain change");
2105                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
2106                                      NULL);
2107                 break;
2108         case NL80211_CMD_REG_BEACON_HINT:
2109                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory beacon hint");
2110                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
2111                                      NULL);
2112                 break;
2113         case NL80211_CMD_NEW_STATION:
2114                 nl80211_new_station_event(drv, tb);
2115                 break;
2116         case NL80211_CMD_DEL_STATION:
2117                 nl80211_del_station_event(drv, tb);
2118                 break;
2119         case NL80211_CMD_SET_REKEY_OFFLOAD:
2120                 nl80211_rekey_offload_event(drv, tb);
2121                 break;
2122         case NL80211_CMD_PMKSA_CANDIDATE:
2123                 nl80211_pmksa_candidate_event(drv, tb);
2124                 break;
2125         case NL80211_CMD_PROBE_CLIENT:
2126                 nl80211_client_probe_event(drv, tb);
2127                 break;
2128         default:
2129                 wpa_printf(MSG_DEBUG, "nl80211: Ignored unknown event "
2130                            "(cmd=%d)", cmd);
2131                 break;
2132         }
2136 static int process_drv_event(struct nl_msg *msg, void *arg)
2138         struct wpa_driver_nl80211_data *drv = arg;
2139         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2140         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2142         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2143                   genlmsg_attrlen(gnlh, 0), NULL);
2145         if (tb[NL80211_ATTR_IFINDEX]) {
2146                 int ifindex = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
2147                 if (ifindex != drv->ifindex && !have_ifidx(drv, ifindex)) {
2148                         wpa_printf(MSG_DEBUG, "nl80211: Ignored event (cmd=%d)"
2149                                    " for foreign interface (ifindex %d)",
2150                                    gnlh->cmd, ifindex);
2151                         return NL_SKIP;
2152                 }
2153         }
2155         do_process_drv_event(drv, gnlh->cmd, tb);
2156         return NL_SKIP;
2160 static int process_global_event(struct nl_msg *msg, void *arg)
2162         struct nl80211_global *global = arg;
2163         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2164         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2165         struct wpa_driver_nl80211_data *drv;
2166         int ifidx = -1;
2168         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2169                   genlmsg_attrlen(gnlh, 0), NULL);
2171         if (tb[NL80211_ATTR_IFINDEX])
2172                 ifidx = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
2174         dl_list_for_each(drv, &global->interfaces,
2175                          struct wpa_driver_nl80211_data, list) {
2176                 if (ifidx == -1 || ifidx == drv->ifindex ||
2177                     have_ifidx(drv, ifidx))
2178                         do_process_drv_event(drv, gnlh->cmd, tb);
2179         }
2181         return NL_SKIP;
2185 static int process_bss_event(struct nl_msg *msg, void *arg)
2187         struct i802_bss *bss = arg;
2188         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2189         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2191         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2192                   genlmsg_attrlen(gnlh, 0), NULL);
2194         switch (gnlh->cmd) {
2195         case NL80211_CMD_FRAME:
2196         case NL80211_CMD_FRAME_TX_STATUS:
2197                 mlme_event(bss->drv, gnlh->cmd, tb[NL80211_ATTR_FRAME],
2198                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
2199                            tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
2200                            tb[NL80211_ATTR_COOKIE]);
2201                 break;
2202         case NL80211_CMD_UNEXPECTED_FRAME:
2203                 nl80211_spurious_frame(bss, tb, 0);
2204                 break;
2205         case NL80211_CMD_UNEXPECTED_4ADDR_FRAME:
2206                 nl80211_spurious_frame(bss, tb, 1);
2207                 break;
2208         default:
2209                 wpa_printf(MSG_DEBUG, "nl80211: Ignored unknown event "
2210                            "(cmd=%d)", gnlh->cmd);
2211                 break;
2212         }
2214         return NL_SKIP;
2218 static void wpa_driver_nl80211_event_receive(int sock, void *eloop_ctx,
2219                                              void *handle)
2221         struct nl_cb *cb = eloop_ctx;
2223         wpa_printf(MSG_DEBUG, "nl80211: Event message available");
2225         nl_recvmsgs(handle, cb);
2229 /**
2230  * wpa_driver_nl80211_set_country - ask nl80211 to set the regulatory domain
2231  * @priv: driver_nl80211 private data
2232  * @alpha2_arg: country to which to switch to
2233  * Returns: 0 on success, -1 on failure
2234  *
2235  * This asks nl80211 to set the regulatory domain for given
2236  * country ISO / IEC alpha2.
2237  */
2238 static int wpa_driver_nl80211_set_country(void *priv, const char *alpha2_arg)
2240         struct i802_bss *bss = priv;
2241         struct wpa_driver_nl80211_data *drv = bss->drv;
2242         char alpha2[3];
2243         struct nl_msg *msg;
2245         msg = nlmsg_alloc();
2246         if (!msg)
2247                 return -ENOMEM;
2249         alpha2[0] = alpha2_arg[0];
2250         alpha2[1] = alpha2_arg[1];
2251         alpha2[2] = '\0';
2253         nl80211_cmd(drv, msg, 0, NL80211_CMD_REQ_SET_REG);
2255         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
2256         if (send_and_recv_msgs(drv, msg, NULL, NULL))
2257                 return -EINVAL;
2258         return 0;
2259 nla_put_failure:
2260         nlmsg_free(msg);
2261         return -EINVAL;
2265 struct wiphy_info_data {
2266         struct wpa_driver_capa *capa;
2268         unsigned int error:1;
2269         unsigned int device_ap_sme:1;
2270         unsigned int poll_command_supported:1;
2271         unsigned int data_tx_status:1;
2272         unsigned int monitor_supported:1;
2273 };
2276 static unsigned int probe_resp_offload_support(int supp_protocols)
2278         unsigned int prot = 0;
2280         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS)
2281                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS;
2282         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2)
2283                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS2;
2284         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P)
2285                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_P2P;
2286         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_80211U)
2287                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_INTERWORKING;
2289         return prot;
2293 static int wiphy_info_handler(struct nl_msg *msg, void *arg)
2295         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2296         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2297         struct wiphy_info_data *info = arg;
2298         int p2p_go_supported = 0, p2p_client_supported = 0;
2299         int p2p_concurrent = 0;
2300         int auth_supported = 0, connect_supported = 0;
2301         struct wpa_driver_capa *capa = info->capa;
2302         static struct nla_policy
2303         iface_combination_policy[NUM_NL80211_IFACE_COMB] = {
2304                 [NL80211_IFACE_COMB_LIMITS] = { .type = NLA_NESTED },
2305                 [NL80211_IFACE_COMB_MAXNUM] = { .type = NLA_U32 },
2306                 [NL80211_IFACE_COMB_STA_AP_BI_MATCH] = { .type = NLA_FLAG },
2307                 [NL80211_IFACE_COMB_NUM_CHANNELS] = { .type = NLA_U32 },
2308         },
2309         iface_limit_policy[NUM_NL80211_IFACE_LIMIT] = {
2310                 [NL80211_IFACE_LIMIT_TYPES] = { .type = NLA_NESTED },
2311                 [NL80211_IFACE_LIMIT_MAX] = { .type = NLA_U32 },
2312         };
2314         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2315                   genlmsg_attrlen(gnlh, 0), NULL);
2317         if (tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS])
2318                 capa->max_scan_ssids =
2319                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS]);
2321         if (tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS])
2322                 capa->max_sched_scan_ssids =
2323                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS]);
2325         if (tb[NL80211_ATTR_MAX_MATCH_SETS])
2326                 capa->max_match_sets =
2327                         nla_get_u8(tb[NL80211_ATTR_MAX_MATCH_SETS]);
2329         if (tb[NL80211_ATTR_SUPPORTED_IFTYPES]) {
2330                 struct nlattr *nl_mode;
2331                 int i;
2332                 nla_for_each_nested(nl_mode,
2333                                     tb[NL80211_ATTR_SUPPORTED_IFTYPES], i) {
2334                         switch (nla_type(nl_mode)) {
2335                         case NL80211_IFTYPE_AP:
2336                                 capa->flags |= WPA_DRIVER_FLAGS_AP;
2337                                 break;
2338                         case NL80211_IFTYPE_P2P_GO:
2339                                 p2p_go_supported = 1;
2340                                 break;
2341                         case NL80211_IFTYPE_P2P_CLIENT:
2342                                 p2p_client_supported = 1;
2343                                 break;
2344                         case NL80211_IFTYPE_MONITOR:
2345                                 info->monitor_supported = 1;
2346                                 break;
2347                         }
2348                 }
2349         }
2351         if (tb[NL80211_ATTR_INTERFACE_COMBINATIONS]) {
2352                 struct nlattr *nl_combi;
2353                 int rem_combi;
2355                 nla_for_each_nested(nl_combi,
2356                                     tb[NL80211_ATTR_INTERFACE_COMBINATIONS],
2357                                     rem_combi) {
2358                         struct nlattr *tb_comb[NUM_NL80211_IFACE_COMB];
2359                         struct nlattr *tb_limit[NUM_NL80211_IFACE_LIMIT];
2360                         struct nlattr *nl_limit, *nl_mode;
2361                         int err, rem_limit, rem_mode;
2362                         int combination_has_p2p = 0, combination_has_mgd = 0;
2364                         err = nla_parse_nested(tb_comb, MAX_NL80211_IFACE_COMB,
2365                                                nl_combi,
2366                                                iface_combination_policy);
2367                         if (err || !tb_comb[NL80211_IFACE_COMB_LIMITS] ||
2368                             !tb_comb[NL80211_IFACE_COMB_MAXNUM] ||
2369                             !tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS])
2370                                 goto broken_combination;
2372                         nla_for_each_nested(nl_limit,
2373                                             tb_comb[NL80211_IFACE_COMB_LIMITS],
2374                                             rem_limit) {
2375                                 err = nla_parse_nested(tb_limit,
2376                                                        MAX_NL80211_IFACE_LIMIT,
2377                                                        nl_limit,
2378                                                        iface_limit_policy);
2379                                 if (err ||
2380                                     !tb_limit[NL80211_IFACE_LIMIT_TYPES])
2381                                         goto broken_combination;
2383                                 nla_for_each_nested(
2384                                         nl_mode,
2385                                         tb_limit[NL80211_IFACE_LIMIT_TYPES],
2386                                         rem_mode) {
2387                                         int ift = nla_type(nl_mode);
2388                                         if (ift == NL80211_IFTYPE_P2P_GO ||
2389                                             ift == NL80211_IFTYPE_P2P_CLIENT)
2390                                                 combination_has_p2p = 1;
2391                                         if (ift == NL80211_IFTYPE_STATION)
2392                                                 combination_has_mgd = 1;
2393                                 }
2394                                 if (combination_has_p2p && combination_has_mgd)
2395                                         break;
2396                         }
2398                         if (combination_has_p2p && combination_has_mgd) {
2399                                 p2p_concurrent = 1;
2400                                 break;
2401                         }
2403 broken_combination:
2404                         ;
2405                 }
2406         }
2408         if (tb[NL80211_ATTR_SUPPORTED_COMMANDS]) {
2409                 struct nlattr *nl_cmd;
2410                 int i;
2412                 nla_for_each_nested(nl_cmd,
2413                                     tb[NL80211_ATTR_SUPPORTED_COMMANDS], i) {
2414                         switch (nla_get_u32(nl_cmd)) {
2415                         case NL80211_CMD_AUTHENTICATE:
2416                                 auth_supported = 1;
2417                                 break;
2418                         case NL80211_CMD_CONNECT:
2419                                 connect_supported = 1;
2420                                 break;
2421                         case NL80211_CMD_START_SCHED_SCAN:
2422                                 capa->sched_scan_supported = 1;
2423                                 break;
2424                         case NL80211_CMD_PROBE_CLIENT:
2425                                 info->poll_command_supported = 1;
2426                                 break;
2427                         }
2428                 }
2429         }
2431         if (tb[NL80211_ATTR_OFFCHANNEL_TX_OK]) {
2432                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based "
2433                            "off-channel TX");
2434                 capa->flags |= WPA_DRIVER_FLAGS_OFFCHANNEL_TX;
2435         }
2437         if (tb[NL80211_ATTR_ROAM_SUPPORT]) {
2438                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based roaming");
2439                 capa->flags |= WPA_DRIVER_FLAGS_BSS_SELECTION;
2440         }
2442         /* default to 5000 since early versions of mac80211 don't set it */
2443         capa->max_remain_on_chan = 5000;
2445         if (tb[NL80211_ATTR_SUPPORT_AP_UAPSD])
2446                 capa->flags |= WPA_DRIVER_FLAGS_AP_UAPSD;
2448         if (tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION])
2449                 capa->max_remain_on_chan =
2450                         nla_get_u32(tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION]);
2452         if (auth_supported)
2453                 capa->flags |= WPA_DRIVER_FLAGS_SME;
2454         else if (!connect_supported) {
2455                 wpa_printf(MSG_INFO, "nl80211: Driver does not support "
2456                            "authentication/association or connect commands");
2457                 info->error = 1;
2458         }
2460         if (p2p_go_supported && p2p_client_supported)
2461                 capa->flags |= WPA_DRIVER_FLAGS_P2P_CAPABLE;
2462         if (p2p_concurrent) {
2463                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
2464                            "interface (driver advertised support)");
2465                 capa->flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
2466                 capa->flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
2467         }
2469         if (tb[NL80211_ATTR_TDLS_SUPPORT]) {
2470                 wpa_printf(MSG_DEBUG, "nl80211: TDLS supported");
2471                 capa->flags |= WPA_DRIVER_FLAGS_TDLS_SUPPORT;
2473                 if (tb[NL80211_ATTR_TDLS_EXTERNAL_SETUP]) {
2474                         wpa_printf(MSG_DEBUG, "nl80211: TDLS external setup");
2475                         capa->flags |=
2476                                 WPA_DRIVER_FLAGS_TDLS_EXTERNAL_SETUP;
2477                 }
2478         }
2480         if (tb[NL80211_ATTR_DEVICE_AP_SME])
2481                 info->device_ap_sme = 1;
2483         if (tb[NL80211_ATTR_FEATURE_FLAGS]) {
2484                 u32 flags = nla_get_u32(tb[NL80211_ATTR_FEATURE_FLAGS]);
2486                 if (flags & NL80211_FEATURE_SK_TX_STATUS)
2487                         info->data_tx_status = 1;
2488         }
2490         if (tb[NL80211_ATTR_PROBE_RESP_OFFLOAD]) {
2491                 int protocols =
2492                         nla_get_u32(tb[NL80211_ATTR_PROBE_RESP_OFFLOAD]);
2493                 wpa_printf(MSG_DEBUG, "nl80211: Supports Probe Response "
2494                            "offload in AP mode");
2495                 capa->flags |= WPA_DRIVER_FLAGS_PROBE_RESP_OFFLOAD;
2496                 capa->probe_resp_offloads =
2497                         probe_resp_offload_support(protocols);
2498         }
2500         return NL_SKIP;
2504 static int wpa_driver_nl80211_get_info(struct wpa_driver_nl80211_data *drv,
2505                                        struct wiphy_info_data *info)
2507         struct nl_msg *msg;
2509         os_memset(info, 0, sizeof(*info));
2510         info->capa = &drv->capa;
2512         msg = nlmsg_alloc();
2513         if (!msg)
2514                 return -1;
2516         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
2518         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->first_bss.ifindex);
2520         if (send_and_recv_msgs(drv, msg, wiphy_info_handler, info) == 0)
2521                 return 0;
2522         msg = NULL;
2523 nla_put_failure:
2524         nlmsg_free(msg);
2525         return -1;
2529 static int wpa_driver_nl80211_capa(struct wpa_driver_nl80211_data *drv)
2531         struct wiphy_info_data info;
2532         if (wpa_driver_nl80211_get_info(drv, &info))
2533                 return -1;
2535         if (info.error)
2536                 return -1;
2538         drv->has_capability = 1;
2539         /* For now, assume TKIP, CCMP, WPA, WPA2 are supported */
2540         drv->capa.key_mgmt = WPA_DRIVER_CAPA_KEY_MGMT_WPA |
2541                 WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK |
2542                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2 |
2543                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK;
2544         drv->capa.enc = WPA_DRIVER_CAPA_ENC_WEP40 |
2545                 WPA_DRIVER_CAPA_ENC_WEP104 |
2546                 WPA_DRIVER_CAPA_ENC_TKIP |
2547                 WPA_DRIVER_CAPA_ENC_CCMP;
2548         drv->capa.auth = WPA_DRIVER_AUTH_OPEN |
2549                 WPA_DRIVER_AUTH_SHARED |
2550                 WPA_DRIVER_AUTH_LEAP;
2552         drv->capa.flags |= WPA_DRIVER_FLAGS_SANE_ERROR_CODES;
2553         drv->capa.flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE;
2554         drv->capa.flags |= WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2555         drv->capa.flags |= WPA_DRIVER_FLAGS_DEAUTH_TX_STATUS;
2557         drv->device_ap_sme = info.device_ap_sme;
2558         drv->poll_command_supported = info.poll_command_supported;
2559         drv->data_tx_status = info.data_tx_status;
2561         /*
2562          * If poll command is supported mac80211 is new enough to
2563          * have everything we need to not need monitor interfaces.
2564          */
2565         drv->use_monitor = !info.poll_command_supported;
2567         if (drv->device_ap_sme && drv->use_monitor) {
2568                 /*
2569                  * Non-mac80211 drivers may not support monitor interface.
2570                  * Make sure we do not get stuck with incorrect capability here
2571                  * by explicitly testing this.
2572                  */
2573                 if (!info.monitor_supported) {
2574                         wpa_printf(MSG_DEBUG, "nl80211: Disable use_monitor "
2575                                    "with device_ap_sme since no monitor mode "
2576                                    "support detected");
2577                         drv->use_monitor = 0;
2578                 }
2579         }
2581         /*
2582          * If we aren't going to use monitor interfaces, but the
2583          * driver doesn't support data TX status, we won't get TX
2584          * status for EAPOL frames.
2585          */
2586         if (!drv->use_monitor && !info.data_tx_status)
2587                 drv->capa.flags &= ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2589         return 0;
2593 #ifdef ANDROID
2594 static int android_genl_ctrl_resolve(struct nl_handle *handle,
2595                                      const char *name)
2597         /*
2598          * Android ICS has very minimal genl_ctrl_resolve() implementation, so
2599          * need to work around that.
2600          */
2601         struct nl_cache *cache = NULL;
2602         struct genl_family *nl80211 = NULL;
2603         int id = -1;
2605         if (genl_ctrl_alloc_cache(handle, &cache) < 0) {
2606                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
2607                            "netlink cache");
2608                 goto fail;
2609         }
2611         nl80211 = genl_ctrl_search_by_name(cache, name);
2612         if (nl80211 == NULL)
2613                 goto fail;
2615         id = genl_family_get_id(nl80211);
2617 fail:
2618         if (nl80211)
2619                 genl_family_put(nl80211);
2620         if (cache)
2621                 nl_cache_free(cache);
2623         return id;
2625 #define genl_ctrl_resolve android_genl_ctrl_resolve
2626 #endif /* ANDROID */
2629 static int wpa_driver_nl80211_init_nl_global(struct nl80211_global *global)
2631         int ret;
2633         global->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2634         if (global->nl_cb == NULL) {
2635                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
2636                            "callbacks");
2637                 return -1;
2638         }
2640         global->nl = nl_create_handle(global->nl_cb, "nl");
2641         if (global->nl == NULL)
2642                 goto err;
2644         global->nl80211_id = genl_ctrl_resolve(global->nl, "nl80211");
2645         if (global->nl80211_id < 0) {
2646                 wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
2647                            "found");
2648                 goto err;
2649         }
2651         global->nl_event = nl_create_handle(global->nl_cb, "event");
2652         if (global->nl_event == NULL)
2653                 goto err;
2655         ret = nl_get_multicast_id(global, "nl80211", "scan");
2656         if (ret >= 0)
2657                 ret = nl_socket_add_membership(global->nl_event, ret);
2658         if (ret < 0) {
2659                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
2660                            "membership for scan events: %d (%s)",
2661                            ret, strerror(-ret));
2662                 goto err;
2663         }
2665         ret = nl_get_multicast_id(global, "nl80211", "mlme");
2666         if (ret >= 0)
2667                 ret = nl_socket_add_membership(global->nl_event, ret);
2668         if (ret < 0) {
2669                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
2670                            "membership for mlme events: %d (%s)",
2671                            ret, strerror(-ret));
2672                 goto err;
2673         }
2675         ret = nl_get_multicast_id(global, "nl80211", "regulatory");
2676         if (ret >= 0)
2677                 ret = nl_socket_add_membership(global->nl_event, ret);
2678         if (ret < 0) {
2679                 wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
2680                            "membership for regulatory events: %d (%s)",
2681                            ret, strerror(-ret));
2682                 /* Continue without regulatory events */
2683         }
2685         nl_cb_set(global->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2686                   no_seq_check, NULL);
2687         nl_cb_set(global->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2688                   process_global_event, global);
2690         eloop_register_read_sock(nl_socket_get_fd(global->nl_event),
2691                                  wpa_driver_nl80211_event_receive,
2692                                  global->nl_cb, global->nl_event);
2694         return 0;
2696 err:
2697         nl_destroy_handles(&global->nl_event);
2698         nl_destroy_handles(&global->nl);
2699         nl_cb_put(global->nl_cb);
2700         global->nl_cb = NULL;
2701         return -1;
2705 static int wpa_driver_nl80211_init_nl(struct wpa_driver_nl80211_data *drv)
2707         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2708         if (!drv->nl_cb) {
2709                 wpa_printf(MSG_ERROR, "nl80211: Failed to alloc cb struct");
2710                 return -1;
2711         }
2713         nl_cb_set(drv->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2714                   no_seq_check, NULL);
2715         nl_cb_set(drv->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2716                   process_drv_event, drv);
2718         return 0;
2722 static void wpa_driver_nl80211_rfkill_blocked(void *ctx)
2724         wpa_printf(MSG_DEBUG, "nl80211: RFKILL blocked");
2725         /*
2726          * This may be for any interface; use ifdown event to disable
2727          * interface.
2728          */
2732 static void wpa_driver_nl80211_rfkill_unblocked(void *ctx)
2734         struct wpa_driver_nl80211_data *drv = ctx;
2735         wpa_printf(MSG_DEBUG, "nl80211: RFKILL unblocked");
2736         if (linux_set_iface_flags(drv->global->ioctl_sock,
2737                                   drv->first_bss.ifname, 1)) {
2738                 wpa_printf(MSG_DEBUG, "nl80211: Could not set interface UP "
2739                            "after rfkill unblock");
2740                 return;
2741         }
2742         /* rtnetlink ifup handler will report interface as enabled */
2746 static void nl80211_get_phy_name(struct wpa_driver_nl80211_data *drv)
2748         /* Find phy (radio) to which this interface belongs */
2749         char buf[90], *pos;
2750         int f, rv;
2752         drv->phyname[0] = '\0';
2753         snprintf(buf, sizeof(buf) - 1, "/sys/class/net/%s/phy80211/name",
2754                  drv->first_bss.ifname);
2755         f = open(buf, O_RDONLY);
2756         if (f < 0) {
2757                 wpa_printf(MSG_DEBUG, "Could not open file %s: %s",
2758                            buf, strerror(errno));
2759                 return;
2760         }
2762         rv = read(f, drv->phyname, sizeof(drv->phyname) - 1);
2763         close(f);
2764         if (rv < 0) {
2765                 wpa_printf(MSG_DEBUG, "Could not read file %s: %s",
2766                            buf, strerror(errno));
2767                 return;
2768         }
2770         drv->phyname[rv] = '\0';
2771         pos = os_strchr(drv->phyname, '\n');
2772         if (pos)
2773                 *pos = '\0';
2774         wpa_printf(MSG_DEBUG, "nl80211: interface %s in phy %s",
2775                    drv->first_bss.ifname, drv->phyname);
2779 static void wpa_driver_nl80211_handle_eapol_tx_status(int sock,
2780                                                       void *eloop_ctx,
2781                                                       void *handle)
2783         struct wpa_driver_nl80211_data *drv = eloop_ctx;
2784         u8 data[2048];
2785         struct msghdr msg;
2786         struct iovec entry;
2787         struct {
2788                 struct cmsghdr cm;
2789                 char control[512];
2790         } control;
2791         struct cmsghdr *cmsg;
2792         int res, found_ee = 0, found_wifi = 0, acked = 0;
2793         union wpa_event_data event;
2795         memset(&msg, 0, sizeof(msg));
2796         msg.msg_iov = &entry;
2797         msg.msg_iovlen = 1;
2798         entry.iov_base = data;
2799         entry.iov_len = sizeof(data);
2800         msg.msg_control = &control;
2801         msg.msg_controllen = sizeof(control);
2803         res = recvmsg(sock, &msg, MSG_ERRQUEUE);
2804         /* if error or not fitting 802.3 header, return */
2805         if (res < 14)
2806                 return;
2808         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg))
2809         {
2810                 if (cmsg->cmsg_level == SOL_SOCKET &&
2811                     cmsg->cmsg_type == SCM_WIFI_STATUS) {
2812                         int *ack;
2814                         found_wifi = 1;
2815                         ack = (void *)CMSG_DATA(cmsg);
2816                         acked = *ack;
2817                 }
2819                 if (cmsg->cmsg_level == SOL_PACKET &&
2820                     cmsg->cmsg_type == PACKET_TX_TIMESTAMP) {
2821                         struct sock_extended_err *err =
2822                                 (struct sock_extended_err *)CMSG_DATA(cmsg);
2824                         if (err->ee_origin == SO_EE_ORIGIN_TXSTATUS)
2825                                 found_ee = 1;
2826                 }
2827         }
2829         if (!found_ee || !found_wifi)
2830                 return;
2832         memset(&event, 0, sizeof(event));
2833         event.eapol_tx_status.dst = data;
2834         event.eapol_tx_status.data = data + 14;
2835         event.eapol_tx_status.data_len = res - 14;
2836         event.eapol_tx_status.ack = acked;
2837         wpa_supplicant_event(drv->ctx, EVENT_EAPOL_TX_STATUS, &event);
2841 static int nl80211_init_bss(struct i802_bss *bss)
2843         bss->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2844         if (!bss->nl_cb)
2845                 return -1;
2847         nl_cb_set(bss->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2848                   no_seq_check, NULL);
2849         nl_cb_set(bss->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2850                   process_bss_event, bss);
2852         return 0;
2856 static void nl80211_destroy_bss(struct i802_bss *bss)
2858         nl_cb_put(bss->nl_cb);
2859         bss->nl_cb = NULL;
2863 /**
2864  * wpa_driver_nl80211_init - Initialize nl80211 driver interface
2865  * @ctx: context to be used when calling wpa_supplicant functions,
2866  * e.g., wpa_supplicant_event()
2867  * @ifname: interface name, e.g., wlan0
2868  * @global_priv: private driver global data from global_init()
2869  * Returns: Pointer to private data, %NULL on failure
2870  */
2871 static void * wpa_driver_nl80211_init(void *ctx, const char *ifname,
2872                                       void *global_priv)
2874         struct wpa_driver_nl80211_data *drv;
2875         struct rfkill_config *rcfg;
2876         struct i802_bss *bss;
2878         if (global_priv == NULL)
2879                 return NULL;
2880         drv = os_zalloc(sizeof(*drv));
2881         if (drv == NULL)
2882                 return NULL;
2883         drv->global = global_priv;
2884         drv->ctx = ctx;
2885         bss = &drv->first_bss;
2886         bss->drv = drv;
2887         os_strlcpy(bss->ifname, ifname, sizeof(bss->ifname));
2888         drv->monitor_ifidx = -1;
2889         drv->monitor_sock = -1;
2890         drv->eapol_tx_sock = -1;
2891         drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
2893         if (wpa_driver_nl80211_init_nl(drv)) {
2894                 os_free(drv);
2895                 return NULL;
2896         }
2898         if (nl80211_init_bss(bss))
2899                 goto failed;
2901         nl80211_get_phy_name(drv);
2903         rcfg = os_zalloc(sizeof(*rcfg));
2904         if (rcfg == NULL)
2905                 goto failed;
2906         rcfg->ctx = drv;
2907         os_strlcpy(rcfg->ifname, ifname, sizeof(rcfg->ifname));
2908         rcfg->blocked_cb = wpa_driver_nl80211_rfkill_blocked;
2909         rcfg->unblocked_cb = wpa_driver_nl80211_rfkill_unblocked;
2910         drv->rfkill = rfkill_init(rcfg);
2911         if (drv->rfkill == NULL) {
2912                 wpa_printf(MSG_DEBUG, "nl80211: RFKILL status not available");
2913                 os_free(rcfg);
2914         }
2916         if (wpa_driver_nl80211_finish_drv_init(drv))
2917                 goto failed;
2919         drv->eapol_tx_sock = socket(PF_PACKET, SOCK_DGRAM, 0);
2920         if (drv->eapol_tx_sock < 0)
2921                 goto failed;
2923         if (drv->data_tx_status) {
2924                 int enabled = 1;
2926                 if (setsockopt(drv->eapol_tx_sock, SOL_SOCKET, SO_WIFI_STATUS,
2927                                &enabled, sizeof(enabled)) < 0) {
2928                         wpa_printf(MSG_DEBUG,
2929                                 "nl80211: wifi status sockopt failed\n");
2930                         drv->data_tx_status = 0;
2931                         if (!drv->use_monitor)
2932                                 drv->capa.flags &=
2933                                         ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2934                 } else {
2935                         eloop_register_read_sock(drv->eapol_tx_sock,
2936                                 wpa_driver_nl80211_handle_eapol_tx_status,
2937                                 drv, NULL);
2938                 }
2939         }
2941         if (drv->global) {
2942                 dl_list_add(&drv->global->interfaces, &drv->list);
2943                 drv->in_interface_list = 1;
2944         }
2946         return bss;
2948 failed:
2949         wpa_driver_nl80211_deinit(bss);
2950         return NULL;
2954 static int nl80211_register_frame(struct i802_bss *bss,
2955                                   struct nl_handle *nl_handle,
2956                                   u16 type, const u8 *match, size_t match_len)
2958         struct wpa_driver_nl80211_data *drv = bss->drv;
2959         struct nl_msg *msg;
2960         int ret = -1;
2962         msg = nlmsg_alloc();
2963         if (!msg)
2964                 return -1;
2966         wpa_printf(MSG_DEBUG, "nl80211: Register frame type=0x%x nl_handle=%p",
2967                    type, nl_handle);
2968         wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
2969                     match, match_len);
2971         nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_ACTION);
2973         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
2974         NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE, type);
2975         NLA_PUT(msg, NL80211_ATTR_FRAME_MATCH, match_len, match);
2977         ret = send_and_recv(drv->global, nl_handle, msg, NULL, NULL);
2978         msg = NULL;
2979         if (ret) {
2980                 wpa_printf(MSG_DEBUG, "nl80211: Register frame command "
2981                            "failed (type=%u): ret=%d (%s)",
2982                            type, ret, strerror(-ret));
2983                 wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
2984                             match, match_len);
2985                 goto nla_put_failure;
2986         }
2987         ret = 0;
2988 nla_put_failure:
2989         nlmsg_free(msg);
2990         return ret;
2994 static int nl80211_alloc_mgmt_handle(struct i802_bss *bss)
2996         struct wpa_driver_nl80211_data *drv = bss->drv;
2998         if (bss->nl_mgmt) {
2999                 wpa_printf(MSG_DEBUG, "nl80211: Mgmt reporting "
3000                            "already on! (nl_mgmt=%p)", bss->nl_mgmt);
3001                 return -1;
3002         }
3004         bss->nl_mgmt = nl_create_handle(drv->nl_cb, "mgmt");
3005         if (bss->nl_mgmt == NULL)
3006                 return -1;
3008         eloop_register_read_sock(nl_socket_get_fd(bss->nl_mgmt),
3009                                  wpa_driver_nl80211_event_receive, bss->nl_cb,
3010                                  bss->nl_mgmt);
3012         return 0;
3016 static int nl80211_register_action_frame(struct i802_bss *bss,
3017                                          const u8 *match, size_t match_len)
3019         u16 type = (WLAN_FC_TYPE_MGMT << 2) | (WLAN_FC_STYPE_ACTION << 4);
3020         return nl80211_register_frame(bss, bss->nl_mgmt,
3021                                       type, match, match_len);
3025 static int nl80211_mgmt_subscribe_non_ap(struct i802_bss *bss)
3027         struct wpa_driver_nl80211_data *drv = bss->drv;
3029         if (nl80211_alloc_mgmt_handle(bss))
3030                 return -1;
3031         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with non-AP "
3032                    "handle %p", bss->nl_mgmt);
3034 #if defined(CONFIG_P2P) || defined(CONFIG_INTERWORKING)
3035         /* GAS Initial Request */
3036         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0a", 2) < 0)
3037                 return -1;
3038         /* GAS Initial Response */
3039         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0b", 2) < 0)
3040                 return -1;
3041         /* GAS Comeback Request */
3042         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0c", 2) < 0)
3043                 return -1;
3044         /* GAS Comeback Response */
3045         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0d", 2) < 0)
3046                 return -1;
3047 #endif /* CONFIG_P2P || CONFIG_INTERWORKING */
3048 #ifdef CONFIG_P2P
3049         /* P2P Public Action */
3050         if (nl80211_register_action_frame(bss,
3051                                           (u8 *) "\x04\x09\x50\x6f\x9a\x09",
3052                                           6) < 0)
3053                 return -1;
3054         /* P2P Action */
3055         if (nl80211_register_action_frame(bss,
3056                                           (u8 *) "\x7f\x50\x6f\x9a\x09",
3057                                           5) < 0)
3058                 return -1;
3059 #endif /* CONFIG_P2P */
3060 #ifdef CONFIG_IEEE80211W
3061         /* SA Query Response */
3062         if (nl80211_register_action_frame(bss, (u8 *) "\x08\x01", 2) < 0)
3063                 return -1;
3064 #endif /* CONFIG_IEEE80211W */
3065 #ifdef CONFIG_TDLS
3066         if ((drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT)) {
3067                 /* TDLS Discovery Response */
3068                 if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0e", 2) <
3069                     0)
3070                         return -1;
3071         }
3072 #endif /* CONFIG_TDLS */
3074         /* FT Action frames */
3075         if (nl80211_register_action_frame(bss, (u8 *) "\x06", 1) < 0)
3076                 return -1;
3077         else
3078                 drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_FT |
3079                         WPA_DRIVER_CAPA_KEY_MGMT_FT_PSK;
3081         /* WNM - BSS Transition Management Request */
3082         if (nl80211_register_action_frame(bss, (u8 *) "\x0a\x07", 2) < 0)
3083                 return -1;
3085         return 0;
3089 static int nl80211_register_spurious_class3(struct i802_bss *bss)
3091         struct wpa_driver_nl80211_data *drv = bss->drv;
3092         struct nl_msg *msg;
3093         int ret = -1;
3095         msg = nlmsg_alloc();
3096         if (!msg)
3097                 return -1;
3099         nl80211_cmd(drv, msg, 0, NL80211_CMD_UNEXPECTED_FRAME);
3101         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3103         ret = send_and_recv(drv->global, bss->nl_mgmt, msg, NULL, NULL);
3104         msg = NULL;
3105         if (ret) {
3106                 wpa_printf(MSG_DEBUG, "nl80211: Register spurious class3 "
3107                            "failed: ret=%d (%s)",
3108                            ret, strerror(-ret));
3109                 goto nla_put_failure;
3110         }
3111         ret = 0;
3112 nla_put_failure:
3113         nlmsg_free(msg);
3114         return ret;
3118 static int nl80211_mgmt_subscribe_ap(struct i802_bss *bss)
3120         static const int stypes[] = {
3121                 WLAN_FC_STYPE_AUTH,
3122                 WLAN_FC_STYPE_ASSOC_REQ,
3123                 WLAN_FC_STYPE_REASSOC_REQ,
3124                 WLAN_FC_STYPE_DISASSOC,
3125                 WLAN_FC_STYPE_DEAUTH,
3126                 WLAN_FC_STYPE_ACTION,
3127                 WLAN_FC_STYPE_PROBE_REQ,
3128 /* Beacon doesn't work as mac80211 doesn't currently allow
3129  * it, but it wouldn't really be the right thing anyway as
3130  * it isn't per interface ... maybe just dump the scan
3131  * results periodically for OLBC?
3132  */
3133 //              WLAN_FC_STYPE_BEACON,
3134         };
3135         unsigned int i;
3137         if (nl80211_alloc_mgmt_handle(bss))
3138                 return -1;
3139         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3140                    "handle %p", bss->nl_mgmt);
3142         for (i = 0; i < sizeof(stypes) / sizeof(stypes[0]); i++) {
3143                 if (nl80211_register_frame(bss, bss->nl_mgmt,
3144                                            (WLAN_FC_TYPE_MGMT << 2) |
3145                                            (stypes[i] << 4),
3146                                            NULL, 0) < 0) {
3147                         goto out_err;
3148                 }
3149         }
3151         if (nl80211_register_spurious_class3(bss))
3152                 goto out_err;
3154         if (nl80211_get_wiphy_data_ap(bss) == NULL)
3155                 goto out_err;
3157         return 0;
3159 out_err:
3160         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3161         nl_destroy_handles(&bss->nl_mgmt);
3162         return -1;
3166 static int nl80211_mgmt_subscribe_ap_dev_sme(struct i802_bss *bss)
3168         if (nl80211_alloc_mgmt_handle(bss))
3169                 return -1;
3170         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3171                    "handle %p (device SME)", bss->nl_mgmt);
3173         if (nl80211_register_frame(bss, bss->nl_mgmt,
3174                                    (WLAN_FC_TYPE_MGMT << 2) |
3175                                    (WLAN_FC_STYPE_ACTION << 4),
3176                                    NULL, 0) < 0)
3177                 goto out_err;
3179         return 0;
3181 out_err:
3182         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3183         nl_destroy_handles(&bss->nl_mgmt);
3184         return -1;
3188 static void nl80211_mgmt_unsubscribe(struct i802_bss *bss, const char *reason)
3190         if (bss->nl_mgmt == NULL)
3191                 return;
3192         wpa_printf(MSG_DEBUG, "nl80211: Unsubscribe mgmt frames handle %p "
3193                    "(%s)", bss->nl_mgmt, reason);
3194         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3195         nl_destroy_handles(&bss->nl_mgmt);
3197         nl80211_put_wiphy_data_ap(bss);
3201 static void wpa_driver_nl80211_send_rfkill(void *eloop_ctx, void *timeout_ctx)
3203         wpa_supplicant_event(timeout_ctx, EVENT_INTERFACE_DISABLED, NULL);
3207 static int
3208 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv)
3210         struct i802_bss *bss = &drv->first_bss;
3211         int send_rfkill_event = 0;
3213         drv->ifindex = if_nametoindex(bss->ifname);
3214         drv->first_bss.ifindex = drv->ifindex;
3216 #ifndef HOSTAPD
3217         /*
3218          * Make sure the interface starts up in station mode unless this is a
3219          * dynamically added interface (e.g., P2P) that was already configured
3220          * with proper iftype.
3221          */
3222         if (drv->ifindex != drv->global->if_add_ifindex &&
3223             wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION) < 0) {
3224                 wpa_printf(MSG_ERROR, "nl80211: Could not configure driver to "
3225                            "use managed mode");
3226                 return -1;
3227         }
3229         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
3230                 if (rfkill_is_blocked(drv->rfkill)) {
3231                         wpa_printf(MSG_DEBUG, "nl80211: Could not yet enable "
3232                                    "interface '%s' due to rfkill",
3233                                    bss->ifname);
3234                         drv->if_disabled = 1;
3235                         send_rfkill_event = 1;
3236                 } else {
3237                         wpa_printf(MSG_ERROR, "nl80211: Could not set "
3238                                    "interface '%s' UP", bss->ifname);
3239                         return -1;
3240                 }
3241         }
3243         netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
3244                                1, IF_OPER_DORMANT);
3245 #endif /* HOSTAPD */
3247         if (wpa_driver_nl80211_capa(drv))
3248                 return -1;
3250         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
3251                                bss->addr))
3252                 return -1;
3254         if (send_rfkill_event) {
3255                 eloop_register_timeout(0, 0, wpa_driver_nl80211_send_rfkill,
3256                                        drv, drv->ctx);
3257         }
3259         return 0;
3263 static int wpa_driver_nl80211_del_beacon(struct wpa_driver_nl80211_data *drv)
3265         struct nl_msg *msg;
3267         msg = nlmsg_alloc();
3268         if (!msg)
3269                 return -ENOMEM;
3271         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_BEACON);
3272         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3274         return send_and_recv_msgs(drv, msg, NULL, NULL);
3275  nla_put_failure:
3276         nlmsg_free(msg);
3277         return -ENOBUFS;
3281 /**
3282  * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
3283  * @priv: Pointer to private nl80211 data from wpa_driver_nl80211_init()
3284  *
3285  * Shut down driver interface and processing of driver events. Free
3286  * private data buffer if one was allocated in wpa_driver_nl80211_init().
3287  */
3288 static void wpa_driver_nl80211_deinit(void *priv)
3290         struct i802_bss *bss = priv;
3291         struct wpa_driver_nl80211_data *drv = bss->drv;
3293         if (drv->data_tx_status)
3294                 eloop_unregister_read_sock(drv->eapol_tx_sock);
3295         if (drv->eapol_tx_sock >= 0)
3296                 close(drv->eapol_tx_sock);
3298         if (bss->nl_preq)
3299                 wpa_driver_nl80211_probe_req_report(bss, 0);
3300         if (bss->added_if_into_bridge) {
3301                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
3302                                     bss->ifname) < 0)
3303                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3304                                    "interface %s from bridge %s: %s",
3305                                    bss->ifname, bss->brname, strerror(errno));
3306         }
3307         if (bss->added_bridge) {
3308                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
3309                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3310                                    "bridge %s: %s",
3311                                    bss->brname, strerror(errno));
3312         }
3314         nl80211_remove_monitor_interface(drv);
3316         if (is_ap_interface(drv->nlmode))
3317                 wpa_driver_nl80211_del_beacon(drv);
3319 #ifdef HOSTAPD
3320         if (drv->last_freq_ht) {
3321                 /* Clear HT flags from the driver */
3322                 struct hostapd_freq_params freq;
3323                 os_memset(&freq, 0, sizeof(freq));
3324                 freq.freq = drv->last_freq;
3325                 i802_set_freq(priv, &freq);
3326         }
3328         if (drv->eapol_sock >= 0) {
3329                 eloop_unregister_read_sock(drv->eapol_sock);
3330                 close(drv->eapol_sock);
3331         }
3333         if (drv->if_indices != drv->default_if_indices)
3334                 os_free(drv->if_indices);
3335 #endif /* HOSTAPD */
3337         if (drv->disabled_11b_rates)
3338                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
3340         netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, 0,
3341                                IF_OPER_UP);
3342         rfkill_deinit(drv->rfkill);
3344         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3346         (void) linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0);
3347         wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION);
3348         nl80211_mgmt_unsubscribe(bss, "deinit");
3350         nl_cb_put(drv->nl_cb);
3352         nl80211_destroy_bss(&drv->first_bss);
3354         os_free(drv->filter_ssids);
3356         os_free(drv->auth_ie);
3358         if (drv->in_interface_list)
3359                 dl_list_del(&drv->list);
3361         os_free(drv);
3365 /**
3366  * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
3367  * @eloop_ctx: Driver private data
3368  * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
3369  *
3370  * This function can be used as registered timeout when starting a scan to
3371  * generate a scan completed event if the driver does not report this.
3372  */
3373 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
3375         struct wpa_driver_nl80211_data *drv = eloop_ctx;
3376         if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED) {
3377                 wpa_driver_nl80211_set_mode(&drv->first_bss,
3378                                             drv->ap_scan_as_station);
3379                 drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
3380         }
3381         wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
3382         wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
3386 /**
3387  * wpa_driver_nl80211_scan - Request the driver to initiate scan
3388  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3389  * @params: Scan parameters
3390  * Returns: 0 on success, -1 on failure
3391  */
3392 static int wpa_driver_nl80211_scan(void *priv,
3393                                    struct wpa_driver_scan_params *params)
3395         struct i802_bss *bss = priv;
3396         struct wpa_driver_nl80211_data *drv = bss->drv;
3397         int ret = 0, timeout;
3398         struct nl_msg *msg, *ssids, *freqs, *rates;
3399         size_t i;
3401         drv->scan_for_auth = 0;
3403         msg = nlmsg_alloc();
3404         ssids = nlmsg_alloc();
3405         freqs = nlmsg_alloc();
3406         rates = nlmsg_alloc();
3407         if (!msg || !ssids || !freqs || !rates) {
3408                 nlmsg_free(msg);
3409                 nlmsg_free(ssids);
3410                 nlmsg_free(freqs);
3411                 nlmsg_free(rates);
3412                 return -1;
3413         }
3415         os_free(drv->filter_ssids);
3416         drv->filter_ssids = params->filter_ssids;
3417         params->filter_ssids = NULL;
3418         drv->num_filter_ssids = params->num_filter_ssids;
3420         nl80211_cmd(drv, msg, 0, NL80211_CMD_TRIGGER_SCAN);
3422         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3424         for (i = 0; i < params->num_ssids; i++) {
3425                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan SSID",
3426                                   params->ssids[i].ssid,
3427                                   params->ssids[i].ssid_len);
3428                 NLA_PUT(ssids, i + 1, params->ssids[i].ssid_len,
3429                         params->ssids[i].ssid);
3430         }
3431         if (params->num_ssids)
3432                 nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
3434         if (params->extra_ies) {
3435                 wpa_hexdump(MSG_MSGDUMP, "nl80211: Scan extra IEs",
3436                             params->extra_ies, params->extra_ies_len);
3437                 NLA_PUT(msg, NL80211_ATTR_IE, params->extra_ies_len,
3438                         params->extra_ies);
3439         }
3441         if (params->freqs) {
3442                 for (i = 0; params->freqs[i]; i++) {
3443                         wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
3444                                    "MHz", params->freqs[i]);
3445                         NLA_PUT_U32(freqs, i + 1, params->freqs[i]);
3446                 }
3447                 nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs);
3448         }
3450         if (params->p2p_probe) {
3451                 /*
3452                  * Remove 2.4 GHz rates 1, 2, 5.5, 11 Mbps from supported rates
3453                  * by masking out everything else apart from the OFDM rates 6,
3454                  * 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS rates. All 5 GHz
3455                  * rates are left enabled.
3456                  */
3457                 NLA_PUT(rates, NL80211_BAND_2GHZ, 8,
3458                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
3459                 nla_put_nested(msg, NL80211_ATTR_SCAN_SUPP_RATES, rates);
3461                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
3462         }
3464         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3465         msg = NULL;
3466         if (ret) {
3467                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
3468                            "(%s)", ret, strerror(-ret));
3469 #ifdef HOSTAPD
3470                 if (is_ap_interface(drv->nlmode)) {
3471                         /*
3472                          * mac80211 does not allow scan requests in AP mode, so
3473                          * try to do this in station mode.
3474                          */
3475                         if (wpa_driver_nl80211_set_mode(
3476                                     bss, NL80211_IFTYPE_STATION))
3477                                 goto nla_put_failure;
3479                         if (wpa_driver_nl80211_scan(drv, params)) {
3480                                 wpa_driver_nl80211_set_mode(bss, drv->nlmode);
3481                                 goto nla_put_failure;
3482                         }
3484                         /* Restore AP mode when processing scan results */
3485                         drv->ap_scan_as_station = drv->nlmode;
3486                         ret = 0;
3487                 } else
3488                         goto nla_put_failure;
3489 #else /* HOSTAPD */
3490                 goto nla_put_failure;
3491 #endif /* HOSTAPD */
3492         }
3494         /* Not all drivers generate "scan completed" wireless event, so try to
3495          * read results after a timeout. */
3496         timeout = 10;
3497         if (drv->scan_complete_events) {
3498                 /*
3499                  * The driver seems to deliver events to notify when scan is
3500                  * complete, so use longer timeout to avoid race conditions
3501                  * with scanning and following association request.
3502                  */
3503                 timeout = 30;
3504         }
3505         wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
3506                    "seconds", ret, timeout);
3507         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3508         eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
3509                                drv, drv->ctx);
3511 nla_put_failure:
3512         nlmsg_free(ssids);
3513         nlmsg_free(msg);
3514         nlmsg_free(freqs);
3515         nlmsg_free(rates);
3516         return ret;
3520 /**
3521  * wpa_driver_nl80211_sched_scan - Initiate a scheduled scan
3522  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3523  * @params: Scan parameters
3524  * @interval: Interval between scan cycles in milliseconds
3525  * Returns: 0 on success, -1 on failure or if not supported
3526  */
3527 static int wpa_driver_nl80211_sched_scan(void *priv,
3528                                          struct wpa_driver_scan_params *params,
3529                                          u32 interval)
3531         struct i802_bss *bss = priv;
3532         struct wpa_driver_nl80211_data *drv = bss->drv;
3533         int ret = 0;
3534         struct nl_msg *msg, *ssids, *freqs, *match_set_ssid, *match_sets;
3535         size_t i;
3537 #ifdef ANDROID
3538         if (!drv->capa.sched_scan_supported)
3539                 return android_pno_start(bss, params);
3540 #endif /* ANDROID */
3542         msg = nlmsg_alloc();
3543         ssids = nlmsg_alloc();
3544         freqs = nlmsg_alloc();
3545         if (!msg || !ssids || !freqs) {
3546                 nlmsg_free(msg);
3547                 nlmsg_free(ssids);
3548                 nlmsg_free(freqs);
3549                 return -1;
3550         }
3552         os_free(drv->filter_ssids);
3553         drv->filter_ssids = params->filter_ssids;
3554         params->filter_ssids = NULL;
3555         drv->num_filter_ssids = params->num_filter_ssids;
3557         nl80211_cmd(drv, msg, 0, NL80211_CMD_START_SCHED_SCAN);
3559         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3561         NLA_PUT_U32(msg, NL80211_ATTR_SCHED_SCAN_INTERVAL, interval);
3563         if (drv->num_filter_ssids &&
3564             (int) drv->num_filter_ssids <= drv->capa.max_match_sets) {
3565                 match_sets = nlmsg_alloc();
3567                 for (i = 0; i < drv->num_filter_ssids; i++) {
3568                         wpa_hexdump_ascii(MSG_MSGDUMP,
3569                                           "nl80211: Sched scan filter SSID",
3570                                           drv->filter_ssids[i].ssid,
3571                                           drv->filter_ssids[i].ssid_len);
3573                         match_set_ssid = nlmsg_alloc();
3574                         nla_put(match_set_ssid,
3575                                 NL80211_ATTR_SCHED_SCAN_MATCH_SSID,
3576                                 drv->filter_ssids[i].ssid_len,
3577                                 drv->filter_ssids[i].ssid);
3579                         nla_put_nested(match_sets, i + 1, match_set_ssid);
3581                         nlmsg_free(match_set_ssid);
3582                 }
3584                 nla_put_nested(msg, NL80211_ATTR_SCHED_SCAN_MATCH,
3585                                match_sets);
3586                 nlmsg_free(match_sets);
3587         }
3589         for (i = 0; i < params->num_ssids; i++) {
3590                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Sched scan SSID",
3591                                   params->ssids[i].ssid,
3592                                   params->ssids[i].ssid_len);
3593                 NLA_PUT(ssids, i + 1, params->ssids[i].ssid_len,
3594                         params->ssids[i].ssid);
3595         }
3596         if (params->num_ssids)
3597                 nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
3599         if (params->extra_ies) {
3600                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Sched scan extra IEs",
3601                                   params->extra_ies, params->extra_ies_len);
3602                 NLA_PUT(msg, NL80211_ATTR_IE, params->extra_ies_len,
3603                         params->extra_ies);
3604         }
3606         if (params->freqs) {
3607                 for (i = 0; params->freqs[i]; i++) {
3608                         wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
3609                                    "MHz", params->freqs[i]);
3610                         NLA_PUT_U32(freqs, i + 1, params->freqs[i]);
3611                 }
3612                 nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs);
3613         }
3615         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3617         /* TODO: if we get an error here, we should fall back to normal scan */
3619         msg = NULL;
3620         if (ret) {
3621                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan start failed: "
3622                            "ret=%d (%s)", ret, strerror(-ret));
3623                 goto nla_put_failure;
3624         }
3626         wpa_printf(MSG_DEBUG, "nl80211: Sched scan requested (ret=%d) - "
3627                    "scan interval %d msec", ret, interval);
3629 nla_put_failure:
3630         nlmsg_free(ssids);
3631         nlmsg_free(msg);
3632         nlmsg_free(freqs);
3633         return ret;
3637 /**
3638  * wpa_driver_nl80211_stop_sched_scan - Stop a scheduled scan
3639  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3640  * Returns: 0 on success, -1 on failure or if not supported
3641  */
3642 static int wpa_driver_nl80211_stop_sched_scan(void *priv)
3644         struct i802_bss *bss = priv;
3645         struct wpa_driver_nl80211_data *drv = bss->drv;
3646         int ret = 0;
3647         struct nl_msg *msg;
3649 #ifdef ANDROID
3650         if (!drv->capa.sched_scan_supported)
3651                 return android_pno_stop(bss);
3652 #endif /* ANDROID */
3654         msg = nlmsg_alloc();
3655         if (!msg)
3656                 return -1;
3658         nl80211_cmd(drv, msg, 0, NL80211_CMD_STOP_SCHED_SCAN);
3660         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3662         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3663         msg = NULL;
3664         if (ret) {
3665                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop failed: "
3666                            "ret=%d (%s)", ret, strerror(-ret));
3667                 goto nla_put_failure;
3668         }
3670         wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop sent (ret=%d)", ret);
3672 nla_put_failure:
3673         nlmsg_free(msg);
3674         return ret;
3678 static const u8 * nl80211_get_ie(const u8 *ies, size_t ies_len, u8 ie)
3680         const u8 *end, *pos;
3682         if (ies == NULL)
3683                 return NULL;
3685         pos = ies;
3686         end = ies + ies_len;
3688         while (pos + 1 < end) {
3689                 if (pos + 2 + pos[1] > end)
3690                         break;
3691                 if (pos[0] == ie)
3692                         return pos;
3693                 pos += 2 + pos[1];
3694         }
3696         return NULL;
3700 static int nl80211_scan_filtered(struct wpa_driver_nl80211_data *drv,
3701                                  const u8 *ie, size_t ie_len)
3703         const u8 *ssid;
3704         size_t i;
3706         if (drv->filter_ssids == NULL)
3707                 return 0;
3709         ssid = nl80211_get_ie(ie, ie_len, WLAN_EID_SSID);
3710         if (ssid == NULL)
3711                 return 1;
3713         for (i = 0; i < drv->num_filter_ssids; i++) {
3714                 if (ssid[1] == drv->filter_ssids[i].ssid_len &&
3715                     os_memcmp(ssid + 2, drv->filter_ssids[i].ssid, ssid[1]) ==
3716                     0)
3717                         return 0;
3718         }
3720         return 1;
3724 static int bss_info_handler(struct nl_msg *msg, void *arg)
3726         struct nlattr *tb[NL80211_ATTR_MAX + 1];
3727         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3728         struct nlattr *bss[NL80211_BSS_MAX + 1];
3729         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
3730                 [NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
3731                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
3732                 [NL80211_BSS_TSF] = { .type = NLA_U64 },
3733                 [NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
3734                 [NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
3735                 [NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
3736                 [NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
3737                 [NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
3738                 [NL80211_BSS_STATUS] = { .type = NLA_U32 },
3739                 [NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
3740                 [NL80211_BSS_BEACON_IES] = { .type = NLA_UNSPEC },
3741         };
3742         struct nl80211_bss_info_arg *_arg = arg;
3743         struct wpa_scan_results *res = _arg->res;
3744         struct wpa_scan_res **tmp;
3745         struct wpa_scan_res *r;
3746         const u8 *ie, *beacon_ie;
3747         size_t ie_len, beacon_ie_len;
3748         u8 *pos;
3749         size_t i;
3751         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3752                   genlmsg_attrlen(gnlh, 0), NULL);
3753         if (!tb[NL80211_ATTR_BSS])
3754                 return NL_SKIP;
3755         if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
3756                              bss_policy))
3757                 return NL_SKIP;
3758         if (bss[NL80211_BSS_STATUS]) {
3759                 enum nl80211_bss_status status;
3760                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
3761                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
3762                     bss[NL80211_BSS_FREQUENCY]) {
3763                         _arg->assoc_freq =
3764                                 nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
3765                         wpa_printf(MSG_DEBUG, "nl80211: Associated on %u MHz",
3766                                    _arg->assoc_freq);
3767                 }
3768                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
3769                     bss[NL80211_BSS_BSSID]) {
3770                         os_memcpy(_arg->assoc_bssid,
3771                                   nla_data(bss[NL80211_BSS_BSSID]), ETH_ALEN);
3772                         wpa_printf(MSG_DEBUG, "nl80211: Associated with "
3773                                    MACSTR, MAC2STR(_arg->assoc_bssid));
3774                 }
3775         }
3776         if (!res)
3777                 return NL_SKIP;
3778         if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
3779                 ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
3780                 ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
3781         } else {
3782                 ie = NULL;
3783                 ie_len = 0;
3784         }
3785         if (bss[NL80211_BSS_BEACON_IES]) {
3786                 beacon_ie = nla_data(bss[NL80211_BSS_BEACON_IES]);
3787                 beacon_ie_len = nla_len(bss[NL80211_BSS_BEACON_IES]);
3788         } else {
3789                 beacon_ie = NULL;
3790                 beacon_ie_len = 0;
3791         }
3793         if (nl80211_scan_filtered(_arg->drv, ie ? ie : beacon_ie,
3794                                   ie ? ie_len : beacon_ie_len))
3795                 return NL_SKIP;
3797         r = os_zalloc(sizeof(*r) + ie_len + beacon_ie_len);
3798         if (r == NULL)
3799                 return NL_SKIP;
3800         if (bss[NL80211_BSS_BSSID])
3801                 os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
3802                           ETH_ALEN);
3803         if (bss[NL80211_BSS_FREQUENCY])
3804                 r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
3805         if (bss[NL80211_BSS_BEACON_INTERVAL])
3806                 r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
3807         if (bss[NL80211_BSS_CAPABILITY])
3808                 r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
3809         r->flags |= WPA_SCAN_NOISE_INVALID;
3810         if (bss[NL80211_BSS_SIGNAL_MBM]) {
3811                 r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
3812                 r->level /= 100; /* mBm to dBm */
3813                 r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
3814         } else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
3815                 r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
3816                 r->flags |= WPA_SCAN_QUAL_INVALID;
3817         } else
3818                 r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
3819         if (bss[NL80211_BSS_TSF])
3820                 r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
3821         if (bss[NL80211_BSS_SEEN_MS_AGO])
3822                 r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
3823         r->ie_len = ie_len;
3824         pos = (u8 *) (r + 1);
3825         if (ie) {
3826                 os_memcpy(pos, ie, ie_len);
3827                 pos += ie_len;
3828         }
3829         r->beacon_ie_len = beacon_ie_len;
3830         if (beacon_ie)
3831                 os_memcpy(pos, beacon_ie, beacon_ie_len);
3833         if (bss[NL80211_BSS_STATUS]) {
3834                 enum nl80211_bss_status status;
3835                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
3836                 switch (status) {
3837                 case NL80211_BSS_STATUS_AUTHENTICATED:
3838                         r->flags |= WPA_SCAN_AUTHENTICATED;
3839                         break;
3840                 case NL80211_BSS_STATUS_ASSOCIATED:
3841                         r->flags |= WPA_SCAN_ASSOCIATED;
3842                         break;
3843                 default:
3844                         break;
3845                 }
3846         }
3848         /*
3849          * cfg80211 maintains separate BSS table entries for APs if the same
3850          * BSSID,SSID pair is seen on multiple channels. wpa_supplicant does
3851          * not use frequency as a separate key in the BSS table, so filter out
3852          * duplicated entries. Prefer associated BSS entry in such a case in
3853          * order to get the correct frequency into the BSS table.
3854          */
3855         for (i = 0; i < res->num; i++) {
3856                 const u8 *s1, *s2;
3857                 if (os_memcmp(res->res[i]->bssid, r->bssid, ETH_ALEN) != 0)
3858                         continue;
3860                 s1 = nl80211_get_ie((u8 *) (res->res[i] + 1),
3861                                     res->res[i]->ie_len, WLAN_EID_SSID);
3862                 s2 = nl80211_get_ie((u8 *) (r + 1), r->ie_len, WLAN_EID_SSID);
3863                 if (s1 == NULL || s2 == NULL || s1[1] != s2[1] ||
3864                     os_memcmp(s1, s2, 2 + s1[1]) != 0)
3865                         continue;
3867                 /* Same BSSID,SSID was already included in scan results */
3868                 wpa_printf(MSG_DEBUG, "nl80211: Remove duplicated scan result "
3869                            "for " MACSTR, MAC2STR(r->bssid));
3871                 if ((r->flags & WPA_SCAN_ASSOCIATED) &&
3872                     !(res->res[i]->flags & WPA_SCAN_ASSOCIATED)) {
3873                         os_free(res->res[i]);
3874                         res->res[i] = r;
3875                 } else
3876                         os_free(r);
3877                 return NL_SKIP;
3878         }
3880         tmp = os_realloc(res->res,
3881                          (res->num + 1) * sizeof(struct wpa_scan_res *));
3882         if (tmp == NULL) {
3883                 os_free(r);
3884                 return NL_SKIP;
3885         }
3886         tmp[res->num++] = r;
3887         res->res = tmp;
3889         return NL_SKIP;
3893 static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
3894                                  const u8 *addr)
3896         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
3897                 wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
3898                            "mismatch (" MACSTR ")", MAC2STR(addr));
3899                 wpa_driver_nl80211_mlme(drv, addr,
3900                                         NL80211_CMD_DEAUTHENTICATE,
3901                                         WLAN_REASON_PREV_AUTH_NOT_VALID, 1);
3902         }
3906 static void wpa_driver_nl80211_check_bss_status(
3907         struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
3909         size_t i;
3911         for (i = 0; i < res->num; i++) {
3912                 struct wpa_scan_res *r = res->res[i];
3913                 if (r->flags & WPA_SCAN_AUTHENTICATED) {
3914                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
3915                                    "indicates BSS status with " MACSTR
3916                                    " as authenticated",
3917                                    MAC2STR(r->bssid));
3918                         if (is_sta_interface(drv->nlmode) &&
3919                             os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
3920                             os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
3921                             0) {
3922                                 wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
3923                                            " in local state (auth=" MACSTR
3924                                            " assoc=" MACSTR ")",
3925                                            MAC2STR(drv->auth_bssid),
3926                                            MAC2STR(drv->bssid));
3927                                 clear_state_mismatch(drv, r->bssid);
3928                         }
3929                 }
3931                 if (r->flags & WPA_SCAN_ASSOCIATED) {
3932                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
3933                                    "indicate BSS status with " MACSTR
3934                                    " as associated",
3935                                    MAC2STR(r->bssid));
3936                         if (is_sta_interface(drv->nlmode) &&
3937                             !drv->associated) {
3938                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
3939                                            "(not associated) does not match "
3940                                            "with BSS state");
3941                                 clear_state_mismatch(drv, r->bssid);
3942                         } else if (is_sta_interface(drv->nlmode) &&
3943                                    os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
3944                                    0) {
3945                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
3946                                            "(associated with " MACSTR ") does "
3947                                            "not match with BSS state",
3948                                            MAC2STR(drv->bssid));
3949                                 clear_state_mismatch(drv, r->bssid);
3950                                 clear_state_mismatch(drv, drv->bssid);
3951                         }
3952                 }
3953         }
3957 static struct wpa_scan_results *
3958 nl80211_get_scan_results(struct wpa_driver_nl80211_data *drv)
3960         struct nl_msg *msg;
3961         struct wpa_scan_results *res;
3962         int ret;
3963         struct nl80211_bss_info_arg arg;
3965         res = os_zalloc(sizeof(*res));
3966         if (res == NULL)
3967                 return NULL;
3968         msg = nlmsg_alloc();
3969         if (!msg)
3970                 goto nla_put_failure;
3972         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
3973         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3975         arg.drv = drv;
3976         arg.res = res;
3977         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
3978         msg = NULL;
3979         if (ret == 0) {
3980                 wpa_printf(MSG_DEBUG, "nl80211: Received scan results (%lu "
3981                            "BSSes)", (unsigned long) res->num);
3982                 nl80211_get_noise_for_scan_results(drv, res);
3983                 return res;
3984         }
3985         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
3986                    "(%s)", ret, strerror(-ret));
3987 nla_put_failure:
3988         nlmsg_free(msg);
3989         wpa_scan_results_free(res);
3990         return NULL;
3994 /**
3995  * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
3996  * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
3997  * Returns: Scan results on success, -1 on failure
3998  */
3999 static struct wpa_scan_results *
4000 wpa_driver_nl80211_get_scan_results(void *priv)
4002         struct i802_bss *bss = priv;
4003         struct wpa_driver_nl80211_data *drv = bss->drv;
4004         struct wpa_scan_results *res;
4006         res = nl80211_get_scan_results(drv);
4007         if (res)
4008                 wpa_driver_nl80211_check_bss_status(drv, res);
4009         return res;
4013 static void nl80211_dump_scan(struct wpa_driver_nl80211_data *drv)
4015         struct wpa_scan_results *res;
4016         size_t i;
4018         res = nl80211_get_scan_results(drv);
4019         if (res == NULL) {
4020                 wpa_printf(MSG_DEBUG, "nl80211: Failed to get scan results");
4021                 return;
4022         }
4024         wpa_printf(MSG_DEBUG, "nl80211: Scan result dump");
4025         for (i = 0; i < res->num; i++) {
4026                 struct wpa_scan_res *r = res->res[i];
4027                 wpa_printf(MSG_DEBUG, "nl80211: %d/%d " MACSTR "%s%s",
4028                            (int) i, (int) res->num, MAC2STR(r->bssid),
4029                            r->flags & WPA_SCAN_AUTHENTICATED ? " [auth]" : "",
4030                            r->flags & WPA_SCAN_ASSOCIATED ? " [assoc]" : "");
4031         }
4033         wpa_scan_results_free(res);
4037 static int wpa_driver_nl80211_set_key(const char *ifname, void *priv,
4038                                       enum wpa_alg alg, const u8 *addr,
4039                                       int key_idx, int set_tx,
4040                                       const u8 *seq, size_t seq_len,
4041                                       const u8 *key, size_t key_len)
4043         struct i802_bss *bss = priv;
4044         struct wpa_driver_nl80211_data *drv = bss->drv;
4045         int ifindex = if_nametoindex(ifname);
4046         struct nl_msg *msg;
4047         int ret;
4049         wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
4050                    "set_tx=%d seq_len=%lu key_len=%lu",
4051                    __func__, ifindex, alg, addr, key_idx, set_tx,
4052                    (unsigned long) seq_len, (unsigned long) key_len);
4053 #ifdef CONFIG_TDLS
4054         if (key_idx == -1)
4055                 key_idx = 0;
4056 #endif /* CONFIG_TDLS */
4058         msg = nlmsg_alloc();
4059         if (!msg)
4060                 return -ENOMEM;
4062         if (alg == WPA_ALG_NONE) {
4063                 nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_KEY);
4064         } else {
4065                 nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_KEY);
4066                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
4067                 switch (alg) {
4068                 case WPA_ALG_WEP:
4069                         if (key_len == 5)
4070                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4071                                             WLAN_CIPHER_SUITE_WEP40);
4072                         else
4073                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4074                                             WLAN_CIPHER_SUITE_WEP104);
4075                         break;
4076                 case WPA_ALG_TKIP:
4077                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4078                                     WLAN_CIPHER_SUITE_TKIP);
4079                         break;
4080                 case WPA_ALG_CCMP:
4081                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4082                                     WLAN_CIPHER_SUITE_CCMP);
4083                         break;
4084                 case WPA_ALG_IGTK:
4085                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4086                                     WLAN_CIPHER_SUITE_AES_CMAC);
4087                         break;
4088                 default:
4089                         wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4090                                    "algorithm %d", __func__, alg);
4091                         nlmsg_free(msg);
4092                         return -1;
4093                 }
4094         }
4096         if (seq && seq_len)
4097                 NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
4099         if (addr && !is_broadcast_ether_addr(addr)) {
4100                 wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
4101                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4103                 if (alg != WPA_ALG_WEP && key_idx && !set_tx) {
4104                         wpa_printf(MSG_DEBUG, "   RSN IBSS RX GTK");
4105                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_TYPE,
4106                                     NL80211_KEYTYPE_GROUP);
4107                 }
4108         } else if (addr && is_broadcast_ether_addr(addr)) {
4109                 struct nl_msg *types;
4110                 int err;
4111                 wpa_printf(MSG_DEBUG, "   broadcast key");
4112                 types = nlmsg_alloc();
4113                 if (!types)
4114                         goto nla_put_failure;
4115                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4116                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4117                                      types);
4118                 nlmsg_free(types);
4119                 if (err)
4120                         goto nla_put_failure;
4121         }
4122         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4123         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4125         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4126         if ((ret == -ENOENT || ret == -ENOLINK) && alg == WPA_ALG_NONE)
4127                 ret = 0;
4128         if (ret)
4129                 wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
4130                            ret, strerror(-ret));
4132         /*
4133          * If we failed or don't need to set the default TX key (below),
4134          * we're done here.
4135          */
4136         if (ret || !set_tx || alg == WPA_ALG_NONE)
4137                 return ret;
4138         if (is_ap_interface(drv->nlmode) && addr &&
4139             !is_broadcast_ether_addr(addr))
4140                 return ret;
4142         msg = nlmsg_alloc();
4143         if (!msg)
4144                 return -ENOMEM;
4146         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_KEY);
4147         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4148         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4149         if (alg == WPA_ALG_IGTK)
4150                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
4151         else
4152                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
4153         if (addr && is_broadcast_ether_addr(addr)) {
4154                 struct nl_msg *types;
4155                 int err;
4156                 types = nlmsg_alloc();
4157                 if (!types)
4158                         goto nla_put_failure;
4159                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4160                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4161                                      types);
4162                 nlmsg_free(types);
4163                 if (err)
4164                         goto nla_put_failure;
4165         } else if (addr) {
4166                 struct nl_msg *types;
4167                 int err;
4168                 types = nlmsg_alloc();
4169                 if (!types)
4170                         goto nla_put_failure;
4171                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_UNICAST);
4172                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4173                                      types);
4174                 nlmsg_free(types);
4175                 if (err)
4176                         goto nla_put_failure;
4177         }
4179         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4180         if (ret == -ENOENT)
4181                 ret = 0;
4182         if (ret)
4183                 wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
4184                            "err=%d %s)", ret, strerror(-ret));
4185         return ret;
4187 nla_put_failure:
4188         nlmsg_free(msg);
4189         return -ENOBUFS;
4193 static int nl_add_key(struct nl_msg *msg, enum wpa_alg alg,
4194                       int key_idx, int defkey,
4195                       const u8 *seq, size_t seq_len,
4196                       const u8 *key, size_t key_len)
4198         struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
4199         if (!key_attr)
4200                 return -1;
4202         if (defkey && alg == WPA_ALG_IGTK)
4203                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
4204         else if (defkey)
4205                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4207         NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
4209         switch (alg) {
4210         case WPA_ALG_WEP:
4211                 if (key_len == 5)
4212                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4213                                     WLAN_CIPHER_SUITE_WEP40);
4214                 else
4215                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4216                                     WLAN_CIPHER_SUITE_WEP104);
4217                 break;
4218         case WPA_ALG_TKIP:
4219                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_TKIP);
4220                 break;
4221         case WPA_ALG_CCMP:
4222                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_CCMP);
4223                 break;
4224         case WPA_ALG_IGTK:
4225                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4226                             WLAN_CIPHER_SUITE_AES_CMAC);
4227                 break;
4228         default:
4229                 wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4230                            "algorithm %d", __func__, alg);
4231                 return -1;
4232         }
4234         if (seq && seq_len)
4235                 NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
4237         NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
4239         nla_nest_end(msg, key_attr);
4241         return 0;
4242  nla_put_failure:
4243         return -1;
4247 static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
4248                                  struct nl_msg *msg)
4250         int i, privacy = 0;
4251         struct nlattr *nl_keys, *nl_key;
4253         for (i = 0; i < 4; i++) {
4254                 if (!params->wep_key[i])
4255                         continue;
4256                 privacy = 1;
4257                 break;
4258         }
4259         if (params->wps == WPS_MODE_PRIVACY)
4260                 privacy = 1;
4261         if (params->pairwise_suite &&
4262             params->pairwise_suite != WPA_CIPHER_NONE)
4263                 privacy = 1;
4265         if (!privacy)
4266                 return 0;
4268         NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
4270         nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
4271         if (!nl_keys)
4272                 goto nla_put_failure;
4274         for (i = 0; i < 4; i++) {
4275                 if (!params->wep_key[i])
4276                         continue;
4278                 nl_key = nla_nest_start(msg, i);
4279                 if (!nl_key)
4280                         goto nla_put_failure;
4282                 NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
4283                         params->wep_key[i]);
4284                 if (params->wep_key_len[i] == 5)
4285                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4286                                     WLAN_CIPHER_SUITE_WEP40);
4287                 else
4288                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4289                                     WLAN_CIPHER_SUITE_WEP104);
4291                 NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
4293                 if (i == params->wep_tx_keyidx)
4294                         NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4296                 nla_nest_end(msg, nl_key);
4297         }
4298         nla_nest_end(msg, nl_keys);
4300         return 0;
4302 nla_put_failure:
4303         return -ENOBUFS;
4307 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
4308                                    const u8 *addr, int cmd, u16 reason_code,
4309                                    int local_state_change)
4311         int ret = -1;
4312         struct nl_msg *msg;
4314         msg = nlmsg_alloc();
4315         if (!msg)
4316                 return -1;
4318         nl80211_cmd(drv, msg, 0, cmd);
4320         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4321         NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
4322         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4323         if (local_state_change)
4324                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4326         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4327         msg = NULL;
4328         if (ret) {
4329                 wpa_dbg(drv->ctx, MSG_DEBUG,
4330                         "nl80211: MLME command failed: reason=%u ret=%d (%s)",
4331                         reason_code, ret, strerror(-ret));
4332                 goto nla_put_failure;
4333         }
4334         ret = 0;
4336 nla_put_failure:
4337         nlmsg_free(msg);
4338         return ret;
4342 static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
4343                                          const u8 *addr, int reason_code)
4345         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
4346                    __func__, MAC2STR(addr), reason_code);
4347         drv->associated = 0;
4348         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISCONNECT,
4349                                        reason_code, 0);
4353 static int wpa_driver_nl80211_deauthenticate(void *priv, const u8 *addr,
4354                                              int reason_code)
4356         struct i802_bss *bss = priv;
4357         struct wpa_driver_nl80211_data *drv = bss->drv;
4358         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
4359                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
4360         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
4361                    __func__, MAC2STR(addr), reason_code);
4362         drv->associated = 0;
4363         if (drv->nlmode == NL80211_IFTYPE_ADHOC)
4364                 return nl80211_leave_ibss(drv);
4365         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
4366                                        reason_code, 0);
4370 static int wpa_driver_nl80211_disassociate(void *priv, const u8 *addr,
4371                                            int reason_code)
4373         struct i802_bss *bss = priv;
4374         struct wpa_driver_nl80211_data *drv = bss->drv;
4375         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
4376                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
4377         wpa_printf(MSG_DEBUG, "%s", __func__);
4378         drv->associated = 0;
4379         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISASSOCIATE,
4380                                        reason_code, 0);
4384 static void nl80211_copy_auth_params(struct wpa_driver_nl80211_data *drv,
4385                                      struct wpa_driver_auth_params *params)
4387         int i;
4389         drv->auth_freq = params->freq;
4390         drv->auth_alg = params->auth_alg;
4391         drv->auth_wep_tx_keyidx = params->wep_tx_keyidx;
4392         drv->auth_local_state_change = params->local_state_change;
4393         drv->auth_p2p = params->p2p;
4395         if (params->bssid)
4396                 os_memcpy(drv->auth_bssid_, params->bssid, ETH_ALEN);
4397         else
4398                 os_memset(drv->auth_bssid_, 0, ETH_ALEN);
4400         if (params->ssid) {
4401                 os_memcpy(drv->auth_ssid, params->ssid, params->ssid_len);
4402                 drv->auth_ssid_len = params->ssid_len;
4403         } else
4404                 drv->auth_ssid_len = 0;
4407         os_free(drv->auth_ie);
4408         drv->auth_ie = NULL;
4409         drv->auth_ie_len = 0;
4410         if (params->ie) {
4411                 drv->auth_ie = os_malloc(params->ie_len);
4412                 if (drv->auth_ie) {
4413                         os_memcpy(drv->auth_ie, params->ie, params->ie_len);
4414                         drv->auth_ie_len = params->ie_len;
4415                 }
4416         }
4418         for (i = 0; i < 4; i++) {
4419                 if (params->wep_key[i] && params->wep_key_len[i] &&
4420                     params->wep_key_len[i] <= 16) {
4421                         os_memcpy(drv->auth_wep_key[i], params->wep_key[i],
4422                                   params->wep_key_len[i]);
4423                         drv->auth_wep_key_len[i] = params->wep_key_len[i];
4424                 } else
4425                         drv->auth_wep_key_len[i] = 0;
4426         }
4430 static int wpa_driver_nl80211_authenticate(
4431         void *priv, struct wpa_driver_auth_params *params)
4433         struct i802_bss *bss = priv;
4434         struct wpa_driver_nl80211_data *drv = bss->drv;
4435         int ret = -1, i;
4436         struct nl_msg *msg;
4437         enum nl80211_auth_type type;
4438         enum nl80211_iftype nlmode;
4439         int count = 0;
4440         int is_retry;
4442         is_retry = drv->retry_auth;
4443         drv->retry_auth = 0;
4445         drv->associated = 0;
4446         os_memset(drv->auth_bssid, 0, ETH_ALEN);
4447         /* FIX: IBSS mode */
4448         nlmode = params->p2p ?
4449                 NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
4450         if (drv->nlmode != nlmode &&
4451             wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
4452                 return -1;
4454 retry:
4455         msg = nlmsg_alloc();
4456         if (!msg)
4457                 return -1;
4459         wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
4460                    drv->ifindex);
4462         nl80211_cmd(drv, msg, 0, NL80211_CMD_AUTHENTICATE);
4464         for (i = 0; i < 4; i++) {
4465                 if (!params->wep_key[i])
4466                         continue;
4467                 wpa_driver_nl80211_set_key(bss->ifname, priv, WPA_ALG_WEP,
4468                                            NULL, i,
4469                                            i == params->wep_tx_keyidx, NULL, 0,
4470                                            params->wep_key[i],
4471                                            params->wep_key_len[i]);
4472                 if (params->wep_tx_keyidx != i)
4473                         continue;
4474                 if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
4475                                params->wep_key[i], params->wep_key_len[i])) {
4476                         nlmsg_free(msg);
4477                         return -1;
4478                 }
4479         }
4481         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4482         if (params->bssid) {
4483                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4484                            MAC2STR(params->bssid));
4485                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4486         }
4487         if (params->freq) {
4488                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4489                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4490         }
4491         if (params->ssid) {
4492                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4493                                   params->ssid, params->ssid_len);
4494                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4495                         params->ssid);
4496         }
4497         wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
4498         if (params->ie)
4499                 NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
4500         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
4501                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
4502         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
4503                 type = NL80211_AUTHTYPE_SHARED_KEY;
4504         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
4505                 type = NL80211_AUTHTYPE_NETWORK_EAP;
4506         else if (params->auth_alg & WPA_AUTH_ALG_FT)
4507                 type = NL80211_AUTHTYPE_FT;
4508         else
4509                 goto nla_put_failure;
4510         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
4511         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
4512         if (params->local_state_change) {
4513                 wpa_printf(MSG_DEBUG, "  * Local state change only");
4514                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4515         }
4517         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4518         msg = NULL;
4519         if (ret) {
4520                 wpa_dbg(drv->ctx, MSG_DEBUG,
4521                         "nl80211: MLME command failed (auth): ret=%d (%s)",
4522                         ret, strerror(-ret));
4523                 count++;
4524                 if (ret == -EALREADY && count == 1 && params->bssid &&
4525                     !params->local_state_change) {
4526                         /*
4527                          * mac80211 does not currently accept new
4528                          * authentication if we are already authenticated. As a
4529                          * workaround, force deauthentication and try again.
4530                          */
4531                         wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
4532                                    "after forced deauthentication");
4533                         wpa_driver_nl80211_deauthenticate(
4534                                 bss, params->bssid,
4535                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
4536                         nlmsg_free(msg);
4537                         goto retry;
4538                 }
4540                 if (ret == -ENOENT && params->freq && !is_retry) {
4541                         /*
4542                          * cfg80211 has likely expired the BSS entry even
4543                          * though it was previously available in our internal
4544                          * BSS table. To recover quickly, start a single
4545                          * channel scan on the specified channel.
4546                          */
4547                         struct wpa_driver_scan_params scan;
4548                         int freqs[2];
4550                         os_memset(&scan, 0, sizeof(scan));
4551                         scan.num_ssids = 1;
4552                         if (params->ssid) {
4553                                 scan.ssids[0].ssid = params->ssid;
4554                                 scan.ssids[0].ssid_len = params->ssid_len;
4555                         }
4556                         freqs[0] = params->freq;
4557                         freqs[1] = 0;
4558                         scan.freqs = freqs;
4559                         wpa_printf(MSG_DEBUG, "nl80211: Trigger single "
4560                                    "channel scan to refresh cfg80211 BSS "
4561                                    "entry");
4562                         ret = wpa_driver_nl80211_scan(bss, &scan);
4563                         if (ret == 0) {
4564                                 nl80211_copy_auth_params(drv, params);
4565                                 drv->scan_for_auth = 1;
4566                         }
4567                 } else if (is_retry) {
4568                         /*
4569                          * Need to indicate this with an event since the return
4570                          * value from the retry is not delivered to core code.
4571                          */
4572                         union wpa_event_data event;
4573                         wpa_printf(MSG_DEBUG, "nl80211: Authentication retry "
4574                                    "failed");
4575                         os_memset(&event, 0, sizeof(event));
4576                         os_memcpy(event.timeout_event.addr, drv->auth_bssid_,
4577                                   ETH_ALEN);
4578                         wpa_supplicant_event(drv->ctx, EVENT_AUTH_TIMED_OUT,
4579                                              &event);
4580                 }
4582                 goto nla_put_failure;
4583         }
4584         ret = 0;
4585         wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
4586                    "successfully");
4588 nla_put_failure:
4589         nlmsg_free(msg);
4590         return ret;
4594 static int wpa_driver_nl80211_authenticate_retry(
4595         struct wpa_driver_nl80211_data *drv)
4597         struct wpa_driver_auth_params params;
4598         struct i802_bss *bss = &drv->first_bss;
4599         int i;
4601         wpa_printf(MSG_DEBUG, "nl80211: Try to authenticate again");
4603         os_memset(&params, 0, sizeof(params));
4604         params.freq = drv->auth_freq;
4605         params.auth_alg = drv->auth_alg;
4606         params.wep_tx_keyidx = drv->auth_wep_tx_keyidx;
4607         params.local_state_change = drv->auth_local_state_change;
4608         params.p2p = drv->auth_p2p;
4610         if (!is_zero_ether_addr(drv->auth_bssid_))
4611                 params.bssid = drv->auth_bssid_;
4613         if (drv->auth_ssid_len) {
4614                 params.ssid = drv->auth_ssid;
4615                 params.ssid_len = drv->auth_ssid_len;
4616         }
4618         params.ie = drv->auth_ie;
4619         params.ie_len = drv->auth_ie_len;
4621         for (i = 0; i < 4; i++) {
4622                 if (drv->auth_wep_key_len[i]) {
4623                         params.wep_key[i] = drv->auth_wep_key[i];
4624                         params.wep_key_len[i] = drv->auth_wep_key_len[i];
4625                 }
4626         }
4628         drv->retry_auth = 1;
4629         return wpa_driver_nl80211_authenticate(bss, &params);
4633 struct phy_info_arg {
4634         u16 *num_modes;
4635         struct hostapd_hw_modes *modes;
4636 };
4638 static int phy_info_handler(struct nl_msg *msg, void *arg)
4640         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
4641         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
4642         struct phy_info_arg *phy_info = arg;
4644         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
4646         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
4647         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
4648                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
4649                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
4650                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
4651                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
4652                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
4653                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
4654         };
4656         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
4657         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
4658                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
4659                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
4660         };
4662         struct nlattr *nl_band;
4663         struct nlattr *nl_freq;
4664         struct nlattr *nl_rate;
4665         int rem_band, rem_freq, rem_rate;
4666         struct hostapd_hw_modes *mode;
4667         int idx, mode_is_set;
4669         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
4670                   genlmsg_attrlen(gnlh, 0), NULL);
4672         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
4673                 return NL_SKIP;
4675         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
4676                 mode = os_realloc(phy_info->modes, (*phy_info->num_modes + 1) * sizeof(*mode));
4677                 if (!mode)
4678                         return NL_SKIP;
4679                 phy_info->modes = mode;
4681                 mode_is_set = 0;
4683                 mode = &phy_info->modes[*(phy_info->num_modes)];
4684                 memset(mode, 0, sizeof(*mode));
4685                 mode->flags = HOSTAPD_MODE_FLAG_HT_INFO_KNOWN;
4686                 *(phy_info->num_modes) += 1;
4688                 nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
4689                           nla_len(nl_band), NULL);
4691                 if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
4692                         mode->ht_capab = nla_get_u16(
4693                                 tb_band[NL80211_BAND_ATTR_HT_CAPA]);
4694                 }
4696                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) {
4697                         mode->a_mpdu_params |= nla_get_u8(
4698                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) &
4699                                 0x03;
4700                 }
4702                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) {
4703                         mode->a_mpdu_params |= nla_get_u8(
4704                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) <<
4705                                 2;
4706                 }
4708                 if (tb_band[NL80211_BAND_ATTR_HT_MCS_SET] &&
4709                     nla_len(tb_band[NL80211_BAND_ATTR_HT_MCS_SET])) {
4710                         u8 *mcs;
4711                         mcs = nla_data(tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
4712                         os_memcpy(mode->mcs_set, mcs, 16);
4713                 }
4715                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
4716                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
4717                                   nla_len(nl_freq), freq_policy);
4718                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
4719                                 continue;
4720                         mode->num_channels++;
4721                 }
4723                 mode->channels = os_zalloc(mode->num_channels * sizeof(struct hostapd_channel_data));
4724                 if (!mode->channels)
4725                         return NL_SKIP;
4727                 idx = 0;
4729                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
4730                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
4731                                   nla_len(nl_freq), freq_policy);
4732                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
4733                                 continue;
4735                         mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
4736                         mode->channels[idx].flag = 0;
4738                         if (!mode_is_set) {
4739                                 /* crude heuristic */
4740                                 if (mode->channels[idx].freq < 4000)
4741                                         mode->mode = HOSTAPD_MODE_IEEE80211B;
4742                                 else
4743                                         mode->mode = HOSTAPD_MODE_IEEE80211A;
4744                                 mode_is_set = 1;
4745                         }
4747                         /* crude heuristic */
4748                         if (mode->channels[idx].freq < 4000)
4749                                 if (mode->channels[idx].freq == 2484)
4750                                         mode->channels[idx].chan = 14;
4751                                 else
4752                                         mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
4753                         else
4754                                 mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
4756                         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
4757                                 mode->channels[idx].flag |=
4758                                         HOSTAPD_CHAN_DISABLED;
4759                         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
4760                                 mode->channels[idx].flag |=
4761                                         HOSTAPD_CHAN_PASSIVE_SCAN;
4762                         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
4763                                 mode->channels[idx].flag |=
4764                                         HOSTAPD_CHAN_NO_IBSS;
4765                         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
4766                                 mode->channels[idx].flag |=
4767                                         HOSTAPD_CHAN_RADAR;
4769                         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
4770                             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
4771                                 mode->channels[idx].max_tx_power =
4772                                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
4774                         idx++;
4775                 }
4777                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
4778                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
4779                                   nla_len(nl_rate), rate_policy);
4780                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
4781                                 continue;
4782                         mode->num_rates++;
4783                 }
4785                 mode->rates = os_zalloc(mode->num_rates * sizeof(int));
4786                 if (!mode->rates)
4787                         return NL_SKIP;
4789                 idx = 0;
4791                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
4792                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
4793                                   nla_len(nl_rate), rate_policy);
4794                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
4795                                 continue;
4796                         mode->rates[idx] = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
4798                         /* crude heuristic */
4799                         if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
4800                             mode->rates[idx] > 200)
4801                                 mode->mode = HOSTAPD_MODE_IEEE80211G;
4803                         idx++;
4804                 }
4805         }
4807         return NL_SKIP;
4810 static struct hostapd_hw_modes *
4811 wpa_driver_nl80211_add_11b(struct hostapd_hw_modes *modes, u16 *num_modes)
4813         u16 m;
4814         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
4815         int i, mode11g_idx = -1;
4817         /* If only 802.11g mode is included, use it to construct matching
4818          * 802.11b mode data. */
4820         for (m = 0; m < *num_modes; m++) {
4821                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
4822                         return modes; /* 802.11b already included */
4823                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
4824                         mode11g_idx = m;
4825         }
4827         if (mode11g_idx < 0)
4828                 return modes; /* 2.4 GHz band not supported at all */
4830         nmodes = os_realloc(modes, (*num_modes + 1) * sizeof(*nmodes));
4831         if (nmodes == NULL)
4832                 return modes; /* Could not add 802.11b mode */
4834         mode = &nmodes[*num_modes];
4835         os_memset(mode, 0, sizeof(*mode));
4836         (*num_modes)++;
4837         modes = nmodes;
4839         mode->mode = HOSTAPD_MODE_IEEE80211B;
4841         mode11g = &modes[mode11g_idx];
4842         mode->num_channels = mode11g->num_channels;
4843         mode->channels = os_malloc(mode11g->num_channels *
4844                                    sizeof(struct hostapd_channel_data));
4845         if (mode->channels == NULL) {
4846                 (*num_modes)--;
4847                 return modes; /* Could not add 802.11b mode */
4848         }
4849         os_memcpy(mode->channels, mode11g->channels,
4850                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
4852         mode->num_rates = 0;
4853         mode->rates = os_malloc(4 * sizeof(int));
4854         if (mode->rates == NULL) {
4855                 os_free(mode->channels);
4856                 (*num_modes)--;
4857                 return modes; /* Could not add 802.11b mode */
4858         }
4860         for (i = 0; i < mode11g->num_rates; i++) {
4861                 if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 &&
4862                     mode11g->rates[i] != 55 && mode11g->rates[i] != 110)
4863                         continue;
4864                 mode->rates[mode->num_rates] = mode11g->rates[i];
4865                 mode->num_rates++;
4866                 if (mode->num_rates == 4)
4867                         break;
4868         }
4870         if (mode->num_rates == 0) {
4871                 os_free(mode->channels);
4872                 os_free(mode->rates);
4873                 (*num_modes)--;
4874                 return modes; /* No 802.11b rates */
4875         }
4877         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
4878                    "information");
4880         return modes;
4884 static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start,
4885                                   int end)
4887         int c;
4889         for (c = 0; c < mode->num_channels; c++) {
4890                 struct hostapd_channel_data *chan = &mode->channels[c];
4891                 if (chan->freq - 10 >= start && chan->freq + 10 <= end)
4892                         chan->flag |= HOSTAPD_CHAN_HT40;
4893         }
4897 static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start,
4898                                       int end)
4900         int c;
4902         for (c = 0; c < mode->num_channels; c++) {
4903                 struct hostapd_channel_data *chan = &mode->channels[c];
4904                 if (!(chan->flag & HOSTAPD_CHAN_HT40))
4905                         continue;
4906                 if (chan->freq - 30 >= start && chan->freq - 10 <= end)
4907                         chan->flag |= HOSTAPD_CHAN_HT40MINUS;
4908                 if (chan->freq + 10 >= start && chan->freq + 30 <= end)
4909                         chan->flag |= HOSTAPD_CHAN_HT40PLUS;
4910         }
4914 static void nl80211_reg_rule_ht40(struct nlattr *tb[],
4915                                   struct phy_info_arg *results)
4917         u32 start, end, max_bw;
4918         u16 m;
4920         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
4921             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
4922             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
4923                 return;
4925         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
4926         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
4927         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
4929         wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz",
4930                    start, end, max_bw);
4931         if (max_bw < 40)
4932                 return;
4934         for (m = 0; m < *results->num_modes; m++) {
4935                 if (!(results->modes[m].ht_capab &
4936                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
4937                         continue;
4938                 nl80211_set_ht40_mode(&results->modes[m], start, end);
4939         }
4943 static void nl80211_reg_rule_sec(struct nlattr *tb[],
4944                                  struct phy_info_arg *results)
4946         u32 start, end, max_bw;
4947         u16 m;
4949         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
4950             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
4951             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
4952                 return;
4954         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
4955         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
4956         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
4958         if (max_bw < 20)
4959                 return;
4961         for (m = 0; m < *results->num_modes; m++) {
4962                 if (!(results->modes[m].ht_capab &
4963                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
4964                         continue;
4965                 nl80211_set_ht40_mode_sec(&results->modes[m], start, end);
4966         }
4970 static int nl80211_get_reg(struct nl_msg *msg, void *arg)
4972         struct phy_info_arg *results = arg;
4973         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
4974         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
4975         struct nlattr *nl_rule;
4976         struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1];
4977         int rem_rule;
4978         static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
4979                 [NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
4980                 [NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
4981                 [NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
4982                 [NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
4983                 [NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
4984                 [NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
4985         };
4987         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
4988                   genlmsg_attrlen(gnlh, 0), NULL);
4989         if (!tb_msg[NL80211_ATTR_REG_ALPHA2] ||
4990             !tb_msg[NL80211_ATTR_REG_RULES]) {
4991                 wpa_printf(MSG_DEBUG, "nl80211: No regulatory information "
4992                            "available");
4993                 return NL_SKIP;
4994         }
4996         wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s",
4997                    (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]));
4999         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5000         {
5001                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5002                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5003                 nl80211_reg_rule_ht40(tb_rule, results);
5004         }
5006         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5007         {
5008                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5009                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5010                 nl80211_reg_rule_sec(tb_rule, results);
5011         }
5013         return NL_SKIP;
5017 static int nl80211_set_ht40_flags(struct wpa_driver_nl80211_data *drv,
5018                                   struct phy_info_arg *results)
5020         struct nl_msg *msg;
5022         msg = nlmsg_alloc();
5023         if (!msg)
5024                 return -ENOMEM;
5026         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_REG);
5027         return send_and_recv_msgs(drv, msg, nl80211_get_reg, results);
5031 static struct hostapd_hw_modes *
5032 wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
5034         struct i802_bss *bss = priv;
5035         struct wpa_driver_nl80211_data *drv = bss->drv;
5036         struct nl_msg *msg;
5037         struct phy_info_arg result = {
5038                 .num_modes = num_modes,
5039                 .modes = NULL,
5040         };
5042         *num_modes = 0;
5043         *flags = 0;
5045         msg = nlmsg_alloc();
5046         if (!msg)
5047                 return NULL;
5049         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
5051         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5053         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) {
5054                 nl80211_set_ht40_flags(drv, &result);
5055                 return wpa_driver_nl80211_add_11b(result.modes, num_modes);
5056         }
5057         msg = NULL;
5058  nla_put_failure:
5059         nlmsg_free(msg);
5060         return NULL;
5064 static int wpa_driver_nl80211_send_mntr(struct wpa_driver_nl80211_data *drv,
5065                                         const void *data, size_t len,
5066                                         int encrypt, int noack)
5068         __u8 rtap_hdr[] = {
5069                 0x00, 0x00, /* radiotap version */
5070                 0x0e, 0x00, /* radiotap length */
5071                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
5072                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
5073                 0x00,       /* padding */
5074                 0x00, 0x00, /* RX and TX flags to indicate that */
5075                 0x00, 0x00, /* this is the injected frame directly */
5076         };
5077         struct iovec iov[2] = {
5078                 {
5079                         .iov_base = &rtap_hdr,
5080                         .iov_len = sizeof(rtap_hdr),
5081                 },
5082                 {
5083                         .iov_base = (void *) data,
5084                         .iov_len = len,
5085                 }
5086         };
5087         struct msghdr msg = {
5088                 .msg_name = NULL,
5089                 .msg_namelen = 0,
5090                 .msg_iov = iov,
5091                 .msg_iovlen = 2,
5092                 .msg_control = NULL,
5093                 .msg_controllen = 0,
5094                 .msg_flags = 0,
5095         };
5096         int res;
5097         u16 txflags = 0;
5099         if (encrypt)
5100                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
5102         if (drv->monitor_sock < 0) {
5103                 wpa_printf(MSG_DEBUG, "nl80211: No monitor socket available "
5104                            "for %s", __func__);
5105                 return -1;
5106         }
5108         if (noack)
5109                 txflags |= IEEE80211_RADIOTAP_F_TX_NOACK;
5110         *(le16 *) &rtap_hdr[12] = host_to_le16(txflags);
5112         res = sendmsg(drv->monitor_sock, &msg, 0);
5113         if (res < 0) {
5114                 wpa_printf(MSG_INFO, "nl80211: sendmsg: %s", strerror(errno));
5115                 return -1;
5116         }
5117         return 0;
5121 static int wpa_driver_nl80211_send_frame(struct i802_bss *bss,
5122                                          const void *data, size_t len,
5123                                          int encrypt, int noack)
5125         struct wpa_driver_nl80211_data *drv = bss->drv;
5126         u64 cookie;
5128         if (drv->use_monitor)
5129                 return wpa_driver_nl80211_send_mntr(drv, data, len,
5130                                                     encrypt, noack);
5132         return nl80211_send_frame_cmd(bss, bss->freq, 0, data, len,
5133                                       &cookie, 0, noack, 0);
5137 static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
5138                                         size_t data_len, int noack)
5140         struct i802_bss *bss = priv;
5141         struct wpa_driver_nl80211_data *drv = bss->drv;
5142         struct ieee80211_mgmt *mgmt;
5143         int encrypt = 1;
5144         u16 fc;
5146         mgmt = (struct ieee80211_mgmt *) data;
5147         fc = le_to_host16(mgmt->frame_control);
5149         if (is_sta_interface(drv->nlmode) &&
5150             WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5151             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_PROBE_RESP) {
5152                 /*
5153                  * The use of last_mgmt_freq is a bit of a hack,
5154                  * but it works due to the single-threaded nature
5155                  * of wpa_supplicant.
5156                  */
5157                 return nl80211_send_frame_cmd(bss, drv->last_mgmt_freq, 0,
5158                                               data, data_len, NULL, 1, noack,
5159                                               1);
5160         }
5162         if (drv->device_ap_sme && is_ap_interface(drv->nlmode)) {
5163                 return nl80211_send_frame_cmd(bss, bss->freq, 0,
5164                                               data, data_len, NULL,
5165                                               0, noack, 0);
5166         }
5168         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5169             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
5170                 /*
5171                  * Only one of the authentication frame types is encrypted.
5172                  * In order for static WEP encryption to work properly (i.e.,
5173                  * to not encrypt the frame), we need to tell mac80211 about
5174                  * the frames that must not be encrypted.
5175                  */
5176                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
5177                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
5178                 if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
5179                         encrypt = 0;
5180         }
5182         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt,
5183                                              noack);
5187 static int nl80211_set_bss(struct i802_bss *bss, int cts, int preamble,
5188                            int slot, int ht_opmode, int ap_isolate,
5189                            int *basic_rates)
5191         struct wpa_driver_nl80211_data *drv = bss->drv;
5192         struct nl_msg *msg;
5194         msg = nlmsg_alloc();
5195         if (!msg)
5196                 return -ENOMEM;
5198         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_BSS);
5200         if (cts >= 0)
5201                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
5202         if (preamble >= 0)
5203                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
5204         if (slot >= 0)
5205                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
5206         if (ht_opmode >= 0)
5207                 NLA_PUT_U16(msg, NL80211_ATTR_BSS_HT_OPMODE, ht_opmode);
5208         if (ap_isolate >= 0)
5209                 NLA_PUT_U8(msg, NL80211_ATTR_AP_ISOLATE, ap_isolate);
5211         if (basic_rates) {
5212                 u8 rates[NL80211_MAX_SUPP_RATES];
5213                 u8 rates_len = 0;
5214                 int i;
5216                 for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0;
5217                      i++)
5218                         rates[rates_len++] = basic_rates[i] / 5;
5220                 NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
5221         }
5223         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5225         return send_and_recv_msgs(drv, msg, NULL, NULL);
5226  nla_put_failure:
5227         nlmsg_free(msg);
5228         return -ENOBUFS;
5232 static int wpa_driver_nl80211_set_ap(void *priv,
5233                                      struct wpa_driver_ap_params *params)
5235         struct i802_bss *bss = priv;
5236         struct wpa_driver_nl80211_data *drv = bss->drv;
5237         struct nl_msg *msg;
5238         u8 cmd = NL80211_CMD_NEW_BEACON;
5239         int ret;
5240         int beacon_set;
5241         int ifindex = if_nametoindex(bss->ifname);
5242         int num_suites;
5243         u32 suites[10];
5244         u32 ver;
5246         beacon_set = bss->beacon_set;
5248         msg = nlmsg_alloc();
5249         if (!msg)
5250                 return -ENOMEM;
5252         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
5253                    beacon_set);
5254         if (beacon_set)
5255                 cmd = NL80211_CMD_SET_BEACON;
5257         nl80211_cmd(drv, msg, 0, cmd);
5258         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, params->head_len, params->head);
5259         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, params->tail_len, params->tail);
5260         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
5261         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, params->beacon_int);
5262         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, params->dtim_period);
5263         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
5264                 params->ssid);
5265         if (params->proberesp && params->proberesp_len)
5266                 NLA_PUT(msg, NL80211_ATTR_PROBE_RESP, params->proberesp_len,
5267                         params->proberesp);
5268         switch (params->hide_ssid) {
5269         case NO_SSID_HIDING:
5270                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5271                             NL80211_HIDDEN_SSID_NOT_IN_USE);
5272                 break;
5273         case HIDDEN_SSID_ZERO_LEN:
5274                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5275                             NL80211_HIDDEN_SSID_ZERO_LEN);
5276                 break;
5277         case HIDDEN_SSID_ZERO_CONTENTS:
5278                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5279                             NL80211_HIDDEN_SSID_ZERO_CONTENTS);
5280                 break;
5281         }
5282         if (params->privacy)
5283                 NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
5284         if ((params->auth_algs & (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) ==
5285             (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) {
5286                 /* Leave out the attribute */
5287         } else if (params->auth_algs & WPA_AUTH_ALG_SHARED)
5288                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5289                             NL80211_AUTHTYPE_SHARED_KEY);
5290         else
5291                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5292                             NL80211_AUTHTYPE_OPEN_SYSTEM);
5294         ver = 0;
5295         if (params->wpa_version & WPA_PROTO_WPA)
5296                 ver |= NL80211_WPA_VERSION_1;
5297         if (params->wpa_version & WPA_PROTO_RSN)
5298                 ver |= NL80211_WPA_VERSION_2;
5299         if (ver)
5300                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
5302         num_suites = 0;
5303         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X)
5304                 suites[num_suites++] = WLAN_AKM_SUITE_8021X;
5305         if (params->key_mgmt_suites & WPA_KEY_MGMT_PSK)
5306                 suites[num_suites++] = WLAN_AKM_SUITE_PSK;
5307         if (num_suites) {
5308                 NLA_PUT(msg, NL80211_ATTR_AKM_SUITES,
5309                         num_suites * sizeof(u32), suites);
5310         }
5312         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X &&
5313             params->pairwise_ciphers & (WPA_CIPHER_WEP104 | WPA_CIPHER_WEP40))
5314                 NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT);
5316         num_suites = 0;
5317         if (params->pairwise_ciphers & WPA_CIPHER_CCMP)
5318                 suites[num_suites++] = WLAN_CIPHER_SUITE_CCMP;
5319         if (params->pairwise_ciphers & WPA_CIPHER_TKIP)
5320                 suites[num_suites++] = WLAN_CIPHER_SUITE_TKIP;
5321         if (params->pairwise_ciphers & WPA_CIPHER_WEP104)
5322                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP104;
5323         if (params->pairwise_ciphers & WPA_CIPHER_WEP40)
5324                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP40;
5325         if (num_suites) {
5326                 NLA_PUT(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE,
5327                         num_suites * sizeof(u32), suites);
5328         }
5330         switch (params->group_cipher) {
5331         case WPA_CIPHER_CCMP:
5332                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5333                             WLAN_CIPHER_SUITE_CCMP);
5334                 break;
5335         case WPA_CIPHER_TKIP:
5336                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5337                             WLAN_CIPHER_SUITE_TKIP);
5338                 break;
5339         case WPA_CIPHER_WEP104:
5340                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5341                             WLAN_CIPHER_SUITE_WEP104);
5342                 break;
5343         case WPA_CIPHER_WEP40:
5344                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5345                             WLAN_CIPHER_SUITE_WEP40);
5346                 break;
5347         }
5349         if (params->beacon_ies) {
5350                 NLA_PUT(msg, NL80211_ATTR_IE, wpabuf_len(params->beacon_ies),
5351                         wpabuf_head(params->beacon_ies));
5352         }
5353         if (params->proberesp_ies) {
5354                 NLA_PUT(msg, NL80211_ATTR_IE_PROBE_RESP,
5355                         wpabuf_len(params->proberesp_ies),
5356                         wpabuf_head(params->proberesp_ies));
5357         }
5358         if (params->assocresp_ies) {
5359                 NLA_PUT(msg, NL80211_ATTR_IE_ASSOC_RESP,
5360                         wpabuf_len(params->assocresp_ies),
5361                         wpabuf_head(params->assocresp_ies));
5362         }
5364         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5365         if (ret) {
5366                 wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
5367                            ret, strerror(-ret));
5368         } else {
5369                 bss->beacon_set = 1;
5370                 nl80211_set_bss(bss, params->cts_protect, params->preamble,
5371                                 params->short_slot_time, params->ht_opmode,
5372                                 params->isolate, params->basic_rates);
5373         }
5374         return ret;
5375  nla_put_failure:
5376         nlmsg_free(msg);
5377         return -ENOBUFS;
5381 static int wpa_driver_nl80211_set_freq(struct i802_bss *bss,
5382                                        int freq, int ht_enabled,
5383                                        int sec_channel_offset)
5385         struct wpa_driver_nl80211_data *drv = bss->drv;
5386         struct nl_msg *msg;
5387         int ret;
5389         wpa_printf(MSG_DEBUG, "nl80211: Set freq %d (ht_enabled=%d "
5390                    "sec_channel_offset=%d)",
5391                    freq, ht_enabled, sec_channel_offset);
5392         msg = nlmsg_alloc();
5393         if (!msg)
5394                 return -1;
5396         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
5398         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5399         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
5400         if (ht_enabled) {
5401                 switch (sec_channel_offset) {
5402                 case -1:
5403                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5404                                     NL80211_CHAN_HT40MINUS);
5405                         break;
5406                 case 1:
5407                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5408                                     NL80211_CHAN_HT40PLUS);
5409                         break;
5410                 default:
5411                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5412                                     NL80211_CHAN_HT20);
5413                         break;
5414                 }
5415         }
5417         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5418         msg = NULL;
5419         if (ret == 0) {
5420                 bss->freq = freq;
5421                 return 0;
5422         }
5423         wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
5424                    "%d (%s)", freq, ret, strerror(-ret));
5425 nla_put_failure:
5426         nlmsg_free(msg);
5427         return -1;
5431 static u32 sta_flags_nl80211(int flags)
5433         u32 f = 0;
5435         if (flags & WPA_STA_AUTHORIZED)
5436                 f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
5437         if (flags & WPA_STA_WMM)
5438                 f |= BIT(NL80211_STA_FLAG_WME);
5439         if (flags & WPA_STA_SHORT_PREAMBLE)
5440                 f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
5441         if (flags & WPA_STA_MFP)
5442                 f |= BIT(NL80211_STA_FLAG_MFP);
5443         if (flags & WPA_STA_TDLS_PEER)
5444                 f |= BIT(NL80211_STA_FLAG_TDLS_PEER);
5446         return f;
5450 static int wpa_driver_nl80211_sta_add(void *priv,
5451                                       struct hostapd_sta_add_params *params)
5453         struct i802_bss *bss = priv;
5454         struct wpa_driver_nl80211_data *drv = bss->drv;
5455         struct nl_msg *msg, *wme = NULL;
5456         struct nl80211_sta_flag_update upd;
5457         int ret = -ENOBUFS;
5459         if ((params->flags & WPA_STA_TDLS_PEER) &&
5460             !(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
5461                 return -EOPNOTSUPP;
5463         msg = nlmsg_alloc();
5464         if (!msg)
5465                 return -ENOMEM;
5467         nl80211_cmd(drv, msg, 0, params->set ? NL80211_CMD_SET_STATION :
5468                     NL80211_CMD_NEW_STATION);
5470         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5471         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
5472         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
5473                 params->supp_rates);
5474         if (!params->set) {
5475                 NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
5476                 NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
5477                             params->listen_interval);
5478         }
5479         if (params->ht_capabilities) {
5480                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
5481                         sizeof(*params->ht_capabilities),
5482                         params->ht_capabilities);
5483         }
5485         os_memset(&upd, 0, sizeof(upd));
5486         upd.mask = sta_flags_nl80211(params->flags);
5487         upd.set = upd.mask;
5488         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
5490         if (params->flags & WPA_STA_WMM) {
5491                 wme = nlmsg_alloc();
5492                 if (!wme)
5493                         goto nla_put_failure;
5495                 NLA_PUT_U8(wme, NL80211_STA_WME_UAPSD_QUEUES,
5496                                 params->qosinfo & WMM_QOSINFO_STA_AC_MASK);
5497                 NLA_PUT_U8(wme, NL80211_STA_WME_MAX_SP,
5498                                 (params->qosinfo > WMM_QOSINFO_STA_SP_SHIFT) &
5499                                 WMM_QOSINFO_STA_SP_MASK);
5500                 nla_put_nested(msg, NL80211_ATTR_STA_WME, wme);
5501         }
5503         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5504         msg = NULL;
5505         if (ret)
5506                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_%s_STATION "
5507                            "result: %d (%s)", params->set ? "SET" : "NEW", ret,
5508                            strerror(-ret));
5509         if (ret == -EEXIST)
5510                 ret = 0;
5511  nla_put_failure:
5512         nlmsg_free(wme);
5513         nlmsg_free(msg);
5514         return ret;
5518 static int wpa_driver_nl80211_sta_remove(void *priv, const u8 *addr)
5520         struct i802_bss *bss = priv;
5521         struct wpa_driver_nl80211_data *drv = bss->drv;
5522         struct nl_msg *msg;
5523         int ret;
5525         msg = nlmsg_alloc();
5526         if (!msg)
5527                 return -ENOMEM;
5529         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
5531         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5532                     if_nametoindex(bss->ifname));
5533         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5535         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5536         if (ret == -ENOENT)
5537                 return 0;
5538         return ret;
5539  nla_put_failure:
5540         nlmsg_free(msg);
5541         return -ENOBUFS;
5545 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
5546                                  int ifidx)
5548         struct nl_msg *msg;
5550         wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
5552         /* stop listening for EAPOL on this interface */
5553         del_ifidx(drv, ifidx);
5555         msg = nlmsg_alloc();
5556         if (!msg)
5557                 goto nla_put_failure;
5559         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_INTERFACE);
5560         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
5562         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
5563                 return;
5564         msg = NULL;
5565  nla_put_failure:
5566         nlmsg_free(msg);
5567         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
5571 static const char * nl80211_iftype_str(enum nl80211_iftype mode)
5573         switch (mode) {
5574         case NL80211_IFTYPE_ADHOC:
5575                 return "ADHOC";
5576         case NL80211_IFTYPE_STATION:
5577                 return "STATION";
5578         case NL80211_IFTYPE_AP:
5579                 return "AP";
5580         case NL80211_IFTYPE_MONITOR:
5581                 return "MONITOR";
5582         case NL80211_IFTYPE_P2P_CLIENT:
5583                 return "P2P_CLIENT";
5584         case NL80211_IFTYPE_P2P_GO:
5585                 return "P2P_GO";
5586         default:
5587                 return "unknown";
5588         }
5592 static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
5593                                      const char *ifname,
5594                                      enum nl80211_iftype iftype,
5595                                      const u8 *addr, int wds)
5597         struct nl_msg *msg, *flags = NULL;
5598         int ifidx;
5599         int ret = -ENOBUFS;
5601         wpa_printf(MSG_DEBUG, "nl80211: Create interface iftype %d (%s)",
5602                    iftype, nl80211_iftype_str(iftype));
5604         msg = nlmsg_alloc();
5605         if (!msg)
5606                 return -1;
5608         nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_INTERFACE);
5609         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5610         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
5611         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
5613         if (iftype == NL80211_IFTYPE_MONITOR) {
5614                 int err;
5616                 flags = nlmsg_alloc();
5617                 if (!flags)
5618                         goto nla_put_failure;
5620                 NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
5622                 err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
5624                 nlmsg_free(flags);
5626                 if (err)
5627                         goto nla_put_failure;
5628         } else if (wds) {
5629                 NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
5630         }
5632         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5633         msg = NULL;
5634         if (ret) {
5635  nla_put_failure:
5636                 nlmsg_free(msg);
5637                 wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
5638                            ifname, ret, strerror(-ret));
5639                 return ret;
5640         }
5642         ifidx = if_nametoindex(ifname);
5643         wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
5644                    ifname, ifidx);
5646         if (ifidx <= 0)
5647                 return -1;
5649         /* start listening for EAPOL on this interface */
5650         add_ifidx(drv, ifidx);
5652         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
5653             linux_set_ifhwaddr(drv->global->ioctl_sock, ifname, addr)) {
5654                 nl80211_remove_iface(drv, ifidx);
5655                 return -1;
5656         }
5658         return ifidx;
5662 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
5663                                 const char *ifname, enum nl80211_iftype iftype,
5664                                 const u8 *addr, int wds)
5666         int ret;
5668         ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds);
5670         /* if error occurred and interface exists already */
5671         if (ret == -ENFILE && if_nametoindex(ifname)) {
5672                 wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
5674                 /* Try to remove the interface that was already there. */
5675                 nl80211_remove_iface(drv, if_nametoindex(ifname));
5677                 /* Try to create the interface again */
5678                 ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
5679                                                 wds);
5680         }
5682         if (ret >= 0 && is_p2p_interface(iftype))
5683                 nl80211_disable_11b_rates(drv, ret, 1);
5685         return ret;
5689 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
5691         struct ieee80211_hdr *hdr;
5692         u16 fc;
5693         union wpa_event_data event;
5695         hdr = (struct ieee80211_hdr *) buf;
5696         fc = le_to_host16(hdr->frame_control);
5698         os_memset(&event, 0, sizeof(event));
5699         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
5700         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
5701         event.tx_status.dst = hdr->addr1;
5702         event.tx_status.data = buf;
5703         event.tx_status.data_len = len;
5704         event.tx_status.ack = ok;
5705         wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
5709 static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
5710                              u8 *buf, size_t len)
5712         struct ieee80211_hdr *hdr = (void *)buf;
5713         u16 fc;
5714         union wpa_event_data event;
5716         if (len < sizeof(*hdr))
5717                 return;
5719         fc = le_to_host16(hdr->frame_control);
5721         os_memset(&event, 0, sizeof(event));
5722         event.rx_from_unknown.bssid = get_hdr_bssid(hdr, len);
5723         event.rx_from_unknown.addr = hdr->addr2;
5724         event.rx_from_unknown.wds = (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) ==
5725                 (WLAN_FC_FROMDS | WLAN_FC_TODS);
5726         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
5730 static void handle_frame(struct wpa_driver_nl80211_data *drv,
5731                          u8 *buf, size_t len, int datarate, int ssi_signal)
5733         struct ieee80211_hdr *hdr;
5734         u16 fc;
5735         union wpa_event_data event;
5737         hdr = (struct ieee80211_hdr *) buf;
5738         fc = le_to_host16(hdr->frame_control);
5740         switch (WLAN_FC_GET_TYPE(fc)) {
5741         case WLAN_FC_TYPE_MGMT:
5742                 os_memset(&event, 0, sizeof(event));
5743                 event.rx_mgmt.frame = buf;
5744                 event.rx_mgmt.frame_len = len;
5745                 event.rx_mgmt.datarate = datarate;
5746                 event.rx_mgmt.ssi_signal = ssi_signal;
5747                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
5748                 break;
5749         case WLAN_FC_TYPE_CTRL:
5750                 /* can only get here with PS-Poll frames */
5751                 wpa_printf(MSG_DEBUG, "CTRL");
5752                 from_unknown_sta(drv, buf, len);
5753                 break;
5754         case WLAN_FC_TYPE_DATA:
5755                 from_unknown_sta(drv, buf, len);
5756                 break;
5757         }
5761 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
5763         struct wpa_driver_nl80211_data *drv = eloop_ctx;
5764         int len;
5765         unsigned char buf[3000];
5766         struct ieee80211_radiotap_iterator iter;
5767         int ret;
5768         int datarate = 0, ssi_signal = 0;
5769         int injected = 0, failed = 0, rxflags = 0;
5771         len = recv(sock, buf, sizeof(buf), 0);
5772         if (len < 0) {
5773                 perror("recv");
5774                 return;
5775         }
5777         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
5778                 printf("received invalid radiotap frame\n");
5779                 return;
5780         }
5782         while (1) {
5783                 ret = ieee80211_radiotap_iterator_next(&iter);
5784                 if (ret == -ENOENT)
5785                         break;
5786                 if (ret) {
5787                         printf("received invalid radiotap frame (%d)\n", ret);
5788                         return;
5789                 }
5790                 switch (iter.this_arg_index) {
5791                 case IEEE80211_RADIOTAP_FLAGS:
5792                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
5793                                 len -= 4;
5794                         break;
5795                 case IEEE80211_RADIOTAP_RX_FLAGS:
5796                         rxflags = 1;
5797                         break;
5798                 case IEEE80211_RADIOTAP_TX_FLAGS:
5799                         injected = 1;
5800                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
5801                                         IEEE80211_RADIOTAP_F_TX_FAIL;
5802                         break;
5803                 case IEEE80211_RADIOTAP_DATA_RETRIES:
5804                         break;
5805                 case IEEE80211_RADIOTAP_CHANNEL:
5806                         /* TODO: convert from freq/flags to channel number */
5807                         break;
5808                 case IEEE80211_RADIOTAP_RATE:
5809                         datarate = *iter.this_arg * 5;
5810                         break;
5811                 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
5812                         ssi_signal = *iter.this_arg;
5813                         break;
5814                 }
5815         }
5817         if (rxflags && injected)
5818                 return;
5820         if (!injected)
5821                 handle_frame(drv, buf + iter.max_length,
5822                              len - iter.max_length, datarate, ssi_signal);
5823         else
5824                 handle_tx_callback(drv->ctx, buf + iter.max_length,
5825                                    len - iter.max_length, !failed);
5829 /*
5830  * we post-process the filter code later and rewrite
5831  * this to the offset to the last instruction
5832  */
5833 #define PASS    0xFF
5834 #define FAIL    0xFE
5836 static struct sock_filter msock_filter_insns[] = {
5837         /*
5838          * do a little-endian load of the radiotap length field
5839          */
5840         /* load lower byte into A */
5841         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
5842         /* put it into X (== index register) */
5843         BPF_STMT(BPF_MISC| BPF_TAX, 0),
5844         /* load upper byte into A */
5845         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
5846         /* left-shift it by 8 */
5847         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
5848         /* or with X */
5849         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
5850         /* put result into X */
5851         BPF_STMT(BPF_MISC| BPF_TAX, 0),
5853         /*
5854          * Allow management frames through, this also gives us those
5855          * management frames that we sent ourselves with status
5856          */
5857         /* load the lower byte of the IEEE 802.11 frame control field */
5858         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
5859         /* mask off frame type and version */
5860         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
5861         /* accept frame if it's both 0, fall through otherwise */
5862         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
5864         /*
5865          * TODO: add a bit to radiotap RX flags that indicates
5866          * that the sending station is not associated, then
5867          * add a filter here that filters on our DA and that flag
5868          * to allow us to deauth frames to that bad station.
5869          *
5870          * For now allow all To DS data frames through.
5871          */
5872         /* load the IEEE 802.11 frame control field */
5873         BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
5874         /* mask off frame type, version and DS status */
5875         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
5876         /* accept frame if version 0, type 2 and To DS, fall through otherwise
5877          */
5878         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
5880 #if 0
5881         /*
5882          * drop non-data frames
5883          */
5884         /* load the lower byte of the frame control field */
5885         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
5886         /* mask off QoS bit */
5887         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
5888         /* drop non-data frames */
5889         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
5890 #endif
5891         /* load the upper byte of the frame control field */
5892         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
5893         /* mask off toDS/fromDS */
5894         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
5895         /* accept WDS frames */
5896         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
5898         /*
5899          * add header length to index
5900          */
5901         /* load the lower byte of the frame control field */
5902         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
5903         /* mask off QoS bit */
5904         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
5905         /* right shift it by 6 to give 0 or 2 */
5906         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
5907         /* add data frame header length */
5908         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
5909         /* add index, was start of 802.11 header */
5910         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
5911         /* move to index, now start of LL header */
5912         BPF_STMT(BPF_MISC | BPF_TAX, 0),
5914         /*
5915          * Accept empty data frames, we use those for
5916          * polling activity.
5917          */
5918         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
5919         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
5921         /*
5922          * Accept EAPOL frames
5923          */
5924         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
5925         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
5926         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
5927         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
5929         /* keep these last two statements or change the code below */
5930         /* return 0 == "DROP" */
5931         BPF_STMT(BPF_RET | BPF_K, 0),
5932         /* return ~0 == "keep all" */
5933         BPF_STMT(BPF_RET | BPF_K, ~0),
5934 };
5936 static struct sock_fprog msock_filter = {
5937         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
5938         .filter = msock_filter_insns,
5939 };
5942 static int add_monitor_filter(int s)
5944         int idx;
5946         /* rewrite all PASS/FAIL jump offsets */
5947         for (idx = 0; idx < msock_filter.len; idx++) {
5948                 struct sock_filter *insn = &msock_filter_insns[idx];
5950                 if (BPF_CLASS(insn->code) == BPF_JMP) {
5951                         if (insn->code == (BPF_JMP|BPF_JA)) {
5952                                 if (insn->k == PASS)
5953                                         insn->k = msock_filter.len - idx - 2;
5954                                 else if (insn->k == FAIL)
5955                                         insn->k = msock_filter.len - idx - 3;
5956                         }
5958                         if (insn->jt == PASS)
5959                                 insn->jt = msock_filter.len - idx - 2;
5960                         else if (insn->jt == FAIL)
5961                                 insn->jt = msock_filter.len - idx - 3;
5963                         if (insn->jf == PASS)
5964                                 insn->jf = msock_filter.len - idx - 2;
5965                         else if (insn->jf == FAIL)
5966                                 insn->jf = msock_filter.len - idx - 3;
5967                 }
5968         }
5970         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
5971                        &msock_filter, sizeof(msock_filter))) {
5972                 perror("SO_ATTACH_FILTER");
5973                 return -1;
5974         }
5976         return 0;
5980 static void nl80211_remove_monitor_interface(
5981         struct wpa_driver_nl80211_data *drv)
5983         drv->monitor_refcount--;
5984         if (drv->monitor_refcount > 0)
5985                 return;
5987         if (drv->monitor_ifidx >= 0) {
5988                 nl80211_remove_iface(drv, drv->monitor_ifidx);
5989                 drv->monitor_ifidx = -1;
5990         }
5991         if (drv->monitor_sock >= 0) {
5992                 eloop_unregister_read_sock(drv->monitor_sock);
5993                 close(drv->monitor_sock);
5994                 drv->monitor_sock = -1;
5995         }
5999 static int
6000 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
6002         char buf[IFNAMSIZ];
6003         struct sockaddr_ll ll;
6004         int optval;
6005         socklen_t optlen;
6007         if (drv->monitor_ifidx >= 0) {
6008                 drv->monitor_refcount++;
6009                 return 0;
6010         }
6012         if (os_strncmp(drv->first_bss.ifname, "p2p-", 4) == 0) {
6013                 /*
6014                  * P2P interface name is of the format p2p-%s-%d. For monitor
6015                  * interface name corresponding to P2P GO, replace "p2p-" with
6016                  * "mon-" to retain the same interface name length and to
6017                  * indicate that it is a monitor interface.
6018                  */
6019                 snprintf(buf, IFNAMSIZ, "mon-%s", drv->first_bss.ifname + 4);
6020         } else {
6021                 /* Non-P2P interface with AP functionality. */
6022                 snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss.ifname);
6023         }
6025         buf[IFNAMSIZ - 1] = '\0';
6027         drv->monitor_ifidx =
6028                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
6029                                      0);
6031         if (drv->monitor_ifidx == -EOPNOTSUPP) {
6032                 /*
6033                  * This is backward compatibility for a few versions of
6034                  * the kernel only that didn't advertise the right
6035                  * attributes for the only driver that then supported
6036                  * AP mode w/o monitor -- ath6kl.
6037                  */
6038                 wpa_printf(MSG_DEBUG, "nl80211: Driver does not support "
6039                            "monitor interface type - try to run without it");
6040                 drv->device_ap_sme = 1;
6041         }
6043         if (drv->monitor_ifidx < 0)
6044                 return -1;
6046         if (linux_set_iface_flags(drv->global->ioctl_sock, buf, 1))
6047                 goto error;
6049         memset(&ll, 0, sizeof(ll));
6050         ll.sll_family = AF_PACKET;
6051         ll.sll_ifindex = drv->monitor_ifidx;
6052         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
6053         if (drv->monitor_sock < 0) {
6054                 perror("socket[PF_PACKET,SOCK_RAW]");
6055                 goto error;
6056         }
6058         if (add_monitor_filter(drv->monitor_sock)) {
6059                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
6060                            "interface; do filtering in user space");
6061                 /* This works, but will cost in performance. */
6062         }
6064         if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
6065                 perror("monitor socket bind");
6066                 goto error;
6067         }
6069         optlen = sizeof(optval);
6070         optval = 20;
6071         if (setsockopt
6072             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
6073                 perror("Failed to set socket priority");
6074                 goto error;
6075         }
6077         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
6078                                      drv, NULL)) {
6079                 printf("Could not register monitor read socket\n");
6080                 goto error;
6081         }
6083         return 0;
6084  error:
6085         nl80211_remove_monitor_interface(drv);
6086         return -1;
6090 static int nl80211_setup_ap(struct i802_bss *bss)
6092         struct wpa_driver_nl80211_data *drv = bss->drv;
6094         wpa_printf(MSG_DEBUG, "nl80211: Setup AP - device_ap_sme=%d "
6095                    "use_monitor=%d", drv->device_ap_sme, drv->use_monitor);
6097         /*
6098          * Disable Probe Request reporting unless we need it in this way for
6099          * devices that include the AP SME, in the other case (unless using
6100          * monitor iface) we'll get it through the nl_mgmt socket instead.
6101          */
6102         if (!drv->device_ap_sme)
6103                 wpa_driver_nl80211_probe_req_report(bss, 0);
6105         if (!drv->device_ap_sme && !drv->use_monitor)
6106                 if (nl80211_mgmt_subscribe_ap(bss))
6107                         return -1;
6109         if (drv->device_ap_sme && !drv->use_monitor)
6110                 if (nl80211_mgmt_subscribe_ap_dev_sme(bss))
6111                         return -1;
6113         if (!drv->device_ap_sme && drv->use_monitor &&
6114             nl80211_create_monitor_interface(drv) &&
6115             !drv->device_ap_sme)
6116                 return -1;
6118         if (drv->device_ap_sme &&
6119             wpa_driver_nl80211_probe_req_report(bss, 1) < 0) {
6120                 wpa_printf(MSG_DEBUG, "nl80211: Failed to enable "
6121                            "Probe Request frame reporting in AP mode");
6122                 /* Try to survive without this */
6123         }
6125         return 0;
6129 static void nl80211_teardown_ap(struct i802_bss *bss)
6131         struct wpa_driver_nl80211_data *drv = bss->drv;
6133         if (drv->device_ap_sme) {
6134                 wpa_driver_nl80211_probe_req_report(bss, 0);
6135                 if (!drv->use_monitor)
6136                         nl80211_mgmt_unsubscribe(bss, "AP teardown (dev SME)");
6137         } else if (drv->use_monitor)
6138                 nl80211_remove_monitor_interface(drv);
6139         else
6140                 nl80211_mgmt_unsubscribe(bss, "AP teardown");
6142         bss->beacon_set = 0;
6146 static int nl80211_send_eapol_data(struct i802_bss *bss,
6147                                    const u8 *addr, const u8 *data,
6148                                    size_t data_len)
6150         struct sockaddr_ll ll;
6151         int ret;
6153         if (bss->drv->eapol_tx_sock < 0) {
6154                 wpa_printf(MSG_DEBUG, "nl80211: No socket to send EAPOL");
6155                 return -1;
6156         }
6158         os_memset(&ll, 0, sizeof(ll));
6159         ll.sll_family = AF_PACKET;
6160         ll.sll_ifindex = bss->ifindex;
6161         ll.sll_protocol = htons(ETH_P_PAE);
6162         ll.sll_halen = ETH_ALEN;
6163         os_memcpy(ll.sll_addr, addr, ETH_ALEN);
6164         ret = sendto(bss->drv->eapol_tx_sock, data, data_len, 0,
6165                      (struct sockaddr *) &ll, sizeof(ll));
6166         if (ret < 0)
6167                 wpa_printf(MSG_ERROR, "nl80211: EAPOL TX: %s",
6168                            strerror(errno));
6170         return ret;
6174 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
6176 static int wpa_driver_nl80211_hapd_send_eapol(
6177         void *priv, const u8 *addr, const u8 *data,
6178         size_t data_len, int encrypt, const u8 *own_addr, u32 flags)
6180         struct i802_bss *bss = priv;
6181         struct wpa_driver_nl80211_data *drv = bss->drv;
6182         struct ieee80211_hdr *hdr;
6183         size_t len;
6184         u8 *pos;
6185         int res;
6186         int qos = flags & WPA_STA_WMM;
6188         if (drv->device_ap_sme || !drv->use_monitor)
6189                 return nl80211_send_eapol_data(bss, addr, data, data_len);
6191         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
6192                 data_len;
6193         hdr = os_zalloc(len);
6194         if (hdr == NULL) {
6195                 printf("malloc() failed for i802_send_data(len=%lu)\n",
6196                        (unsigned long) len);
6197                 return -1;
6198         }
6200         hdr->frame_control =
6201                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
6202         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
6203         if (encrypt)
6204                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
6205         if (qos) {
6206                 hdr->frame_control |=
6207                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
6208         }
6210         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
6211         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
6212         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
6213         pos = (u8 *) (hdr + 1);
6215         if (qos) {
6216                 /* add an empty QoS header if needed */
6217                 pos[0] = 0;
6218                 pos[1] = 0;
6219                 pos += 2;
6220         }
6222         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
6223         pos += sizeof(rfc1042_header);
6224         WPA_PUT_BE16(pos, ETH_P_PAE);
6225         pos += 2;
6226         memcpy(pos, data, data_len);
6228         res = wpa_driver_nl80211_send_frame(bss, (u8 *) hdr, len, encrypt, 0);
6229         if (res < 0) {
6230                 wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
6231                            "failed: %d (%s)",
6232                            (unsigned long) len, errno, strerror(errno));
6233         }
6234         os_free(hdr);
6236         return res;
6240 static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
6241                                             int total_flags,
6242                                             int flags_or, int flags_and)
6244         struct i802_bss *bss = priv;
6245         struct wpa_driver_nl80211_data *drv = bss->drv;
6246         struct nl_msg *msg, *flags = NULL;
6247         struct nl80211_sta_flag_update upd;
6249         msg = nlmsg_alloc();
6250         if (!msg)
6251                 return -ENOMEM;
6253         flags = nlmsg_alloc();
6254         if (!flags) {
6255                 nlmsg_free(msg);
6256                 return -ENOMEM;
6257         }
6259         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
6261         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
6262                     if_nametoindex(bss->ifname));
6263         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
6265         /*
6266          * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
6267          * can be removed eventually.
6268          */
6269         if (total_flags & WPA_STA_AUTHORIZED)
6270                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
6272         if (total_flags & WPA_STA_WMM)
6273                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
6275         if (total_flags & WPA_STA_SHORT_PREAMBLE)
6276                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
6278         if (total_flags & WPA_STA_MFP)
6279                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
6281         if (total_flags & WPA_STA_TDLS_PEER)
6282                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_TDLS_PEER);
6284         if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
6285                 goto nla_put_failure;
6287         os_memset(&upd, 0, sizeof(upd));
6288         upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
6289         upd.set = sta_flags_nl80211(flags_or);
6290         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
6292         nlmsg_free(flags);
6294         return send_and_recv_msgs(drv, msg, NULL, NULL);
6295  nla_put_failure:
6296         nlmsg_free(msg);
6297         nlmsg_free(flags);
6298         return -ENOBUFS;
6302 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
6303                                  struct wpa_driver_associate_params *params)
6305         enum nl80211_iftype nlmode;
6307         if (params->p2p) {
6308                 wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
6309                            "group (GO)");
6310                 nlmode = NL80211_IFTYPE_P2P_GO;
6311         } else
6312                 nlmode = NL80211_IFTYPE_AP;
6314         if (wpa_driver_nl80211_set_mode(&drv->first_bss, nlmode) ||
6315             wpa_driver_nl80211_set_freq(&drv->first_bss, params->freq, 0, 0)) {
6316                 nl80211_remove_monitor_interface(drv);
6317                 return -1;
6318         }
6320         return 0;
6324 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
6326         struct nl_msg *msg;
6327         int ret = -1;
6329         msg = nlmsg_alloc();
6330         if (!msg)
6331                 return -1;
6333         nl80211_cmd(drv, msg, 0, NL80211_CMD_LEAVE_IBSS);
6334         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6335         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6336         msg = NULL;
6337         if (ret) {
6338                 wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
6339                            "(%s)", ret, strerror(-ret));
6340                 goto nla_put_failure;
6341         }
6343         ret = 0;
6344         wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
6346 nla_put_failure:
6347         nlmsg_free(msg);
6348         return ret;
6352 static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
6353                                    struct wpa_driver_associate_params *params)
6355         struct nl_msg *msg;
6356         int ret = -1;
6357         int count = 0;
6359         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
6361         if (wpa_driver_nl80211_set_mode(&drv->first_bss,
6362                                         NL80211_IFTYPE_ADHOC)) {
6363                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
6364                            "IBSS mode");
6365                 return -1;
6366         }
6368 retry:
6369         msg = nlmsg_alloc();
6370         if (!msg)
6371                 return -1;
6373         nl80211_cmd(drv, msg, 0, NL80211_CMD_JOIN_IBSS);
6374         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6376         if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
6377                 goto nla_put_failure;
6379         wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6380                           params->ssid, params->ssid_len);
6381         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6382                 params->ssid);
6383         os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6384         drv->ssid_len = params->ssid_len;
6386         wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6387         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6389         ret = nl80211_set_conn_keys(params, msg);
6390         if (ret)
6391                 goto nla_put_failure;
6393         if (params->wpa_ie) {
6394                 wpa_hexdump(MSG_DEBUG,
6395                             "  * Extra IEs for Beacon/Probe Response frames",
6396                             params->wpa_ie, params->wpa_ie_len);
6397                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6398                         params->wpa_ie);
6399         }
6401         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6402         msg = NULL;
6403         if (ret) {
6404                 wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
6405                            ret, strerror(-ret));
6406                 count++;
6407                 if (ret == -EALREADY && count == 1) {
6408                         wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
6409                                    "forced leave");
6410                         nl80211_leave_ibss(drv);
6411                         nlmsg_free(msg);
6412                         goto retry;
6413                 }
6415                 goto nla_put_failure;
6416         }
6417         ret = 0;
6418         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
6420 nla_put_failure:
6421         nlmsg_free(msg);
6422         return ret;
6426 static unsigned int nl80211_get_assoc_bssid(struct wpa_driver_nl80211_data *drv,
6427                                             u8 *bssid)
6429         struct nl_msg *msg;
6430         int ret;
6431         struct nl80211_bss_info_arg arg;
6433         os_memset(&arg, 0, sizeof(arg));
6434         msg = nlmsg_alloc();
6435         if (!msg)
6436                 goto nla_put_failure;
6438         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
6439         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6441         arg.drv = drv;
6442         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
6443         msg = NULL;
6444         if (ret == 0) {
6445                 if (is_zero_ether_addr(arg.assoc_bssid))
6446                         return -ENOTCONN;
6447                 os_memcpy(bssid, arg.assoc_bssid, ETH_ALEN);
6448                 return 0;
6449         }
6450         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
6451                    "(%s)", ret, strerror(-ret));
6452 nla_put_failure:
6453         nlmsg_free(msg);
6454         return drv->assoc_freq;
6458 static int nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
6459                               const u8 *bssid)
6461         u8 addr[ETH_ALEN];
6463         if (bssid == NULL) {
6464                 int res = nl80211_get_assoc_bssid(drv, addr);
6465                 if (res)
6466                         return res;
6467                 bssid = addr;
6468         }
6470         return wpa_driver_nl80211_disconnect(drv, bssid,
6471                                              WLAN_REASON_PREV_AUTH_NOT_VALID);
6475 static int wpa_driver_nl80211_connect(
6476         struct wpa_driver_nl80211_data *drv,
6477         struct wpa_driver_associate_params *params)
6479         struct nl_msg *msg;
6480         enum nl80211_auth_type type;
6481         int ret = 0;
6482         int algs;
6484         msg = nlmsg_alloc();
6485         if (!msg)
6486                 return -1;
6488         wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
6489         nl80211_cmd(drv, msg, 0, NL80211_CMD_CONNECT);
6491         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6492         if (params->bssid) {
6493                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
6494                            MAC2STR(params->bssid));
6495                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6496         }
6497         if (params->freq) {
6498                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6499                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6500         }
6501         if (params->ssid) {
6502                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6503                                   params->ssid, params->ssid_len);
6504                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6505                         params->ssid);
6506                 if (params->ssid_len > sizeof(drv->ssid))
6507                         goto nla_put_failure;
6508                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6509                 drv->ssid_len = params->ssid_len;
6510         }
6511         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
6512         if (params->wpa_ie)
6513                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6514                         params->wpa_ie);
6516         algs = 0;
6517         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
6518                 algs++;
6519         if (params->auth_alg & WPA_AUTH_ALG_SHARED)
6520                 algs++;
6521         if (params->auth_alg & WPA_AUTH_ALG_LEAP)
6522                 algs++;
6523         if (algs > 1) {
6524                 wpa_printf(MSG_DEBUG, "  * Leave out Auth Type for automatic "
6525                            "selection");
6526                 goto skip_auth_type;
6527         }
6529         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
6530                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
6531         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
6532                 type = NL80211_AUTHTYPE_SHARED_KEY;
6533         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
6534                 type = NL80211_AUTHTYPE_NETWORK_EAP;
6535         else if (params->auth_alg & WPA_AUTH_ALG_FT)
6536                 type = NL80211_AUTHTYPE_FT;
6537         else
6538                 goto nla_put_failure;
6540         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
6541         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
6543 skip_auth_type:
6544         if (params->wpa_proto) {
6545                 enum nl80211_wpa_versions ver = 0;
6547                 if (params->wpa_proto & WPA_PROTO_WPA)
6548                         ver |= NL80211_WPA_VERSION_1;
6549                 if (params->wpa_proto & WPA_PROTO_RSN)
6550                         ver |= NL80211_WPA_VERSION_2;
6552                 wpa_printf(MSG_DEBUG, "  * WPA Versions 0x%x", ver);
6553                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
6554         }
6556         if (params->pairwise_suite != CIPHER_NONE) {
6557                 int cipher;
6559                 switch (params->pairwise_suite) {
6560                 case CIPHER_WEP40:
6561                         cipher = WLAN_CIPHER_SUITE_WEP40;
6562                         break;
6563                 case CIPHER_WEP104:
6564                         cipher = WLAN_CIPHER_SUITE_WEP104;
6565                         break;
6566                 case CIPHER_CCMP:
6567                         cipher = WLAN_CIPHER_SUITE_CCMP;
6568                         break;
6569                 case CIPHER_TKIP:
6570                 default:
6571                         cipher = WLAN_CIPHER_SUITE_TKIP;
6572                         break;
6573                 }
6574                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
6575         }
6577         if (params->group_suite != CIPHER_NONE) {
6578                 int cipher;
6580                 switch (params->group_suite) {
6581                 case CIPHER_WEP40:
6582                         cipher = WLAN_CIPHER_SUITE_WEP40;
6583                         break;
6584                 case CIPHER_WEP104:
6585                         cipher = WLAN_CIPHER_SUITE_WEP104;
6586                         break;
6587                 case CIPHER_CCMP:
6588                         cipher = WLAN_CIPHER_SUITE_CCMP;
6589                         break;
6590                 case CIPHER_TKIP:
6591                 default:
6592                         cipher = WLAN_CIPHER_SUITE_TKIP;
6593                         break;
6594                 }
6595                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
6596         }
6598         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
6599             params->key_mgmt_suite == KEY_MGMT_PSK) {
6600                 int mgmt = WLAN_AKM_SUITE_PSK;
6602                 switch (params->key_mgmt_suite) {
6603                 case KEY_MGMT_802_1X:
6604                         mgmt = WLAN_AKM_SUITE_8021X;
6605                         break;
6606                 case KEY_MGMT_PSK:
6607                 default:
6608                         mgmt = WLAN_AKM_SUITE_PSK;
6609                         break;
6610                 }
6611                 NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
6612         }
6614         ret = nl80211_set_conn_keys(params, msg);
6615         if (ret)
6616                 goto nla_put_failure;
6618         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6619         msg = NULL;
6620         if (ret) {
6621                 wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
6622                            "(%s)", ret, strerror(-ret));
6623                 /*
6624                  * cfg80211 does not currently accept new connection if we are
6625                  * already connected. As a workaround, force disconnection and
6626                  * try again once the driver indicates it completed
6627                  * disconnection.
6628                  */
6629                 if (ret == -EALREADY)
6630                         nl80211_disconnect(drv, params->bssid);
6631                 goto nla_put_failure;
6632         }
6633         ret = 0;
6634         wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
6636 nla_put_failure:
6637         nlmsg_free(msg);
6638         return ret;
6643 static int wpa_driver_nl80211_associate(
6644         void *priv, struct wpa_driver_associate_params *params)
6646         struct i802_bss *bss = priv;
6647         struct wpa_driver_nl80211_data *drv = bss->drv;
6648         int ret = -1;
6649         struct nl_msg *msg;
6651         if (params->mode == IEEE80211_MODE_AP)
6652                 return wpa_driver_nl80211_ap(drv, params);
6654         if (params->mode == IEEE80211_MODE_IBSS)
6655                 return wpa_driver_nl80211_ibss(drv, params);
6657         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
6658                 enum nl80211_iftype nlmode = params->p2p ?
6659                         NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
6661                 if (wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
6662                         return -1;
6663                 return wpa_driver_nl80211_connect(drv, params);
6664         }
6666         drv->associated = 0;
6668         msg = nlmsg_alloc();
6669         if (!msg)
6670                 return -1;
6672         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
6673                    drv->ifindex);
6674         nl80211_cmd(drv, msg, 0, NL80211_CMD_ASSOCIATE);
6676         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6677         if (params->bssid) {
6678                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
6679                            MAC2STR(params->bssid));
6680                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6681         }
6682         if (params->freq) {
6683                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6684                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6685                 drv->assoc_freq = params->freq;
6686         } else
6687                 drv->assoc_freq = 0;
6688         if (params->ssid) {
6689                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6690                                   params->ssid, params->ssid_len);
6691                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6692                         params->ssid);
6693                 if (params->ssid_len > sizeof(drv->ssid))
6694                         goto nla_put_failure;
6695                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6696                 drv->ssid_len = params->ssid_len;
6697         }
6698         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
6699         if (params->wpa_ie)
6700                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6701                         params->wpa_ie);
6703         if (params->pairwise_suite != CIPHER_NONE) {
6704                 int cipher;
6706                 switch (params->pairwise_suite) {
6707                 case CIPHER_WEP40:
6708                         cipher = WLAN_CIPHER_SUITE_WEP40;
6709                         break;
6710                 case CIPHER_WEP104:
6711                         cipher = WLAN_CIPHER_SUITE_WEP104;
6712                         break;
6713                 case CIPHER_CCMP:
6714                         cipher = WLAN_CIPHER_SUITE_CCMP;
6715                         break;
6716                 case CIPHER_TKIP:
6717                 default:
6718                         cipher = WLAN_CIPHER_SUITE_TKIP;
6719                         break;
6720                 }
6721                 wpa_printf(MSG_DEBUG, "  * pairwise=0x%x", cipher);
6722                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
6723         }
6725         if (params->group_suite != CIPHER_NONE) {
6726                 int cipher;
6728                 switch (params->group_suite) {
6729                 case CIPHER_WEP40:
6730                         cipher = WLAN_CIPHER_SUITE_WEP40;
6731                         break;
6732                 case CIPHER_WEP104:
6733                         cipher = WLAN_CIPHER_SUITE_WEP104;
6734                         break;
6735                 case CIPHER_CCMP:
6736                         cipher = WLAN_CIPHER_SUITE_CCMP;
6737                         break;
6738                 case CIPHER_TKIP:
6739                 default:
6740                         cipher = WLAN_CIPHER_SUITE_TKIP;
6741                         break;
6742                 }
6743                 wpa_printf(MSG_DEBUG, "  * group=0x%x", cipher);
6744                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
6745         }
6747 #ifdef CONFIG_IEEE80211W
6748         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
6749                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
6750 #endif /* CONFIG_IEEE80211W */
6752         NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
6754         if (params->prev_bssid) {
6755                 wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
6756                            MAC2STR(params->prev_bssid));
6757                 NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
6758                         params->prev_bssid);
6759         }
6761         if (params->p2p)
6762                 wpa_printf(MSG_DEBUG, "  * P2P group");
6764         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6765         msg = NULL;
6766         if (ret) {
6767                 wpa_dbg(drv->ctx, MSG_DEBUG,
6768                         "nl80211: MLME command failed (assoc): ret=%d (%s)",
6769                         ret, strerror(-ret));
6770                 nl80211_dump_scan(drv);
6771                 goto nla_put_failure;
6772         }
6773         ret = 0;
6774         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
6775                    "successfully");
6777 nla_put_failure:
6778         nlmsg_free(msg);
6779         return ret;
6783 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
6784                             int ifindex, enum nl80211_iftype mode)
6786         struct nl_msg *msg;
6787         int ret = -ENOBUFS;
6789         wpa_printf(MSG_DEBUG, "nl80211: Set mode ifindex %d iftype %d (%s)",
6790                    ifindex, mode, nl80211_iftype_str(mode));
6792         msg = nlmsg_alloc();
6793         if (!msg)
6794                 return -ENOMEM;
6796         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_INTERFACE);
6797         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
6798         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
6800         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6801         msg = NULL;
6802         if (!ret)
6803                 return 0;
6804 nla_put_failure:
6805         nlmsg_free(msg);
6806         wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
6807                    " %d (%s)", ifindex, mode, ret, strerror(-ret));
6808         return ret;
6812 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
6813                                        enum nl80211_iftype nlmode)
6815         struct wpa_driver_nl80211_data *drv = bss->drv;
6816         int ret = -1;
6817         int i;
6818         int was_ap = is_ap_interface(drv->nlmode);
6819         int res;
6821         res = nl80211_set_mode(drv, drv->ifindex, nlmode);
6822         if (res == 0) {
6823                 drv->nlmode = nlmode;
6824                 ret = 0;
6825                 goto done;
6826         }
6828         if (res == -ENODEV)
6829                 return -1;
6831         if (nlmode == drv->nlmode) {
6832                 wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
6833                            "requested mode - ignore error");
6834                 ret = 0;
6835                 goto done; /* Already in the requested mode */
6836         }
6838         /* mac80211 doesn't allow mode changes while the device is up, so
6839          * take the device down, try to set the mode again, and bring the
6840          * device back up.
6841          */
6842         wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
6843                    "interface down");
6844         for (i = 0; i < 10; i++) {
6845                 res = linux_set_iface_flags(drv->global->ioctl_sock,
6846                                             bss->ifname, 0);
6847                 if (res == -EACCES || res == -ENODEV)
6848                         break;
6849                 if (res == 0) {
6850                         /* Try to set the mode again while the interface is
6851                          * down */
6852                         ret = nl80211_set_mode(drv, drv->ifindex, nlmode);
6853                         if (ret == -EACCES)
6854                                 break;
6855                         res = linux_set_iface_flags(drv->global->ioctl_sock,
6856                                                     bss->ifname, 1);
6857                         if (res && !ret)
6858                                 ret = -1;
6859                         else if (ret != -EBUSY)
6860                                 break;
6861                 } else
6862                         wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
6863                                    "interface down");
6864                 os_sleep(0, 100000);
6865         }
6867         if (!ret) {
6868                 wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
6869                            "interface is down");
6870                 drv->nlmode = nlmode;
6871                 drv->ignore_if_down_event = 1;
6872         }
6874 done:
6875         if (ret) {
6876                 wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
6877                            "from %d failed", nlmode, drv->nlmode);
6878                 return ret;
6879         }
6881         if (is_ap_interface(nlmode)) {
6882                 nl80211_mgmt_unsubscribe(bss, "start AP");
6883                 /* Setup additional AP mode functionality if needed */
6884                 if (nl80211_setup_ap(bss))
6885                         return -1;
6886         } else if (was_ap) {
6887                 /* Remove additional AP mode functionality */
6888                 nl80211_teardown_ap(bss);
6889         } else {
6890                 nl80211_mgmt_unsubscribe(bss, "mode change");
6891         }
6893         if (!is_ap_interface(nlmode) &&
6894             nl80211_mgmt_subscribe_non_ap(bss) < 0)
6895                 wpa_printf(MSG_DEBUG, "nl80211: Failed to register Action "
6896                            "frame processing - ignore for now");
6898         return 0;
6902 static int wpa_driver_nl80211_get_capa(void *priv,
6903                                        struct wpa_driver_capa *capa)
6905         struct i802_bss *bss = priv;
6906         struct wpa_driver_nl80211_data *drv = bss->drv;
6907         if (!drv->has_capability)
6908                 return -1;
6909         os_memcpy(capa, &drv->capa, sizeof(*capa));
6910         return 0;
6914 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
6916         struct i802_bss *bss = priv;
6917         struct wpa_driver_nl80211_data *drv = bss->drv;
6919         wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
6920                    __func__, drv->operstate, state, state ? "UP" : "DORMANT");
6921         drv->operstate = state;
6922         return netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, -1,
6923                                       state ? IF_OPER_UP : IF_OPER_DORMANT);
6927 static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
6929         struct i802_bss *bss = priv;
6930         struct wpa_driver_nl80211_data *drv = bss->drv;
6931         struct nl_msg *msg;
6932         struct nl80211_sta_flag_update upd;
6934         msg = nlmsg_alloc();
6935         if (!msg)
6936                 return -ENOMEM;
6938         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
6940         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
6941                     if_nametoindex(bss->ifname));
6942         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
6944         os_memset(&upd, 0, sizeof(upd));
6945         upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
6946         if (authorized)
6947                 upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
6948         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
6950         return send_and_recv_msgs(drv, msg, NULL, NULL);
6951  nla_put_failure:
6952         nlmsg_free(msg);
6953         return -ENOBUFS;
6957 /* Set kernel driver on given frequency (MHz) */
6958 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
6960         struct i802_bss *bss = priv;
6961         return wpa_driver_nl80211_set_freq(bss, freq->freq, freq->ht_enabled,
6962                                            freq->sec_channel_offset);
6966 #if defined(HOSTAPD) || defined(CONFIG_AP)
6968 static inline int min_int(int a, int b)
6970         if (a < b)
6971                 return a;
6972         return b;
6976 static int get_key_handler(struct nl_msg *msg, void *arg)
6978         struct nlattr *tb[NL80211_ATTR_MAX + 1];
6979         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
6981         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
6982                   genlmsg_attrlen(gnlh, 0), NULL);
6984         /*
6985          * TODO: validate the key index and mac address!
6986          * Otherwise, there's a race condition as soon as
6987          * the kernel starts sending key notifications.
6988          */
6990         if (tb[NL80211_ATTR_KEY_SEQ])
6991                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
6992                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
6993         return NL_SKIP;
6997 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
6998                            int idx, u8 *seq)
7000         struct i802_bss *bss = priv;
7001         struct wpa_driver_nl80211_data *drv = bss->drv;
7002         struct nl_msg *msg;
7004         msg = nlmsg_alloc();
7005         if (!msg)
7006                 return -ENOMEM;
7008         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_KEY);
7010         if (addr)
7011                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7012         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
7013         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
7015         memset(seq, 0, 6);
7017         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
7018  nla_put_failure:
7019         nlmsg_free(msg);
7020         return -ENOBUFS;
7024 static int i802_set_rts(void *priv, int rts)
7026         struct i802_bss *bss = priv;
7027         struct wpa_driver_nl80211_data *drv = bss->drv;
7028         struct nl_msg *msg;
7029         int ret = -ENOBUFS;
7030         u32 val;
7032         msg = nlmsg_alloc();
7033         if (!msg)
7034                 return -ENOMEM;
7036         if (rts >= 2347)
7037                 val = (u32) -1;
7038         else
7039                 val = rts;
7041         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7042         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7043         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
7045         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7046         msg = NULL;
7047         if (!ret)
7048                 return 0;
7049 nla_put_failure:
7050         nlmsg_free(msg);
7051         wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
7052                    "%d (%s)", rts, ret, strerror(-ret));
7053         return ret;
7057 static int i802_set_frag(void *priv, int frag)
7059         struct i802_bss *bss = priv;
7060         struct wpa_driver_nl80211_data *drv = bss->drv;
7061         struct nl_msg *msg;
7062         int ret = -ENOBUFS;
7063         u32 val;
7065         msg = nlmsg_alloc();
7066         if (!msg)
7067                 return -ENOMEM;
7069         if (frag >= 2346)
7070                 val = (u32) -1;
7071         else
7072                 val = frag;
7074         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7075         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7076         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
7078         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7079         msg = NULL;
7080         if (!ret)
7081                 return 0;
7082 nla_put_failure:
7083         nlmsg_free(msg);
7084         wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
7085                    "%d: %d (%s)", frag, ret, strerror(-ret));
7086         return ret;
7090 static int i802_flush(void *priv)
7092         struct i802_bss *bss = priv;
7093         struct wpa_driver_nl80211_data *drv = bss->drv;
7094         struct nl_msg *msg;
7095         int res;
7097         msg = nlmsg_alloc();
7098         if (!msg)
7099                 return -1;
7101         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
7103         /*
7104          * XXX: FIX! this needs to flush all VLANs too
7105          */
7106         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7107                     if_nametoindex(bss->ifname));
7109         res = send_and_recv_msgs(drv, msg, NULL, NULL);
7110         if (res) {
7111                 wpa_printf(MSG_DEBUG, "nl80211: Station flush failed: ret=%d "
7112                            "(%s)", res, strerror(-res));
7113         }
7114         return res;
7115  nla_put_failure:
7116         nlmsg_free(msg);
7117         return -ENOBUFS;
7121 static int get_sta_handler(struct nl_msg *msg, void *arg)
7123         struct nlattr *tb[NL80211_ATTR_MAX + 1];
7124         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7125         struct hostap_sta_driver_data *data = arg;
7126         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
7127         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
7128                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
7129                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
7130                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
7131                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
7132                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
7133         };
7135         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7136                   genlmsg_attrlen(gnlh, 0), NULL);
7138         /*
7139          * TODO: validate the interface and mac address!
7140          * Otherwise, there's a race condition as soon as
7141          * the kernel starts sending station notifications.
7142          */
7144         if (!tb[NL80211_ATTR_STA_INFO]) {
7145                 wpa_printf(MSG_DEBUG, "sta stats missing!");
7146                 return NL_SKIP;
7147         }
7148         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
7149                              tb[NL80211_ATTR_STA_INFO],
7150                              stats_policy)) {
7151                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
7152                 return NL_SKIP;
7153         }
7155         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
7156                 data->inactive_msec =
7157                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
7158         if (stats[NL80211_STA_INFO_RX_BYTES])
7159                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
7160         if (stats[NL80211_STA_INFO_TX_BYTES])
7161                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
7162         if (stats[NL80211_STA_INFO_RX_PACKETS])
7163                 data->rx_packets =
7164                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
7165         if (stats[NL80211_STA_INFO_TX_PACKETS])
7166                 data->tx_packets =
7167                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
7169         return NL_SKIP;
7172 static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
7173                               const u8 *addr)
7175         struct i802_bss *bss = priv;
7176         struct wpa_driver_nl80211_data *drv = bss->drv;
7177         struct nl_msg *msg;
7179         os_memset(data, 0, sizeof(*data));
7180         msg = nlmsg_alloc();
7181         if (!msg)
7182                 return -ENOMEM;
7184         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
7186         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7187         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7189         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
7190  nla_put_failure:
7191         nlmsg_free(msg);
7192         return -ENOBUFS;
7196 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
7197                                     int cw_min, int cw_max, int burst_time)
7199         struct i802_bss *bss = priv;
7200         struct wpa_driver_nl80211_data *drv = bss->drv;
7201         struct nl_msg *msg;
7202         struct nlattr *txq, *params;
7204         msg = nlmsg_alloc();
7205         if (!msg)
7206                 return -1;
7208         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7210         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7212         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
7213         if (!txq)
7214                 goto nla_put_failure;
7216         /* We are only sending parameters for a single TXQ at a time */
7217         params = nla_nest_start(msg, 1);
7218         if (!params)
7219                 goto nla_put_failure;
7221         switch (queue) {
7222         case 0:
7223                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
7224                 break;
7225         case 1:
7226                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
7227                 break;
7228         case 2:
7229                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
7230                 break;
7231         case 3:
7232                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
7233                 break;
7234         }
7235         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
7236          * 32 usec, so need to convert the value here. */
7237         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
7238         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
7239         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
7240         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
7242         nla_nest_end(msg, params);
7244         nla_nest_end(msg, txq);
7246         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
7247                 return 0;
7248         msg = NULL;
7249  nla_put_failure:
7250         nlmsg_free(msg);
7251         return -1;
7255 static int i802_set_sta_vlan(void *priv, const u8 *addr,
7256                              const char *ifname, int vlan_id)
7258         struct i802_bss *bss = priv;
7259         struct wpa_driver_nl80211_data *drv = bss->drv;
7260         struct nl_msg *msg;
7261         int ret = -ENOBUFS;
7263         msg = nlmsg_alloc();
7264         if (!msg)
7265                 return -ENOMEM;
7267         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
7269         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7270                     if_nametoindex(bss->ifname));
7271         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7272         NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
7273                     if_nametoindex(ifname));
7275         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7276         msg = NULL;
7277         if (ret < 0) {
7278                 wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
7279                            MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
7280                            MAC2STR(addr), ifname, vlan_id, ret,
7281                            strerror(-ret));
7282         }
7283  nla_put_failure:
7284         nlmsg_free(msg);
7285         return ret;
7289 static int i802_get_inact_sec(void *priv, const u8 *addr)
7291         struct hostap_sta_driver_data data;
7292         int ret;
7294         data.inactive_msec = (unsigned long) -1;
7295         ret = i802_read_sta_data(priv, &data, addr);
7296         if (ret || data.inactive_msec == (unsigned long) -1)
7297                 return -1;
7298         return data.inactive_msec / 1000;
7302 static int i802_sta_clear_stats(void *priv, const u8 *addr)
7304 #if 0
7305         /* TODO */
7306 #endif
7307         return 0;
7311 static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
7312                            int reason)
7314         struct i802_bss *bss = priv;
7315         struct ieee80211_mgmt mgmt;
7317         memset(&mgmt, 0, sizeof(mgmt));
7318         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
7319                                           WLAN_FC_STYPE_DEAUTH);
7320         memcpy(mgmt.da, addr, ETH_ALEN);
7321         memcpy(mgmt.sa, own_addr, ETH_ALEN);
7322         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
7323         mgmt.u.deauth.reason_code = host_to_le16(reason);
7324         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
7325                                             IEEE80211_HDRLEN +
7326                                             sizeof(mgmt.u.deauth), 0);
7330 static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
7331                              int reason)
7333         struct i802_bss *bss = priv;
7334         struct ieee80211_mgmt mgmt;
7336         memset(&mgmt, 0, sizeof(mgmt));
7337         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
7338                                           WLAN_FC_STYPE_DISASSOC);
7339         memcpy(mgmt.da, addr, ETH_ALEN);
7340         memcpy(mgmt.sa, own_addr, ETH_ALEN);
7341         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
7342         mgmt.u.disassoc.reason_code = host_to_le16(reason);
7343         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
7344                                             IEEE80211_HDRLEN +
7345                                             sizeof(mgmt.u.disassoc), 0);
7348 #endif /* HOSTAPD || CONFIG_AP */
7350 #ifdef HOSTAPD
7352 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7354         int i;
7355         int *old;
7357         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
7358                    ifidx);
7359         for (i = 0; i < drv->num_if_indices; i++) {
7360                 if (drv->if_indices[i] == 0) {
7361                         drv->if_indices[i] = ifidx;
7362                         return;
7363                 }
7364         }
7366         if (drv->if_indices != drv->default_if_indices)
7367                 old = drv->if_indices;
7368         else
7369                 old = NULL;
7371         drv->if_indices = os_realloc(old,
7372                                      sizeof(int) * (drv->num_if_indices + 1));
7373         if (!drv->if_indices) {
7374                 if (!old)
7375                         drv->if_indices = drv->default_if_indices;
7376                 else
7377                         drv->if_indices = old;
7378                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
7379                            "interfaces");
7380                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
7381                 return;
7382         } else if (!old)
7383                 os_memcpy(drv->if_indices, drv->default_if_indices,
7384                           sizeof(drv->default_if_indices));
7385         drv->if_indices[drv->num_if_indices] = ifidx;
7386         drv->num_if_indices++;
7390 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7392         int i;
7394         for (i = 0; i < drv->num_if_indices; i++) {
7395                 if (drv->if_indices[i] == ifidx) {
7396                         drv->if_indices[i] = 0;
7397                         break;
7398                 }
7399         }
7403 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7405         int i;
7407         for (i = 0; i < drv->num_if_indices; i++)
7408                 if (drv->if_indices[i] == ifidx)
7409                         return 1;
7411         return 0;
7415 static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
7416                             const char *bridge_ifname)
7418         struct i802_bss *bss = priv;
7419         struct wpa_driver_nl80211_data *drv = bss->drv;
7420         char name[IFNAMSIZ + 1];
7422         os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
7423         wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
7424                    " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
7425         if (val) {
7426                 if (!if_nametoindex(name)) {
7427                         if (nl80211_create_iface(drv, name,
7428                                                  NL80211_IFTYPE_AP_VLAN,
7429                                                  NULL, 1) < 0)
7430                                 return -1;
7431                         if (bridge_ifname &&
7432                             linux_br_add_if(drv->global->ioctl_sock,
7433                                             bridge_ifname, name) < 0)
7434                                 return -1;
7435                 }
7436                 linux_set_iface_flags(drv->global->ioctl_sock, name, 1);
7437                 return i802_set_sta_vlan(priv, addr, name, 0);
7438         } else {
7439                 i802_set_sta_vlan(priv, addr, bss->ifname, 0);
7440                 return wpa_driver_nl80211_if_remove(priv, WPA_IF_AP_VLAN,
7441                                                     name);
7442         }
7446 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
7448         struct wpa_driver_nl80211_data *drv = eloop_ctx;
7449         struct sockaddr_ll lladdr;
7450         unsigned char buf[3000];
7451         int len;
7452         socklen_t fromlen = sizeof(lladdr);
7454         len = recvfrom(sock, buf, sizeof(buf), 0,
7455                        (struct sockaddr *)&lladdr, &fromlen);
7456         if (len < 0) {
7457                 perror("recv");
7458                 return;
7459         }
7461         if (have_ifidx(drv, lladdr.sll_ifindex))
7462                 drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
7466 static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
7467                              struct i802_bss *bss,
7468                              const char *brname, const char *ifname)
7470         int ifindex;
7471         char in_br[IFNAMSIZ];
7473         os_strlcpy(bss->brname, brname, IFNAMSIZ);
7474         ifindex = if_nametoindex(brname);
7475         if (ifindex == 0) {
7476                 /*
7477                  * Bridge was configured, but the bridge device does
7478                  * not exist. Try to add it now.
7479                  */
7480                 if (linux_br_add(drv->global->ioctl_sock, brname) < 0) {
7481                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
7482                                    "bridge interface %s: %s",
7483                                    brname, strerror(errno));
7484                         return -1;
7485                 }
7486                 bss->added_bridge = 1;
7487                 add_ifidx(drv, if_nametoindex(brname));
7488         }
7490         if (linux_br_get(in_br, ifname) == 0) {
7491                 if (os_strcmp(in_br, brname) == 0)
7492                         return 0; /* already in the bridge */
7494                 wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
7495                            "bridge %s", ifname, in_br);
7496                 if (linux_br_del_if(drv->global->ioctl_sock, in_br, ifname) <
7497                     0) {
7498                         wpa_printf(MSG_ERROR, "nl80211: Failed to "
7499                                    "remove interface %s from bridge "
7500                                    "%s: %s",
7501                                    ifname, brname, strerror(errno));
7502                         return -1;
7503                 }
7504         }
7506         wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
7507                    ifname, brname);
7508         if (linux_br_add_if(drv->global->ioctl_sock, brname, ifname) < 0) {
7509                 wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
7510                            "into bridge %s: %s",
7511                            ifname, brname, strerror(errno));
7512                 return -1;
7513         }
7514         bss->added_if_into_bridge = 1;
7516         return 0;
7520 static void *i802_init(struct hostapd_data *hapd,
7521                        struct wpa_init_params *params)
7523         struct wpa_driver_nl80211_data *drv;
7524         struct i802_bss *bss;
7525         size_t i;
7526         char brname[IFNAMSIZ];
7527         int ifindex, br_ifindex;
7528         int br_added = 0;
7530         bss = wpa_driver_nl80211_init(hapd, params->ifname,
7531                                       params->global_priv);
7532         if (bss == NULL)
7533                 return NULL;
7535         drv = bss->drv;
7536         drv->nlmode = NL80211_IFTYPE_AP;
7537         drv->eapol_sock = -1;
7539         if (linux_br_get(brname, params->ifname) == 0) {
7540                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
7541                            params->ifname, brname);
7542                 br_ifindex = if_nametoindex(brname);
7543         } else {
7544                 brname[0] = '\0';
7545                 br_ifindex = 0;
7546         }
7548         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
7549         drv->if_indices = drv->default_if_indices;
7550         for (i = 0; i < params->num_bridge; i++) {
7551                 if (params->bridge[i]) {
7552                         ifindex = if_nametoindex(params->bridge[i]);
7553                         if (ifindex)
7554                                 add_ifidx(drv, ifindex);
7555                         if (ifindex == br_ifindex)
7556                                 br_added = 1;
7557                 }
7558         }
7559         if (!br_added && br_ifindex &&
7560             (params->num_bridge == 0 || !params->bridge[0]))
7561                 add_ifidx(drv, br_ifindex);
7563         /* start listening for EAPOL on the default AP interface */
7564         add_ifidx(drv, drv->ifindex);
7566         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0))
7567                 goto failed;
7569         if (params->bssid) {
7570                 if (linux_set_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7571                                        params->bssid))
7572                         goto failed;
7573         }
7575         if (wpa_driver_nl80211_set_mode(bss, drv->nlmode)) {
7576                 wpa_printf(MSG_ERROR, "nl80211: Failed to set interface %s "
7577                            "into AP mode", bss->ifname);
7578                 goto failed;
7579         }
7581         if (params->num_bridge && params->bridge[0] &&
7582             i802_check_bridge(drv, bss, params->bridge[0], params->ifname) < 0)
7583                 goto failed;
7585         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1))
7586                 goto failed;
7588         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
7589         if (drv->eapol_sock < 0) {
7590                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
7591                 goto failed;
7592         }
7594         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
7595         {
7596                 printf("Could not register read socket for eapol\n");
7597                 goto failed;
7598         }
7600         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7601                                params->own_addr))
7602                 goto failed;
7604         memcpy(bss->addr, params->own_addr, ETH_ALEN);
7606         return bss;
7608 failed:
7609         wpa_driver_nl80211_deinit(bss);
7610         return NULL;
7614 static void i802_deinit(void *priv)
7616         wpa_driver_nl80211_deinit(priv);
7619 #endif /* HOSTAPD */
7622 static enum nl80211_iftype wpa_driver_nl80211_if_type(
7623         enum wpa_driver_if_type type)
7625         switch (type) {
7626         case WPA_IF_STATION:
7627                 return NL80211_IFTYPE_STATION;
7628         case WPA_IF_P2P_CLIENT:
7629         case WPA_IF_P2P_GROUP:
7630                 return NL80211_IFTYPE_P2P_CLIENT;
7631         case WPA_IF_AP_VLAN:
7632                 return NL80211_IFTYPE_AP_VLAN;
7633         case WPA_IF_AP_BSS:
7634                 return NL80211_IFTYPE_AP;
7635         case WPA_IF_P2P_GO:
7636                 return NL80211_IFTYPE_P2P_GO;
7637         }
7638         return -1;
7642 #ifdef CONFIG_P2P
7644 static int nl80211_addr_in_use(struct nl80211_global *global, const u8 *addr)
7646         struct wpa_driver_nl80211_data *drv;
7647         dl_list_for_each(drv, &global->interfaces,
7648                          struct wpa_driver_nl80211_data, list) {
7649                 if (os_memcmp(addr, drv->first_bss.addr, ETH_ALEN) == 0)
7650                         return 1;
7651         }
7652         return 0;
7656 static int nl80211_p2p_interface_addr(struct wpa_driver_nl80211_data *drv,
7657                                       u8 *new_addr)
7659         unsigned int idx;
7661         if (!drv->global)
7662                 return -1;
7664         os_memcpy(new_addr, drv->first_bss.addr, ETH_ALEN);
7665         for (idx = 0; idx < 64; idx++) {
7666                 new_addr[0] = drv->first_bss.addr[0] | 0x02;
7667                 new_addr[0] ^= idx << 2;
7668                 if (!nl80211_addr_in_use(drv->global, new_addr))
7669                         break;
7670         }
7671         if (idx == 64)
7672                 return -1;
7674         wpa_printf(MSG_DEBUG, "nl80211: Assigned new P2P Interface Address "
7675                    MACSTR, MAC2STR(new_addr));
7677         return 0;
7680 #endif /* CONFIG_P2P */
7683 static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
7684                                      const char *ifname, const u8 *addr,
7685                                      void *bss_ctx, void **drv_priv,
7686                                      char *force_ifname, u8 *if_addr,
7687                                      const char *bridge)
7689         struct i802_bss *bss = priv;
7690         struct wpa_driver_nl80211_data *drv = bss->drv;
7691         int ifidx;
7692 #ifdef HOSTAPD
7693         struct i802_bss *new_bss = NULL;
7695         if (type == WPA_IF_AP_BSS) {
7696                 new_bss = os_zalloc(sizeof(*new_bss));
7697                 if (new_bss == NULL)
7698                         return -1;
7699         }
7700 #endif /* HOSTAPD */
7702         if (addr)
7703                 os_memcpy(if_addr, addr, ETH_ALEN);
7704         ifidx = nl80211_create_iface(drv, ifname,
7705                                      wpa_driver_nl80211_if_type(type), addr,
7706                                      0);
7707         if (ifidx < 0) {
7708 #ifdef HOSTAPD
7709                 os_free(new_bss);
7710 #endif /* HOSTAPD */
7711                 return -1;
7712         }
7714         if (!addr &&
7715             linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7716                                if_addr) < 0) {
7717                 nl80211_remove_iface(drv, ifidx);
7718                 return -1;
7719         }
7721 #ifdef CONFIG_P2P
7722         if (!addr &&
7723             (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
7724              type == WPA_IF_P2P_GO)) {
7725                 /* Enforce unique P2P Interface Address */
7726                 u8 new_addr[ETH_ALEN], own_addr[ETH_ALEN];
7728                 if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7729                                        own_addr) < 0 ||
7730                     linux_get_ifhwaddr(drv->global->ioctl_sock, ifname,
7731                                        new_addr) < 0) {
7732                         nl80211_remove_iface(drv, ifidx);
7733                         return -1;
7734                 }
7735                 if (os_memcmp(own_addr, new_addr, ETH_ALEN) == 0) {
7736                         wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
7737                                    "for P2P group interface");
7738                         if (nl80211_p2p_interface_addr(drv, new_addr) < 0) {
7739                                 nl80211_remove_iface(drv, ifidx);
7740                                 return -1;
7741                         }
7742                         if (linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
7743                                                new_addr) < 0) {
7744                                 nl80211_remove_iface(drv, ifidx);
7745                                 return -1;
7746                         }
7747                 }
7748                 os_memcpy(if_addr, new_addr, ETH_ALEN);
7749         }
7750 #endif /* CONFIG_P2P */
7752 #ifdef HOSTAPD
7753         if (bridge &&
7754             i802_check_bridge(drv, new_bss, bridge, ifname) < 0) {
7755                 wpa_printf(MSG_ERROR, "nl80211: Failed to add the new "
7756                            "interface %s to a bridge %s", ifname, bridge);
7757                 nl80211_remove_iface(drv, ifidx);
7758                 os_free(new_bss);
7759                 return -1;
7760         }
7762         if (type == WPA_IF_AP_BSS) {
7763                 if (linux_set_iface_flags(drv->global->ioctl_sock, ifname, 1))
7764                 {
7765                         nl80211_remove_iface(drv, ifidx);
7766                         os_free(new_bss);
7767                         return -1;
7768                 }
7769                 os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
7770                 os_memcpy(new_bss->addr, if_addr, ETH_ALEN);
7771                 new_bss->ifindex = ifidx;
7772                 new_bss->drv = drv;
7773                 new_bss->next = drv->first_bss.next;
7774                 drv->first_bss.next = new_bss;
7775                 if (drv_priv)
7776                         *drv_priv = new_bss;
7777                 nl80211_init_bss(new_bss);
7778         }
7779 #endif /* HOSTAPD */
7781         if (drv->global)
7782                 drv->global->if_add_ifindex = ifidx;
7784         return 0;
7788 static int wpa_driver_nl80211_if_remove(void *priv,
7789                                         enum wpa_driver_if_type type,
7790                                         const char *ifname)
7792         struct i802_bss *bss = priv;
7793         struct wpa_driver_nl80211_data *drv = bss->drv;
7794         int ifindex = if_nametoindex(ifname);
7796         wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d",
7797                    __func__, type, ifname, ifindex);
7798         if (ifindex <= 0)
7799                 return -1;
7801 #ifdef HOSTAPD
7802         if (bss->added_if_into_bridge) {
7803                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
7804                                     bss->ifname) < 0)
7805                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
7806                                    "interface %s from bridge %s: %s",
7807                                    bss->ifname, bss->brname, strerror(errno));
7808         }
7809         if (bss->added_bridge) {
7810                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
7811                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
7812                                    "bridge %s: %s",
7813                                    bss->brname, strerror(errno));
7814         }
7815 #endif /* HOSTAPD */
7817         nl80211_remove_iface(drv, ifindex);
7819 #ifdef HOSTAPD
7820         if (type != WPA_IF_AP_BSS)
7821                 return 0;
7823         if (bss != &drv->first_bss) {
7824                 struct i802_bss *tbss;
7826                 for (tbss = &drv->first_bss; tbss; tbss = tbss->next) {
7827                         if (tbss->next == bss) {
7828                                 tbss->next = bss->next;
7829                                 nl80211_destroy_bss(bss);
7830                                 os_free(bss);
7831                                 bss = NULL;
7832                                 break;
7833                         }
7834                 }
7835                 if (bss)
7836                         wpa_printf(MSG_INFO, "nl80211: %s - could not find "
7837                                    "BSS %p in the list", __func__, bss);
7838         }
7839 #endif /* HOSTAPD */
7841         return 0;
7845 static int cookie_handler(struct nl_msg *msg, void *arg)
7847         struct nlattr *tb[NL80211_ATTR_MAX + 1];
7848         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7849         u64 *cookie = arg;
7850         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7851                   genlmsg_attrlen(gnlh, 0), NULL);
7852         if (tb[NL80211_ATTR_COOKIE])
7853                 *cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
7854         return NL_SKIP;
7858 static int nl80211_send_frame_cmd(struct i802_bss *bss,
7859                                   unsigned int freq, unsigned int wait,
7860                                   const u8 *buf, size_t buf_len,
7861                                   u64 *cookie_out, int no_cck, int no_ack,
7862                                   int offchanok)
7864         struct wpa_driver_nl80211_data *drv = bss->drv;
7865         struct nl_msg *msg;
7866         u64 cookie;
7867         int ret = -1;
7869         msg = nlmsg_alloc();
7870         if (!msg)
7871                 return -1;
7873         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME);
7875         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
7876         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
7877         if (wait)
7878                 NLA_PUT_U32(msg, NL80211_ATTR_DURATION, wait);
7879         if (offchanok && (drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX))
7880                 NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
7881         if (no_cck)
7882                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
7883         if (no_ack)
7884                 NLA_PUT_FLAG(msg, NL80211_ATTR_DONT_WAIT_FOR_ACK);
7886         NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
7888         cookie = 0;
7889         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
7890         msg = NULL;
7891         if (ret) {
7892                 wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
7893                            "(%s) (freq=%u wait=%u)", ret, strerror(-ret),
7894                            freq, wait);
7895                 goto nla_put_failure;
7896         }
7897         wpa_printf(MSG_DEBUG, "nl80211: Frame TX command accepted%s; "
7898                    "cookie 0x%llx", no_ack ? " (no ACK)" : "",
7899                    (long long unsigned int) cookie);
7901         if (cookie_out)
7902                 *cookie_out = no_ack ? (u64) -1 : cookie;
7904 nla_put_failure:
7905         nlmsg_free(msg);
7906         return ret;
7910 static int wpa_driver_nl80211_send_action(void *priv, unsigned int freq,
7911                                           unsigned int wait_time,
7912                                           const u8 *dst, const u8 *src,
7913                                           const u8 *bssid,
7914                                           const u8 *data, size_t data_len,
7915                                           int no_cck)
7917         struct i802_bss *bss = priv;
7918         struct wpa_driver_nl80211_data *drv = bss->drv;
7919         int ret = -1;
7920         u8 *buf;
7921         struct ieee80211_hdr *hdr;
7923         wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d, "
7924                    "wait=%d ms no_cck=%d)", drv->ifindex, wait_time, no_cck);
7926         buf = os_zalloc(24 + data_len);
7927         if (buf == NULL)
7928                 return ret;
7929         os_memcpy(buf + 24, data, data_len);
7930         hdr = (struct ieee80211_hdr *) buf;
7931         hdr->frame_control =
7932                 IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
7933         os_memcpy(hdr->addr1, dst, ETH_ALEN);
7934         os_memcpy(hdr->addr2, src, ETH_ALEN);
7935         os_memcpy(hdr->addr3, bssid, ETH_ALEN);
7937         if (is_ap_interface(drv->nlmode))
7938                 ret = wpa_driver_nl80211_send_mlme(priv, buf, 24 + data_len,
7939                                                    0);
7940         else
7941                 ret = nl80211_send_frame_cmd(bss, freq, wait_time, buf,
7942                                              24 + data_len,
7943                                              &drv->send_action_cookie,
7944                                              no_cck, 0, 1);
7946         os_free(buf);
7947         return ret;
7951 static void wpa_driver_nl80211_send_action_cancel_wait(void *priv)
7953         struct i802_bss *bss = priv;
7954         struct wpa_driver_nl80211_data *drv = bss->drv;
7955         struct nl_msg *msg;
7956         int ret;
7958         msg = nlmsg_alloc();
7959         if (!msg)
7960                 return;
7962         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME_WAIT_CANCEL);
7964         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7965         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->send_action_cookie);
7967         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7968         msg = NULL;
7969         if (ret)
7970                 wpa_printf(MSG_DEBUG, "nl80211: wait cancel failed: ret=%d "
7971                            "(%s)", ret, strerror(-ret));
7973  nla_put_failure:
7974         nlmsg_free(msg);
7978 static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
7979                                                 unsigned int duration)
7981         struct i802_bss *bss = priv;
7982         struct wpa_driver_nl80211_data *drv = bss->drv;
7983         struct nl_msg *msg;
7984         int ret;
7985         u64 cookie;
7987         msg = nlmsg_alloc();
7988         if (!msg)
7989                 return -1;
7991         nl80211_cmd(drv, msg, 0, NL80211_CMD_REMAIN_ON_CHANNEL);
7993         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7994         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
7995         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
7997         cookie = 0;
7998         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
7999         msg = NULL;
8000         if (ret == 0) {
8001                 wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
8002                            "0x%llx for freq=%u MHz duration=%u",
8003                            (long long unsigned int) cookie, freq, duration);
8004                 drv->remain_on_chan_cookie = cookie;
8005                 drv->pending_remain_on_chan = 1;
8006                 return 0;
8007         }
8008         wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
8009                    "(freq=%d duration=%u): %d (%s)",
8010                    freq, duration, ret, strerror(-ret));
8011 nla_put_failure:
8012         nlmsg_free(msg);
8013         return -1;
8017 static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
8019         struct i802_bss *bss = priv;
8020         struct wpa_driver_nl80211_data *drv = bss->drv;
8021         struct nl_msg *msg;
8022         int ret;
8024         if (!drv->pending_remain_on_chan) {
8025                 wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
8026                            "to cancel");
8027                 return -1;
8028         }
8030         wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
8031                    "0x%llx",
8032                    (long long unsigned int) drv->remain_on_chan_cookie);
8034         msg = nlmsg_alloc();
8035         if (!msg)
8036                 return -1;
8038         nl80211_cmd(drv, msg, 0, NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL);
8040         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8041         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
8043         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8044         msg = NULL;
8045         if (ret == 0)
8046                 return 0;
8047         wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
8048                    "%d (%s)", ret, strerror(-ret));
8049 nla_put_failure:
8050         nlmsg_free(msg);
8051         return -1;
8055 static int wpa_driver_nl80211_probe_req_report(void *priv, int report)
8057         struct i802_bss *bss = priv;
8058         struct wpa_driver_nl80211_data *drv = bss->drv;
8060         if (!report) {
8061                 if (bss->nl_preq && drv->device_ap_sme &&
8062                     is_ap_interface(drv->nlmode)) {
8063                         /*
8064                          * Do not disable Probe Request reporting that was
8065                          * enabled in nl80211_setup_ap().
8066                          */
8067                         wpa_printf(MSG_DEBUG, "nl80211: Skip disabling of "
8068                                    "Probe Request reporting nl_preq=%p while "
8069                                    "in AP mode", bss->nl_preq);
8070                 } else if (bss->nl_preq) {
8071                         wpa_printf(MSG_DEBUG, "nl80211: Disable Probe Request "
8072                                    "reporting nl_preq=%p", bss->nl_preq);
8073                         eloop_unregister_read_sock(
8074                                 nl_socket_get_fd(bss->nl_preq));
8075                         nl_destroy_handles(&bss->nl_preq);
8076                 }
8077                 return 0;
8078         }
8080         if (bss->nl_preq) {
8081                 wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
8082                            "already on! nl_preq=%p", bss->nl_preq);
8083                 return 0;
8084         }
8086         bss->nl_preq = nl_create_handle(drv->global->nl_cb, "preq");
8087         if (bss->nl_preq == NULL)
8088                 return -1;
8089         wpa_printf(MSG_DEBUG, "nl80211: Enable Probe Request "
8090                    "reporting nl_preq=%p", bss->nl_preq);
8092         if (nl80211_register_frame(bss, bss->nl_preq,
8093                                    (WLAN_FC_TYPE_MGMT << 2) |
8094                                    (WLAN_FC_STYPE_PROBE_REQ << 4),
8095                                    NULL, 0) < 0)
8096                 goto out_err;
8098         eloop_register_read_sock(nl_socket_get_fd(bss->nl_preq),
8099                                  wpa_driver_nl80211_event_receive, bss->nl_cb,
8100                                  bss->nl_preq);
8102         return 0;
8104  out_err:
8105         nl_destroy_handles(&bss->nl_preq);
8106         return -1;
8110 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
8111                                      int ifindex, int disabled)
8113         struct nl_msg *msg;
8114         struct nlattr *bands, *band;
8115         int ret;
8117         msg = nlmsg_alloc();
8118         if (!msg)
8119                 return -1;
8121         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_TX_BITRATE_MASK);
8122         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
8124         bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
8125         if (!bands)
8126                 goto nla_put_failure;
8128         /*
8129          * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
8130          * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
8131          * rates. All 5 GHz rates are left enabled.
8132          */
8133         band = nla_nest_start(msg, NL80211_BAND_2GHZ);
8134         if (!band)
8135                 goto nla_put_failure;
8136         if (disabled) {
8137                 NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
8138                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
8139         }
8140         nla_nest_end(msg, band);
8142         nla_nest_end(msg, bands);
8144         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8145         msg = NULL;
8146         if (ret) {
8147                 wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
8148                            "(%s)", ret, strerror(-ret));
8149         }
8151         return ret;
8153 nla_put_failure:
8154         nlmsg_free(msg);
8155         return -1;
8159 static int wpa_driver_nl80211_deinit_ap(void *priv)
8161         struct i802_bss *bss = priv;
8162         struct wpa_driver_nl80211_data *drv = bss->drv;
8163         if (!is_ap_interface(drv->nlmode))
8164                 return -1;
8165         wpa_driver_nl80211_del_beacon(drv);
8166         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
8170 static void wpa_driver_nl80211_resume(void *priv)
8172         struct i802_bss *bss = priv;
8173         struct wpa_driver_nl80211_data *drv = bss->drv;
8174         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
8175                 wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on "
8176                            "resume event");
8177         }
8181 static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
8182                                   const u8 *ies, size_t ies_len)
8184         struct i802_bss *bss = priv;
8185         struct wpa_driver_nl80211_data *drv = bss->drv;
8186         int ret;
8187         u8 *data, *pos;
8188         size_t data_len;
8189         const u8 *own_addr = bss->addr;
8191         if (action != 1) {
8192                 wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
8193                            "action %d", action);
8194                 return -1;
8195         }
8197         /*
8198          * Action frame payload:
8199          * Category[1] = 6 (Fast BSS Transition)
8200          * Action[1] = 1 (Fast BSS Transition Request)
8201          * STA Address
8202          * Target AP Address
8203          * FT IEs
8204          */
8206         data_len = 2 + 2 * ETH_ALEN + ies_len;
8207         data = os_malloc(data_len);
8208         if (data == NULL)
8209                 return -1;
8210         pos = data;
8211         *pos++ = 0x06; /* FT Action category */
8212         *pos++ = action;
8213         os_memcpy(pos, own_addr, ETH_ALEN);
8214         pos += ETH_ALEN;
8215         os_memcpy(pos, target_ap, ETH_ALEN);
8216         pos += ETH_ALEN;
8217         os_memcpy(pos, ies, ies_len);
8219         ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, 0,
8220                                              drv->bssid, own_addr, drv->bssid,
8221                                              data, data_len, 0);
8222         os_free(data);
8224         return ret;
8228 static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
8230         struct i802_bss *bss = priv;
8231         struct wpa_driver_nl80211_data *drv = bss->drv;
8232         struct nl_msg *msg, *cqm = NULL;
8234         wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
8235                    "hysteresis=%d", threshold, hysteresis);
8237         msg = nlmsg_alloc();
8238         if (!msg)
8239                 return -1;
8241         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_CQM);
8243         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8245         cqm = nlmsg_alloc();
8246         if (cqm == NULL)
8247                 return -1;
8249         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
8250         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
8251         nla_put_nested(msg, NL80211_ATTR_CQM, cqm);
8253         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
8254                 return 0;
8255         msg = NULL;
8257 nla_put_failure:
8258         nlmsg_free(cqm);
8259         nlmsg_free(msg);
8260         return -1;
8264 static int nl80211_signal_poll(void *priv, struct wpa_signal_info *si)
8266         struct i802_bss *bss = priv;
8267         struct wpa_driver_nl80211_data *drv = bss->drv;
8268         int res;
8270         os_memset(si, 0, sizeof(*si));
8271         res = nl80211_get_link_signal(drv, si);
8272         if (res != 0)
8273                 return res;
8275         return nl80211_get_link_noise(drv, si);
8279 static int wpa_driver_nl80211_shared_freq(void *priv)
8281         struct i802_bss *bss = priv;
8282         struct wpa_driver_nl80211_data *drv = bss->drv;
8283         struct wpa_driver_nl80211_data *driver;
8284         int freq = 0;
8286         /*
8287          * If the same PHY is in connected state with some other interface,
8288          * then retrieve the assoc freq.
8289          */
8290         wpa_printf(MSG_DEBUG, "nl80211: Get shared freq for PHY %s",
8291                    drv->phyname);
8293         dl_list_for_each(driver, &drv->global->interfaces,
8294                          struct wpa_driver_nl80211_data, list) {
8295                 if (drv == driver ||
8296                     os_strcmp(drv->phyname, driver->phyname) != 0 ||
8297                     !driver->associated)
8298                         continue;
8300                 wpa_printf(MSG_DEBUG, "nl80211: Found a match for PHY %s - %s "
8301                            MACSTR,
8302                            driver->phyname, driver->first_bss.ifname,
8303                            MAC2STR(driver->first_bss.addr));
8304                 freq = nl80211_get_assoc_freq(driver);
8305                 wpa_printf(MSG_DEBUG, "nl80211: Shared freq for PHY %s: %d",
8306                            drv->phyname, freq);
8307         }
8309         if (!freq)
8310                 wpa_printf(MSG_DEBUG, "nl80211: No shared interface for "
8311                            "PHY (%s) in associated state", drv->phyname);
8313         return freq;
8317 static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
8318                               int encrypt)
8320         struct i802_bss *bss = priv;
8321         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt, 0);
8325 static int nl80211_set_param(void *priv, const char *param)
8327         wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
8328         if (param == NULL)
8329                 return 0;
8331 #ifdef CONFIG_P2P
8332         if (os_strstr(param, "use_p2p_group_interface=1")) {
8333                 struct i802_bss *bss = priv;
8334                 struct wpa_driver_nl80211_data *drv = bss->drv;
8336                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
8337                            "interface");
8338                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
8339                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
8340         }
8341 #endif /* CONFIG_P2P */
8343         return 0;
8347 static void * nl80211_global_init(void)
8349         struct nl80211_global *global;
8350         struct netlink_config *cfg;
8352         global = os_zalloc(sizeof(*global));
8353         if (global == NULL)
8354                 return NULL;
8355         global->ioctl_sock = -1;
8356         dl_list_init(&global->interfaces);
8357         global->if_add_ifindex = -1;
8359         cfg = os_zalloc(sizeof(*cfg));
8360         if (cfg == NULL)
8361                 goto err;
8363         cfg->ctx = global;
8364         cfg->newlink_cb = wpa_driver_nl80211_event_rtm_newlink;
8365         cfg->dellink_cb = wpa_driver_nl80211_event_rtm_dellink;
8366         global->netlink = netlink_init(cfg);
8367         if (global->netlink == NULL) {
8368                 os_free(cfg);
8369                 goto err;
8370         }
8372         if (wpa_driver_nl80211_init_nl_global(global) < 0)
8373                 goto err;
8375         global->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
8376         if (global->ioctl_sock < 0) {
8377                 perror("socket(PF_INET,SOCK_DGRAM)");
8378                 goto err;
8379         }
8381         return global;
8383 err:
8384         nl80211_global_deinit(global);
8385         return NULL;
8389 static void nl80211_global_deinit(void *priv)
8391         struct nl80211_global *global = priv;
8392         if (global == NULL)
8393                 return;
8394         if (!dl_list_empty(&global->interfaces)) {
8395                 wpa_printf(MSG_ERROR, "nl80211: %u interface(s) remain at "
8396                            "nl80211_global_deinit",
8397                            dl_list_len(&global->interfaces));
8398         }
8400         if (global->netlink)
8401                 netlink_deinit(global->netlink);
8403         nl_destroy_handles(&global->nl);
8405         if (global->nl_event) {
8406                 eloop_unregister_read_sock(
8407                         nl_socket_get_fd(global->nl_event));
8408                 nl_destroy_handles(&global->nl_event);
8409         }
8411         nl_cb_put(global->nl_cb);
8413         if (global->ioctl_sock >= 0)
8414                 close(global->ioctl_sock);
8416         os_free(global);
8420 static const char * nl80211_get_radio_name(void *priv)
8422         struct i802_bss *bss = priv;
8423         struct wpa_driver_nl80211_data *drv = bss->drv;
8424         return drv->phyname;
8428 static int nl80211_pmkid(struct i802_bss *bss, int cmd, const u8 *bssid,
8429                          const u8 *pmkid)
8431         struct nl_msg *msg;
8433         msg = nlmsg_alloc();
8434         if (!msg)
8435                 return -ENOMEM;
8437         nl80211_cmd(bss->drv, msg, 0, cmd);
8439         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
8440         if (pmkid)
8441                 NLA_PUT(msg, NL80211_ATTR_PMKID, 16, pmkid);
8442         if (bssid)
8443                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
8445         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
8446  nla_put_failure:
8447         nlmsg_free(msg);
8448         return -ENOBUFS;
8452 static int nl80211_add_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
8454         struct i802_bss *bss = priv;
8455         wpa_printf(MSG_DEBUG, "nl80211: Add PMKID for " MACSTR, MAC2STR(bssid));
8456         return nl80211_pmkid(bss, NL80211_CMD_SET_PMKSA, bssid, pmkid);
8460 static int nl80211_remove_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
8462         struct i802_bss *bss = priv;
8463         wpa_printf(MSG_DEBUG, "nl80211: Delete PMKID for " MACSTR,
8464                    MAC2STR(bssid));
8465         return nl80211_pmkid(bss, NL80211_CMD_DEL_PMKSA, bssid, pmkid);
8469 static int nl80211_flush_pmkid(void *priv)
8471         struct i802_bss *bss = priv;
8472         wpa_printf(MSG_DEBUG, "nl80211: Flush PMKIDs");
8473         return nl80211_pmkid(bss, NL80211_CMD_FLUSH_PMKSA, NULL, NULL);
8477 static void nl80211_set_rekey_info(void *priv, const u8 *kek, const u8 *kck,
8478                                    const u8 *replay_ctr)
8480         struct i802_bss *bss = priv;
8481         struct wpa_driver_nl80211_data *drv = bss->drv;
8482         struct nlattr *replay_nested;
8483         struct nl_msg *msg;
8485         msg = nlmsg_alloc();
8486         if (!msg)
8487                 return;
8489         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_REKEY_OFFLOAD);
8491         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8493         replay_nested = nla_nest_start(msg, NL80211_ATTR_REKEY_DATA);
8494         if (!replay_nested)
8495                 goto nla_put_failure;
8497         NLA_PUT(msg, NL80211_REKEY_DATA_KEK, NL80211_KEK_LEN, kek);
8498         NLA_PUT(msg, NL80211_REKEY_DATA_KCK, NL80211_KCK_LEN, kck);
8499         NLA_PUT(msg, NL80211_REKEY_DATA_REPLAY_CTR, NL80211_REPLAY_CTR_LEN,
8500                 replay_ctr);
8502         nla_nest_end(msg, replay_nested);
8504         send_and_recv_msgs(drv, msg, NULL, NULL);
8505         return;
8506  nla_put_failure:
8507         nlmsg_free(msg);
8511 static void nl80211_send_null_frame(struct i802_bss *bss, const u8 *own_addr,
8512                                     const u8 *addr, int qos)
8514         /* send data frame to poll STA and check whether
8515          * this frame is ACKed */
8516         struct {
8517                 struct ieee80211_hdr hdr;
8518                 u16 qos_ctl;
8519         } STRUCT_PACKED nulldata;
8520         size_t size;
8522         /* Send data frame to poll STA and check whether this frame is ACKed */
8524         os_memset(&nulldata, 0, sizeof(nulldata));
8526         if (qos) {
8527                 nulldata.hdr.frame_control =
8528                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
8529                                      WLAN_FC_STYPE_QOS_NULL);
8530                 size = sizeof(nulldata);
8531         } else {
8532                 nulldata.hdr.frame_control =
8533                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
8534                                      WLAN_FC_STYPE_NULLFUNC);
8535                 size = sizeof(struct ieee80211_hdr);
8536         }
8538         nulldata.hdr.frame_control |= host_to_le16(WLAN_FC_FROMDS);
8539         os_memcpy(nulldata.hdr.IEEE80211_DA_FROMDS, addr, ETH_ALEN);
8540         os_memcpy(nulldata.hdr.IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
8541         os_memcpy(nulldata.hdr.IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
8543         if (wpa_driver_nl80211_send_mlme(bss, (u8 *) &nulldata, size, 0) < 0)
8544                 wpa_printf(MSG_DEBUG, "nl80211_send_null_frame: Failed to "
8545                            "send poll frame");
8548 static void nl80211_poll_client(void *priv, const u8 *own_addr, const u8 *addr,
8549                                 int qos)
8551         struct i802_bss *bss = priv;
8552         struct wpa_driver_nl80211_data *drv = bss->drv;
8553         struct nl_msg *msg;
8555         if (!drv->poll_command_supported) {
8556                 nl80211_send_null_frame(bss, own_addr, addr, qos);
8557                 return;
8558         }
8560         msg = nlmsg_alloc();
8561         if (!msg)
8562                 return;
8564         nl80211_cmd(drv, msg, 0, NL80211_CMD_PROBE_CLIENT);
8566         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8567         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
8569         send_and_recv_msgs(drv, msg, NULL, NULL);
8570         return;
8571  nla_put_failure:
8572         nlmsg_free(msg);
8576 static int nl80211_set_power_save(struct i802_bss *bss, int enabled)
8578         struct nl_msg *msg;
8580         msg = nlmsg_alloc();
8581         if (!msg)
8582                 return -ENOMEM;
8584         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_SET_POWER_SAVE);
8585         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8586         NLA_PUT_U32(msg, NL80211_ATTR_PS_STATE,
8587                     enabled ? NL80211_PS_ENABLED : NL80211_PS_DISABLED);
8588         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
8589 nla_put_failure:
8590         nlmsg_free(msg);
8591         return -ENOBUFS;
8595 static int nl80211_set_p2p_powersave(void *priv, int legacy_ps, int opp_ps,
8596                                      int ctwindow)
8598         struct i802_bss *bss = priv;
8600         wpa_printf(MSG_DEBUG, "nl80211: set_p2p_powersave (legacy_ps=%d "
8601                    "opp_ps=%d ctwindow=%d)", legacy_ps, opp_ps, ctwindow);
8603         if (opp_ps != -1 || ctwindow != -1)
8604                 return -1; /* Not yet supported */
8606         if (legacy_ps == -1)
8607                 return 0;
8608         if (legacy_ps != 0 && legacy_ps != 1)
8609                 return -1; /* Not yet supported */
8611         return nl80211_set_power_save(bss, legacy_ps);
8615 #ifdef CONFIG_TDLS
8617 static int nl80211_send_tdls_mgmt(void *priv, const u8 *dst, u8 action_code,
8618                                   u8 dialog_token, u16 status_code,
8619                                   const u8 *buf, size_t len)
8621         struct i802_bss *bss = priv;
8622         struct wpa_driver_nl80211_data *drv = bss->drv;
8623         struct nl_msg *msg;
8625         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
8626                 return -EOPNOTSUPP;
8628         if (!dst)
8629                 return -EINVAL;
8631         msg = nlmsg_alloc();
8632         if (!msg)
8633                 return -ENOMEM;
8635         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_MGMT);
8636         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8637         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, dst);
8638         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_ACTION, action_code);
8639         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_DIALOG_TOKEN, dialog_token);
8640         NLA_PUT_U16(msg, NL80211_ATTR_STATUS_CODE, status_code);
8641         NLA_PUT(msg, NL80211_ATTR_IE, len, buf);
8643         return send_and_recv_msgs(drv, msg, NULL, NULL);
8645 nla_put_failure:
8646         nlmsg_free(msg);
8647         return -ENOBUFS;
8651 static int nl80211_tdls_oper(void *priv, enum tdls_oper oper, const u8 *peer)
8653         struct i802_bss *bss = priv;
8654         struct wpa_driver_nl80211_data *drv = bss->drv;
8655         struct nl_msg *msg;
8656         enum nl80211_tdls_operation nl80211_oper;
8658         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
8659                 return -EOPNOTSUPP;
8661         switch (oper) {
8662         case TDLS_DISCOVERY_REQ:
8663                 nl80211_oper = NL80211_TDLS_DISCOVERY_REQ;
8664                 break;
8665         case TDLS_SETUP:
8666                 nl80211_oper = NL80211_TDLS_SETUP;
8667                 break;
8668         case TDLS_TEARDOWN:
8669                 nl80211_oper = NL80211_TDLS_TEARDOWN;
8670                 break;
8671         case TDLS_ENABLE_LINK:
8672                 nl80211_oper = NL80211_TDLS_ENABLE_LINK;
8673                 break;
8674         case TDLS_DISABLE_LINK:
8675                 nl80211_oper = NL80211_TDLS_DISABLE_LINK;
8676                 break;
8677         case TDLS_ENABLE:
8678                 return 0;
8679         case TDLS_DISABLE:
8680                 return 0;
8681         default:
8682                 return -EINVAL;
8683         }
8685         msg = nlmsg_alloc();
8686         if (!msg)
8687                 return -ENOMEM;
8689         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_OPER);
8690         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_OPERATION, nl80211_oper);
8691         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8692         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, peer);
8694         return send_and_recv_msgs(drv, msg, NULL, NULL);
8696 nla_put_failure:
8697         nlmsg_free(msg);
8698         return -ENOBUFS;
8701 #endif /* CONFIG TDLS */
8704 #ifdef ANDROID
8706 typedef struct android_wifi_priv_cmd {
8707         char *buf;
8708         int used_len;
8709         int total_len;
8710 } android_wifi_priv_cmd;
8712 static int drv_errors = 0;
8714 static void wpa_driver_send_hang_msg(struct wpa_driver_nl80211_data *drv)
8716         drv_errors++;
8717         if (drv_errors > DRV_NUMBER_SEQUENTIAL_ERRORS) {
8718                 drv_errors = 0;
8719                 wpa_msg(drv->ctx, MSG_INFO, WPA_EVENT_DRIVER_STATE "HANGED");
8720         }
8724 static int android_priv_cmd(struct i802_bss *bss, const char *cmd)
8726         struct wpa_driver_nl80211_data *drv = bss->drv;
8727         struct ifreq ifr;
8728         android_wifi_priv_cmd priv_cmd;
8729         char buf[MAX_DRV_CMD_SIZE];
8730         int ret;
8732         os_memset(&ifr, 0, sizeof(ifr));
8733         os_memset(&priv_cmd, 0, sizeof(priv_cmd));
8734         os_strlcpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
8736         os_memset(buf, 0, sizeof(buf));
8737         os_strlcpy(buf, cmd, sizeof(buf));
8739         priv_cmd.buf = buf;
8740         priv_cmd.used_len = sizeof(buf);
8741         priv_cmd.total_len = sizeof(buf);
8742         ifr.ifr_data = &priv_cmd;
8744         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
8745         if (ret < 0) {
8746                 wpa_printf(MSG_ERROR, "%s: failed to issue private commands",
8747                            __func__);
8748                 wpa_driver_send_hang_msg(drv);
8749                 return ret;
8750         }
8752         drv_errors = 0;
8753         return 0;
8757 static int android_pno_start(struct i802_bss *bss,
8758                              struct wpa_driver_scan_params *params)
8760         struct wpa_driver_nl80211_data *drv = bss->drv;
8761         struct ifreq ifr;
8762         android_wifi_priv_cmd priv_cmd;
8763         int ret = 0, i = 0, bp;
8764         char buf[WEXT_PNO_MAX_COMMAND_SIZE];
8766         bp = WEXT_PNOSETUP_HEADER_SIZE;
8767         os_memcpy(buf, WEXT_PNOSETUP_HEADER, bp);
8768         buf[bp++] = WEXT_PNO_TLV_PREFIX;
8769         buf[bp++] = WEXT_PNO_TLV_VERSION;
8770         buf[bp++] = WEXT_PNO_TLV_SUBVERSION;
8771         buf[bp++] = WEXT_PNO_TLV_RESERVED;
8773         while (i < WEXT_PNO_AMOUNT && (size_t) i < params->num_ssids) {
8774                 /* Check that there is enough space needed for 1 more SSID, the
8775                  * other sections and null termination */
8776                 if ((bp + WEXT_PNO_SSID_HEADER_SIZE + MAX_SSID_LEN +
8777                      WEXT_PNO_NONSSID_SECTIONS_SIZE + 1) >= (int) sizeof(buf))
8778                         break;
8779                 wpa_hexdump_ascii(MSG_DEBUG, "For PNO Scan",
8780                                   params->ssids[i].ssid,
8781                                   params->ssids[i].ssid_len);
8782                 buf[bp++] = WEXT_PNO_SSID_SECTION;
8783                 buf[bp++] = params->ssids[i].ssid_len;
8784                 os_memcpy(&buf[bp], params->ssids[i].ssid,
8785                           params->ssids[i].ssid_len);
8786                 bp += params->ssids[i].ssid_len;
8787                 i++;
8788         }
8790         buf[bp++] = WEXT_PNO_SCAN_INTERVAL_SECTION;
8791         os_snprintf(&buf[bp], WEXT_PNO_SCAN_INTERVAL_LENGTH + 1, "%x",
8792                     WEXT_PNO_SCAN_INTERVAL);
8793         bp += WEXT_PNO_SCAN_INTERVAL_LENGTH;
8795         buf[bp++] = WEXT_PNO_REPEAT_SECTION;
8796         os_snprintf(&buf[bp], WEXT_PNO_REPEAT_LENGTH + 1, "%x",
8797                     WEXT_PNO_REPEAT);
8798         bp += WEXT_PNO_REPEAT_LENGTH;
8800         buf[bp++] = WEXT_PNO_MAX_REPEAT_SECTION;
8801         os_snprintf(&buf[bp], WEXT_PNO_MAX_REPEAT_LENGTH + 1, "%x",
8802                     WEXT_PNO_MAX_REPEAT);
8803         bp += WEXT_PNO_MAX_REPEAT_LENGTH + 1;
8805         memset(&ifr, 0, sizeof(ifr));
8806         memset(&priv_cmd, 0, sizeof(priv_cmd));
8807         os_strncpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
8809         priv_cmd.buf = buf;
8810         priv_cmd.used_len = bp;
8811         priv_cmd.total_len = bp;
8812         ifr.ifr_data = &priv_cmd;
8814         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
8816         if (ret < 0) {
8817                 wpa_printf(MSG_ERROR, "ioctl[SIOCSIWPRIV] (pnosetup): %d",
8818                            ret);
8819                 wpa_driver_send_hang_msg(drv);
8820                 return ret;
8821         }
8823         drv_errors = 0;
8825         return android_priv_cmd(bss, "PNOFORCE 1");
8829 static int android_pno_stop(struct i802_bss *bss)
8831         return android_priv_cmd(bss, "PNOFORCE 0");
8834 #endif /* ANDROID */
8837 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
8838         .name = "nl80211",
8839         .desc = "Linux nl80211/cfg80211",
8840         .get_bssid = wpa_driver_nl80211_get_bssid,
8841         .get_ssid = wpa_driver_nl80211_get_ssid,
8842         .set_key = wpa_driver_nl80211_set_key,
8843         .scan2 = wpa_driver_nl80211_scan,
8844         .sched_scan = wpa_driver_nl80211_sched_scan,
8845         .stop_sched_scan = wpa_driver_nl80211_stop_sched_scan,
8846         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
8847         .deauthenticate = wpa_driver_nl80211_deauthenticate,
8848         .disassociate = wpa_driver_nl80211_disassociate,
8849         .authenticate = wpa_driver_nl80211_authenticate,
8850         .associate = wpa_driver_nl80211_associate,
8851         .global_init = nl80211_global_init,
8852         .global_deinit = nl80211_global_deinit,
8853         .init2 = wpa_driver_nl80211_init,
8854         .deinit = wpa_driver_nl80211_deinit,
8855         .get_capa = wpa_driver_nl80211_get_capa,
8856         .set_operstate = wpa_driver_nl80211_set_operstate,
8857         .set_supp_port = wpa_driver_nl80211_set_supp_port,
8858         .set_country = wpa_driver_nl80211_set_country,
8859         .set_ap = wpa_driver_nl80211_set_ap,
8860         .if_add = wpa_driver_nl80211_if_add,
8861         .if_remove = wpa_driver_nl80211_if_remove,
8862         .send_mlme = wpa_driver_nl80211_send_mlme,
8863         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
8864         .sta_add = wpa_driver_nl80211_sta_add,
8865         .sta_remove = wpa_driver_nl80211_sta_remove,
8866         .hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
8867         .sta_set_flags = wpa_driver_nl80211_sta_set_flags,
8868 #ifdef HOSTAPD
8869         .hapd_init = i802_init,
8870         .hapd_deinit = i802_deinit,
8871         .set_wds_sta = i802_set_wds_sta,
8872 #endif /* HOSTAPD */
8873 #if defined(HOSTAPD) || defined(CONFIG_AP)
8874         .get_seqnum = i802_get_seqnum,
8875         .flush = i802_flush,
8876         .read_sta_data = i802_read_sta_data,
8877         .get_inact_sec = i802_get_inact_sec,
8878         .sta_clear_stats = i802_sta_clear_stats,
8879         .set_rts = i802_set_rts,
8880         .set_frag = i802_set_frag,
8881         .set_tx_queue_params = i802_set_tx_queue_params,
8882         .set_sta_vlan = i802_set_sta_vlan,
8883         .sta_deauth = i802_sta_deauth,
8884         .sta_disassoc = i802_sta_disassoc,
8885 #endif /* HOSTAPD || CONFIG_AP */
8886         .set_freq = i802_set_freq,
8887         .send_action = wpa_driver_nl80211_send_action,
8888         .send_action_cancel_wait = wpa_driver_nl80211_send_action_cancel_wait,
8889         .remain_on_channel = wpa_driver_nl80211_remain_on_channel,
8890         .cancel_remain_on_channel =
8891         wpa_driver_nl80211_cancel_remain_on_channel,
8892         .probe_req_report = wpa_driver_nl80211_probe_req_report,
8893         .deinit_ap = wpa_driver_nl80211_deinit_ap,
8894         .resume = wpa_driver_nl80211_resume,
8895         .send_ft_action = nl80211_send_ft_action,
8896         .signal_monitor = nl80211_signal_monitor,
8897         .signal_poll = nl80211_signal_poll,
8898         .send_frame = nl80211_send_frame,
8899         .shared_freq = wpa_driver_nl80211_shared_freq,
8900         .set_param = nl80211_set_param,
8901         .get_radio_name = nl80211_get_radio_name,
8902         .add_pmkid = nl80211_add_pmkid,
8903         .remove_pmkid = nl80211_remove_pmkid,
8904         .flush_pmkid = nl80211_flush_pmkid,
8905         .set_rekey_info = nl80211_set_rekey_info,
8906         .poll_client = nl80211_poll_client,
8907         .set_p2p_powersave = nl80211_set_p2p_powersave,
8908 #ifdef CONFIG_TDLS
8909         .send_tdls_mgmt = nl80211_send_tdls_mgmt,
8910         .tdls_oper = nl80211_tdls_oper,
8911 #endif /* CONFIG_TDLS */
8912 };