]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - build-utilities/hostap.git/blob - src/drivers/driver_nl80211.c
Add P2P support for BRCM CFG80211 driver (nl80211)
[build-utilities/hostap.git] / src / drivers / driver_nl80211.c
1 /*
2  * Driver interaction with Linux nl80211/cfg80211
3  * Copyright (c) 2002-2012, 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 software may be distributed under the terms of the BSD license.
10  * See README for more details.
11  */
13 #include "includes.h"
14 #include <sys/ioctl.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <fcntl.h>
18 #include <net/if.h>
19 #include <netlink/genl/genl.h>
20 #include <netlink/genl/family.h>
21 #include <netlink/genl/ctrl.h>
22 #include <linux/rtnetlink.h>
23 #include <netpacket/packet.h>
24 #include <linux/filter.h>
25 #include <linux/errqueue.h>
26 #include "nl80211_copy.h"
28 #include "common.h"
29 #include "eloop.h"
30 #include "utils/list.h"
31 #include "common/ieee802_11_defs.h"
32 #include "common/ieee802_11_common.h"
33 #include "l2_packet/l2_packet.h"
34 #include "netlink.h"
35 #include "linux_ioctl.h"
36 #include "radiotap.h"
37 #include "radiotap_iter.h"
38 #include "rfkill.h"
39 #include "driver.h"
41 #ifndef SO_WIFI_STATUS
42 # if defined(__sparc__)
43 #  define SO_WIFI_STATUS        0x0025
44 # elif defined(__parisc__)
45 #  define SO_WIFI_STATUS        0x4022
46 # else
47 #  define SO_WIFI_STATUS        41
48 # endif
50 # define SCM_WIFI_STATUS        SO_WIFI_STATUS
51 #endif
53 #ifndef SO_EE_ORIGIN_TXSTATUS
54 #define SO_EE_ORIGIN_TXSTATUS   4
55 #endif
57 #ifndef PACKET_TX_TIMESTAMP
58 #define PACKET_TX_TIMESTAMP     16
59 #endif
61 #ifdef ANDROID
62 #include "android_drv.h"
63 #endif /* ANDROID */
64 #ifdef CONFIG_LIBNL20
65 /* libnl 2.0 compatibility code */
66 #define nl_handle nl_sock
67 #define nl80211_handle_alloc nl_socket_alloc_cb
68 #define nl80211_handle_destroy nl_socket_free
69 #else
70 /*
71  * libnl 1.1 has a bug, it tries to allocate socket numbers densely
72  * but when you free a socket again it will mess up its bitmap and
73  * and use the wrong number the next time it needs a socket ID.
74  * Therefore, we wrap the handle alloc/destroy and add our own pid
75  * accounting.
76  */
77 static uint32_t port_bitmap[32] = { 0 };
79 static struct nl_handle *nl80211_handle_alloc(void *cb)
80 {
81         struct nl_handle *handle;
82         uint32_t pid = getpid() & 0x3FFFFF;
83         int i;
85         handle = nl_handle_alloc_cb(cb);
87         for (i = 0; i < 1024; i++) {
88                 if (port_bitmap[i / 32] & (1 << (i % 32)))
89                         continue;
90                 port_bitmap[i / 32] |= 1 << (i % 32);
91                 pid += i << 22;
92                 break;
93         }
95         nl_socket_set_local_port(handle, pid);
97         return handle;
98 }
100 static void nl80211_handle_destroy(struct nl_handle *handle)
102         uint32_t port = nl_socket_get_local_port(handle);
104         port >>= 22;
105         port_bitmap[port / 32] &= ~(1 << (port % 32));
107         nl_handle_destroy(handle);
109 #endif /* CONFIG_LIBNL20 */
112 static struct nl_handle * nl_create_handle(struct nl_cb *cb, const char *dbg)
114         struct nl_handle *handle;
116         handle = nl80211_handle_alloc(cb);
117         if (handle == NULL) {
118                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
119                            "callbacks (%s)", dbg);
120                 return NULL;
121         }
123         if (genl_connect(handle)) {
124                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
125                            "netlink (%s)", dbg);
126                 nl80211_handle_destroy(handle);
127                 return NULL;
128         }
130         return handle;
134 static void nl_destroy_handles(struct nl_handle **handle)
136         if (*handle == NULL)
137                 return;
138         nl80211_handle_destroy(*handle);
139         *handle = NULL;
143 #ifndef IFF_LOWER_UP
144 #define IFF_LOWER_UP   0x10000         /* driver signals L1 up         */
145 #endif
146 #ifndef IFF_DORMANT
147 #define IFF_DORMANT    0x20000         /* driver signals dormant       */
148 #endif
150 #ifndef IF_OPER_DORMANT
151 #define IF_OPER_DORMANT 5
152 #endif
153 #ifndef IF_OPER_UP
154 #define IF_OPER_UP 6
155 #endif
157 struct nl80211_global {
158         struct dl_list interfaces;
159         int if_add_ifindex;
160         struct netlink_data *netlink;
161         struct nl_cb *nl_cb;
162         struct nl_handle *nl;
163         int nl80211_id;
164         int ioctl_sock; /* socket for ioctl() use */
166         struct nl_handle *nl_event;
167 };
169 struct nl80211_wiphy_data {
170         struct dl_list list;
171         struct dl_list bsss;
172         struct dl_list drvs;
174         struct nl_handle *nl_beacons;
175         struct nl_cb *nl_cb;
177         int wiphy_idx;
178 };
180 static void nl80211_global_deinit(void *priv);
181 static void wpa_driver_nl80211_deinit(void *priv);
183 struct i802_bss {
184         struct wpa_driver_nl80211_data *drv;
185         struct i802_bss *next;
186         int ifindex;
187         char ifname[IFNAMSIZ + 1];
188         char brname[IFNAMSIZ];
189         unsigned int beacon_set:1;
190         unsigned int added_if_into_bridge:1;
191         unsigned int added_bridge:1;
193         u8 addr[ETH_ALEN];
195         int freq;
197         struct nl_handle *nl_preq, *nl_mgmt;
198         struct nl_cb *nl_cb;
200         struct nl80211_wiphy_data *wiphy_data;
201         struct dl_list wiphy_list;
202 };
204 struct wpa_driver_nl80211_data {
205         struct nl80211_global *global;
206         struct dl_list list;
207         struct dl_list wiphy_list;
208         char phyname[32];
209         void *ctx;
210         int ifindex;
211         int if_removed;
212         int if_disabled;
213         int ignore_if_down_event;
214         struct rfkill_data *rfkill;
215         struct wpa_driver_capa capa;
216         int has_capability;
218         int operstate;
220         int scan_complete_events;
222         struct nl_cb *nl_cb;
224         u8 auth_bssid[ETH_ALEN];
225         u8 bssid[ETH_ALEN];
226         int associated;
227         u8 ssid[32];
228         size_t ssid_len;
229         enum nl80211_iftype nlmode;
230         enum nl80211_iftype ap_scan_as_station;
231         unsigned int assoc_freq;
233         int monitor_sock;
234         int monitor_ifidx;
235         int monitor_refcount;
237         unsigned int disabled_11b_rates:1;
238         unsigned int pending_remain_on_chan:1;
239         unsigned int in_interface_list:1;
240         unsigned int device_ap_sme:1;
241         unsigned int poll_command_supported:1;
242         unsigned int data_tx_status:1;
243         unsigned int scan_for_auth:1;
244         unsigned int retry_auth:1;
245         unsigned int use_monitor:1;
247         u64 remain_on_chan_cookie;
248         u64 send_action_cookie;
250         unsigned int last_mgmt_freq;
252         struct wpa_driver_scan_filter *filter_ssids;
253         size_t num_filter_ssids;
255         struct i802_bss first_bss;
257         int eapol_tx_sock;
259 #ifdef HOSTAPD
260         int eapol_sock; /* socket for EAPOL frames */
262         int default_if_indices[16];
263         int *if_indices;
264         int num_if_indices;
266         int last_freq;
267         int last_freq_ht;
268 #endif /* HOSTAPD */
270         /* From failed authentication command */
271         int auth_freq;
272         u8 auth_bssid_[ETH_ALEN];
273         u8 auth_ssid[32];
274         size_t auth_ssid_len;
275         int auth_alg;
276         u8 *auth_ie;
277         size_t auth_ie_len;
278         u8 auth_wep_key[4][16];
279         size_t auth_wep_key_len[4];
280         int auth_wep_tx_keyidx;
281         int auth_local_state_change;
282         int auth_p2p;
283 };
286 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx,
287                                             void *timeout_ctx);
288 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
289                                        enum nl80211_iftype nlmode);
290 static int
291 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv);
292 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
293                                    const u8 *addr, int cmd, u16 reason_code,
294                                    int local_state_change);
295 static void nl80211_remove_monitor_interface(
296         struct wpa_driver_nl80211_data *drv);
297 static int nl80211_send_frame_cmd(struct i802_bss *bss,
298                                   unsigned int freq, unsigned int wait,
299                                   const u8 *buf, size_t buf_len, u64 *cookie,
300                                   int no_cck, int no_ack, int offchanok);
301 static int wpa_driver_nl80211_probe_req_report(void *priv, int report);
302 #ifdef ANDROID
303 static int android_pno_start(struct i802_bss *bss,
304                              struct wpa_driver_scan_params *params);
305 static int android_pno_stop(struct i802_bss *bss);
306 #endif /* ANDROID */
308 #ifdef HOSTAPD
309 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
310 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
311 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
312 static int wpa_driver_nl80211_if_remove(void *priv,
313                                         enum wpa_driver_if_type type,
314                                         const char *ifname);
315 #else /* HOSTAPD */
316 static inline void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
320 static inline void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
324 static inline int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
326         return 0;
328 #endif /* HOSTAPD */
330 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq);
331 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
332                                      int ifindex, int disabled);
334 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv);
335 static int wpa_driver_nl80211_authenticate_retry(
336         struct wpa_driver_nl80211_data *drv);
339 static int is_ap_interface(enum nl80211_iftype nlmode)
341         return (nlmode == NL80211_IFTYPE_AP ||
342                 nlmode == NL80211_IFTYPE_P2P_GO);
346 static int is_sta_interface(enum nl80211_iftype nlmode)
348         return (nlmode == NL80211_IFTYPE_STATION ||
349                 nlmode == NL80211_IFTYPE_P2P_CLIENT);
353 static int is_p2p_interface(enum nl80211_iftype nlmode)
355         return (nlmode == NL80211_IFTYPE_P2P_CLIENT ||
356                 nlmode == NL80211_IFTYPE_P2P_GO);
360 struct nl80211_bss_info_arg {
361         struct wpa_driver_nl80211_data *drv;
362         struct wpa_scan_results *res;
363         unsigned int assoc_freq;
364         u8 assoc_bssid[ETH_ALEN];
365 };
367 static int bss_info_handler(struct nl_msg *msg, void *arg);
370 /* nl80211 code */
371 static int ack_handler(struct nl_msg *msg, void *arg)
373         int *err = arg;
374         *err = 0;
375         return NL_STOP;
378 static int finish_handler(struct nl_msg *msg, void *arg)
380         int *ret = arg;
381         *ret = 0;
382         return NL_SKIP;
385 static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err,
386                          void *arg)
388         int *ret = arg;
389         *ret = err->error;
390         return NL_SKIP;
394 static int no_seq_check(struct nl_msg *msg, void *arg)
396         return NL_OK;
400 static int send_and_recv(struct nl80211_global *global,
401                          struct nl_handle *nl_handle, struct nl_msg *msg,
402                          int (*valid_handler)(struct nl_msg *, void *),
403                          void *valid_data)
405         struct nl_cb *cb;
406         int err = -ENOMEM;
408         cb = nl_cb_clone(global->nl_cb);
409         if (!cb)
410                 goto out;
412         err = nl_send_auto_complete(nl_handle, msg);
413         if (err < 0)
414                 goto out;
416         err = 1;
418         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
419         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
420         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
422         if (valid_handler)
423                 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM,
424                           valid_handler, valid_data);
426         while (err > 0)
427                 nl_recvmsgs(nl_handle, cb);
428  out:
429         nl_cb_put(cb);
430         nlmsg_free(msg);
431         return err;
435 static int send_and_recv_msgs_global(struct nl80211_global *global,
436                                      struct nl_msg *msg,
437                                      int (*valid_handler)(struct nl_msg *, void *),
438                                      void *valid_data)
440         return send_and_recv(global, global->nl, msg, valid_handler,
441                              valid_data);
445 static int send_and_recv_msgs(struct wpa_driver_nl80211_data *drv,
446                               struct nl_msg *msg,
447                               int (*valid_handler)(struct nl_msg *, void *),
448                               void *valid_data)
450         return send_and_recv(drv->global, drv->global->nl, msg,
451                              valid_handler, valid_data);
455 struct family_data {
456         const char *group;
457         int id;
458 };
461 static int family_handler(struct nl_msg *msg, void *arg)
463         struct family_data *res = arg;
464         struct nlattr *tb[CTRL_ATTR_MAX + 1];
465         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
466         struct nlattr *mcgrp;
467         int i;
469         nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
470                   genlmsg_attrlen(gnlh, 0), NULL);
471         if (!tb[CTRL_ATTR_MCAST_GROUPS])
472                 return NL_SKIP;
474         nla_for_each_nested(mcgrp, tb[CTRL_ATTR_MCAST_GROUPS], i) {
475                 struct nlattr *tb2[CTRL_ATTR_MCAST_GRP_MAX + 1];
476                 nla_parse(tb2, CTRL_ATTR_MCAST_GRP_MAX, nla_data(mcgrp),
477                           nla_len(mcgrp), NULL);
478                 if (!tb2[CTRL_ATTR_MCAST_GRP_NAME] ||
479                     !tb2[CTRL_ATTR_MCAST_GRP_ID] ||
480                     os_strncmp(nla_data(tb2[CTRL_ATTR_MCAST_GRP_NAME]),
481                                res->group,
482                                nla_len(tb2[CTRL_ATTR_MCAST_GRP_NAME])) != 0)
483                         continue;
484                 res->id = nla_get_u32(tb2[CTRL_ATTR_MCAST_GRP_ID]);
485                 break;
486         };
488         return NL_SKIP;
492 static int nl_get_multicast_id(struct nl80211_global *global,
493                                const char *family, const char *group)
495         struct nl_msg *msg;
496         int ret = -1;
497         struct family_data res = { group, -ENOENT };
499         msg = nlmsg_alloc();
500         if (!msg)
501                 return -ENOMEM;
502         genlmsg_put(msg, 0, 0, genl_ctrl_resolve(global->nl, "nlctrl"),
503                     0, 0, CTRL_CMD_GETFAMILY, 0);
504         NLA_PUT_STRING(msg, CTRL_ATTR_FAMILY_NAME, family);
506         ret = send_and_recv_msgs_global(global, msg, family_handler, &res);
507         msg = NULL;
508         if (ret == 0)
509                 ret = res.id;
511 nla_put_failure:
512         nlmsg_free(msg);
513         return ret;
517 static void * nl80211_cmd(struct wpa_driver_nl80211_data *drv,
518                           struct nl_msg *msg, int flags, uint8_t cmd)
520         return genlmsg_put(msg, 0, 0, drv->global->nl80211_id,
521                            0, flags, cmd, 0);
525 struct wiphy_idx_data {
526         int wiphy_idx;
527 };
530 static int netdev_info_handler(struct nl_msg *msg, void *arg)
532         struct nlattr *tb[NL80211_ATTR_MAX + 1];
533         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
534         struct wiphy_idx_data *info = arg;
536         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
537                   genlmsg_attrlen(gnlh, 0), NULL);
539         if (tb[NL80211_ATTR_WIPHY])
540                 info->wiphy_idx = nla_get_u32(tb[NL80211_ATTR_WIPHY]);
542         return NL_SKIP;
546 static int nl80211_get_wiphy_index(struct i802_bss *bss)
548         struct nl_msg *msg;
549         struct wiphy_idx_data data = {
550                 .wiphy_idx = -1,
551         };
553         msg = nlmsg_alloc();
554         if (!msg)
555                 return -1;
557         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_GET_INTERFACE);
559         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
561         if (send_and_recv_msgs(bss->drv, msg, netdev_info_handler, &data) == 0)
562                 return data.wiphy_idx;
563         msg = NULL;
564 nla_put_failure:
565         nlmsg_free(msg);
566         return -1;
570 static int nl80211_register_beacons(struct wpa_driver_nl80211_data *drv,
571                                     struct nl80211_wiphy_data *w)
573         struct nl_msg *msg;
574         int ret = -1;
576         msg = nlmsg_alloc();
577         if (!msg)
578                 return -1;
580         nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_BEACONS);
582         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, w->wiphy_idx);
584         ret = send_and_recv(drv->global, w->nl_beacons, msg, NULL, NULL);
585         msg = NULL;
586         if (ret) {
587                 wpa_printf(MSG_DEBUG, "nl80211: Register beacons command "
588                            "failed: ret=%d (%s)",
589                            ret, strerror(-ret));
590                 goto nla_put_failure;
591         }
592         ret = 0;
593 nla_put_failure:
594         nlmsg_free(msg);
595         return ret;
599 static void nl80211_recv_beacons(int sock, void *eloop_ctx, void *handle)
601         struct nl80211_wiphy_data *w = eloop_ctx;
603         wpa_printf(MSG_EXCESSIVE, "nl80211: Beacon event message available");
605         nl_recvmsgs(handle, w->nl_cb);
609 static int process_beacon_event(struct nl_msg *msg, void *arg)
611         struct nl80211_wiphy_data *w = arg;
612         struct wpa_driver_nl80211_data *drv;
613         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
614         struct nlattr *tb[NL80211_ATTR_MAX + 1];
615         union wpa_event_data event;
617         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
618                   genlmsg_attrlen(gnlh, 0), NULL);
620         if (gnlh->cmd != NL80211_CMD_FRAME) {
621                 wpa_printf(MSG_DEBUG, "nl80211: Unexpected beacon event? (%d)",
622                            gnlh->cmd);
623                 return NL_SKIP;
624         }
626         if (!tb[NL80211_ATTR_FRAME])
627                 return NL_SKIP;
629         dl_list_for_each(drv, &w->drvs, struct wpa_driver_nl80211_data,
630                          wiphy_list) {
631                 os_memset(&event, 0, sizeof(event));
632                 event.rx_mgmt.frame = nla_data(tb[NL80211_ATTR_FRAME]);
633                 event.rx_mgmt.frame_len = nla_len(tb[NL80211_ATTR_FRAME]);
634                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
635         }
637         return NL_SKIP;
641 static struct nl80211_wiphy_data *
642 nl80211_get_wiphy_data_ap(struct i802_bss *bss)
644         static DEFINE_DL_LIST(nl80211_wiphys);
645         struct nl80211_wiphy_data *w;
646         int wiphy_idx, found = 0;
647         struct i802_bss *tmp_bss;
649         if (bss->wiphy_data != NULL)
650                 return bss->wiphy_data;
652         wiphy_idx = nl80211_get_wiphy_index(bss);
654         dl_list_for_each(w, &nl80211_wiphys, struct nl80211_wiphy_data, list) {
655                 if (w->wiphy_idx == wiphy_idx)
656                         goto add;
657         }
659         /* alloc new one */
660         w = os_zalloc(sizeof(*w));
661         if (w == NULL)
662                 return NULL;
663         w->wiphy_idx = wiphy_idx;
664         dl_list_init(&w->bsss);
665         dl_list_init(&w->drvs);
667         w->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
668         if (!w->nl_cb) {
669                 os_free(w);
670                 return NULL;
671         }
672         nl_cb_set(w->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, no_seq_check, NULL);
673         nl_cb_set(w->nl_cb, NL_CB_VALID, NL_CB_CUSTOM, process_beacon_event,
674                   w);
676         w->nl_beacons = nl_create_handle(bss->drv->global->nl_cb,
677                                          "wiphy beacons");
678         if (w->nl_beacons == NULL) {
679                 os_free(w);
680                 return NULL;
681         }
683         if (nl80211_register_beacons(bss->drv, w)) {
684                 nl_destroy_handles(&w->nl_beacons);
685                 os_free(w);
686                 return NULL;
687         }
689         eloop_register_read_sock(nl_socket_get_fd(w->nl_beacons),
690                                  nl80211_recv_beacons, w, w->nl_beacons);
692         dl_list_add(&nl80211_wiphys, &w->list);
694 add:
695         /* drv entry for this bss already there? */
696         dl_list_for_each(tmp_bss, &w->bsss, struct i802_bss, wiphy_list) {
697                 if (tmp_bss->drv == bss->drv) {
698                         found = 1;
699                         break;
700                 }
701         }
702         /* if not add it */
703         if (!found)
704                 dl_list_add(&w->drvs, &bss->drv->wiphy_list);
706         dl_list_add(&w->bsss, &bss->wiphy_list);
707         bss->wiphy_data = w;
708         return w;
712 static void nl80211_put_wiphy_data_ap(struct i802_bss *bss)
714         struct nl80211_wiphy_data *w = bss->wiphy_data;
715         struct i802_bss *tmp_bss;
716         int found = 0;
718         if (w == NULL)
719                 return;
720         bss->wiphy_data = NULL;
721         dl_list_del(&bss->wiphy_list);
723         /* still any for this drv present? */
724         dl_list_for_each(tmp_bss, &w->bsss, struct i802_bss, wiphy_list) {
725                 if (tmp_bss->drv == bss->drv) {
726                         found = 1;
727                         break;
728                 }
729         }
730         /* if not remove it */
731         if (!found)
732                 dl_list_del(&bss->drv->wiphy_list);
734         if (!dl_list_empty(&w->bsss))
735                 return;
737         eloop_unregister_read_sock(nl_socket_get_fd(w->nl_beacons));
739         nl_cb_put(w->nl_cb);
740         nl_destroy_handles(&w->nl_beacons);
741         dl_list_del(&w->list);
742         os_free(w);
746 static int wpa_driver_nl80211_get_bssid(void *priv, u8 *bssid)
748         struct i802_bss *bss = priv;
749         struct wpa_driver_nl80211_data *drv = bss->drv;
750         if (!drv->associated)
751                 return -1;
752         os_memcpy(bssid, drv->bssid, ETH_ALEN);
753         return 0;
757 static int wpa_driver_nl80211_get_ssid(void *priv, u8 *ssid)
759         struct i802_bss *bss = priv;
760         struct wpa_driver_nl80211_data *drv = bss->drv;
761         if (!drv->associated)
762                 return -1;
763         os_memcpy(ssid, drv->ssid, drv->ssid_len);
764         return drv->ssid_len;
768 static void wpa_driver_nl80211_event_link(struct wpa_driver_nl80211_data *drv,
769                                           char *buf, size_t len, int del)
771         union wpa_event_data event;
773         os_memset(&event, 0, sizeof(event));
774         if (len > sizeof(event.interface_status.ifname))
775                 len = sizeof(event.interface_status.ifname) - 1;
776         os_memcpy(event.interface_status.ifname, buf, len);
777         event.interface_status.ievent = del ? EVENT_INTERFACE_REMOVED :
778                 EVENT_INTERFACE_ADDED;
780         wpa_printf(MSG_DEBUG, "RTM_%sLINK, IFLA_IFNAME: Interface '%s' %s",
781                    del ? "DEL" : "NEW",
782                    event.interface_status.ifname,
783                    del ? "removed" : "added");
785         if (os_strcmp(drv->first_bss.ifname, event.interface_status.ifname) == 0) {
786                 if (del) {
787                         if (drv->if_removed) {
788                                 wpa_printf(MSG_DEBUG, "nl80211: if_removed "
789                                            "already set - ignore event");
790                                 return;
791                         }
792                         drv->if_removed = 1;
793                 } else {
794                         if (if_nametoindex(drv->first_bss.ifname) == 0) {
795                                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s "
796                                            "does not exist - ignore "
797                                            "RTM_NEWLINK",
798                                            drv->first_bss.ifname);
799                                 return;
800                         }
801                         if (!drv->if_removed) {
802                                 wpa_printf(MSG_DEBUG, "nl80211: if_removed "
803                                            "already cleared - ignore event");
804                                 return;
805                         }
806                         drv->if_removed = 0;
807                 }
808         }
810         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_STATUS, &event);
814 static int wpa_driver_nl80211_own_ifname(struct wpa_driver_nl80211_data *drv,
815                                          u8 *buf, size_t len)
817         int attrlen, rta_len;
818         struct rtattr *attr;
820         attrlen = len;
821         attr = (struct rtattr *) buf;
823         rta_len = RTA_ALIGN(sizeof(struct rtattr));
824         while (RTA_OK(attr, attrlen)) {
825                 if (attr->rta_type == IFLA_IFNAME) {
826                         if (os_strcmp(((char *) attr) + rta_len, drv->first_bss.ifname)
827                             == 0)
828                                 return 1;
829                         else
830                                 break;
831                 }
832                 attr = RTA_NEXT(attr, attrlen);
833         }
835         return 0;
839 static int wpa_driver_nl80211_own_ifindex(struct wpa_driver_nl80211_data *drv,
840                                           int ifindex, u8 *buf, size_t len)
842         if (drv->ifindex == ifindex)
843                 return 1;
845         if (drv->if_removed && wpa_driver_nl80211_own_ifname(drv, buf, len)) {
846                 drv->first_bss.ifindex = if_nametoindex(drv->first_bss.ifname);
847                 wpa_printf(MSG_DEBUG, "nl80211: Update ifindex for a removed "
848                            "interface");
849                 wpa_driver_nl80211_finish_drv_init(drv);
850                 return 1;
851         }
853         return 0;
857 static struct wpa_driver_nl80211_data *
858 nl80211_find_drv(struct nl80211_global *global, int idx, u8 *buf, size_t len)
860         struct wpa_driver_nl80211_data *drv;
861         dl_list_for_each(drv, &global->interfaces,
862                          struct wpa_driver_nl80211_data, list) {
863                 if (wpa_driver_nl80211_own_ifindex(drv, idx, buf, len) ||
864                     have_ifidx(drv, idx))
865                         return drv;
866         }
867         return NULL;
871 static void wpa_driver_nl80211_event_rtm_newlink(void *ctx,
872                                                  struct ifinfomsg *ifi,
873                                                  u8 *buf, size_t len)
875         struct nl80211_global *global = ctx;
876         struct wpa_driver_nl80211_data *drv;
877         int attrlen, rta_len;
878         struct rtattr *attr;
879         u32 brid = 0;
880         char namebuf[IFNAMSIZ];
882         drv = nl80211_find_drv(global, ifi->ifi_index, buf, len);
883         if (!drv) {
884                 wpa_printf(MSG_DEBUG, "nl80211: Ignore event for foreign "
885                            "ifindex %d", ifi->ifi_index);
886                 return;
887         }
889         wpa_printf(MSG_DEBUG, "RTM_NEWLINK: operstate=%d ifi_flags=0x%x "
890                    "(%s%s%s%s)",
891                    drv->operstate, ifi->ifi_flags,
892                    (ifi->ifi_flags & IFF_UP) ? "[UP]" : "",
893                    (ifi->ifi_flags & IFF_RUNNING) ? "[RUNNING]" : "",
894                    (ifi->ifi_flags & IFF_LOWER_UP) ? "[LOWER_UP]" : "",
895                    (ifi->ifi_flags & IFF_DORMANT) ? "[DORMANT]" : "");
897         if (!drv->if_disabled && !(ifi->ifi_flags & IFF_UP)) {
898                 if (if_indextoname(ifi->ifi_index, namebuf) &&
899                     linux_iface_up(drv->global->ioctl_sock,
900                                    drv->first_bss.ifname) > 0) {
901                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface down "
902                                    "event since interface %s is up", namebuf);
903                         return;
904                 }
905                 wpa_printf(MSG_DEBUG, "nl80211: Interface down");
906                 if (drv->ignore_if_down_event) {
907                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface down "
908                                    "event generated by mode change");
909                         drv->ignore_if_down_event = 0;
910                 } else {
911                         drv->if_disabled = 1;
912                         wpa_supplicant_event(drv->ctx,
913                                              EVENT_INTERFACE_DISABLED, NULL);
914                 }
915         }
917         if (drv->if_disabled && (ifi->ifi_flags & IFF_UP)) {
918                 if (if_indextoname(ifi->ifi_index, namebuf) &&
919                     linux_iface_up(drv->global->ioctl_sock,
920                                    drv->first_bss.ifname) == 0) {
921                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
922                                    "event since interface %s is down",
923                                    namebuf);
924                 } else if (if_nametoindex(drv->first_bss.ifname) == 0) {
925                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
926                                    "event since interface %s does not exist",
927                                    drv->first_bss.ifname);
928                 } else if (drv->if_removed) {
929                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
930                                    "event since interface %s is marked "
931                                    "removed", drv->first_bss.ifname);
932                 } else {
933                         wpa_printf(MSG_DEBUG, "nl80211: Interface up");
934                         drv->if_disabled = 0;
935                         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_ENABLED,
936                                              NULL);
937                 }
938         }
940         /*
941          * Some drivers send the association event before the operup event--in
942          * this case, lifting operstate in wpa_driver_nl80211_set_operstate()
943          * fails. This will hit us when wpa_supplicant does not need to do
944          * IEEE 802.1X authentication
945          */
946         if (drv->operstate == 1 &&
947             (ifi->ifi_flags & (IFF_LOWER_UP | IFF_DORMANT)) == IFF_LOWER_UP &&
948             !(ifi->ifi_flags & IFF_RUNNING))
949                 netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
950                                        -1, IF_OPER_UP);
952         attrlen = len;
953         attr = (struct rtattr *) buf;
954         rta_len = RTA_ALIGN(sizeof(struct rtattr));
955         while (RTA_OK(attr, attrlen)) {
956                 if (attr->rta_type == IFLA_IFNAME) {
957                         wpa_driver_nl80211_event_link(
958                                 drv,
959                                 ((char *) attr) + rta_len,
960                                 attr->rta_len - rta_len, 0);
961                 } else if (attr->rta_type == IFLA_MASTER)
962                         brid = nla_get_u32((struct nlattr *) attr);
963                 attr = RTA_NEXT(attr, attrlen);
964         }
966         if (ifi->ifi_family == AF_BRIDGE && brid) {
967                 /* device has been added to bridge */
968                 if_indextoname(brid, namebuf);
969                 wpa_printf(MSG_DEBUG, "nl80211: Add ifindex %u for bridge %s",
970                            brid, namebuf);
971                 add_ifidx(drv, brid);
972         }
976 static void wpa_driver_nl80211_event_rtm_dellink(void *ctx,
977                                                  struct ifinfomsg *ifi,
978                                                  u8 *buf, size_t len)
980         struct nl80211_global *global = ctx;
981         struct wpa_driver_nl80211_data *drv;
982         int attrlen, rta_len;
983         struct rtattr *attr;
984         u32 brid = 0;
986         drv = nl80211_find_drv(global, ifi->ifi_index, buf, len);
987         if (!drv) {
988                 wpa_printf(MSG_DEBUG, "nl80211: Ignore dellink event for "
989                            "foreign ifindex %d", ifi->ifi_index);
990                 return;
991         }
993         attrlen = len;
994         attr = (struct rtattr *) buf;
996         rta_len = RTA_ALIGN(sizeof(struct rtattr));
997         while (RTA_OK(attr, attrlen)) {
998                 if (attr->rta_type == IFLA_IFNAME) {
999                         wpa_driver_nl80211_event_link(
1000                                 drv,
1001                                 ((char *) attr) + rta_len,
1002                                 attr->rta_len - rta_len, 1);
1003                 } else if (attr->rta_type == IFLA_MASTER)
1004                         brid = nla_get_u32((struct nlattr *) attr);
1005                 attr = RTA_NEXT(attr, attrlen);
1006         }
1008         if (ifi->ifi_family == AF_BRIDGE && brid) {
1009                 /* device has been removed from bridge */
1010                 char namebuf[IFNAMSIZ];
1011                 if_indextoname(brid, namebuf);
1012                 wpa_printf(MSG_DEBUG, "nl80211: Remove ifindex %u for bridge "
1013                            "%s", brid, namebuf);
1014                 del_ifidx(drv, brid);
1015         }
1019 static void mlme_event_auth(struct wpa_driver_nl80211_data *drv,
1020                             const u8 *frame, size_t len)
1022         const struct ieee80211_mgmt *mgmt;
1023         union wpa_event_data event;
1025         mgmt = (const struct ieee80211_mgmt *) frame;
1026         if (len < 24 + sizeof(mgmt->u.auth)) {
1027                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1028                            "frame");
1029                 return;
1030         }
1032         os_memcpy(drv->auth_bssid, mgmt->sa, ETH_ALEN);
1033         os_memset(&event, 0, sizeof(event));
1034         os_memcpy(event.auth.peer, mgmt->sa, ETH_ALEN);
1035         event.auth.auth_type = le_to_host16(mgmt->u.auth.auth_alg);
1036         event.auth.status_code = le_to_host16(mgmt->u.auth.status_code);
1037         if (len > 24 + sizeof(mgmt->u.auth)) {
1038                 event.auth.ies = mgmt->u.auth.variable;
1039                 event.auth.ies_len = len - 24 - sizeof(mgmt->u.auth);
1040         }
1042         wpa_supplicant_event(drv->ctx, EVENT_AUTH, &event);
1046 static unsigned int nl80211_get_assoc_freq(struct wpa_driver_nl80211_data *drv)
1048         struct nl_msg *msg;
1049         int ret;
1050         struct nl80211_bss_info_arg arg;
1052         os_memset(&arg, 0, sizeof(arg));
1053         msg = nlmsg_alloc();
1054         if (!msg)
1055                 goto nla_put_failure;
1057         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
1058         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1060         arg.drv = drv;
1061         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
1062         msg = NULL;
1063         if (ret == 0) {
1064                 wpa_printf(MSG_DEBUG, "nl80211: Operating frequency for the "
1065                            "associated BSS from scan results: %u MHz",
1066                            arg.assoc_freq);
1067                 return arg.assoc_freq ? arg.assoc_freq : drv->assoc_freq;
1068         }
1069         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
1070                    "(%s)", ret, strerror(-ret));
1071 nla_put_failure:
1072         nlmsg_free(msg);
1073         return drv->assoc_freq;
1077 static void mlme_event_assoc(struct wpa_driver_nl80211_data *drv,
1078                             const u8 *frame, size_t len)
1080         const struct ieee80211_mgmt *mgmt;
1081         union wpa_event_data event;
1082         u16 status;
1084         mgmt = (const struct ieee80211_mgmt *) frame;
1085 #if (defined (CONFIG_AP) || defined (HOSTAPD) ) && defined (ANDROID_BRCM_P2P_PATCH)
1086         if (drv->nlmode == NL80211_IFTYPE_AP || drv->nlmode == NL80211_IFTYPE_P2P_GO) {
1087                 if (len < 24 + sizeof(mgmt->u.assoc_req)) {
1088                         wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1089                            "frame");
1090                         return;
1091                 }
1092                 os_memset(&event, 0, sizeof(event));
1093                 event.assoc_info.freq = drv->assoc_freq;
1094                 event.assoc_info.req_ies = (u8 *) mgmt->u.assoc_req.variable;
1095                 event.assoc_info.req_ies_len = len - 24 - sizeof(mgmt->u.assoc_req);
1096                 event.assoc_info.addr = mgmt->sa;
1097         } else {
1098 #endif
1099         if (len < 24 + sizeof(mgmt->u.assoc_resp)) {
1100                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1101                            "frame");
1102                 return;
1103         }
1105         status = le_to_host16(mgmt->u.assoc_resp.status_code);
1106         if (status != WLAN_STATUS_SUCCESS) {
1107                 os_memset(&event, 0, sizeof(event));
1108                 event.assoc_reject.bssid = mgmt->bssid;
1109                 if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
1110                         event.assoc_reject.resp_ies =
1111                                 (u8 *) mgmt->u.assoc_resp.variable;
1112                         event.assoc_reject.resp_ies_len =
1113                                 len - 24 - sizeof(mgmt->u.assoc_resp);
1114                 }
1115                 event.assoc_reject.status_code = status;
1117                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
1118                 return;
1119         }
1121         drv->associated = 1;
1122         os_memcpy(drv->bssid, mgmt->sa, ETH_ALEN);
1124         os_memset(&event, 0, sizeof(event));
1125         if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
1126                 event.assoc_info.resp_ies = (u8 *) mgmt->u.assoc_resp.variable;
1127                 event.assoc_info.resp_ies_len =
1128                         len - 24 - sizeof(mgmt->u.assoc_resp);
1129         }
1131         event.assoc_info.freq = drv->assoc_freq;
1132 #if (defined (CONFIG_AP) || defined(HOSTAPD)) && defined (ANDROID_BRCM_P2P_PATCH)
1133         }
1134 #endif
1136         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
1140 static void mlme_event_connect(struct wpa_driver_nl80211_data *drv,
1141                                enum nl80211_commands cmd, struct nlattr *status,
1142                                struct nlattr *addr, struct nlattr *req_ie,
1143                                struct nlattr *resp_ie)
1145         union wpa_event_data event;
1147         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1148                 /*
1149                  * Avoid reporting two association events that would confuse
1150                  * the core code.
1151                  */
1152                 wpa_printf(MSG_DEBUG, "nl80211: Ignore connect event (cmd=%d) "
1153                            "when using userspace SME", cmd);
1154                 return;
1155         }
1157         os_memset(&event, 0, sizeof(event));
1158         if (cmd == NL80211_CMD_CONNECT &&
1159             nla_get_u16(status) != WLAN_STATUS_SUCCESS) {
1160                 if (addr)
1161                         event.assoc_reject.bssid = nla_data(addr);
1162                 if (resp_ie) {
1163                         event.assoc_reject.resp_ies = nla_data(resp_ie);
1164                         event.assoc_reject.resp_ies_len = nla_len(resp_ie);
1165                 }
1166                 event.assoc_reject.status_code = nla_get_u16(status);
1167                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
1168                 return;
1169         }
1171         drv->associated = 1;
1172         if (addr)
1173                 os_memcpy(drv->bssid, nla_data(addr), ETH_ALEN);
1175         if (req_ie) {
1176                 event.assoc_info.req_ies = nla_data(req_ie);
1177                 event.assoc_info.req_ies_len = nla_len(req_ie);
1178         }
1179         if (resp_ie) {
1180                 event.assoc_info.resp_ies = nla_data(resp_ie);
1181                 event.assoc_info.resp_ies_len = nla_len(resp_ie);
1182         }
1184         event.assoc_info.freq = nl80211_get_assoc_freq(drv);
1186         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
1190 static void mlme_event_disconnect(struct wpa_driver_nl80211_data *drv,
1191                                   struct nlattr *reason, struct nlattr *addr,
1192                                   struct nlattr *by_ap)
1194         union wpa_event_data data;
1196         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1197                 /*
1198                  * Avoid reporting two disassociation events that could
1199                  * confuse the core code.
1200                  */
1201                 wpa_printf(MSG_DEBUG, "nl80211: Ignore disconnect "
1202                            "event when using userspace SME");
1203                 return;
1204         }
1206         drv->associated = 0;
1207         os_memset(&data, 0, sizeof(data));
1208         if (reason)
1209                 data.disassoc_info.reason_code = nla_get_u16(reason);
1210         data.disassoc_info.locally_generated = by_ap == NULL;
1211         wpa_supplicant_event(drv->ctx, EVENT_DISASSOC, &data);
1215 static void mlme_timeout_event(struct wpa_driver_nl80211_data *drv,
1216                                enum nl80211_commands cmd, struct nlattr *addr)
1218         union wpa_event_data event;
1219         enum wpa_event_type ev;
1221         if (nla_len(addr) != ETH_ALEN)
1222                 return;
1224         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d; timeout with " MACSTR,
1225                    cmd, MAC2STR((u8 *) nla_data(addr)));
1227         if (cmd == NL80211_CMD_AUTHENTICATE)
1228                 ev = EVENT_AUTH_TIMED_OUT;
1229         else if (cmd == NL80211_CMD_ASSOCIATE)
1230                 ev = EVENT_ASSOC_TIMED_OUT;
1231         else
1232                 return;
1234         os_memset(&event, 0, sizeof(event));
1235         os_memcpy(event.timeout_event.addr, nla_data(addr), ETH_ALEN);
1236         wpa_supplicant_event(drv->ctx, ev, &event);
1240 static void mlme_event_mgmt(struct wpa_driver_nl80211_data *drv,
1241                             struct nlattr *freq, const u8 *frame, size_t len)
1243         const struct ieee80211_mgmt *mgmt;
1244         union wpa_event_data event;
1245         u16 fc, stype;
1247         mgmt = (const struct ieee80211_mgmt *) frame;
1248         if (len < 24) {
1249                 wpa_printf(MSG_DEBUG, "nl80211: Too short action frame");
1250                 return;
1251         }
1253         fc = le_to_host16(mgmt->frame_control);
1254         stype = WLAN_FC_GET_STYPE(fc);
1256         os_memset(&event, 0, sizeof(event));
1257         if (freq) {
1258                 event.rx_action.freq = nla_get_u32(freq);
1259                 drv->last_mgmt_freq = event.rx_action.freq;
1260         }
1261         if (stype == WLAN_FC_STYPE_ACTION) {
1262                 event.rx_action.da = mgmt->da;
1263                 event.rx_action.sa = mgmt->sa;
1264                 event.rx_action.bssid = mgmt->bssid;
1265                 event.rx_action.category = mgmt->u.action.category;
1266                 event.rx_action.data = &mgmt->u.action.category + 1;
1267                 event.rx_action.len = frame + len - event.rx_action.data;
1268                 wpa_supplicant_event(drv->ctx, EVENT_RX_ACTION, &event);
1269         } else {
1270                 event.rx_mgmt.frame = frame;
1271                 event.rx_mgmt.frame_len = len;
1272                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
1273         }
1277 static void mlme_event_mgmt_tx_status(struct wpa_driver_nl80211_data *drv,
1278                                       struct nlattr *cookie, const u8 *frame,
1279                                       size_t len, struct nlattr *ack)
1281         union wpa_event_data event;
1282         const struct ieee80211_hdr *hdr;
1283         u16 fc;
1285         if (!is_ap_interface(drv->nlmode)) {
1286                 u64 cookie_val;
1288                 if (!cookie)
1289                         return;
1291                 cookie_val = nla_get_u64(cookie);
1292                 wpa_printf(MSG_DEBUG, "nl80211: Action TX status:"
1293                            " cookie=0%llx%s (ack=%d)",
1294                            (long long unsigned int) cookie_val,
1295                            cookie_val == drv->send_action_cookie ?
1296                            " (match)" : " (unknown)", ack != NULL);
1297                 if (cookie_val != drv->send_action_cookie)
1298                         return;
1299         }
1301         hdr = (const struct ieee80211_hdr *) frame;
1302         fc = le_to_host16(hdr->frame_control);
1304         os_memset(&event, 0, sizeof(event));
1305         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
1306         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
1307         event.tx_status.dst = hdr->addr1;
1308         event.tx_status.data = frame;
1309         event.tx_status.data_len = len;
1310         event.tx_status.ack = ack != NULL;
1311         wpa_supplicant_event(drv->ctx, EVENT_TX_STATUS, &event);
1315 static void mlme_event_deauth_disassoc(struct wpa_driver_nl80211_data *drv,
1316                                        enum wpa_event_type type,
1317                                        const u8 *frame, size_t len)
1319         const struct ieee80211_mgmt *mgmt;
1320         union wpa_event_data event;
1321         const u8 *bssid = NULL;
1322         u16 reason_code = 0;
1324         mgmt = (const struct ieee80211_mgmt *) frame;
1325         if (len >= 24) {
1326                 bssid = mgmt->bssid;
1328                 if (drv->associated != 0 &&
1329                     os_memcmp(bssid, drv->bssid, ETH_ALEN) != 0 &&
1330                     os_memcmp(bssid, drv->auth_bssid, ETH_ALEN) != 0) {
1331                         /*
1332                          * We have presumably received this deauth as a
1333                          * response to a clear_state_mismatch() outgoing
1334                          * deauth.  Don't let it take us offline!
1335                          */
1336                         wpa_printf(MSG_DEBUG, "nl80211: Deauth received "
1337                                    "from Unknown BSSID " MACSTR " -- ignoring",
1338                                    MAC2STR(bssid));
1339                         return;
1340                 }
1341         }
1343         drv->associated = 0;
1344         os_memset(&event, 0, sizeof(event));
1346         /* Note: Same offset for Reason Code in both frame subtypes */
1347         if (len >= 24 + sizeof(mgmt->u.deauth))
1348                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
1350         if (type == EVENT_DISASSOC) {
1351                 event.disassoc_info.locally_generated =
1352                         !os_memcmp(mgmt->sa, drv->first_bss.addr, ETH_ALEN);
1353 #ifdef ANDROID_BRCM_P2P_PATCH
1354                 if (is_ap_interface(drv->nlmode)) {
1355                         event.disassoc_info.addr = mgmt->sa;
1356                 } else
1357 #endif /* ANDROID_BRCM_P2P_PATCH */
1358                 event.disassoc_info.addr = bssid;
1359                 event.disassoc_info.reason_code = reason_code;
1360                 if (frame + len > mgmt->u.disassoc.variable) {
1361                         event.disassoc_info.ie = mgmt->u.disassoc.variable;
1362                         event.disassoc_info.ie_len = frame + len -
1363                                 mgmt->u.disassoc.variable;
1364                 }
1365         } else {
1366                 event.deauth_info.locally_generated =
1367                         !os_memcmp(mgmt->sa, drv->first_bss.addr, ETH_ALEN);
1368 #ifdef ANDROID_BRCM_P2P_PATCH
1369                 if (is_ap_interface(drv->nlmode)) {
1370                         event.deauth_info.addr = mgmt->sa;
1371                 } else
1372 #endif /* ANDROID_BRCM_P2P_PATCH */
1373                 event.deauth_info.addr = bssid;
1374                 event.deauth_info.reason_code = reason_code;
1375                 if (frame + len > mgmt->u.deauth.variable) {
1376                         event.deauth_info.ie = mgmt->u.deauth.variable;
1377                         event.deauth_info.ie_len = frame + len -
1378                                 mgmt->u.deauth.variable;
1379                 }
1380         }
1382         wpa_supplicant_event(drv->ctx, type, &event);
1386 static void mlme_event_unprot_disconnect(struct wpa_driver_nl80211_data *drv,
1387                                          enum wpa_event_type type,
1388                                          const u8 *frame, size_t len)
1390         const struct ieee80211_mgmt *mgmt;
1391         union wpa_event_data event;
1392         u16 reason_code = 0;
1394         if (len < 24)
1395                 return;
1397         mgmt = (const struct ieee80211_mgmt *) frame;
1399         os_memset(&event, 0, sizeof(event));
1400         /* Note: Same offset for Reason Code in both frame subtypes */
1401         if (len >= 24 + sizeof(mgmt->u.deauth))
1402                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
1404         if (type == EVENT_UNPROT_DISASSOC) {
1405                 event.unprot_disassoc.sa = mgmt->sa;
1406                 event.unprot_disassoc.da = mgmt->da;
1407                 event.unprot_disassoc.reason_code = reason_code;
1408         } else {
1409                 event.unprot_deauth.sa = mgmt->sa;
1410                 event.unprot_deauth.da = mgmt->da;
1411                 event.unprot_deauth.reason_code = reason_code;
1412         }
1414         wpa_supplicant_event(drv->ctx, type, &event);
1418 static void mlme_event(struct wpa_driver_nl80211_data *drv,
1419                        enum nl80211_commands cmd, struct nlattr *frame,
1420                        struct nlattr *addr, struct nlattr *timed_out,
1421                        struct nlattr *freq, struct nlattr *ack,
1422                        struct nlattr *cookie)
1424         if (timed_out && addr) {
1425                 mlme_timeout_event(drv, cmd, addr);
1426                 return;
1427         }
1429         if (frame == NULL) {
1430                 wpa_printf(MSG_DEBUG, "nl80211: MLME event %d without frame "
1431                            "data", cmd);
1432                 return;
1433         }
1435         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d", cmd);
1436         wpa_hexdump(MSG_MSGDUMP, "nl80211: MLME event frame",
1437                     nla_data(frame), nla_len(frame));
1439         switch (cmd) {
1440         case NL80211_CMD_AUTHENTICATE:
1441                 mlme_event_auth(drv, nla_data(frame), nla_len(frame));
1442                 break;
1443         case NL80211_CMD_ASSOCIATE:
1444                 mlme_event_assoc(drv, nla_data(frame), nla_len(frame));
1445                 break;
1446         case NL80211_CMD_DEAUTHENTICATE:
1447                 mlme_event_deauth_disassoc(drv, EVENT_DEAUTH,
1448                                            nla_data(frame), nla_len(frame));
1449                 break;
1450         case NL80211_CMD_DISASSOCIATE:
1451                 mlme_event_deauth_disassoc(drv, EVENT_DISASSOC,
1452                                            nla_data(frame), nla_len(frame));
1453                 break;
1454         case NL80211_CMD_FRAME:
1455                 mlme_event_mgmt(drv, freq, nla_data(frame), nla_len(frame));
1456                 break;
1457         case NL80211_CMD_FRAME_TX_STATUS:
1458                 mlme_event_mgmt_tx_status(drv, cookie, nla_data(frame),
1459                                           nla_len(frame), ack);
1460                 break;
1461         case NL80211_CMD_UNPROT_DEAUTHENTICATE:
1462                 mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DEAUTH,
1463                                              nla_data(frame), nla_len(frame));
1464                 break;
1465         case NL80211_CMD_UNPROT_DISASSOCIATE:
1466                 mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DISASSOC,
1467                                              nla_data(frame), nla_len(frame));
1468                 break;
1469         default:
1470                 break;
1471         }
1475 static void mlme_event_michael_mic_failure(struct wpa_driver_nl80211_data *drv,
1476                                            struct nlattr *tb[])
1478         union wpa_event_data data;
1480         wpa_printf(MSG_DEBUG, "nl80211: MLME event Michael MIC failure");
1481         os_memset(&data, 0, sizeof(data));
1482         if (tb[NL80211_ATTR_MAC]) {
1483                 wpa_hexdump(MSG_DEBUG, "nl80211: Source MAC address",
1484                             nla_data(tb[NL80211_ATTR_MAC]),
1485                             nla_len(tb[NL80211_ATTR_MAC]));
1486                 data.michael_mic_failure.src = nla_data(tb[NL80211_ATTR_MAC]);
1487         }
1488         if (tb[NL80211_ATTR_KEY_SEQ]) {
1489                 wpa_hexdump(MSG_DEBUG, "nl80211: TSC",
1490                             nla_data(tb[NL80211_ATTR_KEY_SEQ]),
1491                             nla_len(tb[NL80211_ATTR_KEY_SEQ]));
1492         }
1493         if (tb[NL80211_ATTR_KEY_TYPE]) {
1494                 enum nl80211_key_type key_type =
1495                         nla_get_u32(tb[NL80211_ATTR_KEY_TYPE]);
1496                 wpa_printf(MSG_DEBUG, "nl80211: Key Type %d", key_type);
1497                 if (key_type == NL80211_KEYTYPE_PAIRWISE)
1498                         data.michael_mic_failure.unicast = 1;
1499         } else
1500                 data.michael_mic_failure.unicast = 1;
1502         if (tb[NL80211_ATTR_KEY_IDX]) {
1503                 u8 key_id = nla_get_u8(tb[NL80211_ATTR_KEY_IDX]);
1504                 wpa_printf(MSG_DEBUG, "nl80211: Key Id %d", key_id);
1505         }
1507         wpa_supplicant_event(drv->ctx, EVENT_MICHAEL_MIC_FAILURE, &data);
1511 static void mlme_event_join_ibss(struct wpa_driver_nl80211_data *drv,
1512                                  struct nlattr *tb[])
1514         if (tb[NL80211_ATTR_MAC] == NULL) {
1515                 wpa_printf(MSG_DEBUG, "nl80211: No address in IBSS joined "
1516                            "event");
1517                 return;
1518         }
1519         os_memcpy(drv->bssid, nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
1520         drv->associated = 1;
1521         wpa_printf(MSG_DEBUG, "nl80211: IBSS " MACSTR " joined",
1522                    MAC2STR(drv->bssid));
1524         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, NULL);
1528 static void mlme_event_remain_on_channel(struct wpa_driver_nl80211_data *drv,
1529                                          int cancel_event, struct nlattr *tb[])
1531         unsigned int freq, chan_type, duration;
1532         union wpa_event_data data;
1533         u64 cookie;
1535         if (tb[NL80211_ATTR_WIPHY_FREQ])
1536                 freq = nla_get_u32(tb[NL80211_ATTR_WIPHY_FREQ]);
1537         else
1538                 freq = 0;
1540         if (tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE])
1541                 chan_type = nla_get_u32(tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
1542         else
1543                 chan_type = 0;
1545         if (tb[NL80211_ATTR_DURATION])
1546                 duration = nla_get_u32(tb[NL80211_ATTR_DURATION]);
1547         else
1548                 duration = 0;
1550         if (tb[NL80211_ATTR_COOKIE])
1551                 cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
1552         else
1553                 cookie = 0;
1555         wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel event (cancel=%d "
1556                    "freq=%u channel_type=%u duration=%u cookie=0x%llx (%s))",
1557                    cancel_event, freq, chan_type, duration,
1558                    (long long unsigned int) cookie,
1559                    cookie == drv->remain_on_chan_cookie ? "match" : "unknown");
1561         if (cookie != drv->remain_on_chan_cookie)
1562                 return; /* not for us */
1564         if (cancel_event)
1565                 drv->pending_remain_on_chan = 0;
1567         os_memset(&data, 0, sizeof(data));
1568         data.remain_on_channel.freq = freq;
1569         data.remain_on_channel.duration = duration;
1570         wpa_supplicant_event(drv->ctx, cancel_event ?
1571                              EVENT_CANCEL_REMAIN_ON_CHANNEL :
1572                              EVENT_REMAIN_ON_CHANNEL, &data);
1576 static void send_scan_event(struct wpa_driver_nl80211_data *drv, int aborted,
1577                             struct nlattr *tb[])
1579         union wpa_event_data event;
1580         struct nlattr *nl;
1581         int rem;
1582         struct scan_info *info;
1583 #define MAX_REPORT_FREQS 50
1584         int freqs[MAX_REPORT_FREQS];
1585         int num_freqs = 0;
1587         if (drv->scan_for_auth) {
1588                 drv->scan_for_auth = 0;
1589                 wpa_printf(MSG_DEBUG, "nl80211: Scan results for missing "
1590                            "cfg80211 BSS entry");
1591                 wpa_driver_nl80211_authenticate_retry(drv);
1592                 return;
1593         }
1595         os_memset(&event, 0, sizeof(event));
1596         info = &event.scan_info;
1597         info->aborted = aborted;
1599         if (tb[NL80211_ATTR_SCAN_SSIDS]) {
1600                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_SSIDS], rem) {
1601                         struct wpa_driver_scan_ssid *s =
1602                                 &info->ssids[info->num_ssids];
1603                         s->ssid = nla_data(nl);
1604                         s->ssid_len = nla_len(nl);
1605                         info->num_ssids++;
1606                         if (info->num_ssids == WPAS_MAX_SCAN_SSIDS)
1607                                 break;
1608                 }
1609         }
1610         if (tb[NL80211_ATTR_SCAN_FREQUENCIES]) {
1611                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_FREQUENCIES], rem)
1612                 {
1613                         freqs[num_freqs] = nla_get_u32(nl);
1614                         num_freqs++;
1615                         if (num_freqs == MAX_REPORT_FREQS - 1)
1616                                 break;
1617                 }
1618                 info->freqs = freqs;
1619                 info->num_freqs = num_freqs;
1620         }
1621         wpa_supplicant_event(drv->ctx, EVENT_SCAN_RESULTS, &event);
1625 static int get_link_signal(struct nl_msg *msg, void *arg)
1627         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1628         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1629         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
1630         static struct nla_policy policy[NL80211_STA_INFO_MAX + 1] = {
1631                 [NL80211_STA_INFO_SIGNAL] = { .type = NLA_U8 },
1632         };
1633         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
1634         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
1635                 [NL80211_RATE_INFO_BITRATE] = { .type = NLA_U16 },
1636                 [NL80211_RATE_INFO_MCS] = { .type = NLA_U8 },
1637                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG },
1638                 [NL80211_RATE_INFO_SHORT_GI] = { .type = NLA_FLAG },
1639         };
1640         struct wpa_signal_info *sig_change = arg;
1642         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1643                   genlmsg_attrlen(gnlh, 0), NULL);
1644         if (!tb[NL80211_ATTR_STA_INFO] ||
1645             nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
1646                              tb[NL80211_ATTR_STA_INFO], policy))
1647                 return NL_SKIP;
1648         if (!sinfo[NL80211_STA_INFO_SIGNAL])
1649                 return NL_SKIP;
1651         sig_change->current_signal =
1652                 (s8) nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
1654         if (sinfo[NL80211_STA_INFO_TX_BITRATE]) {
1655                 if (nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1656                                      sinfo[NL80211_STA_INFO_TX_BITRATE],
1657                                      rate_policy)) {
1658                         sig_change->current_txrate = 0;
1659                 } else {
1660                         if (rinfo[NL80211_RATE_INFO_BITRATE]) {
1661                                 sig_change->current_txrate =
1662                                         nla_get_u16(rinfo[
1663                                              NL80211_RATE_INFO_BITRATE]) * 100;
1664                         }
1665                 }
1666         }
1668         return NL_SKIP;
1672 static int nl80211_get_link_signal(struct wpa_driver_nl80211_data *drv,
1673                                    struct wpa_signal_info *sig)
1675         struct nl_msg *msg;
1677         sig->current_signal = -9999;
1678         sig->current_txrate = 0;
1680         msg = nlmsg_alloc();
1681         if (!msg)
1682                 return -ENOMEM;
1684         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
1686         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1687         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
1689         return send_and_recv_msgs(drv, msg, get_link_signal, sig);
1690  nla_put_failure:
1691         nlmsg_free(msg);
1692         return -ENOBUFS;
1696 static int get_link_noise(struct nl_msg *msg, void *arg)
1698         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1699         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1700         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1701         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1702                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1703                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
1704         };
1705         struct wpa_signal_info *sig_change = arg;
1707         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1708                   genlmsg_attrlen(gnlh, 0), NULL);
1710         if (!tb[NL80211_ATTR_SURVEY_INFO]) {
1711                 wpa_printf(MSG_DEBUG, "nl80211: survey data missing!");
1712                 return NL_SKIP;
1713         }
1715         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1716                              tb[NL80211_ATTR_SURVEY_INFO],
1717                              survey_policy)) {
1718                 wpa_printf(MSG_DEBUG, "nl80211: failed to parse nested "
1719                            "attributes!");
1720                 return NL_SKIP;
1721         }
1723         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1724                 return NL_SKIP;
1726         if (nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
1727             sig_change->frequency)
1728                 return NL_SKIP;
1730         if (!sinfo[NL80211_SURVEY_INFO_NOISE])
1731                 return NL_SKIP;
1733         sig_change->current_noise =
1734                 (s8) nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1736         return NL_SKIP;
1740 static int nl80211_get_link_noise(struct wpa_driver_nl80211_data *drv,
1741                                   struct wpa_signal_info *sig_change)
1743         struct nl_msg *msg;
1745         sig_change->current_noise = 9999;
1746         sig_change->frequency = drv->assoc_freq;
1748         msg = nlmsg_alloc();
1749         if (!msg)
1750                 return -ENOMEM;
1752         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
1754         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1756         return send_and_recv_msgs(drv, msg, get_link_noise, sig_change);
1757  nla_put_failure:
1758         nlmsg_free(msg);
1759         return -ENOBUFS;
1763 static int get_noise_for_scan_results(struct nl_msg *msg, void *arg)
1765         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1766         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1767         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1768         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1769                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1770                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
1771         };
1772         struct wpa_scan_results *scan_results = arg;
1773         struct wpa_scan_res *scan_res;
1774         size_t i;
1776         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1777                   genlmsg_attrlen(gnlh, 0), NULL);
1779         if (!tb[NL80211_ATTR_SURVEY_INFO]) {
1780                 wpa_printf(MSG_DEBUG, "nl80211: Survey data missing");
1781                 return NL_SKIP;
1782         }
1784         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1785                              tb[NL80211_ATTR_SURVEY_INFO],
1786                              survey_policy)) {
1787                 wpa_printf(MSG_DEBUG, "nl80211: Failed to parse nested "
1788                            "attributes");
1789                 return NL_SKIP;
1790         }
1792         if (!sinfo[NL80211_SURVEY_INFO_NOISE])
1793                 return NL_SKIP;
1795         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1796                 return NL_SKIP;
1798         for (i = 0; i < scan_results->num; ++i) {
1799                 scan_res = scan_results->res[i];
1800                 if (!scan_res)
1801                         continue;
1802                 if ((int) nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
1803                     scan_res->freq)
1804                         continue;
1805                 if (!(scan_res->flags & WPA_SCAN_NOISE_INVALID))
1806                         continue;
1807                 scan_res->noise = (s8)
1808                         nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1809                 scan_res->flags &= ~WPA_SCAN_NOISE_INVALID;
1810         }
1812         return NL_SKIP;
1816 static int nl80211_get_noise_for_scan_results(
1817         struct wpa_driver_nl80211_data *drv,
1818         struct wpa_scan_results *scan_res)
1820         struct nl_msg *msg;
1822         msg = nlmsg_alloc();
1823         if (!msg)
1824                 return -ENOMEM;
1826         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
1828         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1830         return send_and_recv_msgs(drv, msg, get_noise_for_scan_results,
1831                                   scan_res);
1832  nla_put_failure:
1833         nlmsg_free(msg);
1834         return -ENOBUFS;
1838 static void nl80211_cqm_event(struct wpa_driver_nl80211_data *drv,
1839                               struct nlattr *tb[])
1841         static struct nla_policy cqm_policy[NL80211_ATTR_CQM_MAX + 1] = {
1842                 [NL80211_ATTR_CQM_RSSI_THOLD] = { .type = NLA_U32 },
1843                 [NL80211_ATTR_CQM_RSSI_HYST] = { .type = NLA_U8 },
1844                 [NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] = { .type = NLA_U32 },
1845                 [NL80211_ATTR_CQM_PKT_LOSS_EVENT] = { .type = NLA_U32 },
1846         };
1847         struct nlattr *cqm[NL80211_ATTR_CQM_MAX + 1];
1848         enum nl80211_cqm_rssi_threshold_event event;
1849         union wpa_event_data ed;
1850         struct wpa_signal_info sig;
1851         int res;
1853         if (tb[NL80211_ATTR_CQM] == NULL ||
1854             nla_parse_nested(cqm, NL80211_ATTR_CQM_MAX, tb[NL80211_ATTR_CQM],
1855                              cqm_policy)) {
1856                 wpa_printf(MSG_DEBUG, "nl80211: Ignore invalid CQM event");
1857                 return;
1858         }
1860         os_memset(&ed, 0, sizeof(ed));
1862         if (cqm[NL80211_ATTR_CQM_PKT_LOSS_EVENT]) {
1863                 if (!tb[NL80211_ATTR_MAC])
1864                         return;
1865                 os_memcpy(ed.low_ack.addr, nla_data(tb[NL80211_ATTR_MAC]),
1866                           ETH_ALEN);
1867                 wpa_supplicant_event(drv->ctx, EVENT_STATION_LOW_ACK, &ed);
1868                 return;
1869         }
1871         if (cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] == NULL)
1872                 return;
1873         event = nla_get_u32(cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]);
1875         if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH) {
1876                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1877                            "event: RSSI high");
1878                 ed.signal_change.above_threshold = 1;
1879         } else if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW) {
1880                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1881                            "event: RSSI low");
1882                 ed.signal_change.above_threshold = 0;
1883         } else
1884                 return;
1886         res = nl80211_get_link_signal(drv, &sig);
1887         if (res == 0) {
1888                 ed.signal_change.current_signal = sig.current_signal;
1889                 ed.signal_change.current_txrate = sig.current_txrate;
1890                 wpa_printf(MSG_DEBUG, "nl80211: Signal: %d dBm  txrate: %d",
1891                            sig.current_signal, sig.current_txrate);
1892         }
1894         res = nl80211_get_link_noise(drv, &sig);
1895         if (res == 0) {
1896                 ed.signal_change.current_noise = sig.current_noise;
1897                 wpa_printf(MSG_DEBUG, "nl80211: Noise: %d dBm",
1898                            sig.current_noise);
1899         }
1901         wpa_supplicant_event(drv->ctx, EVENT_SIGNAL_CHANGE, &ed);
1905 static void nl80211_new_station_event(struct wpa_driver_nl80211_data *drv,
1906                                       struct nlattr **tb)
1908         u8 *addr;
1909         union wpa_event_data data;
1911         if (tb[NL80211_ATTR_MAC] == NULL)
1912                 return;
1913         addr = nla_data(tb[NL80211_ATTR_MAC]);
1914         wpa_printf(MSG_DEBUG, "nl80211: New station " MACSTR, MAC2STR(addr));
1916         if (is_ap_interface(drv->nlmode) && drv->device_ap_sme) {
1917                 u8 *ies = NULL;
1918                 size_t ies_len = 0;
1919                 if (tb[NL80211_ATTR_IE]) {
1920                         ies = nla_data(tb[NL80211_ATTR_IE]);
1921                         ies_len = nla_len(tb[NL80211_ATTR_IE]);
1922                 }
1923                 wpa_hexdump(MSG_DEBUG, "nl80211: Assoc Req IEs", ies, ies_len);
1924                 drv_event_assoc(drv->ctx, addr, ies, ies_len, 0);
1925                 return;
1926         }
1928         if (drv->nlmode != NL80211_IFTYPE_ADHOC)
1929                 return;
1931         os_memset(&data, 0, sizeof(data));
1932         os_memcpy(data.ibss_rsn_start.peer, addr, ETH_ALEN);
1933         wpa_supplicant_event(drv->ctx, EVENT_IBSS_RSN_START, &data);
1937 static void nl80211_del_station_event(struct wpa_driver_nl80211_data *drv,
1938                                       struct nlattr **tb)
1940         u8 *addr;
1941         union wpa_event_data data;
1943         if (tb[NL80211_ATTR_MAC] == NULL)
1944                 return;
1945         addr = nla_data(tb[NL80211_ATTR_MAC]);
1946         wpa_printf(MSG_DEBUG, "nl80211: Delete station " MACSTR,
1947                    MAC2STR(addr));
1949         if (is_ap_interface(drv->nlmode) && drv->device_ap_sme) {
1950                 drv_event_disassoc(drv->ctx, addr);
1951                 return;
1952         }
1954         if (drv->nlmode != NL80211_IFTYPE_ADHOC)
1955                 return;
1957         os_memset(&data, 0, sizeof(data));
1958         os_memcpy(data.ibss_peer_lost.peer, addr, ETH_ALEN);
1959         wpa_supplicant_event(drv->ctx, EVENT_IBSS_PEER_LOST, &data);
1963 static void nl80211_rekey_offload_event(struct wpa_driver_nl80211_data *drv,
1964                                         struct nlattr **tb)
1966         struct nlattr *rekey_info[NUM_NL80211_REKEY_DATA];
1967         static struct nla_policy rekey_policy[NUM_NL80211_REKEY_DATA] = {
1968                 [NL80211_REKEY_DATA_KEK] = {
1969                         .minlen = NL80211_KEK_LEN,
1970                         .maxlen = NL80211_KEK_LEN,
1971                 },
1972                 [NL80211_REKEY_DATA_KCK] = {
1973                         .minlen = NL80211_KCK_LEN,
1974                         .maxlen = NL80211_KCK_LEN,
1975                 },
1976                 [NL80211_REKEY_DATA_REPLAY_CTR] = {
1977                         .minlen = NL80211_REPLAY_CTR_LEN,
1978                         .maxlen = NL80211_REPLAY_CTR_LEN,
1979                 },
1980         };
1981         union wpa_event_data data;
1983         if (!tb[NL80211_ATTR_MAC])
1984                 return;
1985         if (!tb[NL80211_ATTR_REKEY_DATA])
1986                 return;
1987         if (nla_parse_nested(rekey_info, MAX_NL80211_REKEY_DATA,
1988                              tb[NL80211_ATTR_REKEY_DATA], rekey_policy))
1989                 return;
1990         if (!rekey_info[NL80211_REKEY_DATA_REPLAY_CTR])
1991                 return;
1993         os_memset(&data, 0, sizeof(data));
1994         data.driver_gtk_rekey.bssid = nla_data(tb[NL80211_ATTR_MAC]);
1995         wpa_printf(MSG_DEBUG, "nl80211: Rekey offload event for BSSID " MACSTR,
1996                    MAC2STR(data.driver_gtk_rekey.bssid));
1997         data.driver_gtk_rekey.replay_ctr =
1998                 nla_data(rekey_info[NL80211_REKEY_DATA_REPLAY_CTR]);
1999         wpa_hexdump(MSG_DEBUG, "nl80211: Rekey offload - Replay Counter",
2000                     data.driver_gtk_rekey.replay_ctr, NL80211_REPLAY_CTR_LEN);
2001         wpa_supplicant_event(drv->ctx, EVENT_DRIVER_GTK_REKEY, &data);
2005 static void nl80211_pmksa_candidate_event(struct wpa_driver_nl80211_data *drv,
2006                                           struct nlattr **tb)
2008         struct nlattr *cand[NUM_NL80211_PMKSA_CANDIDATE];
2009         static struct nla_policy cand_policy[NUM_NL80211_PMKSA_CANDIDATE] = {
2010                 [NL80211_PMKSA_CANDIDATE_INDEX] = { .type = NLA_U32 },
2011                 [NL80211_PMKSA_CANDIDATE_BSSID] = {
2012                         .minlen = ETH_ALEN,
2013                         .maxlen = ETH_ALEN,
2014                 },
2015                 [NL80211_PMKSA_CANDIDATE_PREAUTH] = { .type = NLA_FLAG },
2016         };
2017         union wpa_event_data data;
2019         if (!tb[NL80211_ATTR_PMKSA_CANDIDATE])
2020                 return;
2021         if (nla_parse_nested(cand, MAX_NL80211_PMKSA_CANDIDATE,
2022                              tb[NL80211_ATTR_PMKSA_CANDIDATE], cand_policy))
2023                 return;
2024         if (!cand[NL80211_PMKSA_CANDIDATE_INDEX] ||
2025             !cand[NL80211_PMKSA_CANDIDATE_BSSID])
2026                 return;
2028         os_memset(&data, 0, sizeof(data));
2029         os_memcpy(data.pmkid_candidate.bssid,
2030                   nla_data(cand[NL80211_PMKSA_CANDIDATE_BSSID]), ETH_ALEN);
2031         data.pmkid_candidate.index =
2032                 nla_get_u32(cand[NL80211_PMKSA_CANDIDATE_INDEX]);
2033         data.pmkid_candidate.preauth =
2034                 cand[NL80211_PMKSA_CANDIDATE_PREAUTH] != NULL;
2035         wpa_supplicant_event(drv->ctx, EVENT_PMKID_CANDIDATE, &data);
2039 static void nl80211_client_probe_event(struct wpa_driver_nl80211_data *drv,
2040                                        struct nlattr **tb)
2042         union wpa_event_data data;
2044         if (!tb[NL80211_ATTR_MAC] || !tb[NL80211_ATTR_ACK])
2045                 return;
2047         os_memset(&data, 0, sizeof(data));
2048         os_memcpy(data.client_poll.addr,
2049                   nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2051         wpa_supplicant_event(drv->ctx, EVENT_DRIVER_CLIENT_POLL_OK, &data);
2055 static void nl80211_spurious_frame(struct i802_bss *bss, struct nlattr **tb,
2056                                    int wds)
2058         struct wpa_driver_nl80211_data *drv = bss->drv;
2059         union wpa_event_data event;
2061         if (!tb[NL80211_ATTR_MAC])
2062                 return;
2064         os_memset(&event, 0, sizeof(event));
2065         event.rx_from_unknown.bssid = bss->addr;
2066         event.rx_from_unknown.addr = nla_data(tb[NL80211_ATTR_MAC]);
2067         event.rx_from_unknown.wds = wds;
2069         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
2073 static void do_process_drv_event(struct wpa_driver_nl80211_data *drv,
2074                                  int cmd, struct nlattr **tb)
2076         if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED &&
2077             (cmd == NL80211_CMD_NEW_SCAN_RESULTS ||
2078              cmd == NL80211_CMD_SCAN_ABORTED)) {
2079                 wpa_driver_nl80211_set_mode(&drv->first_bss,
2080                                             drv->ap_scan_as_station);
2081                 drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
2082         }
2084         switch (cmd) {
2085         case NL80211_CMD_TRIGGER_SCAN:
2086                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger");
2087                 break;
2088         case NL80211_CMD_START_SCHED_SCAN:
2089                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan started");
2090                 break;
2091         case NL80211_CMD_SCHED_SCAN_STOPPED:
2092                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan stopped");
2093                 wpa_supplicant_event(drv->ctx, EVENT_SCHED_SCAN_STOPPED, NULL);
2094                 break;
2095         case NL80211_CMD_NEW_SCAN_RESULTS:
2096                 wpa_printf(MSG_DEBUG, "nl80211: New scan results available");
2097                 drv->scan_complete_events = 1;
2098                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
2099                                      drv->ctx);
2100                 send_scan_event(drv, 0, tb);
2101                 break;
2102         case NL80211_CMD_SCHED_SCAN_RESULTS:
2103                 wpa_printf(MSG_DEBUG,
2104                            "nl80211: New sched scan results available");
2105                 send_scan_event(drv, 0, tb);
2106                 break;
2107         case NL80211_CMD_SCAN_ABORTED:
2108                 wpa_printf(MSG_DEBUG, "nl80211: Scan aborted");
2109                 /*
2110                  * Need to indicate that scan results are available in order
2111                  * not to make wpa_supplicant stop its scanning.
2112                  */
2113                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
2114                                      drv->ctx);
2115                 send_scan_event(drv, 1, tb);
2116                 break;
2117         case NL80211_CMD_AUTHENTICATE:
2118         case NL80211_CMD_ASSOCIATE:
2119         case NL80211_CMD_DEAUTHENTICATE:
2120         case NL80211_CMD_DISASSOCIATE:
2121         case NL80211_CMD_FRAME_TX_STATUS:
2122         case NL80211_CMD_UNPROT_DEAUTHENTICATE:
2123         case NL80211_CMD_UNPROT_DISASSOCIATE:
2124                 mlme_event(drv, cmd, tb[NL80211_ATTR_FRAME],
2125                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
2126                            tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
2127                            tb[NL80211_ATTR_COOKIE]);
2128                 break;
2129         case NL80211_CMD_CONNECT:
2130         case NL80211_CMD_ROAM:
2131                 mlme_event_connect(drv, cmd,
2132                                    tb[NL80211_ATTR_STATUS_CODE],
2133                                    tb[NL80211_ATTR_MAC],
2134                                    tb[NL80211_ATTR_REQ_IE],
2135                                    tb[NL80211_ATTR_RESP_IE]);
2136                 break;
2137         case NL80211_CMD_DISCONNECT:
2138                 mlme_event_disconnect(drv, tb[NL80211_ATTR_REASON_CODE],
2139                                       tb[NL80211_ATTR_MAC],
2140                                       tb[NL80211_ATTR_DISCONNECTED_BY_AP]);
2141                 break;
2142         case NL80211_CMD_MICHAEL_MIC_FAILURE:
2143                 mlme_event_michael_mic_failure(drv, tb);
2144                 break;
2145         case NL80211_CMD_JOIN_IBSS:
2146                 mlme_event_join_ibss(drv, tb);
2147                 break;
2148         case NL80211_CMD_REMAIN_ON_CHANNEL:
2149                 mlme_event_remain_on_channel(drv, 0, tb);
2150                 break;
2151         case NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL:
2152                 mlme_event_remain_on_channel(drv, 1, tb);
2153                 break;
2154         case NL80211_CMD_NOTIFY_CQM:
2155                 nl80211_cqm_event(drv, tb);
2156                 break;
2157         case NL80211_CMD_REG_CHANGE:
2158                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory domain change");
2159                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
2160                                      NULL);
2161                 break;
2162         case NL80211_CMD_REG_BEACON_HINT:
2163                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory beacon hint");
2164                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
2165                                      NULL);
2166                 break;
2167         case NL80211_CMD_NEW_STATION:
2168                 nl80211_new_station_event(drv, tb);
2169                 break;
2170         case NL80211_CMD_DEL_STATION:
2171                 nl80211_del_station_event(drv, tb);
2172                 break;
2173         case NL80211_CMD_SET_REKEY_OFFLOAD:
2174                 nl80211_rekey_offload_event(drv, tb);
2175                 break;
2176         case NL80211_CMD_PMKSA_CANDIDATE:
2177                 nl80211_pmksa_candidate_event(drv, tb);
2178                 break;
2179         case NL80211_CMD_PROBE_CLIENT:
2180                 nl80211_client_probe_event(drv, tb);
2181                 break;
2182         default:
2183                 wpa_printf(MSG_DEBUG, "nl80211: Ignored unknown event "
2184                            "(cmd=%d)", cmd);
2185                 break;
2186         }
2190 static int process_drv_event(struct nl_msg *msg, void *arg)
2192         struct wpa_driver_nl80211_data *drv = arg;
2193         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2194         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2196         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2197                   genlmsg_attrlen(gnlh, 0), NULL);
2199         if (tb[NL80211_ATTR_IFINDEX]) {
2200                 int ifindex = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
2201                 if (ifindex != drv->ifindex && !have_ifidx(drv, ifindex)) {
2202                         wpa_printf(MSG_DEBUG, "nl80211: Ignored event (cmd=%d)"
2203                                    " for foreign interface (ifindex %d)",
2204                                    gnlh->cmd, ifindex);
2205                         return NL_SKIP;
2206                 }
2207         }
2209         do_process_drv_event(drv, gnlh->cmd, tb);
2210         return NL_SKIP;
2214 static int process_global_event(struct nl_msg *msg, void *arg)
2216         struct nl80211_global *global = arg;
2217         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2218         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2219         struct wpa_driver_nl80211_data *drv;
2220         int ifidx = -1;
2222         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2223                   genlmsg_attrlen(gnlh, 0), NULL);
2225         if (tb[NL80211_ATTR_IFINDEX])
2226                 ifidx = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
2228         dl_list_for_each(drv, &global->interfaces,
2229                          struct wpa_driver_nl80211_data, list) {
2230                 if (ifidx == -1 || ifidx == drv->ifindex ||
2231                     have_ifidx(drv, ifidx))
2232                         do_process_drv_event(drv, gnlh->cmd, tb);
2233         }
2235         return NL_SKIP;
2239 static int process_bss_event(struct nl_msg *msg, void *arg)
2241         struct i802_bss *bss = arg;
2242         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2243         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2245         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2246                   genlmsg_attrlen(gnlh, 0), NULL);
2248         switch (gnlh->cmd) {
2249         case NL80211_CMD_FRAME:
2250         case NL80211_CMD_FRAME_TX_STATUS:
2251                 mlme_event(bss->drv, gnlh->cmd, tb[NL80211_ATTR_FRAME],
2252                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
2253                            tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
2254                            tb[NL80211_ATTR_COOKIE]);
2255                 break;
2256         case NL80211_CMD_UNEXPECTED_FRAME:
2257                 nl80211_spurious_frame(bss, tb, 0);
2258                 break;
2259         case NL80211_CMD_UNEXPECTED_4ADDR_FRAME:
2260                 nl80211_spurious_frame(bss, tb, 1);
2261                 break;
2262         default:
2263                 wpa_printf(MSG_DEBUG, "nl80211: Ignored unknown event "
2264                            "(cmd=%d)", gnlh->cmd);
2265                 break;
2266         }
2268         return NL_SKIP;
2272 static void wpa_driver_nl80211_event_receive(int sock, void *eloop_ctx,
2273                                              void *handle)
2275         struct nl_cb *cb = eloop_ctx;
2277         wpa_printf(MSG_DEBUG, "nl80211: Event message available");
2279         nl_recvmsgs(handle, cb);
2283 /**
2284  * wpa_driver_nl80211_set_country - ask nl80211 to set the regulatory domain
2285  * @priv: driver_nl80211 private data
2286  * @alpha2_arg: country to which to switch to
2287  * Returns: 0 on success, -1 on failure
2288  *
2289  * This asks nl80211 to set the regulatory domain for given
2290  * country ISO / IEC alpha2.
2291  */
2292 static int wpa_driver_nl80211_set_country(void *priv, const char *alpha2_arg)
2294         struct i802_bss *bss = priv;
2295         struct wpa_driver_nl80211_data *drv = bss->drv;
2296         char alpha2[3];
2297         struct nl_msg *msg;
2299         msg = nlmsg_alloc();
2300         if (!msg)
2301                 return -ENOMEM;
2303         alpha2[0] = alpha2_arg[0];
2304         alpha2[1] = alpha2_arg[1];
2305         alpha2[2] = '\0';
2307         nl80211_cmd(drv, msg, 0, NL80211_CMD_REQ_SET_REG);
2309         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
2310         if (send_and_recv_msgs(drv, msg, NULL, NULL))
2311                 return -EINVAL;
2312         return 0;
2313 nla_put_failure:
2314         nlmsg_free(msg);
2315         return -EINVAL;
2319 struct wiphy_info_data {
2320         struct wpa_driver_capa *capa;
2322         unsigned int error:1;
2323         unsigned int device_ap_sme:1;
2324         unsigned int poll_command_supported:1;
2325         unsigned int data_tx_status:1;
2326         unsigned int monitor_supported:1;
2327 };
2330 static unsigned int probe_resp_offload_support(int supp_protocols)
2332         unsigned int prot = 0;
2334         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS)
2335                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS;
2336         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2)
2337                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS2;
2338         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P)
2339                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_P2P;
2340         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_80211U)
2341                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_INTERWORKING;
2343         return prot;
2347 static int wiphy_info_handler(struct nl_msg *msg, void *arg)
2349         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2350         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2351         struct wiphy_info_data *info = arg;
2352         int p2p_go_supported = 0, p2p_client_supported = 0;
2353         int p2p_concurrent = 0;
2354         int auth_supported = 0, connect_supported = 0;
2355         struct wpa_driver_capa *capa = info->capa;
2356         static struct nla_policy
2357         iface_combination_policy[NUM_NL80211_IFACE_COMB] = {
2358                 [NL80211_IFACE_COMB_LIMITS] = { .type = NLA_NESTED },
2359                 [NL80211_IFACE_COMB_MAXNUM] = { .type = NLA_U32 },
2360                 [NL80211_IFACE_COMB_STA_AP_BI_MATCH] = { .type = NLA_FLAG },
2361                 [NL80211_IFACE_COMB_NUM_CHANNELS] = { .type = NLA_U32 },
2362         },
2363         iface_limit_policy[NUM_NL80211_IFACE_LIMIT] = {
2364                 [NL80211_IFACE_LIMIT_TYPES] = { .type = NLA_NESTED },
2365                 [NL80211_IFACE_LIMIT_MAX] = { .type = NLA_U32 },
2366         };
2368         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2369                   genlmsg_attrlen(gnlh, 0), NULL);
2371         if (tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS])
2372                 capa->max_scan_ssids =
2373                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS]);
2375         if (tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS])
2376                 capa->max_sched_scan_ssids =
2377                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS]);
2379         if (tb[NL80211_ATTR_MAX_MATCH_SETS])
2380                 capa->max_match_sets =
2381                         nla_get_u8(tb[NL80211_ATTR_MAX_MATCH_SETS]);
2383         if (tb[NL80211_ATTR_SUPPORTED_IFTYPES]) {
2384                 struct nlattr *nl_mode;
2385                 int i;
2386                 nla_for_each_nested(nl_mode,
2387                                     tb[NL80211_ATTR_SUPPORTED_IFTYPES], i) {
2388                         switch (nla_type(nl_mode)) {
2389                         case NL80211_IFTYPE_AP:
2390                                 capa->flags |= WPA_DRIVER_FLAGS_AP;
2391                                 break;
2392                         case NL80211_IFTYPE_P2P_GO:
2393                                 p2p_go_supported = 1;
2394                                 break;
2395                         case NL80211_IFTYPE_P2P_CLIENT:
2396                                 p2p_client_supported = 1;
2397                                 break;
2398                         case NL80211_IFTYPE_MONITOR:
2399                                 info->monitor_supported = 1;
2400                                 break;
2401                         }
2402                 }
2403         }
2405         if (tb[NL80211_ATTR_INTERFACE_COMBINATIONS]) {
2406                 struct nlattr *nl_combi;
2407                 int rem_combi;
2409                 nla_for_each_nested(nl_combi,
2410                                     tb[NL80211_ATTR_INTERFACE_COMBINATIONS],
2411                                     rem_combi) {
2412                         struct nlattr *tb_comb[NUM_NL80211_IFACE_COMB];
2413                         struct nlattr *tb_limit[NUM_NL80211_IFACE_LIMIT];
2414                         struct nlattr *nl_limit, *nl_mode;
2415                         int err, rem_limit, rem_mode;
2416                         int combination_has_p2p = 0, combination_has_mgd = 0;
2418                         err = nla_parse_nested(tb_comb, MAX_NL80211_IFACE_COMB,
2419                                                nl_combi,
2420                                                iface_combination_policy);
2421                         if (err || !tb_comb[NL80211_IFACE_COMB_LIMITS] ||
2422                             !tb_comb[NL80211_IFACE_COMB_MAXNUM] ||
2423                             !tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS])
2424                                 goto broken_combination;
2426                         nla_for_each_nested(nl_limit,
2427                                             tb_comb[NL80211_IFACE_COMB_LIMITS],
2428                                             rem_limit) {
2429                                 err = nla_parse_nested(tb_limit,
2430                                                        MAX_NL80211_IFACE_LIMIT,
2431                                                        nl_limit,
2432                                                        iface_limit_policy);
2433                                 if (err ||
2434                                     !tb_limit[NL80211_IFACE_LIMIT_TYPES])
2435                                         goto broken_combination;
2437                                 nla_for_each_nested(
2438                                         nl_mode,
2439                                         tb_limit[NL80211_IFACE_LIMIT_TYPES],
2440                                         rem_mode) {
2441                                         int ift = nla_type(nl_mode);
2442                                         if (ift == NL80211_IFTYPE_P2P_GO ||
2443                                             ift == NL80211_IFTYPE_P2P_CLIENT)
2444                                                 combination_has_p2p = 1;
2445                                         if (ift == NL80211_IFTYPE_STATION)
2446                                                 combination_has_mgd = 1;
2447                                 }
2448                                 if (combination_has_p2p && combination_has_mgd)
2449                                         break;
2450                         }
2452                         if (combination_has_p2p && combination_has_mgd) {
2453                                 p2p_concurrent = 1;
2454                                 break;
2455                         }
2457 broken_combination:
2458                         ;
2459                 }
2460         }
2462         if (tb[NL80211_ATTR_SUPPORTED_COMMANDS]) {
2463                 struct nlattr *nl_cmd;
2464                 int i;
2466                 nla_for_each_nested(nl_cmd,
2467                                     tb[NL80211_ATTR_SUPPORTED_COMMANDS], i) {
2468                         switch (nla_get_u32(nl_cmd)) {
2469                         case NL80211_CMD_AUTHENTICATE:
2470                                 auth_supported = 1;
2471                                 break;
2472                         case NL80211_CMD_CONNECT:
2473                                 connect_supported = 1;
2474                                 break;
2475                         case NL80211_CMD_START_SCHED_SCAN:
2476                                 capa->sched_scan_supported = 1;
2477                                 break;
2478                         case NL80211_CMD_PROBE_CLIENT:
2479                                 info->poll_command_supported = 1;
2480                                 break;
2481                         }
2482                 }
2483         }
2485         if (tb[NL80211_ATTR_OFFCHANNEL_TX_OK]) {
2486                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based "
2487                            "off-channel TX");
2488                 capa->flags |= WPA_DRIVER_FLAGS_OFFCHANNEL_TX;
2489         }
2491         if (tb[NL80211_ATTR_ROAM_SUPPORT]) {
2492                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based roaming");
2493                 capa->flags |= WPA_DRIVER_FLAGS_BSS_SELECTION;
2494         }
2496         /* default to 5000 since early versions of mac80211 don't set it */
2497         capa->max_remain_on_chan = 5000;
2499         if (tb[NL80211_ATTR_SUPPORT_AP_UAPSD])
2500                 capa->flags |= WPA_DRIVER_FLAGS_AP_UAPSD;
2502         if (tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION])
2503                 capa->max_remain_on_chan =
2504                         nla_get_u32(tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION]);
2506         if (auth_supported)
2507                 capa->flags |= WPA_DRIVER_FLAGS_SME;
2508         else if (!connect_supported) {
2509                 wpa_printf(MSG_INFO, "nl80211: Driver does not support "
2510                            "authentication/association or connect commands");
2511                 info->error = 1;
2512         }
2514         if (p2p_go_supported && p2p_client_supported)
2515                 capa->flags |= WPA_DRIVER_FLAGS_P2P_CAPABLE;
2516         if (p2p_concurrent) {
2517                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
2518                            "interface (driver advertised support)");
2519                 capa->flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
2520                 capa->flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
2521         }
2523         if (tb[NL80211_ATTR_TDLS_SUPPORT]) {
2524                 wpa_printf(MSG_DEBUG, "nl80211: TDLS supported");
2525                 capa->flags |= WPA_DRIVER_FLAGS_TDLS_SUPPORT;
2527                 if (tb[NL80211_ATTR_TDLS_EXTERNAL_SETUP]) {
2528                         wpa_printf(MSG_DEBUG, "nl80211: TDLS external setup");
2529                         capa->flags |=
2530                                 WPA_DRIVER_FLAGS_TDLS_EXTERNAL_SETUP;
2531                 }
2532         }
2534         if (tb[NL80211_ATTR_DEVICE_AP_SME])
2535                 info->device_ap_sme = 1;
2537         if (tb[NL80211_ATTR_FEATURE_FLAGS]) {
2538                 u32 flags = nla_get_u32(tb[NL80211_ATTR_FEATURE_FLAGS]);
2540                 if (flags & NL80211_FEATURE_SK_TX_STATUS)
2541                         info->data_tx_status = 1;
2542         }
2544         if (tb[NL80211_ATTR_PROBE_RESP_OFFLOAD]) {
2545                 int protocols =
2546                         nla_get_u32(tb[NL80211_ATTR_PROBE_RESP_OFFLOAD]);
2547                 wpa_printf(MSG_DEBUG, "nl80211: Supports Probe Response "
2548                            "offload in AP mode");
2549                 capa->flags |= WPA_DRIVER_FLAGS_PROBE_RESP_OFFLOAD;
2550                 capa->probe_resp_offloads =
2551                         probe_resp_offload_support(protocols);
2552         }
2554         return NL_SKIP;
2558 static int wpa_driver_nl80211_get_info(struct wpa_driver_nl80211_data *drv,
2559                                        struct wiphy_info_data *info)
2561         struct nl_msg *msg;
2563         os_memset(info, 0, sizeof(*info));
2564         info->capa = &drv->capa;
2566         msg = nlmsg_alloc();
2567         if (!msg)
2568                 return -1;
2570         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
2572         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->first_bss.ifindex);
2574         if (send_and_recv_msgs(drv, msg, wiphy_info_handler, info) == 0)
2575                 return 0;
2576         msg = NULL;
2577 nla_put_failure:
2578         nlmsg_free(msg);
2579         return -1;
2583 static int wpa_driver_nl80211_capa(struct wpa_driver_nl80211_data *drv)
2585         struct wiphy_info_data info;
2586         if (wpa_driver_nl80211_get_info(drv, &info))
2587                 return -1;
2589         if (info.error)
2590                 return -1;
2592         drv->has_capability = 1;
2593         /* For now, assume TKIP, CCMP, WPA, WPA2 are supported */
2594         drv->capa.key_mgmt = WPA_DRIVER_CAPA_KEY_MGMT_WPA |
2595                 WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK |
2596                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2 |
2597                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK;
2598         drv->capa.enc = WPA_DRIVER_CAPA_ENC_WEP40 |
2599                 WPA_DRIVER_CAPA_ENC_WEP104 |
2600                 WPA_DRIVER_CAPA_ENC_TKIP |
2601                 WPA_DRIVER_CAPA_ENC_CCMP;
2602         drv->capa.auth = WPA_DRIVER_AUTH_OPEN |
2603                 WPA_DRIVER_AUTH_SHARED |
2604                 WPA_DRIVER_AUTH_LEAP;
2606         drv->capa.flags |= WPA_DRIVER_FLAGS_SANE_ERROR_CODES;
2607         drv->capa.flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE;
2608         drv->capa.flags |= WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2609         drv->capa.flags |= WPA_DRIVER_FLAGS_DEAUTH_TX_STATUS;
2611         drv->device_ap_sme = info.device_ap_sme;
2612         drv->poll_command_supported = info.poll_command_supported;
2613         drv->data_tx_status = info.data_tx_status;
2615         /*
2616          * If poll command is supported mac80211 is new enough to
2617          * have everything we need to not need monitor interfaces.
2618          */
2619         drv->use_monitor = !info.poll_command_supported;
2621         if (drv->device_ap_sme && drv->use_monitor) {
2622                 /*
2623                  * Non-mac80211 drivers may not support monitor interface.
2624                  * Make sure we do not get stuck with incorrect capability here
2625                  * by explicitly testing this.
2626                  */
2627                 if (!info.monitor_supported) {
2628                         wpa_printf(MSG_DEBUG, "nl80211: Disable use_monitor "
2629                                    "with device_ap_sme since no monitor mode "
2630                                    "support detected");
2631                         drv->use_monitor = 0;
2632                 }
2633         }
2635         /*
2636          * If we aren't going to use monitor interfaces, but the
2637          * driver doesn't support data TX status, we won't get TX
2638          * status for EAPOL frames.
2639          */
2640         if (!drv->use_monitor && !info.data_tx_status)
2641                 drv->capa.flags &= ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2643         return 0;
2647 #ifdef ANDROID
2648 static int android_genl_ctrl_resolve(struct nl_handle *handle,
2649                                      const char *name)
2651         /*
2652          * Android ICS has very minimal genl_ctrl_resolve() implementation, so
2653          * need to work around that.
2654          */
2655         struct nl_cache *cache = NULL;
2656         struct genl_family *nl80211 = NULL;
2657         int id = -1;
2659         if (genl_ctrl_alloc_cache(handle, &cache) < 0) {
2660                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
2661                            "netlink cache");
2662                 goto fail;
2663         }
2665         nl80211 = genl_ctrl_search_by_name(cache, name);
2666         if (nl80211 == NULL)
2667                 goto fail;
2669         id = genl_family_get_id(nl80211);
2671 fail:
2672         if (nl80211)
2673                 genl_family_put(nl80211);
2674         if (cache)
2675                 nl_cache_free(cache);
2677         return id;
2679 #define genl_ctrl_resolve android_genl_ctrl_resolve
2680 #endif /* ANDROID */
2683 static int wpa_driver_nl80211_init_nl_global(struct nl80211_global *global)
2685         int ret;
2687         global->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2688         if (global->nl_cb == NULL) {
2689                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
2690                            "callbacks");
2691                 return -1;
2692         }
2694         global->nl = nl_create_handle(global->nl_cb, "nl");
2695         if (global->nl == NULL)
2696                 goto err;
2698         global->nl80211_id = genl_ctrl_resolve(global->nl, "nl80211");
2699         if (global->nl80211_id < 0) {
2700                 wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
2701                            "found");
2702                 goto err;
2703         }
2705         global->nl_event = nl_create_handle(global->nl_cb, "event");
2706         if (global->nl_event == NULL)
2707                 goto err;
2709         ret = nl_get_multicast_id(global, "nl80211", "scan");
2710         if (ret >= 0)
2711                 ret = nl_socket_add_membership(global->nl_event, ret);
2712         if (ret < 0) {
2713                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
2714                            "membership for scan events: %d (%s)",
2715                            ret, strerror(-ret));
2716                 goto err;
2717         }
2719         ret = nl_get_multicast_id(global, "nl80211", "mlme");
2720         if (ret >= 0)
2721                 ret = nl_socket_add_membership(global->nl_event, ret);
2722         if (ret < 0) {
2723                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
2724                            "membership for mlme events: %d (%s)",
2725                            ret, strerror(-ret));
2726                 goto err;
2727         }
2729         ret = nl_get_multicast_id(global, "nl80211", "regulatory");
2730         if (ret >= 0)
2731                 ret = nl_socket_add_membership(global->nl_event, ret);
2732         if (ret < 0) {
2733                 wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
2734                            "membership for regulatory events: %d (%s)",
2735                            ret, strerror(-ret));
2736                 /* Continue without regulatory events */
2737         }
2739         nl_cb_set(global->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2740                   no_seq_check, NULL);
2741         nl_cb_set(global->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2742                   process_global_event, global);
2744         eloop_register_read_sock(nl_socket_get_fd(global->nl_event),
2745                                  wpa_driver_nl80211_event_receive,
2746                                  global->nl_cb, global->nl_event);
2748         return 0;
2750 err:
2751         nl_destroy_handles(&global->nl_event);
2752         nl_destroy_handles(&global->nl);
2753         nl_cb_put(global->nl_cb);
2754         global->nl_cb = NULL;
2755         return -1;
2759 static int wpa_driver_nl80211_init_nl(struct wpa_driver_nl80211_data *drv)
2761         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2762         if (!drv->nl_cb) {
2763                 wpa_printf(MSG_ERROR, "nl80211: Failed to alloc cb struct");
2764                 return -1;
2765         }
2767         nl_cb_set(drv->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2768                   no_seq_check, NULL);
2769         nl_cb_set(drv->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2770                   process_drv_event, drv);
2772         return 0;
2776 static void wpa_driver_nl80211_rfkill_blocked(void *ctx)
2778         wpa_printf(MSG_DEBUG, "nl80211: RFKILL blocked");
2779         /*
2780          * This may be for any interface; use ifdown event to disable
2781          * interface.
2782          */
2786 static void wpa_driver_nl80211_rfkill_unblocked(void *ctx)
2788         struct wpa_driver_nl80211_data *drv = ctx;
2789         wpa_printf(MSG_DEBUG, "nl80211: RFKILL unblocked");
2790         if (linux_set_iface_flags(drv->global->ioctl_sock,
2791                                   drv->first_bss.ifname, 1)) {
2792                 wpa_printf(MSG_DEBUG, "nl80211: Could not set interface UP "
2793                            "after rfkill unblock");
2794                 return;
2795         }
2796         /* rtnetlink ifup handler will report interface as enabled */
2800 static void nl80211_get_phy_name(struct wpa_driver_nl80211_data *drv)
2802         /* Find phy (radio) to which this interface belongs */
2803         char buf[90], *pos;
2804         int f, rv;
2806         drv->phyname[0] = '\0';
2807         snprintf(buf, sizeof(buf) - 1, "/sys/class/net/%s/phy80211/name",
2808                  drv->first_bss.ifname);
2809         f = open(buf, O_RDONLY);
2810         if (f < 0) {
2811                 wpa_printf(MSG_DEBUG, "Could not open file %s: %s",
2812                            buf, strerror(errno));
2813                 return;
2814         }
2816         rv = read(f, drv->phyname, sizeof(drv->phyname) - 1);
2817         close(f);
2818         if (rv < 0) {
2819                 wpa_printf(MSG_DEBUG, "Could not read file %s: %s",
2820                            buf, strerror(errno));
2821                 return;
2822         }
2824         drv->phyname[rv] = '\0';
2825         pos = os_strchr(drv->phyname, '\n');
2826         if (pos)
2827                 *pos = '\0';
2828         wpa_printf(MSG_DEBUG, "nl80211: interface %s in phy %s",
2829                    drv->first_bss.ifname, drv->phyname);
2833 static void wpa_driver_nl80211_handle_eapol_tx_status(int sock,
2834                                                       void *eloop_ctx,
2835                                                       void *handle)
2837         struct wpa_driver_nl80211_data *drv = eloop_ctx;
2838         u8 data[2048];
2839         struct msghdr msg;
2840         struct iovec entry;
2841         struct {
2842                 struct cmsghdr cm;
2843                 char control[512];
2844         } control;
2845         struct cmsghdr *cmsg;
2846         int res, found_ee = 0, found_wifi = 0, acked = 0;
2847         union wpa_event_data event;
2849         memset(&msg, 0, sizeof(msg));
2850         msg.msg_iov = &entry;
2851         msg.msg_iovlen = 1;
2852         entry.iov_base = data;
2853         entry.iov_len = sizeof(data);
2854         msg.msg_control = &control;
2855         msg.msg_controllen = sizeof(control);
2857         res = recvmsg(sock, &msg, MSG_ERRQUEUE);
2858         /* if error or not fitting 802.3 header, return */
2859         if (res < 14)
2860                 return;
2862         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg))
2863         {
2864                 if (cmsg->cmsg_level == SOL_SOCKET &&
2865                     cmsg->cmsg_type == SCM_WIFI_STATUS) {
2866                         int *ack;
2868                         found_wifi = 1;
2869                         ack = (void *)CMSG_DATA(cmsg);
2870                         acked = *ack;
2871                 }
2873                 if (cmsg->cmsg_level == SOL_PACKET &&
2874                     cmsg->cmsg_type == PACKET_TX_TIMESTAMP) {
2875                         struct sock_extended_err *err =
2876                                 (struct sock_extended_err *)CMSG_DATA(cmsg);
2878                         if (err->ee_origin == SO_EE_ORIGIN_TXSTATUS)
2879                                 found_ee = 1;
2880                 }
2881         }
2883         if (!found_ee || !found_wifi)
2884                 return;
2886         memset(&event, 0, sizeof(event));
2887         event.eapol_tx_status.dst = data;
2888         event.eapol_tx_status.data = data + 14;
2889         event.eapol_tx_status.data_len = res - 14;
2890         event.eapol_tx_status.ack = acked;
2891         wpa_supplicant_event(drv->ctx, EVENT_EAPOL_TX_STATUS, &event);
2895 static int nl80211_init_bss(struct i802_bss *bss)
2897         bss->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2898         if (!bss->nl_cb)
2899                 return -1;
2901         nl_cb_set(bss->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2902                   no_seq_check, NULL);
2903         nl_cb_set(bss->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2904                   process_bss_event, bss);
2906         return 0;
2910 static void nl80211_destroy_bss(struct i802_bss *bss)
2912         nl_cb_put(bss->nl_cb);
2913         bss->nl_cb = NULL;
2917 /**
2918  * wpa_driver_nl80211_init - Initialize nl80211 driver interface
2919  * @ctx: context to be used when calling wpa_supplicant functions,
2920  * e.g., wpa_supplicant_event()
2921  * @ifname: interface name, e.g., wlan0
2922  * @global_priv: private driver global data from global_init()
2923  * Returns: Pointer to private data, %NULL on failure
2924  */
2925 static void * wpa_driver_nl80211_init(void *ctx, const char *ifname,
2926                                       void *global_priv)
2928         struct wpa_driver_nl80211_data *drv;
2929         struct rfkill_config *rcfg;
2930         struct i802_bss *bss;
2932         if (global_priv == NULL)
2933                 return NULL;
2934         drv = os_zalloc(sizeof(*drv));
2935         if (drv == NULL)
2936                 return NULL;
2937         drv->global = global_priv;
2938         drv->ctx = ctx;
2939         bss = &drv->first_bss;
2940         bss->drv = drv;
2941         os_strlcpy(bss->ifname, ifname, sizeof(bss->ifname));
2942         drv->monitor_ifidx = -1;
2943         drv->monitor_sock = -1;
2944         drv->eapol_tx_sock = -1;
2945         drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
2947         if (wpa_driver_nl80211_init_nl(drv)) {
2948                 os_free(drv);
2949                 return NULL;
2950         }
2952         if (nl80211_init_bss(bss))
2953                 goto failed;
2955         nl80211_get_phy_name(drv);
2957         rcfg = os_zalloc(sizeof(*rcfg));
2958         if (rcfg == NULL)
2959                 goto failed;
2960         rcfg->ctx = drv;
2961         os_strlcpy(rcfg->ifname, ifname, sizeof(rcfg->ifname));
2962         rcfg->blocked_cb = wpa_driver_nl80211_rfkill_blocked;
2963         rcfg->unblocked_cb = wpa_driver_nl80211_rfkill_unblocked;
2964         drv->rfkill = rfkill_init(rcfg);
2965         if (drv->rfkill == NULL) {
2966                 wpa_printf(MSG_DEBUG, "nl80211: RFKILL status not available");
2967                 os_free(rcfg);
2968         }
2970         if (wpa_driver_nl80211_finish_drv_init(drv))
2971                 goto failed;
2973         drv->eapol_tx_sock = socket(PF_PACKET, SOCK_DGRAM, 0);
2974         if (drv->eapol_tx_sock < 0)
2975                 goto failed;
2977         if (drv->data_tx_status) {
2978                 int enabled = 1;
2980                 if (setsockopt(drv->eapol_tx_sock, SOL_SOCKET, SO_WIFI_STATUS,
2981                                &enabled, sizeof(enabled)) < 0) {
2982                         wpa_printf(MSG_DEBUG,
2983                                 "nl80211: wifi status sockopt failed\n");
2984                         drv->data_tx_status = 0;
2985                         if (!drv->use_monitor)
2986                                 drv->capa.flags &=
2987                                         ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2988                 } else {
2989                         eloop_register_read_sock(drv->eapol_tx_sock,
2990                                 wpa_driver_nl80211_handle_eapol_tx_status,
2991                                 drv, NULL);
2992                 }
2993         }
2995         if (drv->global) {
2996                 dl_list_add(&drv->global->interfaces, &drv->list);
2997                 drv->in_interface_list = 1;
2998         }
3000         return bss;
3002 failed:
3003         wpa_driver_nl80211_deinit(bss);
3004         return NULL;
3008 static int nl80211_register_frame(struct i802_bss *bss,
3009                                   struct nl_handle *nl_handle,
3010                                   u16 type, const u8 *match, size_t match_len)
3012         struct wpa_driver_nl80211_data *drv = bss->drv;
3013         struct nl_msg *msg;
3014         int ret = -1;
3016         msg = nlmsg_alloc();
3017         if (!msg)
3018                 return -1;
3020         wpa_printf(MSG_DEBUG, "nl80211: Register frame type=0x%x nl_handle=%p",
3021                    type, nl_handle);
3022         wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
3023                     match, match_len);
3025         nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_ACTION);
3027         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3028         NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE, type);
3029         NLA_PUT(msg, NL80211_ATTR_FRAME_MATCH, match_len, match);
3031         ret = send_and_recv(drv->global, nl_handle, msg, NULL, NULL);
3032         msg = NULL;
3033         if (ret) {
3034                 wpa_printf(MSG_DEBUG, "nl80211: Register frame command "
3035                            "failed (type=%u): ret=%d (%s)",
3036                            type, ret, strerror(-ret));
3037                 wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
3038                             match, match_len);
3039                 goto nla_put_failure;
3040         }
3041         ret = 0;
3042 nla_put_failure:
3043         nlmsg_free(msg);
3044         return ret;
3048 static int nl80211_alloc_mgmt_handle(struct i802_bss *bss)
3050         struct wpa_driver_nl80211_data *drv = bss->drv;
3052         if (bss->nl_mgmt) {
3053                 wpa_printf(MSG_DEBUG, "nl80211: Mgmt reporting "
3054                            "already on! (nl_mgmt=%p)", bss->nl_mgmt);
3055                 return -1;
3056         }
3058         bss->nl_mgmt = nl_create_handle(drv->nl_cb, "mgmt");
3059         if (bss->nl_mgmt == NULL)
3060                 return -1;
3062         eloop_register_read_sock(nl_socket_get_fd(bss->nl_mgmt),
3063                                  wpa_driver_nl80211_event_receive, bss->nl_cb,
3064                                  bss->nl_mgmt);
3066         return 0;
3070 static int nl80211_register_action_frame(struct i802_bss *bss,
3071                                          const u8 *match, size_t match_len)
3073         u16 type = (WLAN_FC_TYPE_MGMT << 2) | (WLAN_FC_STYPE_ACTION << 4);
3074         return nl80211_register_frame(bss, bss->nl_mgmt,
3075                                       type, match, match_len);
3079 static int nl80211_mgmt_subscribe_non_ap(struct i802_bss *bss)
3081         struct wpa_driver_nl80211_data *drv = bss->drv;
3083         if (nl80211_alloc_mgmt_handle(bss))
3084                 return -1;
3085         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with non-AP "
3086                    "handle %p", bss->nl_mgmt);
3088 #if defined(CONFIG_P2P) || defined(CONFIG_INTERWORKING)
3089         /* GAS Initial Request */
3090         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0a", 2) < 0)
3091                 return -1;
3092         /* GAS Initial Response */
3093         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0b", 2) < 0)
3094                 return -1;
3095         /* GAS Comeback Request */
3096         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0c", 2) < 0)
3097                 return -1;
3098         /* GAS Comeback Response */
3099         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0d", 2) < 0)
3100                 return -1;
3101 #endif /* CONFIG_P2P || CONFIG_INTERWORKING */
3102 #ifdef CONFIG_P2P
3103         /* P2P Public Action */
3104         if (nl80211_register_action_frame(bss,
3105                                           (u8 *) "\x04\x09\x50\x6f\x9a\x09",
3106                                           6) < 0)
3107                 return -1;
3108         /* P2P Action */
3109         if (nl80211_register_action_frame(bss,
3110                                           (u8 *) "\x7f\x50\x6f\x9a\x09",
3111                                           5) < 0)
3112                 return -1;
3113 #endif /* CONFIG_P2P */
3114 #ifdef CONFIG_IEEE80211W
3115         /* SA Query Response */
3116         if (nl80211_register_action_frame(bss, (u8 *) "\x08\x01", 2) < 0)
3117                 return -1;
3118 #endif /* CONFIG_IEEE80211W */
3119 #ifdef CONFIG_TDLS
3120         if ((drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT)) {
3121                 /* TDLS Discovery Response */
3122                 if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0e", 2) <
3123                     0)
3124                         return -1;
3125         }
3126 #endif /* CONFIG_TDLS */
3128         /* FT Action frames */
3129         if (nl80211_register_action_frame(bss, (u8 *) "\x06", 1) < 0)
3130                 return -1;
3131         else
3132                 drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_FT |
3133                         WPA_DRIVER_CAPA_KEY_MGMT_FT_PSK;
3135         /* WNM - BSS Transition Management Request */
3136         if (nl80211_register_action_frame(bss, (u8 *) "\x0a\x07", 2) < 0)
3137                 return -1;
3139         return 0;
3143 static int nl80211_register_spurious_class3(struct i802_bss *bss)
3145         struct wpa_driver_nl80211_data *drv = bss->drv;
3146         struct nl_msg *msg;
3147         int ret = -1;
3149         msg = nlmsg_alloc();
3150         if (!msg)
3151                 return -1;
3153         nl80211_cmd(drv, msg, 0, NL80211_CMD_UNEXPECTED_FRAME);
3155         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3157         ret = send_and_recv(drv->global, bss->nl_mgmt, msg, NULL, NULL);
3158         msg = NULL;
3159         if (ret) {
3160                 wpa_printf(MSG_DEBUG, "nl80211: Register spurious class3 "
3161                            "failed: ret=%d (%s)",
3162                            ret, strerror(-ret));
3163                 goto nla_put_failure;
3164         }
3165         ret = 0;
3166 nla_put_failure:
3167         nlmsg_free(msg);
3168         return ret;
3172 static int nl80211_mgmt_subscribe_ap(struct i802_bss *bss)
3174         static const int stypes[] = {
3175                 WLAN_FC_STYPE_AUTH,
3176                 WLAN_FC_STYPE_ASSOC_REQ,
3177                 WLAN_FC_STYPE_REASSOC_REQ,
3178                 WLAN_FC_STYPE_DISASSOC,
3179                 WLAN_FC_STYPE_DEAUTH,
3180                 WLAN_FC_STYPE_ACTION,
3181                 WLAN_FC_STYPE_PROBE_REQ,
3182 /* Beacon doesn't work as mac80211 doesn't currently allow
3183  * it, but it wouldn't really be the right thing anyway as
3184  * it isn't per interface ... maybe just dump the scan
3185  * results periodically for OLBC?
3186  */
3187 //              WLAN_FC_STYPE_BEACON,
3188         };
3189         unsigned int i;
3191         if (nl80211_alloc_mgmt_handle(bss))
3192                 return -1;
3193         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3194                    "handle %p", bss->nl_mgmt);
3196         for (i = 0; i < sizeof(stypes) / sizeof(stypes[0]); i++) {
3197                 if (nl80211_register_frame(bss, bss->nl_mgmt,
3198                                            (WLAN_FC_TYPE_MGMT << 2) |
3199                                            (stypes[i] << 4),
3200                                            NULL, 0) < 0) {
3201                         goto out_err;
3202                 }
3203         }
3205         if (nl80211_register_spurious_class3(bss))
3206                 goto out_err;
3208         if (nl80211_get_wiphy_data_ap(bss) == NULL)
3209                 goto out_err;
3211         return 0;
3213 out_err:
3214         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3215         nl_destroy_handles(&bss->nl_mgmt);
3216         return -1;
3220 static int nl80211_mgmt_subscribe_ap_dev_sme(struct i802_bss *bss)
3222         if (nl80211_alloc_mgmt_handle(bss))
3223                 return -1;
3224         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3225                    "handle %p (device SME)", bss->nl_mgmt);
3227         if (nl80211_register_frame(bss, bss->nl_mgmt,
3228                                    (WLAN_FC_TYPE_MGMT << 2) |
3229                                    (WLAN_FC_STYPE_ACTION << 4),
3230                                    NULL, 0) < 0)
3231                 goto out_err;
3233         return 0;
3235 out_err:
3236         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3237         nl_destroy_handles(&bss->nl_mgmt);
3238         return -1;
3242 static void nl80211_mgmt_unsubscribe(struct i802_bss *bss, const char *reason)
3244         if (bss->nl_mgmt == NULL)
3245                 return;
3246         wpa_printf(MSG_DEBUG, "nl80211: Unsubscribe mgmt frames handle %p "
3247                    "(%s)", bss->nl_mgmt, reason);
3248         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3249         nl_destroy_handles(&bss->nl_mgmt);
3251         nl80211_put_wiphy_data_ap(bss);
3255 static void wpa_driver_nl80211_send_rfkill(void *eloop_ctx, void *timeout_ctx)
3257         wpa_supplicant_event(timeout_ctx, EVENT_INTERFACE_DISABLED, NULL);
3261 static int
3262 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv)
3264         struct i802_bss *bss = &drv->first_bss;
3265         int send_rfkill_event = 0;
3267         drv->ifindex = if_nametoindex(bss->ifname);
3268         drv->first_bss.ifindex = drv->ifindex;
3270 #ifndef HOSTAPD
3271         /*
3272          * Make sure the interface starts up in station mode unless this is a
3273          * dynamically added interface (e.g., P2P) that was already configured
3274          * with proper iftype.
3275          */
3276         if (drv->ifindex != drv->global->if_add_ifindex &&
3277             wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION) < 0) {
3278                 wpa_printf(MSG_ERROR, "nl80211: Could not configure driver to "
3279                            "use managed mode");
3280                 return -1;
3281         }
3283         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
3284                 if (rfkill_is_blocked(drv->rfkill)) {
3285                         wpa_printf(MSG_DEBUG, "nl80211: Could not yet enable "
3286                                    "interface '%s' due to rfkill",
3287                                    bss->ifname);
3288                         drv->if_disabled = 1;
3289                         send_rfkill_event = 1;
3290                 } else {
3291                         wpa_printf(MSG_ERROR, "nl80211: Could not set "
3292                                    "interface '%s' UP", bss->ifname);
3293                         return -1;
3294                 }
3295         }
3297         netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
3298                                1, IF_OPER_DORMANT);
3299 #endif /* HOSTAPD */
3301         if (wpa_driver_nl80211_capa(drv))
3302                 return -1;
3304         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
3305                                bss->addr))
3306                 return -1;
3308         if (send_rfkill_event) {
3309                 eloop_register_timeout(0, 0, wpa_driver_nl80211_send_rfkill,
3310                                        drv, drv->ctx);
3311         }
3313         return 0;
3317 static int wpa_driver_nl80211_del_beacon(struct wpa_driver_nl80211_data *drv)
3319         struct nl_msg *msg;
3321         msg = nlmsg_alloc();
3322         if (!msg)
3323                 return -ENOMEM;
3325         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_BEACON);
3326         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3328         return send_and_recv_msgs(drv, msg, NULL, NULL);
3329  nla_put_failure:
3330         nlmsg_free(msg);
3331         return -ENOBUFS;
3335 /**
3336  * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
3337  * @priv: Pointer to private nl80211 data from wpa_driver_nl80211_init()
3338  *
3339  * Shut down driver interface and processing of driver events. Free
3340  * private data buffer if one was allocated in wpa_driver_nl80211_init().
3341  */
3342 static void wpa_driver_nl80211_deinit(void *priv)
3344         struct i802_bss *bss = priv;
3345         struct wpa_driver_nl80211_data *drv = bss->drv;
3347         if (drv->data_tx_status)
3348                 eloop_unregister_read_sock(drv->eapol_tx_sock);
3349         if (drv->eapol_tx_sock >= 0)
3350                 close(drv->eapol_tx_sock);
3352         if (bss->nl_preq)
3353                 wpa_driver_nl80211_probe_req_report(bss, 0);
3354         if (bss->added_if_into_bridge) {
3355                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
3356                                     bss->ifname) < 0)
3357                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3358                                    "interface %s from bridge %s: %s",
3359                                    bss->ifname, bss->brname, strerror(errno));
3360         }
3361         if (bss->added_bridge) {
3362                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
3363                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3364                                    "bridge %s: %s",
3365                                    bss->brname, strerror(errno));
3366         }
3368         nl80211_remove_monitor_interface(drv);
3370         if (is_ap_interface(drv->nlmode))
3371                 wpa_driver_nl80211_del_beacon(drv);
3373 #ifdef HOSTAPD
3374         if (drv->last_freq_ht) {
3375                 /* Clear HT flags from the driver */
3376                 struct hostapd_freq_params freq;
3377                 os_memset(&freq, 0, sizeof(freq));
3378                 freq.freq = drv->last_freq;
3379                 i802_set_freq(priv, &freq);
3380         }
3382         if (drv->eapol_sock >= 0) {
3383                 eloop_unregister_read_sock(drv->eapol_sock);
3384                 close(drv->eapol_sock);
3385         }
3387         if (drv->if_indices != drv->default_if_indices)
3388                 os_free(drv->if_indices);
3389 #endif /* HOSTAPD */
3391         if (drv->disabled_11b_rates)
3392                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
3394         netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, 0,
3395                                IF_OPER_UP);
3396         rfkill_deinit(drv->rfkill);
3398         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3400         (void) linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0);
3401         wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION);
3402         nl80211_mgmt_unsubscribe(bss, "deinit");
3404         nl_cb_put(drv->nl_cb);
3406         nl80211_destroy_bss(&drv->first_bss);
3408         os_free(drv->filter_ssids);
3410         os_free(drv->auth_ie);
3412         if (drv->in_interface_list)
3413                 dl_list_del(&drv->list);
3415         os_free(drv);
3419 /**
3420  * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
3421  * @eloop_ctx: Driver private data
3422  * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
3423  *
3424  * This function can be used as registered timeout when starting a scan to
3425  * generate a scan completed event if the driver does not report this.
3426  */
3427 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
3429         struct wpa_driver_nl80211_data *drv = eloop_ctx;
3430         if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED) {
3431                 wpa_driver_nl80211_set_mode(&drv->first_bss,
3432                                             drv->ap_scan_as_station);
3433                 drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
3434         }
3435         wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
3436         wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
3440 /**
3441  * wpa_driver_nl80211_scan - Request the driver to initiate scan
3442  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3443  * @params: Scan parameters
3444  * Returns: 0 on success, -1 on failure
3445  */
3446 static int wpa_driver_nl80211_scan(void *priv,
3447                                    struct wpa_driver_scan_params *params)
3449         struct i802_bss *bss = priv;
3450         struct wpa_driver_nl80211_data *drv = bss->drv;
3451         int ret = 0, timeout;
3452         struct nl_msg *msg, *ssids, *freqs, *rates;
3453         size_t i;
3455         drv->scan_for_auth = 0;
3457         msg = nlmsg_alloc();
3458         ssids = nlmsg_alloc();
3459         freqs = nlmsg_alloc();
3460         rates = nlmsg_alloc();
3461         if (!msg || !ssids || !freqs || !rates) {
3462                 nlmsg_free(msg);
3463                 nlmsg_free(ssids);
3464                 nlmsg_free(freqs);
3465                 nlmsg_free(rates);
3466                 return -1;
3467         }
3469         os_free(drv->filter_ssids);
3470         drv->filter_ssids = params->filter_ssids;
3471         params->filter_ssids = NULL;
3472         drv->num_filter_ssids = params->num_filter_ssids;
3474         nl80211_cmd(drv, msg, 0, NL80211_CMD_TRIGGER_SCAN);
3476         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3478         for (i = 0; i < params->num_ssids; i++) {
3479                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan SSID",
3480                                   params->ssids[i].ssid,
3481                                   params->ssids[i].ssid_len);
3482                 NLA_PUT(ssids, i + 1, params->ssids[i].ssid_len,
3483                         params->ssids[i].ssid);
3484         }
3485         if (params->num_ssids)
3486                 nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
3488         if (params->extra_ies) {
3489                 wpa_hexdump(MSG_MSGDUMP, "nl80211: Scan extra IEs",
3490                             params->extra_ies, params->extra_ies_len);
3491                 NLA_PUT(msg, NL80211_ATTR_IE, params->extra_ies_len,
3492                         params->extra_ies);
3493         }
3495         if (params->freqs) {
3496                 for (i = 0; params->freqs[i]; i++) {
3497                         wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
3498                                    "MHz", params->freqs[i]);
3499                         NLA_PUT_U32(freqs, i + 1, params->freqs[i]);
3500                 }
3501                 nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs);
3502         }
3504         if (params->p2p_probe) {
3505                 wpa_printf(MSG_DEBUG, "nl80211: P2P probe - mask SuppRates");
3507                 /*
3508                  * Remove 2.4 GHz rates 1, 2, 5.5, 11 Mbps from supported rates
3509                  * by masking out everything else apart from the OFDM rates 6,
3510                  * 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS rates. All 5 GHz
3511                  * rates are left enabled.
3512                  */
3513                 NLA_PUT(rates, NL80211_BAND_2GHZ, 8,
3514                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
3515                 nla_put_nested(msg, NL80211_ATTR_SCAN_SUPP_RATES, rates);
3517                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
3518         }
3520         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3521         msg = NULL;
3522         if (ret) {
3523                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
3524                            "(%s)", ret, strerror(-ret));
3525 #ifdef HOSTAPD
3526                 if (is_ap_interface(drv->nlmode)) {
3527                         /*
3528                          * mac80211 does not allow scan requests in AP mode, so
3529                          * try to do this in station mode.
3530                          */
3531                         if (wpa_driver_nl80211_set_mode(
3532                                     bss, NL80211_IFTYPE_STATION))
3533                                 goto nla_put_failure;
3535                         if (wpa_driver_nl80211_scan(drv, params)) {
3536                                 wpa_driver_nl80211_set_mode(bss, drv->nlmode);
3537                                 goto nla_put_failure;
3538                         }
3540                         /* Restore AP mode when processing scan results */
3541                         drv->ap_scan_as_station = drv->nlmode;
3542                         ret = 0;
3543                 } else
3544                         goto nla_put_failure;
3545 #else /* HOSTAPD */
3546                 goto nla_put_failure;
3547 #endif /* HOSTAPD */
3548         }
3550         /* Not all drivers generate "scan completed" wireless event, so try to
3551          * read results after a timeout. */
3552         timeout = 10;
3553         if (drv->scan_complete_events) {
3554                 /*
3555                  * The driver seems to deliver events to notify when scan is
3556                  * complete, so use longer timeout to avoid race conditions
3557                  * with scanning and following association request.
3558                  */
3559                 timeout = 30;
3560         }
3561         wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
3562                    "seconds", ret, timeout);
3563         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3564         eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
3565                                drv, drv->ctx);
3567 nla_put_failure:
3568         nlmsg_free(ssids);
3569         nlmsg_free(msg);
3570         nlmsg_free(freqs);
3571         nlmsg_free(rates);
3572         return ret;
3576 /**
3577  * wpa_driver_nl80211_sched_scan - Initiate a scheduled scan
3578  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3579  * @params: Scan parameters
3580  * @interval: Interval between scan cycles in milliseconds
3581  * Returns: 0 on success, -1 on failure or if not supported
3582  */
3583 static int wpa_driver_nl80211_sched_scan(void *priv,
3584                                          struct wpa_driver_scan_params *params,
3585                                          u32 interval)
3587         struct i802_bss *bss = priv;
3588         struct wpa_driver_nl80211_data *drv = bss->drv;
3589         int ret = 0;
3590         struct nl_msg *msg, *ssids, *freqs, *match_set_ssid, *match_sets;
3591         size_t i;
3593 #ifdef ANDROID
3594         if (!drv->capa.sched_scan_supported)
3595                 return android_pno_start(bss, params);
3596 #endif /* ANDROID */
3598         msg = nlmsg_alloc();
3599         ssids = nlmsg_alloc();
3600         freqs = nlmsg_alloc();
3601         if (!msg || !ssids || !freqs) {
3602                 nlmsg_free(msg);
3603                 nlmsg_free(ssids);
3604                 nlmsg_free(freqs);
3605                 return -1;
3606         }
3608         os_free(drv->filter_ssids);
3609         drv->filter_ssids = params->filter_ssids;
3610         params->filter_ssids = NULL;
3611         drv->num_filter_ssids = params->num_filter_ssids;
3613         nl80211_cmd(drv, msg, 0, NL80211_CMD_START_SCHED_SCAN);
3615         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3617         NLA_PUT_U32(msg, NL80211_ATTR_SCHED_SCAN_INTERVAL, interval);
3619         if (drv->num_filter_ssids &&
3620             (int) drv->num_filter_ssids <= drv->capa.max_match_sets) {
3621                 match_sets = nlmsg_alloc();
3623                 for (i = 0; i < drv->num_filter_ssids; i++) {
3624                         wpa_hexdump_ascii(MSG_MSGDUMP,
3625                                           "nl80211: Sched scan filter SSID",
3626                                           drv->filter_ssids[i].ssid,
3627                                           drv->filter_ssids[i].ssid_len);
3629                         match_set_ssid = nlmsg_alloc();
3630                         nla_put(match_set_ssid,
3631                                 NL80211_ATTR_SCHED_SCAN_MATCH_SSID,
3632                                 drv->filter_ssids[i].ssid_len,
3633                                 drv->filter_ssids[i].ssid);
3635                         nla_put_nested(match_sets, i + 1, match_set_ssid);
3637                         nlmsg_free(match_set_ssid);
3638                 }
3640                 nla_put_nested(msg, NL80211_ATTR_SCHED_SCAN_MATCH,
3641                                match_sets);
3642                 nlmsg_free(match_sets);
3643         }
3645         for (i = 0; i < params->num_ssids; i++) {
3646                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Sched scan SSID",
3647                                   params->ssids[i].ssid,
3648                                   params->ssids[i].ssid_len);
3649                 NLA_PUT(ssids, i + 1, params->ssids[i].ssid_len,
3650                         params->ssids[i].ssid);
3651         }
3652         if (params->num_ssids)
3653                 nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
3655         if (params->extra_ies) {
3656                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Sched scan extra IEs",
3657                                   params->extra_ies, params->extra_ies_len);
3658                 NLA_PUT(msg, NL80211_ATTR_IE, params->extra_ies_len,
3659                         params->extra_ies);
3660         }
3662         if (params->freqs) {
3663                 for (i = 0; params->freqs[i]; i++) {
3664                         wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
3665                                    "MHz", params->freqs[i]);
3666                         NLA_PUT_U32(freqs, i + 1, params->freqs[i]);
3667                 }
3668                 nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs);
3669         }
3671         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3673         /* TODO: if we get an error here, we should fall back to normal scan */
3675         msg = NULL;
3676         if (ret) {
3677                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan start failed: "
3678                            "ret=%d (%s)", ret, strerror(-ret));
3679                 goto nla_put_failure;
3680         }
3682         wpa_printf(MSG_DEBUG, "nl80211: Sched scan requested (ret=%d) - "
3683                    "scan interval %d msec", ret, interval);
3685 nla_put_failure:
3686         nlmsg_free(ssids);
3687         nlmsg_free(msg);
3688         nlmsg_free(freqs);
3689         return ret;
3693 /**
3694  * wpa_driver_nl80211_stop_sched_scan - Stop a scheduled scan
3695  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3696  * Returns: 0 on success, -1 on failure or if not supported
3697  */
3698 static int wpa_driver_nl80211_stop_sched_scan(void *priv)
3700         struct i802_bss *bss = priv;
3701         struct wpa_driver_nl80211_data *drv = bss->drv;
3702         int ret = 0;
3703         struct nl_msg *msg;
3705 #ifdef ANDROID
3706         if (!drv->capa.sched_scan_supported)
3707                 return android_pno_stop(bss);
3708 #endif /* ANDROID */
3710         msg = nlmsg_alloc();
3711         if (!msg)
3712                 return -1;
3714         nl80211_cmd(drv, msg, 0, NL80211_CMD_STOP_SCHED_SCAN);
3716         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3718         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3719         msg = NULL;
3720         if (ret) {
3721                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop failed: "
3722                            "ret=%d (%s)", ret, strerror(-ret));
3723                 goto nla_put_failure;
3724         }
3726         wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop sent (ret=%d)", ret);
3728 nla_put_failure:
3729         nlmsg_free(msg);
3730         return ret;
3734 static const u8 * nl80211_get_ie(const u8 *ies, size_t ies_len, u8 ie)
3736         const u8 *end, *pos;
3738         if (ies == NULL)
3739                 return NULL;
3741         pos = ies;
3742         end = ies + ies_len;
3744         while (pos + 1 < end) {
3745                 if (pos + 2 + pos[1] > end)
3746                         break;
3747                 if (pos[0] == ie)
3748                         return pos;
3749                 pos += 2 + pos[1];
3750         }
3752         return NULL;
3756 static int nl80211_scan_filtered(struct wpa_driver_nl80211_data *drv,
3757                                  const u8 *ie, size_t ie_len)
3759         const u8 *ssid;
3760         size_t i;
3762         if (drv->filter_ssids == NULL)
3763                 return 0;
3765         ssid = nl80211_get_ie(ie, ie_len, WLAN_EID_SSID);
3766         if (ssid == NULL)
3767                 return 1;
3769         for (i = 0; i < drv->num_filter_ssids; i++) {
3770                 if (ssid[1] == drv->filter_ssids[i].ssid_len &&
3771                     os_memcmp(ssid + 2, drv->filter_ssids[i].ssid, ssid[1]) ==
3772                     0)
3773                         return 0;
3774         }
3776         return 1;
3780 static int bss_info_handler(struct nl_msg *msg, void *arg)
3782         struct nlattr *tb[NL80211_ATTR_MAX + 1];
3783         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3784         struct nlattr *bss[NL80211_BSS_MAX + 1];
3785         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
3786                 [NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
3787                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
3788                 [NL80211_BSS_TSF] = { .type = NLA_U64 },
3789                 [NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
3790                 [NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
3791                 [NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
3792                 [NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
3793                 [NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
3794                 [NL80211_BSS_STATUS] = { .type = NLA_U32 },
3795                 [NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
3796                 [NL80211_BSS_BEACON_IES] = { .type = NLA_UNSPEC },
3797         };
3798         struct nl80211_bss_info_arg *_arg = arg;
3799         struct wpa_scan_results *res = _arg->res;
3800         struct wpa_scan_res **tmp;
3801         struct wpa_scan_res *r;
3802         const u8 *ie, *beacon_ie;
3803         size_t ie_len, beacon_ie_len;
3804         u8 *pos;
3805         size_t i;
3807         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3808                   genlmsg_attrlen(gnlh, 0), NULL);
3809         if (!tb[NL80211_ATTR_BSS])
3810                 return NL_SKIP;
3811         if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
3812                              bss_policy))
3813                 return NL_SKIP;
3814         if (bss[NL80211_BSS_STATUS]) {
3815                 enum nl80211_bss_status status;
3816                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
3817                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
3818                     bss[NL80211_BSS_FREQUENCY]) {
3819                         _arg->assoc_freq =
3820                                 nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
3821                         wpa_printf(MSG_DEBUG, "nl80211: Associated on %u MHz",
3822                                    _arg->assoc_freq);
3823                 }
3824                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
3825                     bss[NL80211_BSS_BSSID]) {
3826                         os_memcpy(_arg->assoc_bssid,
3827                                   nla_data(bss[NL80211_BSS_BSSID]), ETH_ALEN);
3828                         wpa_printf(MSG_DEBUG, "nl80211: Associated with "
3829                                    MACSTR, MAC2STR(_arg->assoc_bssid));
3830                 }
3831         }
3832         if (!res)
3833                 return NL_SKIP;
3834         if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
3835                 ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
3836                 ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
3837         } else {
3838                 ie = NULL;
3839                 ie_len = 0;
3840         }
3841         if (bss[NL80211_BSS_BEACON_IES]) {
3842                 beacon_ie = nla_data(bss[NL80211_BSS_BEACON_IES]);
3843                 beacon_ie_len = nla_len(bss[NL80211_BSS_BEACON_IES]);
3844         } else {
3845                 beacon_ie = NULL;
3846                 beacon_ie_len = 0;
3847         }
3849         if (nl80211_scan_filtered(_arg->drv, ie ? ie : beacon_ie,
3850                                   ie ? ie_len : beacon_ie_len))
3851                 return NL_SKIP;
3853         r = os_zalloc(sizeof(*r) + ie_len + beacon_ie_len);
3854         if (r == NULL)
3855                 return NL_SKIP;
3856         if (bss[NL80211_BSS_BSSID])
3857                 os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
3858                           ETH_ALEN);
3859         if (bss[NL80211_BSS_FREQUENCY])
3860                 r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
3861         if (bss[NL80211_BSS_BEACON_INTERVAL])
3862                 r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
3863         if (bss[NL80211_BSS_CAPABILITY])
3864                 r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
3865         r->flags |= WPA_SCAN_NOISE_INVALID;
3866         if (bss[NL80211_BSS_SIGNAL_MBM]) {
3867                 r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
3868                 r->level /= 100; /* mBm to dBm */
3869                 r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
3870         } else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
3871                 r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
3872                 r->flags |= WPA_SCAN_QUAL_INVALID;
3873         } else
3874                 r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
3875         if (bss[NL80211_BSS_TSF])
3876                 r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
3877         if (bss[NL80211_BSS_SEEN_MS_AGO])
3878                 r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
3879         r->ie_len = ie_len;
3880         pos = (u8 *) (r + 1);
3881         if (ie) {
3882                 os_memcpy(pos, ie, ie_len);
3883                 pos += ie_len;
3884         }
3885         r->beacon_ie_len = beacon_ie_len;
3886         if (beacon_ie)
3887                 os_memcpy(pos, beacon_ie, beacon_ie_len);
3889         if (bss[NL80211_BSS_STATUS]) {
3890                 enum nl80211_bss_status status;
3891                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
3892                 switch (status) {
3893                 case NL80211_BSS_STATUS_AUTHENTICATED:
3894                         r->flags |= WPA_SCAN_AUTHENTICATED;
3895                         break;
3896                 case NL80211_BSS_STATUS_ASSOCIATED:
3897                         r->flags |= WPA_SCAN_ASSOCIATED;
3898                         break;
3899                 default:
3900                         break;
3901                 }
3902         }
3904         /*
3905          * cfg80211 maintains separate BSS table entries for APs if the same
3906          * BSSID,SSID pair is seen on multiple channels. wpa_supplicant does
3907          * not use frequency as a separate key in the BSS table, so filter out
3908          * duplicated entries. Prefer associated BSS entry in such a case in
3909          * order to get the correct frequency into the BSS table.
3910          */
3911         for (i = 0; i < res->num; i++) {
3912                 const u8 *s1, *s2;
3913                 if (os_memcmp(res->res[i]->bssid, r->bssid, ETH_ALEN) != 0)
3914                         continue;
3916                 s1 = nl80211_get_ie((u8 *) (res->res[i] + 1),
3917                                     res->res[i]->ie_len, WLAN_EID_SSID);
3918                 s2 = nl80211_get_ie((u8 *) (r + 1), r->ie_len, WLAN_EID_SSID);
3919                 if (s1 == NULL || s2 == NULL || s1[1] != s2[1] ||
3920                     os_memcmp(s1, s2, 2 + s1[1]) != 0)
3921                         continue;
3923                 /* Same BSSID,SSID was already included in scan results */
3924                 wpa_printf(MSG_DEBUG, "nl80211: Remove duplicated scan result "
3925                            "for " MACSTR, MAC2STR(r->bssid));
3927                 if ((r->flags & WPA_SCAN_ASSOCIATED) &&
3928                     !(res->res[i]->flags & WPA_SCAN_ASSOCIATED)) {
3929                         os_free(res->res[i]);
3930                         res->res[i] = r;
3931                 } else
3932                         os_free(r);
3933                 return NL_SKIP;
3934         }
3936         tmp = os_realloc(res->res,
3937                          (res->num + 1) * sizeof(struct wpa_scan_res *));
3938         if (tmp == NULL) {
3939                 os_free(r);
3940                 return NL_SKIP;
3941         }
3942         tmp[res->num++] = r;
3943         res->res = tmp;
3945         return NL_SKIP;
3949 static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
3950                                  const u8 *addr)
3952         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
3953                 wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
3954                            "mismatch (" MACSTR ")", MAC2STR(addr));
3955                 wpa_driver_nl80211_mlme(drv, addr,
3956                                         NL80211_CMD_DEAUTHENTICATE,
3957                                         WLAN_REASON_PREV_AUTH_NOT_VALID, 1);
3958         }
3962 static void wpa_driver_nl80211_check_bss_status(
3963         struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
3965         size_t i;
3967         for (i = 0; i < res->num; i++) {
3968                 struct wpa_scan_res *r = res->res[i];
3969                 if (r->flags & WPA_SCAN_AUTHENTICATED) {
3970                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
3971                                    "indicates BSS status with " MACSTR
3972                                    " as authenticated",
3973                                    MAC2STR(r->bssid));
3974                         if (is_sta_interface(drv->nlmode) &&
3975                             os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
3976                             os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
3977                             0) {
3978                                 wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
3979                                            " in local state (auth=" MACSTR
3980                                            " assoc=" MACSTR ")",
3981                                            MAC2STR(drv->auth_bssid),
3982                                            MAC2STR(drv->bssid));
3983                                 clear_state_mismatch(drv, r->bssid);
3984                         }
3985                 }
3987                 if (r->flags & WPA_SCAN_ASSOCIATED) {
3988                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
3989                                    "indicate BSS status with " MACSTR
3990                                    " as associated",
3991                                    MAC2STR(r->bssid));
3992                         if (is_sta_interface(drv->nlmode) &&
3993                             !drv->associated) {
3994                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
3995                                            "(not associated) does not match "
3996                                            "with BSS state");
3997                                 clear_state_mismatch(drv, r->bssid);
3998                         } else if (is_sta_interface(drv->nlmode) &&
3999                                    os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
4000                                    0) {
4001                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
4002                                            "(associated with " MACSTR ") does "
4003                                            "not match with BSS state",
4004                                            MAC2STR(drv->bssid));
4005                                 clear_state_mismatch(drv, r->bssid);
4006                                 clear_state_mismatch(drv, drv->bssid);
4007                         }
4008                 }
4009         }
4013 static struct wpa_scan_results *
4014 nl80211_get_scan_results(struct wpa_driver_nl80211_data *drv)
4016         struct nl_msg *msg;
4017         struct wpa_scan_results *res;
4018         int ret;
4019         struct nl80211_bss_info_arg arg;
4021         res = os_zalloc(sizeof(*res));
4022         if (res == NULL)
4023                 return NULL;
4024         msg = nlmsg_alloc();
4025         if (!msg)
4026                 goto nla_put_failure;
4028         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
4029         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4031         arg.drv = drv;
4032         arg.res = res;
4033         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
4034         msg = NULL;
4035         if (ret == 0) {
4036                 wpa_printf(MSG_DEBUG, "nl80211: Received scan results (%lu "
4037                            "BSSes)", (unsigned long) res->num);
4038                 nl80211_get_noise_for_scan_results(drv, res);
4039                 return res;
4040         }
4041         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
4042                    "(%s)", ret, strerror(-ret));
4043 nla_put_failure:
4044         nlmsg_free(msg);
4045         wpa_scan_results_free(res);
4046         return NULL;
4050 /**
4051  * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
4052  * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
4053  * Returns: Scan results on success, -1 on failure
4054  */
4055 static struct wpa_scan_results *
4056 wpa_driver_nl80211_get_scan_results(void *priv)
4058         struct i802_bss *bss = priv;
4059         struct wpa_driver_nl80211_data *drv = bss->drv;
4060         struct wpa_scan_results *res;
4062         res = nl80211_get_scan_results(drv);
4063         if (res)
4064                 wpa_driver_nl80211_check_bss_status(drv, res);
4065         return res;
4069 static void nl80211_dump_scan(struct wpa_driver_nl80211_data *drv)
4071         struct wpa_scan_results *res;
4072         size_t i;
4074         res = nl80211_get_scan_results(drv);
4075         if (res == NULL) {
4076                 wpa_printf(MSG_DEBUG, "nl80211: Failed to get scan results");
4077                 return;
4078         }
4080         wpa_printf(MSG_DEBUG, "nl80211: Scan result dump");
4081         for (i = 0; i < res->num; i++) {
4082                 struct wpa_scan_res *r = res->res[i];
4083                 wpa_printf(MSG_DEBUG, "nl80211: %d/%d " MACSTR "%s%s",
4084                            (int) i, (int) res->num, MAC2STR(r->bssid),
4085                            r->flags & WPA_SCAN_AUTHENTICATED ? " [auth]" : "",
4086                            r->flags & WPA_SCAN_ASSOCIATED ? " [assoc]" : "");
4087         }
4089         wpa_scan_results_free(res);
4093 static int wpa_driver_nl80211_set_key(const char *ifname, void *priv,
4094                                       enum wpa_alg alg, const u8 *addr,
4095                                       int key_idx, int set_tx,
4096                                       const u8 *seq, size_t seq_len,
4097                                       const u8 *key, size_t key_len)
4099         struct i802_bss *bss = priv;
4100         struct wpa_driver_nl80211_data *drv = bss->drv;
4101         int ifindex = if_nametoindex(ifname);
4102         struct nl_msg *msg;
4103         int ret;
4105         wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
4106                    "set_tx=%d seq_len=%lu key_len=%lu",
4107                    __func__, ifindex, alg, addr, key_idx, set_tx,
4108                    (unsigned long) seq_len, (unsigned long) key_len);
4109 #ifdef CONFIG_TDLS
4110         if (key_idx == -1)
4111                 key_idx = 0;
4112 #endif /* CONFIG_TDLS */
4114         msg = nlmsg_alloc();
4115         if (!msg)
4116                 return -ENOMEM;
4118         if (alg == WPA_ALG_NONE) {
4119                 nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_KEY);
4120         } else {
4121                 nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_KEY);
4122                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
4123                 switch (alg) {
4124                 case WPA_ALG_WEP:
4125                         if (key_len == 5)
4126                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4127                                             WLAN_CIPHER_SUITE_WEP40);
4128                         else
4129                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4130                                             WLAN_CIPHER_SUITE_WEP104);
4131                         break;
4132                 case WPA_ALG_TKIP:
4133                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4134                                     WLAN_CIPHER_SUITE_TKIP);
4135                         break;
4136                 case WPA_ALG_CCMP:
4137                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4138                                     WLAN_CIPHER_SUITE_CCMP);
4139                         break;
4140                 case WPA_ALG_IGTK:
4141                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4142                                     WLAN_CIPHER_SUITE_AES_CMAC);
4143                         break;
4144                 default:
4145                         wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4146                                    "algorithm %d", __func__, alg);
4147                         nlmsg_free(msg);
4148                         return -1;
4149                 }
4150         }
4152         if (seq && seq_len)
4153                 NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
4155         if (addr && !is_broadcast_ether_addr(addr)) {
4156                 wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
4157                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4159                 if (alg != WPA_ALG_WEP && key_idx && !set_tx) {
4160                         wpa_printf(MSG_DEBUG, "   RSN IBSS RX GTK");
4161                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_TYPE,
4162                                     NL80211_KEYTYPE_GROUP);
4163                 }
4164         } else if (addr && is_broadcast_ether_addr(addr)) {
4165                 struct nl_msg *types;
4166                 int err;
4167                 wpa_printf(MSG_DEBUG, "   broadcast key");
4168                 types = nlmsg_alloc();
4169                 if (!types)
4170                         goto nla_put_failure;
4171                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
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         }
4178         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4179         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4181         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4182         if ((ret == -ENOENT || ret == -ENOLINK) && alg == WPA_ALG_NONE)
4183                 ret = 0;
4184         if (ret)
4185                 wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
4186                            ret, strerror(-ret));
4188         /*
4189          * If we failed or don't need to set the default TX key (below),
4190          * we're done here.
4191          */
4192         if (ret || !set_tx || alg == WPA_ALG_NONE)
4193                 return ret;
4194         if (is_ap_interface(drv->nlmode) && addr &&
4195             !is_broadcast_ether_addr(addr))
4196                 return ret;
4198         msg = nlmsg_alloc();
4199         if (!msg)
4200                 return -ENOMEM;
4202         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_KEY);
4203         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4204         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4205         if (alg == WPA_ALG_IGTK)
4206                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
4207         else
4208                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
4209         if (addr && is_broadcast_ether_addr(addr)) {
4210                 struct nl_msg *types;
4211                 int err;
4212                 types = nlmsg_alloc();
4213                 if (!types)
4214                         goto nla_put_failure;
4215                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4216                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4217                                      types);
4218                 nlmsg_free(types);
4219                 if (err)
4220                         goto nla_put_failure;
4221         } else if (addr) {
4222                 struct nl_msg *types;
4223                 int err;
4224                 types = nlmsg_alloc();
4225                 if (!types)
4226                         goto nla_put_failure;
4227                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_UNICAST);
4228                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4229                                      types);
4230                 nlmsg_free(types);
4231                 if (err)
4232                         goto nla_put_failure;
4233         }
4235         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4236         if (ret == -ENOENT)
4237                 ret = 0;
4238         if (ret)
4239                 wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
4240                            "err=%d %s)", ret, strerror(-ret));
4241         return ret;
4243 nla_put_failure:
4244         nlmsg_free(msg);
4245         return -ENOBUFS;
4249 static int nl_add_key(struct nl_msg *msg, enum wpa_alg alg,
4250                       int key_idx, int defkey,
4251                       const u8 *seq, size_t seq_len,
4252                       const u8 *key, size_t key_len)
4254         struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
4255         if (!key_attr)
4256                 return -1;
4258         if (defkey && alg == WPA_ALG_IGTK)
4259                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
4260         else if (defkey)
4261                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4263         NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
4265         switch (alg) {
4266         case WPA_ALG_WEP:
4267                 if (key_len == 5)
4268                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4269                                     WLAN_CIPHER_SUITE_WEP40);
4270                 else
4271                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4272                                     WLAN_CIPHER_SUITE_WEP104);
4273                 break;
4274         case WPA_ALG_TKIP:
4275                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_TKIP);
4276                 break;
4277         case WPA_ALG_CCMP:
4278                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_CCMP);
4279                 break;
4280         case WPA_ALG_IGTK:
4281                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4282                             WLAN_CIPHER_SUITE_AES_CMAC);
4283                 break;
4284         default:
4285                 wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4286                            "algorithm %d", __func__, alg);
4287                 return -1;
4288         }
4290         if (seq && seq_len)
4291                 NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
4293         NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
4295         nla_nest_end(msg, key_attr);
4297         return 0;
4298  nla_put_failure:
4299         return -1;
4303 static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
4304                                  struct nl_msg *msg)
4306         int i, privacy = 0;
4307         struct nlattr *nl_keys, *nl_key;
4309         for (i = 0; i < 4; i++) {
4310                 if (!params->wep_key[i])
4311                         continue;
4312                 privacy = 1;
4313                 break;
4314         }
4315         if (params->wps == WPS_MODE_PRIVACY)
4316                 privacy = 1;
4317         if (params->pairwise_suite &&
4318             params->pairwise_suite != WPA_CIPHER_NONE)
4319                 privacy = 1;
4321         if (!privacy)
4322                 return 0;
4324         NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
4326         nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
4327         if (!nl_keys)
4328                 goto nla_put_failure;
4330         for (i = 0; i < 4; i++) {
4331                 if (!params->wep_key[i])
4332                         continue;
4334                 nl_key = nla_nest_start(msg, i);
4335                 if (!nl_key)
4336                         goto nla_put_failure;
4338                 NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
4339                         params->wep_key[i]);
4340                 if (params->wep_key_len[i] == 5)
4341                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4342                                     WLAN_CIPHER_SUITE_WEP40);
4343                 else
4344                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4345                                     WLAN_CIPHER_SUITE_WEP104);
4347                 NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
4349                 if (i == params->wep_tx_keyidx)
4350                         NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4352                 nla_nest_end(msg, nl_key);
4353         }
4354         nla_nest_end(msg, nl_keys);
4356         return 0;
4358 nla_put_failure:
4359         return -ENOBUFS;
4363 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
4364                                    const u8 *addr, int cmd, u16 reason_code,
4365                                    int local_state_change)
4367         int ret = -1;
4368         struct nl_msg *msg;
4370         msg = nlmsg_alloc();
4371         if (!msg)
4372                 return -1;
4374         nl80211_cmd(drv, msg, 0, cmd);
4376         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4377         NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
4378         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4379         if (local_state_change)
4380                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4382         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4383         msg = NULL;
4384         if (ret) {
4385                 wpa_dbg(drv->ctx, MSG_DEBUG,
4386                         "nl80211: MLME command failed: reason=%u ret=%d (%s)",
4387                         reason_code, ret, strerror(-ret));
4388                 goto nla_put_failure;
4389         }
4390         ret = 0;
4392 nla_put_failure:
4393         nlmsg_free(msg);
4394         return ret;
4398 static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
4399                                          const u8 *addr, int reason_code)
4401         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
4402                    __func__, MAC2STR(addr), reason_code);
4403         drv->associated = 0;
4404         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISCONNECT,
4405                                        reason_code, 0);
4409 static int wpa_driver_nl80211_deauthenticate(void *priv, const u8 *addr,
4410                                              int reason_code)
4412         struct i802_bss *bss = priv;
4413         struct wpa_driver_nl80211_data *drv = bss->drv;
4414         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
4415                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
4416         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
4417                    __func__, MAC2STR(addr), reason_code);
4418         drv->associated = 0;
4419         if (drv->nlmode == NL80211_IFTYPE_ADHOC)
4420                 return nl80211_leave_ibss(drv);
4421         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
4422                                        reason_code, 0);
4426 static int wpa_driver_nl80211_disassociate(void *priv, const u8 *addr,
4427                                            int reason_code)
4429         struct i802_bss *bss = priv;
4430         struct wpa_driver_nl80211_data *drv = bss->drv;
4431         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
4432                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
4433         wpa_printf(MSG_DEBUG, "%s", __func__);
4434         drv->associated = 0;
4435         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISASSOCIATE,
4436                                        reason_code, 0);
4440 static void nl80211_copy_auth_params(struct wpa_driver_nl80211_data *drv,
4441                                      struct wpa_driver_auth_params *params)
4443         int i;
4445         drv->auth_freq = params->freq;
4446         drv->auth_alg = params->auth_alg;
4447         drv->auth_wep_tx_keyidx = params->wep_tx_keyidx;
4448         drv->auth_local_state_change = params->local_state_change;
4449         drv->auth_p2p = params->p2p;
4451         if (params->bssid)
4452                 os_memcpy(drv->auth_bssid_, params->bssid, ETH_ALEN);
4453         else
4454                 os_memset(drv->auth_bssid_, 0, ETH_ALEN);
4456         if (params->ssid) {
4457                 os_memcpy(drv->auth_ssid, params->ssid, params->ssid_len);
4458                 drv->auth_ssid_len = params->ssid_len;
4459         } else
4460                 drv->auth_ssid_len = 0;
4463         os_free(drv->auth_ie);
4464         drv->auth_ie = NULL;
4465         drv->auth_ie_len = 0;
4466         if (params->ie) {
4467                 drv->auth_ie = os_malloc(params->ie_len);
4468                 if (drv->auth_ie) {
4469                         os_memcpy(drv->auth_ie, params->ie, params->ie_len);
4470                         drv->auth_ie_len = params->ie_len;
4471                 }
4472         }
4474         for (i = 0; i < 4; i++) {
4475                 if (params->wep_key[i] && params->wep_key_len[i] &&
4476                     params->wep_key_len[i] <= 16) {
4477                         os_memcpy(drv->auth_wep_key[i], params->wep_key[i],
4478                                   params->wep_key_len[i]);
4479                         drv->auth_wep_key_len[i] = params->wep_key_len[i];
4480                 } else
4481                         drv->auth_wep_key_len[i] = 0;
4482         }
4486 static int wpa_driver_nl80211_authenticate(
4487         void *priv, struct wpa_driver_auth_params *params)
4489         struct i802_bss *bss = priv;
4490         struct wpa_driver_nl80211_data *drv = bss->drv;
4491         int ret = -1, i;
4492         struct nl_msg *msg;
4493         enum nl80211_auth_type type;
4494         enum nl80211_iftype nlmode;
4495         int count = 0;
4496         int is_retry;
4498         is_retry = drv->retry_auth;
4499         drv->retry_auth = 0;
4501         drv->associated = 0;
4502         os_memset(drv->auth_bssid, 0, ETH_ALEN);
4503         /* FIX: IBSS mode */
4504         nlmode = params->p2p ?
4505                 NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
4506         if (drv->nlmode != nlmode &&
4507             wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
4508                 return -1;
4510 retry:
4511         msg = nlmsg_alloc();
4512         if (!msg)
4513                 return -1;
4515         wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
4516                    drv->ifindex);
4518         nl80211_cmd(drv, msg, 0, NL80211_CMD_AUTHENTICATE);
4520         for (i = 0; i < 4; i++) {
4521                 if (!params->wep_key[i])
4522                         continue;
4523                 wpa_driver_nl80211_set_key(bss->ifname, priv, WPA_ALG_WEP,
4524                                            NULL, i,
4525                                            i == params->wep_tx_keyidx, NULL, 0,
4526                                            params->wep_key[i],
4527                                            params->wep_key_len[i]);
4528                 if (params->wep_tx_keyidx != i)
4529                         continue;
4530                 if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
4531                                params->wep_key[i], params->wep_key_len[i])) {
4532                         nlmsg_free(msg);
4533                         return -1;
4534                 }
4535         }
4537         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4538         if (params->bssid) {
4539                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4540                            MAC2STR(params->bssid));
4541                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4542         }
4543         if (params->freq) {
4544                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4545                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4546         }
4547         if (params->ssid) {
4548                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4549                                   params->ssid, params->ssid_len);
4550                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4551                         params->ssid);
4552         }
4553         wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
4554         if (params->ie)
4555                 NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
4556         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
4557                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
4558         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
4559                 type = NL80211_AUTHTYPE_SHARED_KEY;
4560         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
4561                 type = NL80211_AUTHTYPE_NETWORK_EAP;
4562         else if (params->auth_alg & WPA_AUTH_ALG_FT)
4563                 type = NL80211_AUTHTYPE_FT;
4564         else
4565                 goto nla_put_failure;
4566         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
4567         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
4568         if (params->local_state_change) {
4569                 wpa_printf(MSG_DEBUG, "  * Local state change only");
4570                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4571         }
4573         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4574         msg = NULL;
4575         if (ret) {
4576                 wpa_dbg(drv->ctx, MSG_DEBUG,
4577                         "nl80211: MLME command failed (auth): ret=%d (%s)",
4578                         ret, strerror(-ret));
4579                 count++;
4580                 if (ret == -EALREADY && count == 1 && params->bssid &&
4581                     !params->local_state_change) {
4582                         /*
4583                          * mac80211 does not currently accept new
4584                          * authentication if we are already authenticated. As a
4585                          * workaround, force deauthentication and try again.
4586                          */
4587                         wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
4588                                    "after forced deauthentication");
4589                         wpa_driver_nl80211_deauthenticate(
4590                                 bss, params->bssid,
4591                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
4592                         nlmsg_free(msg);
4593                         goto retry;
4594                 }
4596                 if (ret == -ENOENT && params->freq && !is_retry) {
4597                         /*
4598                          * cfg80211 has likely expired the BSS entry even
4599                          * though it was previously available in our internal
4600                          * BSS table. To recover quickly, start a single
4601                          * channel scan on the specified channel.
4602                          */
4603                         struct wpa_driver_scan_params scan;
4604                         int freqs[2];
4606                         os_memset(&scan, 0, sizeof(scan));
4607                         scan.num_ssids = 1;
4608                         if (params->ssid) {
4609                                 scan.ssids[0].ssid = params->ssid;
4610                                 scan.ssids[0].ssid_len = params->ssid_len;
4611                         }
4612                         freqs[0] = params->freq;
4613                         freqs[1] = 0;
4614                         scan.freqs = freqs;
4615                         wpa_printf(MSG_DEBUG, "nl80211: Trigger single "
4616                                    "channel scan to refresh cfg80211 BSS "
4617                                    "entry");
4618                         ret = wpa_driver_nl80211_scan(bss, &scan);
4619                         if (ret == 0) {
4620                                 nl80211_copy_auth_params(drv, params);
4621                                 drv->scan_for_auth = 1;
4622                         }
4623                 } else if (is_retry) {
4624                         /*
4625                          * Need to indicate this with an event since the return
4626                          * value from the retry is not delivered to core code.
4627                          */
4628                         union wpa_event_data event;
4629                         wpa_printf(MSG_DEBUG, "nl80211: Authentication retry "
4630                                    "failed");
4631                         os_memset(&event, 0, sizeof(event));
4632                         os_memcpy(event.timeout_event.addr, drv->auth_bssid_,
4633                                   ETH_ALEN);
4634                         wpa_supplicant_event(drv->ctx, EVENT_AUTH_TIMED_OUT,
4635                                              &event);
4636                 }
4638                 goto nla_put_failure;
4639         }
4640         ret = 0;
4641         wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
4642                    "successfully");
4644 nla_put_failure:
4645         nlmsg_free(msg);
4646         return ret;
4650 static int wpa_driver_nl80211_authenticate_retry(
4651         struct wpa_driver_nl80211_data *drv)
4653         struct wpa_driver_auth_params params;
4654         struct i802_bss *bss = &drv->first_bss;
4655         int i;
4657         wpa_printf(MSG_DEBUG, "nl80211: Try to authenticate again");
4659         os_memset(&params, 0, sizeof(params));
4660         params.freq = drv->auth_freq;
4661         params.auth_alg = drv->auth_alg;
4662         params.wep_tx_keyidx = drv->auth_wep_tx_keyidx;
4663         params.local_state_change = drv->auth_local_state_change;
4664         params.p2p = drv->auth_p2p;
4666         if (!is_zero_ether_addr(drv->auth_bssid_))
4667                 params.bssid = drv->auth_bssid_;
4669         if (drv->auth_ssid_len) {
4670                 params.ssid = drv->auth_ssid;
4671                 params.ssid_len = drv->auth_ssid_len;
4672         }
4674         params.ie = drv->auth_ie;
4675         params.ie_len = drv->auth_ie_len;
4677         for (i = 0; i < 4; i++) {
4678                 if (drv->auth_wep_key_len[i]) {
4679                         params.wep_key[i] = drv->auth_wep_key[i];
4680                         params.wep_key_len[i] = drv->auth_wep_key_len[i];
4681                 }
4682         }
4684         drv->retry_auth = 1;
4685         return wpa_driver_nl80211_authenticate(bss, &params);
4689 struct phy_info_arg {
4690         u16 *num_modes;
4691         struct hostapd_hw_modes *modes;
4692 };
4694 static int phy_info_handler(struct nl_msg *msg, void *arg)
4696         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
4697         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
4698         struct phy_info_arg *phy_info = arg;
4700         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
4702         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
4703         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
4704                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
4705                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
4706                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
4707                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
4708                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
4709                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
4710         };
4712         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
4713         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
4714                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
4715                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
4716         };
4718         struct nlattr *nl_band;
4719         struct nlattr *nl_freq;
4720         struct nlattr *nl_rate;
4721         int rem_band, rem_freq, rem_rate;
4722         struct hostapd_hw_modes *mode;
4723         int idx, mode_is_set;
4725         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
4726                   genlmsg_attrlen(gnlh, 0), NULL);
4728         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
4729                 return NL_SKIP;
4731         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
4732                 mode = os_realloc(phy_info->modes, (*phy_info->num_modes + 1) * sizeof(*mode));
4733                 if (!mode)
4734                         return NL_SKIP;
4735                 phy_info->modes = mode;
4737                 mode_is_set = 0;
4739                 mode = &phy_info->modes[*(phy_info->num_modes)];
4740                 memset(mode, 0, sizeof(*mode));
4741                 mode->flags = HOSTAPD_MODE_FLAG_HT_INFO_KNOWN;
4742                 *(phy_info->num_modes) += 1;
4744                 nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
4745                           nla_len(nl_band), NULL);
4747                 if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
4748                         mode->ht_capab = nla_get_u16(
4749                                 tb_band[NL80211_BAND_ATTR_HT_CAPA]);
4750                 }
4752                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) {
4753                         mode->a_mpdu_params |= nla_get_u8(
4754                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) &
4755                                 0x03;
4756                 }
4758                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) {
4759                         mode->a_mpdu_params |= nla_get_u8(
4760                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) <<
4761                                 2;
4762                 }
4764                 if (tb_band[NL80211_BAND_ATTR_HT_MCS_SET] &&
4765                     nla_len(tb_band[NL80211_BAND_ATTR_HT_MCS_SET])) {
4766                         u8 *mcs;
4767                         mcs = nla_data(tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
4768                         os_memcpy(mode->mcs_set, mcs, 16);
4769                 }
4771                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
4772                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
4773                                   nla_len(nl_freq), freq_policy);
4774                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
4775                                 continue;
4776                         mode->num_channels++;
4777                 }
4779                 mode->channels = os_zalloc(mode->num_channels * sizeof(struct hostapd_channel_data));
4780                 if (!mode->channels)
4781                         return NL_SKIP;
4783                 idx = 0;
4785                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
4786                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
4787                                   nla_len(nl_freq), freq_policy);
4788                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
4789                                 continue;
4791                         mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
4792                         mode->channels[idx].flag = 0;
4794                         if (!mode_is_set) {
4795                                 /* crude heuristic */
4796                                 if (mode->channels[idx].freq < 4000)
4797                                         mode->mode = HOSTAPD_MODE_IEEE80211B;
4798                                 else
4799                                         mode->mode = HOSTAPD_MODE_IEEE80211A;
4800                                 mode_is_set = 1;
4801                         }
4803                         /* crude heuristic */
4804                         if (mode->channels[idx].freq < 4000)
4805                                 if (mode->channels[idx].freq == 2484)
4806                                         mode->channels[idx].chan = 14;
4807                                 else
4808                                         mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
4809                         else
4810                                 mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
4812                         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
4813                                 mode->channels[idx].flag |=
4814                                         HOSTAPD_CHAN_DISABLED;
4815                         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
4816                                 mode->channels[idx].flag |=
4817                                         HOSTAPD_CHAN_PASSIVE_SCAN;
4818                         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
4819                                 mode->channels[idx].flag |=
4820                                         HOSTAPD_CHAN_NO_IBSS;
4821                         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
4822                                 mode->channels[idx].flag |=
4823                                         HOSTAPD_CHAN_RADAR;
4825                         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
4826                             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
4827                                 mode->channels[idx].max_tx_power =
4828                                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
4830                         idx++;
4831                 }
4833                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
4834                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
4835                                   nla_len(nl_rate), rate_policy);
4836                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
4837                                 continue;
4838                         mode->num_rates++;
4839                 }
4841                 mode->rates = os_zalloc(mode->num_rates * sizeof(int));
4842                 if (!mode->rates)
4843                         return NL_SKIP;
4845                 idx = 0;
4847                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
4848                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
4849                                   nla_len(nl_rate), rate_policy);
4850                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
4851                                 continue;
4852                         mode->rates[idx] = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
4854                         /* crude heuristic */
4855                         if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
4856                             mode->rates[idx] > 200)
4857                                 mode->mode = HOSTAPD_MODE_IEEE80211G;
4859                         idx++;
4860                 }
4861         }
4863         return NL_SKIP;
4866 static struct hostapd_hw_modes *
4867 wpa_driver_nl80211_add_11b(struct hostapd_hw_modes *modes, u16 *num_modes)
4869         u16 m;
4870         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
4871         int i, mode11g_idx = -1;
4873         /* If only 802.11g mode is included, use it to construct matching
4874          * 802.11b mode data. */
4876         for (m = 0; m < *num_modes; m++) {
4877                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
4878                         return modes; /* 802.11b already included */
4879                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
4880                         mode11g_idx = m;
4881         }
4883         if (mode11g_idx < 0)
4884                 return modes; /* 2.4 GHz band not supported at all */
4886         nmodes = os_realloc(modes, (*num_modes + 1) * sizeof(*nmodes));
4887         if (nmodes == NULL)
4888                 return modes; /* Could not add 802.11b mode */
4890         mode = &nmodes[*num_modes];
4891         os_memset(mode, 0, sizeof(*mode));
4892         (*num_modes)++;
4893         modes = nmodes;
4895         mode->mode = HOSTAPD_MODE_IEEE80211B;
4897         mode11g = &modes[mode11g_idx];
4898         mode->num_channels = mode11g->num_channels;
4899         mode->channels = os_malloc(mode11g->num_channels *
4900                                    sizeof(struct hostapd_channel_data));
4901         if (mode->channels == NULL) {
4902                 (*num_modes)--;
4903                 return modes; /* Could not add 802.11b mode */
4904         }
4905         os_memcpy(mode->channels, mode11g->channels,
4906                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
4908         mode->num_rates = 0;
4909         mode->rates = os_malloc(4 * sizeof(int));
4910         if (mode->rates == NULL) {
4911                 os_free(mode->channels);
4912                 (*num_modes)--;
4913                 return modes; /* Could not add 802.11b mode */
4914         }
4916         for (i = 0; i < mode11g->num_rates; i++) {
4917                 if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 &&
4918                     mode11g->rates[i] != 55 && mode11g->rates[i] != 110)
4919                         continue;
4920                 mode->rates[mode->num_rates] = mode11g->rates[i];
4921                 mode->num_rates++;
4922                 if (mode->num_rates == 4)
4923                         break;
4924         }
4926         if (mode->num_rates == 0) {
4927                 os_free(mode->channels);
4928                 os_free(mode->rates);
4929                 (*num_modes)--;
4930                 return modes; /* No 802.11b rates */
4931         }
4933         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
4934                    "information");
4936         return modes;
4940 static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start,
4941                                   int end)
4943         int c;
4945         for (c = 0; c < mode->num_channels; c++) {
4946                 struct hostapd_channel_data *chan = &mode->channels[c];
4947                 if (chan->freq - 10 >= start && chan->freq + 10 <= end)
4948                         chan->flag |= HOSTAPD_CHAN_HT40;
4949         }
4953 static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start,
4954                                       int end)
4956         int c;
4958         for (c = 0; c < mode->num_channels; c++) {
4959                 struct hostapd_channel_data *chan = &mode->channels[c];
4960                 if (!(chan->flag & HOSTAPD_CHAN_HT40))
4961                         continue;
4962                 if (chan->freq - 30 >= start && chan->freq - 10 <= end)
4963                         chan->flag |= HOSTAPD_CHAN_HT40MINUS;
4964                 if (chan->freq + 10 >= start && chan->freq + 30 <= end)
4965                         chan->flag |= HOSTAPD_CHAN_HT40PLUS;
4966         }
4970 static void nl80211_reg_rule_ht40(struct nlattr *tb[],
4971                                   struct phy_info_arg *results)
4973         u32 start, end, max_bw;
4974         u16 m;
4976         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
4977             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
4978             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
4979                 return;
4981         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
4982         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
4983         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
4985         wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz",
4986                    start, end, max_bw);
4987         if (max_bw < 40)
4988                 return;
4990         for (m = 0; m < *results->num_modes; m++) {
4991                 if (!(results->modes[m].ht_capab &
4992                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
4993                         continue;
4994                 nl80211_set_ht40_mode(&results->modes[m], start, end);
4995         }
4999 static void nl80211_reg_rule_sec(struct nlattr *tb[],
5000                                  struct phy_info_arg *results)
5002         u32 start, end, max_bw;
5003         u16 m;
5005         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
5006             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
5007             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
5008                 return;
5010         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
5011         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
5012         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
5014         if (max_bw < 20)
5015                 return;
5017         for (m = 0; m < *results->num_modes; m++) {
5018                 if (!(results->modes[m].ht_capab &
5019                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
5020                         continue;
5021                 nl80211_set_ht40_mode_sec(&results->modes[m], start, end);
5022         }
5026 static int nl80211_get_reg(struct nl_msg *msg, void *arg)
5028         struct phy_info_arg *results = arg;
5029         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
5030         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5031         struct nlattr *nl_rule;
5032         struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1];
5033         int rem_rule;
5034         static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
5035                 [NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
5036                 [NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
5037                 [NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
5038                 [NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
5039                 [NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
5040                 [NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
5041         };
5043         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5044                   genlmsg_attrlen(gnlh, 0), NULL);
5045         if (!tb_msg[NL80211_ATTR_REG_ALPHA2] ||
5046             !tb_msg[NL80211_ATTR_REG_RULES]) {
5047                 wpa_printf(MSG_DEBUG, "nl80211: No regulatory information "
5048                            "available");
5049                 return NL_SKIP;
5050         }
5052         wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s",
5053                    (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]));
5055         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5056         {
5057                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5058                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5059                 nl80211_reg_rule_ht40(tb_rule, results);
5060         }
5062         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5063         {
5064                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5065                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5066                 nl80211_reg_rule_sec(tb_rule, results);
5067         }
5069         return NL_SKIP;
5073 static int nl80211_set_ht40_flags(struct wpa_driver_nl80211_data *drv,
5074                                   struct phy_info_arg *results)
5076         struct nl_msg *msg;
5078         msg = nlmsg_alloc();
5079         if (!msg)
5080                 return -ENOMEM;
5082         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_REG);
5083         return send_and_recv_msgs(drv, msg, nl80211_get_reg, results);
5087 static struct hostapd_hw_modes *
5088 wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
5090         struct i802_bss *bss = priv;
5091         struct wpa_driver_nl80211_data *drv = bss->drv;
5092         struct nl_msg *msg;
5093         struct phy_info_arg result = {
5094                 .num_modes = num_modes,
5095                 .modes = NULL,
5096         };
5098         *num_modes = 0;
5099         *flags = 0;
5101         msg = nlmsg_alloc();
5102         if (!msg)
5103                 return NULL;
5105         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
5107         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5109         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) {
5110                 nl80211_set_ht40_flags(drv, &result);
5111                 return wpa_driver_nl80211_add_11b(result.modes, num_modes);
5112         }
5113         msg = NULL;
5114  nla_put_failure:
5115         nlmsg_free(msg);
5116         return NULL;
5120 static int wpa_driver_nl80211_send_mntr(struct wpa_driver_nl80211_data *drv,
5121                                         const void *data, size_t len,
5122                                         int encrypt, int noack)
5124         __u8 rtap_hdr[] = {
5125                 0x00, 0x00, /* radiotap version */
5126                 0x0e, 0x00, /* radiotap length */
5127                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
5128                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
5129                 0x00,       /* padding */
5130                 0x00, 0x00, /* RX and TX flags to indicate that */
5131                 0x00, 0x00, /* this is the injected frame directly */
5132         };
5133         struct iovec iov[2] = {
5134                 {
5135                         .iov_base = &rtap_hdr,
5136                         .iov_len = sizeof(rtap_hdr),
5137                 },
5138                 {
5139                         .iov_base = (void *) data,
5140                         .iov_len = len,
5141                 }
5142         };
5143         struct msghdr msg = {
5144                 .msg_name = NULL,
5145                 .msg_namelen = 0,
5146                 .msg_iov = iov,
5147                 .msg_iovlen = 2,
5148                 .msg_control = NULL,
5149                 .msg_controllen = 0,
5150                 .msg_flags = 0,
5151         };
5152         int res;
5153         u16 txflags = 0;
5155         if (encrypt)
5156                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
5158         if (drv->monitor_sock < 0) {
5159                 wpa_printf(MSG_DEBUG, "nl80211: No monitor socket available "
5160                            "for %s", __func__);
5161                 return -1;
5162         }
5164         if (noack)
5165                 txflags |= IEEE80211_RADIOTAP_F_TX_NOACK;
5166         *(le16 *) &rtap_hdr[12] = host_to_le16(txflags);
5168         res = sendmsg(drv->monitor_sock, &msg, 0);
5169         if (res < 0) {
5170                 wpa_printf(MSG_INFO, "nl80211: sendmsg: %s", strerror(errno));
5171                 return -1;
5172         }
5173         return 0;
5177 static int wpa_driver_nl80211_send_frame(struct i802_bss *bss,
5178                                          const void *data, size_t len,
5179                                          int encrypt, int noack,
5180                                          unsigned int freq, int no_cck,
5181                                          int offchanok, unsigned int wait_time)
5183         struct wpa_driver_nl80211_data *drv = bss->drv;
5184         u64 cookie;
5186         if (freq == 0)
5187                 freq = bss->freq;
5189         if (drv->use_monitor)
5190                 return wpa_driver_nl80211_send_mntr(drv, data, len,
5191                                                     encrypt, noack);
5193         return nl80211_send_frame_cmd(bss, freq, wait_time, data, len,
5194                                       &cookie, no_cck, noack, offchanok);
5198 static int wpa_driver_nl80211_send_mlme_freq(struct i802_bss *bss,
5199                                              const u8 *data,
5200                                              size_t data_len, int noack,
5201                                              unsigned int freq, int no_cck,
5202                                              int offchanok,
5203                                              unsigned int wait_time)
5205         struct wpa_driver_nl80211_data *drv = bss->drv;
5206         struct ieee80211_mgmt *mgmt;
5207         int encrypt = 1;
5208         u16 fc;
5210         mgmt = (struct ieee80211_mgmt *) data;
5211         fc = le_to_host16(mgmt->frame_control);
5213         if (is_sta_interface(drv->nlmode) &&
5214             WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5215             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_PROBE_RESP) {
5216                 /*
5217                  * The use of last_mgmt_freq is a bit of a hack,
5218                  * but it works due to the single-threaded nature
5219                  * of wpa_supplicant.
5220                  */
5221                 if (freq == 0)
5222                         freq = drv->last_mgmt_freq;
5223                 return nl80211_send_frame_cmd(bss, freq, 0,
5224                                               data, data_len, NULL, 1, noack,
5225                                               1);
5226         }
5228         if (drv->device_ap_sme && is_ap_interface(drv->nlmode)) {
5229                 if (freq == 0)
5230                         freq = bss->freq;
5231                 return nl80211_send_frame_cmd(bss, freq, 0,
5232                                               data, data_len,
5233                                               &drv->send_action_cookie,
5234                                               no_cck, noack, offchanok);
5235         }
5237         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5238             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
5239                 /*
5240                  * Only one of the authentication frame types is encrypted.
5241                  * In order for static WEP encryption to work properly (i.e.,
5242                  * to not encrypt the frame), we need to tell mac80211 about
5243                  * the frames that must not be encrypted.
5244                  */
5245                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
5246                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
5247                 if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
5248                         encrypt = 0;
5249         }
5251         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt,
5252                                              noack, freq, no_cck, offchanok,
5253                                              wait_time);
5257 static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
5258                                         size_t data_len, int noack)
5260         struct i802_bss *bss = priv;
5261         return wpa_driver_nl80211_send_mlme_freq(bss, data, data_len, noack,
5262                                                  0, 0, 0, 0);
5266 static int nl80211_set_bss(struct i802_bss *bss, int cts, int preamble,
5267                            int slot, int ht_opmode, int ap_isolate,
5268                            int *basic_rates)
5270         struct wpa_driver_nl80211_data *drv = bss->drv;
5271         struct nl_msg *msg;
5273         msg = nlmsg_alloc();
5274         if (!msg)
5275                 return -ENOMEM;
5277         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_BSS);
5279         if (cts >= 0)
5280                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
5281         if (preamble >= 0)
5282                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
5283         if (slot >= 0)
5284                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
5285         if (ht_opmode >= 0)
5286                 NLA_PUT_U16(msg, NL80211_ATTR_BSS_HT_OPMODE, ht_opmode);
5287         if (ap_isolate >= 0)
5288                 NLA_PUT_U8(msg, NL80211_ATTR_AP_ISOLATE, ap_isolate);
5290         if (basic_rates) {
5291                 u8 rates[NL80211_MAX_SUPP_RATES];
5292                 u8 rates_len = 0;
5293                 int i;
5295                 for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0;
5296                      i++)
5297                         rates[rates_len++] = basic_rates[i] / 5;
5299                 NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
5300         }
5302         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5304         return send_and_recv_msgs(drv, msg, NULL, NULL);
5305  nla_put_failure:
5306         nlmsg_free(msg);
5307         return -ENOBUFS;
5311 static int wpa_driver_nl80211_set_ap(void *priv,
5312                                      struct wpa_driver_ap_params *params)
5314         struct i802_bss *bss = priv;
5315         struct wpa_driver_nl80211_data *drv = bss->drv;
5316         struct nl_msg *msg;
5317         u8 cmd = NL80211_CMD_NEW_BEACON;
5318         int ret;
5319         int beacon_set;
5320         int ifindex = if_nametoindex(bss->ifname);
5321         int num_suites;
5322         u32 suites[10];
5323         u32 ver;
5325         beacon_set = bss->beacon_set;
5327         msg = nlmsg_alloc();
5328         if (!msg)
5329                 return -ENOMEM;
5331         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
5332                    beacon_set);
5333         if (beacon_set)
5334                 cmd = NL80211_CMD_SET_BEACON;
5336         nl80211_cmd(drv, msg, 0, cmd);
5337         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, params->head_len, params->head);
5338         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, params->tail_len, params->tail);
5339         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
5340         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, params->beacon_int);
5341         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, params->dtim_period);
5342         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
5343                 params->ssid);
5344         if (params->proberesp && params->proberesp_len)
5345                 NLA_PUT(msg, NL80211_ATTR_PROBE_RESP, params->proberesp_len,
5346                         params->proberesp);
5347         switch (params->hide_ssid) {
5348         case NO_SSID_HIDING:
5349                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5350                             NL80211_HIDDEN_SSID_NOT_IN_USE);
5351                 break;
5352         case HIDDEN_SSID_ZERO_LEN:
5353                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5354                             NL80211_HIDDEN_SSID_ZERO_LEN);
5355                 break;
5356         case HIDDEN_SSID_ZERO_CONTENTS:
5357                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5358                             NL80211_HIDDEN_SSID_ZERO_CONTENTS);
5359                 break;
5360         }
5361         if (params->privacy)
5362                 NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
5363         if ((params->auth_algs & (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) ==
5364             (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) {
5365                 /* Leave out the attribute */
5366         } else if (params->auth_algs & WPA_AUTH_ALG_SHARED)
5367                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5368                             NL80211_AUTHTYPE_SHARED_KEY);
5369         else
5370                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5371                             NL80211_AUTHTYPE_OPEN_SYSTEM);
5373         ver = 0;
5374         if (params->wpa_version & WPA_PROTO_WPA)
5375                 ver |= NL80211_WPA_VERSION_1;
5376         if (params->wpa_version & WPA_PROTO_RSN)
5377                 ver |= NL80211_WPA_VERSION_2;
5378         if (ver)
5379                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
5381         num_suites = 0;
5382         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X)
5383                 suites[num_suites++] = WLAN_AKM_SUITE_8021X;
5384         if (params->key_mgmt_suites & WPA_KEY_MGMT_PSK)
5385                 suites[num_suites++] = WLAN_AKM_SUITE_PSK;
5386         if (num_suites) {
5387                 NLA_PUT(msg, NL80211_ATTR_AKM_SUITES,
5388                         num_suites * sizeof(u32), suites);
5389         }
5391         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X &&
5392             params->pairwise_ciphers & (WPA_CIPHER_WEP104 | WPA_CIPHER_WEP40))
5393                 NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT);
5395         num_suites = 0;
5396         if (params->pairwise_ciphers & WPA_CIPHER_CCMP)
5397                 suites[num_suites++] = WLAN_CIPHER_SUITE_CCMP;
5398         if (params->pairwise_ciphers & WPA_CIPHER_TKIP)
5399                 suites[num_suites++] = WLAN_CIPHER_SUITE_TKIP;
5400         if (params->pairwise_ciphers & WPA_CIPHER_WEP104)
5401                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP104;
5402         if (params->pairwise_ciphers & WPA_CIPHER_WEP40)
5403                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP40;
5404         if (num_suites) {
5405                 NLA_PUT(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE,
5406                         num_suites * sizeof(u32), suites);
5407         }
5409         switch (params->group_cipher) {
5410         case WPA_CIPHER_CCMP:
5411                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5412                             WLAN_CIPHER_SUITE_CCMP);
5413                 break;
5414         case WPA_CIPHER_TKIP:
5415                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5416                             WLAN_CIPHER_SUITE_TKIP);
5417                 break;
5418         case WPA_CIPHER_WEP104:
5419                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5420                             WLAN_CIPHER_SUITE_WEP104);
5421                 break;
5422         case WPA_CIPHER_WEP40:
5423                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5424                             WLAN_CIPHER_SUITE_WEP40);
5425                 break;
5426         }
5428         if (params->beacon_ies) {
5429                 NLA_PUT(msg, NL80211_ATTR_IE, wpabuf_len(params->beacon_ies),
5430                         wpabuf_head(params->beacon_ies));
5431         }
5432         if (params->proberesp_ies) {
5433                 NLA_PUT(msg, NL80211_ATTR_IE_PROBE_RESP,
5434                         wpabuf_len(params->proberesp_ies),
5435                         wpabuf_head(params->proberesp_ies));
5436         }
5437         if (params->assocresp_ies) {
5438                 NLA_PUT(msg, NL80211_ATTR_IE_ASSOC_RESP,
5439                         wpabuf_len(params->assocresp_ies),
5440                         wpabuf_head(params->assocresp_ies));
5441         }
5443         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5444         if (ret) {
5445                 wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
5446                            ret, strerror(-ret));
5447         } else {
5448                 bss->beacon_set = 1;
5449                 nl80211_set_bss(bss, params->cts_protect, params->preamble,
5450                                 params->short_slot_time, params->ht_opmode,
5451                                 params->isolate, params->basic_rates);
5452         }
5453 #if defined(ANDROID_BRCM_P2P_PATCH) && defined(HOSTAPD)
5454         wpa_driver_nl80211_probe_req_report(priv, 1);
5455 #endif
5456         return ret;
5457  nla_put_failure:
5458         nlmsg_free(msg);
5459         return -ENOBUFS;
5463 static int wpa_driver_nl80211_set_freq(struct i802_bss *bss,
5464                                        int freq, int ht_enabled,
5465                                        int sec_channel_offset)
5467         struct wpa_driver_nl80211_data *drv = bss->drv;
5468         struct nl_msg *msg;
5469         int ret;
5471         wpa_printf(MSG_DEBUG, "nl80211: Set freq %d (ht_enabled=%d "
5472                    "sec_channel_offset=%d)",
5473                    freq, ht_enabled, sec_channel_offset);
5474         msg = nlmsg_alloc();
5475         if (!msg)
5476                 return -1;
5478         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
5480         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5481         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
5482         if (ht_enabled) {
5483                 switch (sec_channel_offset) {
5484                 case -1:
5485                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5486                                     NL80211_CHAN_HT40MINUS);
5487                         break;
5488                 case 1:
5489                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5490                                     NL80211_CHAN_HT40PLUS);
5491                         break;
5492                 default:
5493 #ifdef ANDROID_BRCM_P2P_PATCH
5494                         /* Should be changed to HT20 as a default value because
5495                          * P2P firmware does not support 11n for BCM4329 */
5496                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5497                                     NL80211_CHAN_NO_HT);
5498 #else /* ANDROID_BRCM_P2P_PATCH */
5499                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5500                                     NL80211_CHAN_HT20);
5501 #endif /* ANDROID_BRCM_P2P_PATCH */
5502                         break;
5503                 }
5504         }
5506         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5507         msg = NULL;
5508         if (ret == 0) {
5509                 bss->freq = freq;
5510                 return 0;
5511         }
5512         wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
5513                    "%d (%s)", freq, ret, strerror(-ret));
5514 nla_put_failure:
5515         nlmsg_free(msg);
5516         return -1;
5520 static u32 sta_flags_nl80211(int flags)
5522         u32 f = 0;
5524         if (flags & WPA_STA_AUTHORIZED)
5525                 f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
5526         if (flags & WPA_STA_WMM)
5527                 f |= BIT(NL80211_STA_FLAG_WME);
5528         if (flags & WPA_STA_SHORT_PREAMBLE)
5529                 f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
5530         if (flags & WPA_STA_MFP)
5531                 f |= BIT(NL80211_STA_FLAG_MFP);
5532         if (flags & WPA_STA_TDLS_PEER)
5533                 f |= BIT(NL80211_STA_FLAG_TDLS_PEER);
5535         return f;
5539 static int wpa_driver_nl80211_sta_add(void *priv,
5540                                       struct hostapd_sta_add_params *params)
5542         struct i802_bss *bss = priv;
5543         struct wpa_driver_nl80211_data *drv = bss->drv;
5544         struct nl_msg *msg, *wme = NULL;
5545         struct nl80211_sta_flag_update upd;
5546         int ret = -ENOBUFS;
5548         if ((params->flags & WPA_STA_TDLS_PEER) &&
5549             !(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
5550                 return -EOPNOTSUPP;
5552         msg = nlmsg_alloc();
5553         if (!msg)
5554                 return -ENOMEM;
5556         nl80211_cmd(drv, msg, 0, params->set ? NL80211_CMD_SET_STATION :
5557                     NL80211_CMD_NEW_STATION);
5559         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5560         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
5561         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
5562                 params->supp_rates);
5563         if (!params->set) {
5564                 NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
5565                 NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
5566                             params->listen_interval);
5567         }
5568         if (params->ht_capabilities) {
5569                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
5570                         sizeof(*params->ht_capabilities),
5571                         params->ht_capabilities);
5572         }
5574         os_memset(&upd, 0, sizeof(upd));
5575         upd.mask = sta_flags_nl80211(params->flags);
5576         upd.set = upd.mask;
5577         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
5579         if (params->flags & WPA_STA_WMM) {
5580                 wme = nlmsg_alloc();
5581                 if (!wme)
5582                         goto nla_put_failure;
5584                 NLA_PUT_U8(wme, NL80211_STA_WME_UAPSD_QUEUES,
5585                                 params->qosinfo & WMM_QOSINFO_STA_AC_MASK);
5586                 NLA_PUT_U8(wme, NL80211_STA_WME_MAX_SP,
5587                                 (params->qosinfo > WMM_QOSINFO_STA_SP_SHIFT) &
5588                                 WMM_QOSINFO_STA_SP_MASK);
5589                 nla_put_nested(msg, NL80211_ATTR_STA_WME, wme);
5590         }
5592         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5593         msg = NULL;
5594         if (ret)
5595                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_%s_STATION "
5596                            "result: %d (%s)", params->set ? "SET" : "NEW", ret,
5597                            strerror(-ret));
5598         if (ret == -EEXIST)
5599                 ret = 0;
5600  nla_put_failure:
5601         nlmsg_free(wme);
5602         nlmsg_free(msg);
5603         return ret;
5607 static int wpa_driver_nl80211_sta_remove(void *priv, const u8 *addr)
5609         struct i802_bss *bss = priv;
5610         struct wpa_driver_nl80211_data *drv = bss->drv;
5611         struct nl_msg *msg;
5612         int ret;
5614         msg = nlmsg_alloc();
5615         if (!msg)
5616                 return -ENOMEM;
5618         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
5620         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5621                     if_nametoindex(bss->ifname));
5622         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5624         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5625         if (ret == -ENOENT)
5626                 return 0;
5627         return ret;
5628  nla_put_failure:
5629         nlmsg_free(msg);
5630         return -ENOBUFS;
5634 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
5635                                  int ifidx)
5637         struct nl_msg *msg;
5639         wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
5641         /* stop listening for EAPOL on this interface */
5642         del_ifidx(drv, ifidx);
5644         msg = nlmsg_alloc();
5645         if (!msg)
5646                 goto nla_put_failure;
5648         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_INTERFACE);
5649         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
5651         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
5652                 return;
5653         msg = NULL;
5654  nla_put_failure:
5655         nlmsg_free(msg);
5656         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
5660 static const char * nl80211_iftype_str(enum nl80211_iftype mode)
5662         switch (mode) {
5663         case NL80211_IFTYPE_ADHOC:
5664                 return "ADHOC";
5665         case NL80211_IFTYPE_STATION:
5666                 return "STATION";
5667         case NL80211_IFTYPE_AP:
5668                 return "AP";
5669         case NL80211_IFTYPE_MONITOR:
5670                 return "MONITOR";
5671         case NL80211_IFTYPE_P2P_CLIENT:
5672                 return "P2P_CLIENT";
5673         case NL80211_IFTYPE_P2P_GO:
5674                 return "P2P_GO";
5675         default:
5676                 return "unknown";
5677         }
5681 static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
5682                                      const char *ifname,
5683                                      enum nl80211_iftype iftype,
5684                                      const u8 *addr, int wds)
5686         struct nl_msg *msg, *flags = NULL;
5687         int ifidx;
5688         int ret = -ENOBUFS;
5690         wpa_printf(MSG_DEBUG, "nl80211: Create interface iftype %d (%s)",
5691                    iftype, nl80211_iftype_str(iftype));
5693         msg = nlmsg_alloc();
5694         if (!msg)
5695                 return -1;
5697         nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_INTERFACE);
5698         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5699         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
5700         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
5702         if (iftype == NL80211_IFTYPE_MONITOR) {
5703                 int err;
5705                 flags = nlmsg_alloc();
5706                 if (!flags)
5707                         goto nla_put_failure;
5709                 NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
5711                 err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
5713                 nlmsg_free(flags);
5715                 if (err)
5716                         goto nla_put_failure;
5717         } else if (wds) {
5718                 NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
5719         }
5721         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5722         msg = NULL;
5723         if (ret) {
5724  nla_put_failure:
5725                 nlmsg_free(msg);
5726                 wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
5727                            ifname, ret, strerror(-ret));
5728                 return ret;
5729         }
5731         ifidx = if_nametoindex(ifname);
5732         wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
5733                    ifname, ifidx);
5735         if (ifidx <= 0)
5736                 return -1;
5738         /* start listening for EAPOL on this interface */
5739         add_ifidx(drv, ifidx);
5741         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
5742             linux_set_ifhwaddr(drv->global->ioctl_sock, ifname, addr)) {
5743                 nl80211_remove_iface(drv, ifidx);
5744                 return -1;
5745         }
5747         return ifidx;
5751 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
5752                                 const char *ifname, enum nl80211_iftype iftype,
5753                                 const u8 *addr, int wds)
5755         int ret;
5757         ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds);
5759         /* if error occurred and interface exists already */
5760         if (ret == -ENFILE && if_nametoindex(ifname)) {
5761                 wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
5763                 /* Try to remove the interface that was already there. */
5764                 nl80211_remove_iface(drv, if_nametoindex(ifname));
5766                 /* Try to create the interface again */
5767                 ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
5768                                                 wds);
5769         }
5771         if (ret >= 0 && is_p2p_interface(iftype))
5772                 nl80211_disable_11b_rates(drv, ret, 1);
5774         return ret;
5778 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
5780         struct ieee80211_hdr *hdr;
5781         u16 fc;
5782         union wpa_event_data event;
5784         hdr = (struct ieee80211_hdr *) buf;
5785         fc = le_to_host16(hdr->frame_control);
5787         os_memset(&event, 0, sizeof(event));
5788         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
5789         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
5790         event.tx_status.dst = hdr->addr1;
5791         event.tx_status.data = buf;
5792         event.tx_status.data_len = len;
5793         event.tx_status.ack = ok;
5794         wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
5798 static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
5799                              u8 *buf, size_t len)
5801         struct ieee80211_hdr *hdr = (void *)buf;
5802         u16 fc;
5803         union wpa_event_data event;
5805         if (len < sizeof(*hdr))
5806                 return;
5808         fc = le_to_host16(hdr->frame_control);
5810         os_memset(&event, 0, sizeof(event));
5811         event.rx_from_unknown.bssid = get_hdr_bssid(hdr, len);
5812         event.rx_from_unknown.addr = hdr->addr2;
5813         event.rx_from_unknown.wds = (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) ==
5814                 (WLAN_FC_FROMDS | WLAN_FC_TODS);
5815         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
5819 static void handle_frame(struct wpa_driver_nl80211_data *drv,
5820                          u8 *buf, size_t len, int datarate, int ssi_signal)
5822         struct ieee80211_hdr *hdr;
5823         u16 fc;
5824         union wpa_event_data event;
5826         hdr = (struct ieee80211_hdr *) buf;
5827         fc = le_to_host16(hdr->frame_control);
5829         switch (WLAN_FC_GET_TYPE(fc)) {
5830         case WLAN_FC_TYPE_MGMT:
5831                 os_memset(&event, 0, sizeof(event));
5832                 event.rx_mgmt.frame = buf;
5833                 event.rx_mgmt.frame_len = len;
5834                 event.rx_mgmt.datarate = datarate;
5835                 event.rx_mgmt.ssi_signal = ssi_signal;
5836                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
5837                 break;
5838         case WLAN_FC_TYPE_CTRL:
5839                 /* can only get here with PS-Poll frames */
5840                 wpa_printf(MSG_DEBUG, "CTRL");
5841                 from_unknown_sta(drv, buf, len);
5842                 break;
5843         case WLAN_FC_TYPE_DATA:
5844                 from_unknown_sta(drv, buf, len);
5845                 break;
5846         }
5850 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
5852         struct wpa_driver_nl80211_data *drv = eloop_ctx;
5853         int len;
5854         unsigned char buf[3000];
5855         struct ieee80211_radiotap_iterator iter;
5856         int ret;
5857         int datarate = 0, ssi_signal = 0;
5858         int injected = 0, failed = 0, rxflags = 0;
5860         len = recv(sock, buf, sizeof(buf), 0);
5861         if (len < 0) {
5862                 perror("recv");
5863                 return;
5864         }
5866         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
5867                 printf("received invalid radiotap frame\n");
5868                 return;
5869         }
5871         while (1) {
5872                 ret = ieee80211_radiotap_iterator_next(&iter);
5873                 if (ret == -ENOENT)
5874                         break;
5875                 if (ret) {
5876                         printf("received invalid radiotap frame (%d)\n", ret);
5877                         return;
5878                 }
5879                 switch (iter.this_arg_index) {
5880                 case IEEE80211_RADIOTAP_FLAGS:
5881                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
5882                                 len -= 4;
5883                         break;
5884                 case IEEE80211_RADIOTAP_RX_FLAGS:
5885                         rxflags = 1;
5886                         break;
5887                 case IEEE80211_RADIOTAP_TX_FLAGS:
5888                         injected = 1;
5889                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
5890                                         IEEE80211_RADIOTAP_F_TX_FAIL;
5891                         break;
5892                 case IEEE80211_RADIOTAP_DATA_RETRIES:
5893                         break;
5894                 case IEEE80211_RADIOTAP_CHANNEL:
5895                         /* TODO: convert from freq/flags to channel number */
5896                         break;
5897                 case IEEE80211_RADIOTAP_RATE:
5898                         datarate = *iter.this_arg * 5;
5899                         break;
5900                 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
5901                         ssi_signal = *iter.this_arg;
5902                         break;
5903                 }
5904         }
5906         if (rxflags && injected)
5907                 return;
5909         if (!injected)
5910                 handle_frame(drv, buf + iter.max_length,
5911                              len - iter.max_length, datarate, ssi_signal);
5912         else
5913                 handle_tx_callback(drv->ctx, buf + iter.max_length,
5914                                    len - iter.max_length, !failed);
5918 /*
5919  * we post-process the filter code later and rewrite
5920  * this to the offset to the last instruction
5921  */
5922 #define PASS    0xFF
5923 #define FAIL    0xFE
5925 static struct sock_filter msock_filter_insns[] = {
5926         /*
5927          * do a little-endian load of the radiotap length field
5928          */
5929         /* load lower byte into A */
5930         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
5931         /* put it into X (== index register) */
5932         BPF_STMT(BPF_MISC| BPF_TAX, 0),
5933         /* load upper byte into A */
5934         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
5935         /* left-shift it by 8 */
5936         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
5937         /* or with X */
5938         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
5939         /* put result into X */
5940         BPF_STMT(BPF_MISC| BPF_TAX, 0),
5942         /*
5943          * Allow management frames through, this also gives us those
5944          * management frames that we sent ourselves with status
5945          */
5946         /* load the lower byte of the IEEE 802.11 frame control field */
5947         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
5948         /* mask off frame type and version */
5949         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
5950         /* accept frame if it's both 0, fall through otherwise */
5951         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
5953         /*
5954          * TODO: add a bit to radiotap RX flags that indicates
5955          * that the sending station is not associated, then
5956          * add a filter here that filters on our DA and that flag
5957          * to allow us to deauth frames to that bad station.
5958          *
5959          * For now allow all To DS data frames through.
5960          */
5961         /* load the IEEE 802.11 frame control field */
5962         BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
5963         /* mask off frame type, version and DS status */
5964         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
5965         /* accept frame if version 0, type 2 and To DS, fall through otherwise
5966          */
5967         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
5969 #if 0
5970         /*
5971          * drop non-data frames
5972          */
5973         /* load the lower byte of the frame control field */
5974         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
5975         /* mask off QoS bit */
5976         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
5977         /* drop non-data frames */
5978         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
5979 #endif
5980         /* load the upper byte of the frame control field */
5981         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
5982         /* mask off toDS/fromDS */
5983         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
5984         /* accept WDS frames */
5985         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
5987         /*
5988          * add header length to index
5989          */
5990         /* load the lower byte of the frame control field */
5991         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
5992         /* mask off QoS bit */
5993         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
5994         /* right shift it by 6 to give 0 or 2 */
5995         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
5996         /* add data frame header length */
5997         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
5998         /* add index, was start of 802.11 header */
5999         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
6000         /* move to index, now start of LL header */
6001         BPF_STMT(BPF_MISC | BPF_TAX, 0),
6003         /*
6004          * Accept empty data frames, we use those for
6005          * polling activity.
6006          */
6007         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
6008         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
6010         /*
6011          * Accept EAPOL frames
6012          */
6013         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
6014         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
6015         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
6016         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
6018         /* keep these last two statements or change the code below */
6019         /* return 0 == "DROP" */
6020         BPF_STMT(BPF_RET | BPF_K, 0),
6021         /* return ~0 == "keep all" */
6022         BPF_STMT(BPF_RET | BPF_K, ~0),
6023 };
6025 static struct sock_fprog msock_filter = {
6026         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
6027         .filter = msock_filter_insns,
6028 };
6031 static int add_monitor_filter(int s)
6033         int idx;
6035         /* rewrite all PASS/FAIL jump offsets */
6036         for (idx = 0; idx < msock_filter.len; idx++) {
6037                 struct sock_filter *insn = &msock_filter_insns[idx];
6039                 if (BPF_CLASS(insn->code) == BPF_JMP) {
6040                         if (insn->code == (BPF_JMP|BPF_JA)) {
6041                                 if (insn->k == PASS)
6042                                         insn->k = msock_filter.len - idx - 2;
6043                                 else if (insn->k == FAIL)
6044                                         insn->k = msock_filter.len - idx - 3;
6045                         }
6047                         if (insn->jt == PASS)
6048                                 insn->jt = msock_filter.len - idx - 2;
6049                         else if (insn->jt == FAIL)
6050                                 insn->jt = msock_filter.len - idx - 3;
6052                         if (insn->jf == PASS)
6053                                 insn->jf = msock_filter.len - idx - 2;
6054                         else if (insn->jf == FAIL)
6055                                 insn->jf = msock_filter.len - idx - 3;
6056                 }
6057         }
6059         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
6060                        &msock_filter, sizeof(msock_filter))) {
6061                 perror("SO_ATTACH_FILTER");
6062                 return -1;
6063         }
6065         return 0;
6069 static void nl80211_remove_monitor_interface(
6070         struct wpa_driver_nl80211_data *drv)
6072         drv->monitor_refcount--;
6073         if (drv->monitor_refcount > 0)
6074                 return;
6076         if (drv->monitor_ifidx >= 0) {
6077                 nl80211_remove_iface(drv, drv->monitor_ifidx);
6078                 drv->monitor_ifidx = -1;
6079         }
6080         if (drv->monitor_sock >= 0) {
6081                 eloop_unregister_read_sock(drv->monitor_sock);
6082                 close(drv->monitor_sock);
6083                 drv->monitor_sock = -1;
6084         }
6088 static int
6089 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
6091         char buf[IFNAMSIZ];
6092         struct sockaddr_ll ll;
6093         int optval;
6094         socklen_t optlen;
6096         if (drv->monitor_ifidx >= 0) {
6097                 drv->monitor_refcount++;
6098                 return 0;
6099         }
6101         if (os_strncmp(drv->first_bss.ifname, "p2p-", 4) == 0) {
6102                 /*
6103                  * P2P interface name is of the format p2p-%s-%d. For monitor
6104                  * interface name corresponding to P2P GO, replace "p2p-" with
6105                  * "mon-" to retain the same interface name length and to
6106                  * indicate that it is a monitor interface.
6107                  */
6108                 snprintf(buf, IFNAMSIZ, "mon-%s", drv->first_bss.ifname + 4);
6109         } else {
6110                 /* Non-P2P interface with AP functionality. */
6111                 snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss.ifname);
6112         }
6114         buf[IFNAMSIZ - 1] = '\0';
6116         drv->monitor_ifidx =
6117                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
6118                                      0);
6120         if (drv->monitor_ifidx == -EOPNOTSUPP) {
6121                 /*
6122                  * This is backward compatibility for a few versions of
6123                  * the kernel only that didn't advertise the right
6124                  * attributes for the only driver that then supported
6125                  * AP mode w/o monitor -- ath6kl.
6126                  */
6127                 wpa_printf(MSG_DEBUG, "nl80211: Driver does not support "
6128                            "monitor interface type - try to run without it");
6129                 drv->device_ap_sme = 1;
6130         }
6132         if (drv->monitor_ifidx < 0)
6133                 return -1;
6135         if (linux_set_iface_flags(drv->global->ioctl_sock, buf, 1))
6136                 goto error;
6138         memset(&ll, 0, sizeof(ll));
6139         ll.sll_family = AF_PACKET;
6140         ll.sll_ifindex = drv->monitor_ifidx;
6141         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
6142         if (drv->monitor_sock < 0) {
6143                 perror("socket[PF_PACKET,SOCK_RAW]");
6144                 goto error;
6145         }
6147         if (add_monitor_filter(drv->monitor_sock)) {
6148                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
6149                            "interface; do filtering in user space");
6150                 /* This works, but will cost in performance. */
6151         }
6153         if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
6154                 perror("monitor socket bind");
6155                 goto error;
6156         }
6158         optlen = sizeof(optval);
6159         optval = 20;
6160         if (setsockopt
6161             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
6162                 perror("Failed to set socket priority");
6163                 goto error;
6164         }
6166         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
6167                                      drv, NULL)) {
6168                 printf("Could not register monitor read socket\n");
6169                 goto error;
6170         }
6172         return 0;
6173  error:
6174         nl80211_remove_monitor_interface(drv);
6175         return -1;
6179 static int nl80211_setup_ap(struct i802_bss *bss)
6181         struct wpa_driver_nl80211_data *drv = bss->drv;
6183         wpa_printf(MSG_DEBUG, "nl80211: Setup AP - device_ap_sme=%d "
6184                    "use_monitor=%d", drv->device_ap_sme, drv->use_monitor);
6186         /*
6187          * Disable Probe Request reporting unless we need it in this way for
6188          * devices that include the AP SME, in the other case (unless using
6189          * monitor iface) we'll get it through the nl_mgmt socket instead.
6190          */
6191         if (!drv->device_ap_sme)
6192                 wpa_driver_nl80211_probe_req_report(bss, 0);
6194         if (!drv->device_ap_sme && !drv->use_monitor)
6195                 if (nl80211_mgmt_subscribe_ap(bss))
6196                         return -1;
6198         if (drv->device_ap_sme && !drv->use_monitor)
6199                 if (nl80211_mgmt_subscribe_ap_dev_sme(bss))
6200                         return -1;
6202         if (!drv->device_ap_sme && drv->use_monitor &&
6203             nl80211_create_monitor_interface(drv) &&
6204             !drv->device_ap_sme)
6205                 return -1;
6207         if (drv->device_ap_sme &&
6208             wpa_driver_nl80211_probe_req_report(bss, 1) < 0) {
6209                 wpa_printf(MSG_DEBUG, "nl80211: Failed to enable "
6210                            "Probe Request frame reporting in AP mode");
6211                 /* Try to survive without this */
6212         }
6214         return 0;
6218 static void nl80211_teardown_ap(struct i802_bss *bss)
6220         struct wpa_driver_nl80211_data *drv = bss->drv;
6222         if (drv->device_ap_sme) {
6223                 wpa_driver_nl80211_probe_req_report(bss, 0);
6224                 if (!drv->use_monitor)
6225                         nl80211_mgmt_unsubscribe(bss, "AP teardown (dev SME)");
6226         } else if (drv->use_monitor)
6227                 nl80211_remove_monitor_interface(drv);
6228         else
6229                 nl80211_mgmt_unsubscribe(bss, "AP teardown");
6231         bss->beacon_set = 0;
6235 static int nl80211_send_eapol_data(struct i802_bss *bss,
6236                                    const u8 *addr, const u8 *data,
6237                                    size_t data_len)
6239         struct sockaddr_ll ll;
6240         int ret;
6242         if (bss->drv->eapol_tx_sock < 0) {
6243                 wpa_printf(MSG_DEBUG, "nl80211: No socket to send EAPOL");
6244                 return -1;
6245         }
6247         os_memset(&ll, 0, sizeof(ll));
6248         ll.sll_family = AF_PACKET;
6249         ll.sll_ifindex = bss->ifindex;
6250         ll.sll_protocol = htons(ETH_P_PAE);
6251         ll.sll_halen = ETH_ALEN;
6252         os_memcpy(ll.sll_addr, addr, ETH_ALEN);
6253         ret = sendto(bss->drv->eapol_tx_sock, data, data_len, 0,
6254                      (struct sockaddr *) &ll, sizeof(ll));
6255         if (ret < 0)
6256                 wpa_printf(MSG_ERROR, "nl80211: EAPOL TX: %s",
6257                            strerror(errno));
6259         return ret;
6263 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
6265 static int wpa_driver_nl80211_hapd_send_eapol(
6266         void *priv, const u8 *addr, const u8 *data,
6267         size_t data_len, int encrypt, const u8 *own_addr, u32 flags)
6269         struct i802_bss *bss = priv;
6270         struct wpa_driver_nl80211_data *drv = bss->drv;
6271         struct ieee80211_hdr *hdr;
6272         size_t len;
6273         u8 *pos;
6274         int res;
6275         int qos = flags & WPA_STA_WMM;
6277         if (drv->device_ap_sme || !drv->use_monitor)
6278                 return nl80211_send_eapol_data(bss, addr, data, data_len);
6280         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
6281                 data_len;
6282         hdr = os_zalloc(len);
6283         if (hdr == NULL) {
6284                 printf("malloc() failed for i802_send_data(len=%lu)\n",
6285                        (unsigned long) len);
6286                 return -1;
6287         }
6289         hdr->frame_control =
6290                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
6291         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
6292         if (encrypt)
6293                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
6294         if (qos) {
6295                 hdr->frame_control |=
6296                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
6297         }
6299         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
6300         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
6301         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
6302         pos = (u8 *) (hdr + 1);
6304         if (qos) {
6305                 /* add an empty QoS header if needed */
6306                 pos[0] = 0;
6307                 pos[1] = 0;
6308                 pos += 2;
6309         }
6311         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
6312         pos += sizeof(rfc1042_header);
6313         WPA_PUT_BE16(pos, ETH_P_PAE);
6314         pos += 2;
6315         memcpy(pos, data, data_len);
6317         res = wpa_driver_nl80211_send_frame(bss, (u8 *) hdr, len, encrypt, 0,
6318                                             0, 0, 0, 0);
6319         if (res < 0) {
6320                 wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
6321                            "failed: %d (%s)",
6322                            (unsigned long) len, errno, strerror(errno));
6323         }
6324         os_free(hdr);
6326         return res;
6330 static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
6331                                             int total_flags,
6332                                             int flags_or, int flags_and)
6334         struct i802_bss *bss = priv;
6335         struct wpa_driver_nl80211_data *drv = bss->drv;
6336         struct nl_msg *msg, *flags = NULL;
6337         struct nl80211_sta_flag_update upd;
6339         msg = nlmsg_alloc();
6340         if (!msg)
6341                 return -ENOMEM;
6343         flags = nlmsg_alloc();
6344         if (!flags) {
6345                 nlmsg_free(msg);
6346                 return -ENOMEM;
6347         }
6349         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
6351         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
6352                     if_nametoindex(bss->ifname));
6353         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
6355         /*
6356          * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
6357          * can be removed eventually.
6358          */
6359         if (total_flags & WPA_STA_AUTHORIZED)
6360                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
6362         if (total_flags & WPA_STA_WMM)
6363                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
6365         if (total_flags & WPA_STA_SHORT_PREAMBLE)
6366                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
6368         if (total_flags & WPA_STA_MFP)
6369                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
6371         if (total_flags & WPA_STA_TDLS_PEER)
6372                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_TDLS_PEER);
6374         if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
6375                 goto nla_put_failure;
6377         os_memset(&upd, 0, sizeof(upd));
6378         upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
6379         upd.set = sta_flags_nl80211(flags_or);
6380         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
6382         nlmsg_free(flags);
6384         return send_and_recv_msgs(drv, msg, NULL, NULL);
6385  nla_put_failure:
6386         nlmsg_free(msg);
6387         nlmsg_free(flags);
6388         return -ENOBUFS;
6392 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
6393                                  struct wpa_driver_associate_params *params)
6395         enum nl80211_iftype nlmode;
6397         if (params->p2p) {
6398                 wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
6399                            "group (GO)");
6400                 nlmode = NL80211_IFTYPE_P2P_GO;
6401         } else
6402                 nlmode = NL80211_IFTYPE_AP;
6404         if (wpa_driver_nl80211_set_mode(&drv->first_bss, nlmode) ||
6405             wpa_driver_nl80211_set_freq(&drv->first_bss, params->freq, 0, 0)) {
6406                 nl80211_remove_monitor_interface(drv);
6407                 return -1;
6408         }
6410         return 0;
6414 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
6416         struct nl_msg *msg;
6417         int ret = -1;
6419         msg = nlmsg_alloc();
6420         if (!msg)
6421                 return -1;
6423         nl80211_cmd(drv, msg, 0, NL80211_CMD_LEAVE_IBSS);
6424         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6425         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6426         msg = NULL;
6427         if (ret) {
6428                 wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
6429                            "(%s)", ret, strerror(-ret));
6430                 goto nla_put_failure;
6431         }
6433         ret = 0;
6434         wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
6436 nla_put_failure:
6437         nlmsg_free(msg);
6438         return ret;
6442 static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
6443                                    struct wpa_driver_associate_params *params)
6445         struct nl_msg *msg;
6446         int ret = -1;
6447         int count = 0;
6449         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
6451         if (wpa_driver_nl80211_set_mode(&drv->first_bss,
6452                                         NL80211_IFTYPE_ADHOC)) {
6453                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
6454                            "IBSS mode");
6455                 return -1;
6456         }
6458 retry:
6459         msg = nlmsg_alloc();
6460         if (!msg)
6461                 return -1;
6463         nl80211_cmd(drv, msg, 0, NL80211_CMD_JOIN_IBSS);
6464         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6466         if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
6467                 goto nla_put_failure;
6469         wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6470                           params->ssid, params->ssid_len);
6471         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6472                 params->ssid);
6473         os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6474         drv->ssid_len = params->ssid_len;
6476         wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6477         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6479         ret = nl80211_set_conn_keys(params, msg);
6480         if (ret)
6481                 goto nla_put_failure;
6483         if (params->bssid && params->fixed_bssid) {
6484                 wpa_printf(MSG_DEBUG, "  * BSSID=" MACSTR,
6485                            MAC2STR(params->bssid));
6486                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6487         }
6489         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
6490             params->key_mgmt_suite == KEY_MGMT_PSK ||
6491             params->key_mgmt_suite == KEY_MGMT_802_1X_SHA256 ||
6492             params->key_mgmt_suite == KEY_MGMT_PSK_SHA256) {
6493                 wpa_printf(MSG_DEBUG, "  * control port");
6494                 NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
6495         }
6497         if (params->wpa_ie) {
6498                 wpa_hexdump(MSG_DEBUG,
6499                             "  * Extra IEs for Beacon/Probe Response frames",
6500                             params->wpa_ie, params->wpa_ie_len);
6501                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6502                         params->wpa_ie);
6503         }
6505         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6506         msg = NULL;
6507         if (ret) {
6508                 wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
6509                            ret, strerror(-ret));
6510                 count++;
6511                 if (ret == -EALREADY && count == 1) {
6512                         wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
6513                                    "forced leave");
6514                         nl80211_leave_ibss(drv);
6515                         nlmsg_free(msg);
6516                         goto retry;
6517                 }
6519                 goto nla_put_failure;
6520         }
6521         ret = 0;
6522         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
6524 nla_put_failure:
6525         nlmsg_free(msg);
6526         return ret;
6530 static unsigned int nl80211_get_assoc_bssid(struct wpa_driver_nl80211_data *drv,
6531                                             u8 *bssid)
6533         struct nl_msg *msg;
6534         int ret;
6535         struct nl80211_bss_info_arg arg;
6537         os_memset(&arg, 0, sizeof(arg));
6538         msg = nlmsg_alloc();
6539         if (!msg)
6540                 goto nla_put_failure;
6542         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
6543         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6545         arg.drv = drv;
6546         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
6547         msg = NULL;
6548         if (ret == 0) {
6549                 if (is_zero_ether_addr(arg.assoc_bssid))
6550                         return -ENOTCONN;
6551                 os_memcpy(bssid, arg.assoc_bssid, ETH_ALEN);
6552                 return 0;
6553         }
6554         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
6555                    "(%s)", ret, strerror(-ret));
6556 nla_put_failure:
6557         nlmsg_free(msg);
6558         return drv->assoc_freq;
6562 static int nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
6563                               const u8 *bssid)
6565         u8 addr[ETH_ALEN];
6567         if (bssid == NULL) {
6568                 int res = nl80211_get_assoc_bssid(drv, addr);
6569                 if (res)
6570                         return res;
6571                 bssid = addr;
6572         }
6574         return wpa_driver_nl80211_disconnect(drv, bssid,
6575                                              WLAN_REASON_PREV_AUTH_NOT_VALID);
6579 static int wpa_driver_nl80211_connect(
6580         struct wpa_driver_nl80211_data *drv,
6581         struct wpa_driver_associate_params *params)
6583         struct nl_msg *msg;
6584         enum nl80211_auth_type type;
6585         int ret = 0;
6586         int algs;
6588         msg = nlmsg_alloc();
6589         if (!msg)
6590                 return -1;
6592         wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
6593         nl80211_cmd(drv, msg, 0, NL80211_CMD_CONNECT);
6595         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6596         if (params->bssid) {
6597                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
6598                            MAC2STR(params->bssid));
6599                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6600         }
6601         if (params->freq) {
6602                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6603                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6604         }
6605         if (params->ssid) {
6606                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6607                                   params->ssid, params->ssid_len);
6608                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6609                         params->ssid);
6610                 if (params->ssid_len > sizeof(drv->ssid))
6611                         goto nla_put_failure;
6612                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6613                 drv->ssid_len = params->ssid_len;
6614         }
6615         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
6616         if (params->wpa_ie)
6617                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6618                         params->wpa_ie);
6620         algs = 0;
6621         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
6622                 algs++;
6623         if (params->auth_alg & WPA_AUTH_ALG_SHARED)
6624                 algs++;
6625         if (params->auth_alg & WPA_AUTH_ALG_LEAP)
6626                 algs++;
6627         if (algs > 1) {
6628                 wpa_printf(MSG_DEBUG, "  * Leave out Auth Type for automatic "
6629                            "selection");
6630                 goto skip_auth_type;
6631         }
6633         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
6634                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
6635         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
6636                 type = NL80211_AUTHTYPE_SHARED_KEY;
6637         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
6638                 type = NL80211_AUTHTYPE_NETWORK_EAP;
6639         else if (params->auth_alg & WPA_AUTH_ALG_FT)
6640                 type = NL80211_AUTHTYPE_FT;
6641         else
6642                 goto nla_put_failure;
6644         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
6645         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
6647 skip_auth_type:
6648         if (params->wpa_proto) {
6649                 enum nl80211_wpa_versions ver = 0;
6651                 if (params->wpa_proto & WPA_PROTO_WPA)
6652                         ver |= NL80211_WPA_VERSION_1;
6653                 if (params->wpa_proto & WPA_PROTO_RSN)
6654                         ver |= NL80211_WPA_VERSION_2;
6656                 wpa_printf(MSG_DEBUG, "  * WPA Versions 0x%x", ver);
6657                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
6658         }
6660         if (params->pairwise_suite != CIPHER_NONE) {
6661                 int cipher;
6663                 switch (params->pairwise_suite) {
6664                 case CIPHER_WEP40:
6665                         cipher = WLAN_CIPHER_SUITE_WEP40;
6666                         break;
6667                 case CIPHER_WEP104:
6668                         cipher = WLAN_CIPHER_SUITE_WEP104;
6669                         break;
6670                 case CIPHER_CCMP:
6671                         cipher = WLAN_CIPHER_SUITE_CCMP;
6672                         break;
6673                 case CIPHER_TKIP:
6674                 default:
6675                         cipher = WLAN_CIPHER_SUITE_TKIP;
6676                         break;
6677                 }
6678                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
6679         }
6681         if (params->group_suite != CIPHER_NONE) {
6682                 int cipher;
6684                 switch (params->group_suite) {
6685                 case CIPHER_WEP40:
6686                         cipher = WLAN_CIPHER_SUITE_WEP40;
6687                         break;
6688                 case CIPHER_WEP104:
6689                         cipher = WLAN_CIPHER_SUITE_WEP104;
6690                         break;
6691                 case CIPHER_CCMP:
6692                         cipher = WLAN_CIPHER_SUITE_CCMP;
6693                         break;
6694                 case CIPHER_TKIP:
6695                 default:
6696                         cipher = WLAN_CIPHER_SUITE_TKIP;
6697                         break;
6698                 }
6699                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
6700         }
6702         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
6703             params->key_mgmt_suite == KEY_MGMT_PSK) {
6704                 int mgmt = WLAN_AKM_SUITE_PSK;
6706                 switch (params->key_mgmt_suite) {
6707                 case KEY_MGMT_802_1X:
6708                         mgmt = WLAN_AKM_SUITE_8021X;
6709                         break;
6710                 case KEY_MGMT_PSK:
6711                 default:
6712                         mgmt = WLAN_AKM_SUITE_PSK;
6713                         break;
6714                 }
6715                 NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
6716         }
6718         if (params->disable_ht)
6719                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
6721         if (params->htcaps && params->htcaps_mask) {
6722                 int sz = sizeof(struct ieee80211_ht_capabilities);
6723                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
6724                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
6725                         params->htcaps_mask);
6726         }
6728         ret = nl80211_set_conn_keys(params, msg);
6729         if (ret)
6730                 goto nla_put_failure;
6732         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6733         msg = NULL;
6734         if (ret) {
6735                 wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
6736                            "(%s)", ret, strerror(-ret));
6737                 /*
6738                  * cfg80211 does not currently accept new connection if we are
6739                  * already connected. As a workaround, force disconnection and
6740                  * try again once the driver indicates it completed
6741                  * disconnection.
6742                  */
6743                 if (ret == -EALREADY)
6744                         nl80211_disconnect(drv, params->bssid);
6745                 goto nla_put_failure;
6746         }
6747         ret = 0;
6748         wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
6750 nla_put_failure:
6751         nlmsg_free(msg);
6752         return ret;
6757 static int wpa_driver_nl80211_associate(
6758         void *priv, struct wpa_driver_associate_params *params)
6760         struct i802_bss *bss = priv;
6761         struct wpa_driver_nl80211_data *drv = bss->drv;
6762         int ret = -1;
6763         struct nl_msg *msg;
6765         if (params->mode == IEEE80211_MODE_AP)
6766                 return wpa_driver_nl80211_ap(drv, params);
6768         if (params->mode == IEEE80211_MODE_IBSS)
6769                 return wpa_driver_nl80211_ibss(drv, params);
6771         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
6772                 enum nl80211_iftype nlmode = params->p2p ?
6773                         NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
6775                 if (wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
6776                         return -1;
6777                 return wpa_driver_nl80211_connect(drv, params);
6778         }
6780         drv->associated = 0;
6782         msg = nlmsg_alloc();
6783         if (!msg)
6784                 return -1;
6786         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
6787                    drv->ifindex);
6788         nl80211_cmd(drv, msg, 0, NL80211_CMD_ASSOCIATE);
6790         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6791         if (params->bssid) {
6792                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
6793                            MAC2STR(params->bssid));
6794                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6795         }
6796         if (params->freq) {
6797                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6798                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6799                 drv->assoc_freq = params->freq;
6800         } else
6801                 drv->assoc_freq = 0;
6802         if (params->ssid) {
6803                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6804                                   params->ssid, params->ssid_len);
6805                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6806                         params->ssid);
6807                 if (params->ssid_len > sizeof(drv->ssid))
6808                         goto nla_put_failure;
6809                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6810                 drv->ssid_len = params->ssid_len;
6811         }
6812         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
6813         if (params->wpa_ie)
6814                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6815                         params->wpa_ie);
6817         if (params->pairwise_suite != CIPHER_NONE) {
6818                 int cipher;
6820                 switch (params->pairwise_suite) {
6821                 case CIPHER_WEP40:
6822                         cipher = WLAN_CIPHER_SUITE_WEP40;
6823                         break;
6824                 case CIPHER_WEP104:
6825                         cipher = WLAN_CIPHER_SUITE_WEP104;
6826                         break;
6827                 case CIPHER_CCMP:
6828                         cipher = WLAN_CIPHER_SUITE_CCMP;
6829                         break;
6830                 case CIPHER_TKIP:
6831                 default:
6832                         cipher = WLAN_CIPHER_SUITE_TKIP;
6833                         break;
6834                 }
6835                 wpa_printf(MSG_DEBUG, "  * pairwise=0x%x", cipher);
6836                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
6837         }
6839         if (params->group_suite != CIPHER_NONE) {
6840                 int cipher;
6842                 switch (params->group_suite) {
6843                 case CIPHER_WEP40:
6844                         cipher = WLAN_CIPHER_SUITE_WEP40;
6845                         break;
6846                 case CIPHER_WEP104:
6847                         cipher = WLAN_CIPHER_SUITE_WEP104;
6848                         break;
6849                 case CIPHER_CCMP:
6850                         cipher = WLAN_CIPHER_SUITE_CCMP;
6851                         break;
6852                 case CIPHER_TKIP:
6853                 default:
6854                         cipher = WLAN_CIPHER_SUITE_TKIP;
6855                         break;
6856                 }
6857                 wpa_printf(MSG_DEBUG, "  * group=0x%x", cipher);
6858                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
6859         }
6861 #ifdef CONFIG_IEEE80211W
6862         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
6863                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
6864 #endif /* CONFIG_IEEE80211W */
6866         NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
6868         if (params->prev_bssid) {
6869                 wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
6870                            MAC2STR(params->prev_bssid));
6871                 NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
6872                         params->prev_bssid);
6873         }
6875         if (params->disable_ht)
6876                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
6878         if (params->htcaps && params->htcaps_mask) {
6879                 int sz = sizeof(struct ieee80211_ht_capabilities);
6880                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
6881                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
6882                         params->htcaps_mask);
6883         }
6885         if (params->p2p)
6886                 wpa_printf(MSG_DEBUG, "  * P2P group");
6888         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6889         msg = NULL;
6890         if (ret) {
6891                 wpa_dbg(drv->ctx, MSG_DEBUG,
6892                         "nl80211: MLME command failed (assoc): ret=%d (%s)",
6893                         ret, strerror(-ret));
6894                 nl80211_dump_scan(drv);
6895                 goto nla_put_failure;
6896         }
6897         ret = 0;
6898         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
6899                    "successfully");
6901 nla_put_failure:
6902         nlmsg_free(msg);
6903         return ret;
6907 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
6908                             int ifindex, enum nl80211_iftype mode)
6910         struct nl_msg *msg;
6911         int ret = -ENOBUFS;
6913         wpa_printf(MSG_DEBUG, "nl80211: Set mode ifindex %d iftype %d (%s)",
6914                    ifindex, mode, nl80211_iftype_str(mode));
6916         msg = nlmsg_alloc();
6917         if (!msg)
6918                 return -ENOMEM;
6920         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_INTERFACE);
6921         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
6922         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
6924         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6925         msg = NULL;
6926         if (!ret)
6927                 return 0;
6928 nla_put_failure:
6929         nlmsg_free(msg);
6930         wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
6931                    " %d (%s)", ifindex, mode, ret, strerror(-ret));
6932         return ret;
6936 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
6937                                        enum nl80211_iftype nlmode)
6939         struct wpa_driver_nl80211_data *drv = bss->drv;
6940         int ret = -1;
6941         int i;
6942         int was_ap = is_ap_interface(drv->nlmode);
6943         int res;
6945         res = nl80211_set_mode(drv, drv->ifindex, nlmode);
6946         if (res == 0) {
6947                 drv->nlmode = nlmode;
6948                 ret = 0;
6949                 goto done;
6950         }
6952         if (res == -ENODEV)
6953                 return -1;
6955         if (nlmode == drv->nlmode) {
6956                 wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
6957                            "requested mode - ignore error");
6958                 ret = 0;
6959                 goto done; /* Already in the requested mode */
6960         }
6962         /* mac80211 doesn't allow mode changes while the device is up, so
6963          * take the device down, try to set the mode again, and bring the
6964          * device back up.
6965          */
6966         wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
6967                    "interface down");
6968         for (i = 0; i < 10; i++) {
6969                 res = linux_set_iface_flags(drv->global->ioctl_sock,
6970                                             bss->ifname, 0);
6971                 if (res == -EACCES || res == -ENODEV)
6972                         break;
6973                 if (res == 0) {
6974                         /* Try to set the mode again while the interface is
6975                          * down */
6976                         ret = nl80211_set_mode(drv, drv->ifindex, nlmode);
6977                         if (ret == -EACCES)
6978                                 break;
6979                         res = linux_set_iface_flags(drv->global->ioctl_sock,
6980                                                     bss->ifname, 1);
6981                         if (res && !ret)
6982                                 ret = -1;
6983                         else if (ret != -EBUSY)
6984                                 break;
6985                 } else
6986                         wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
6987                                    "interface down");
6988                 os_sleep(0, 100000);
6989         }
6991         if (!ret) {
6992                 wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
6993                            "interface is down");
6994                 drv->nlmode = nlmode;
6995                 drv->ignore_if_down_event = 1;
6996         }
6998 done:
6999         if (ret) {
7000                 wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
7001                            "from %d failed", nlmode, drv->nlmode);
7002                 return ret;
7003         }
7005         if (is_ap_interface(nlmode)) {
7006                 nl80211_mgmt_unsubscribe(bss, "start AP");
7007                 /* Setup additional AP mode functionality if needed */
7008                 if (nl80211_setup_ap(bss))
7009                         return -1;
7010         } else if (was_ap) {
7011                 /* Remove additional AP mode functionality */
7012                 nl80211_teardown_ap(bss);
7013         } else {
7014                 nl80211_mgmt_unsubscribe(bss, "mode change");
7015         }
7017         if (!is_ap_interface(nlmode) &&
7018             nl80211_mgmt_subscribe_non_ap(bss) < 0)
7019                 wpa_printf(MSG_DEBUG, "nl80211: Failed to register Action "
7020                            "frame processing - ignore for now");
7022         return 0;
7026 static int wpa_driver_nl80211_get_capa(void *priv,
7027                                        struct wpa_driver_capa *capa)
7029         struct i802_bss *bss = priv;
7030         struct wpa_driver_nl80211_data *drv = bss->drv;
7031         if (!drv->has_capability)
7032                 return -1;
7033         os_memcpy(capa, &drv->capa, sizeof(*capa));
7034         return 0;
7038 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
7040         struct i802_bss *bss = priv;
7041         struct wpa_driver_nl80211_data *drv = bss->drv;
7043         wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
7044                    __func__, drv->operstate, state, state ? "UP" : "DORMANT");
7045         drv->operstate = state;
7046         return netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, -1,
7047                                       state ? IF_OPER_UP : IF_OPER_DORMANT);
7051 static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
7053         struct i802_bss *bss = priv;
7054         struct wpa_driver_nl80211_data *drv = bss->drv;
7055         struct nl_msg *msg;
7056         struct nl80211_sta_flag_update upd;
7058         msg = nlmsg_alloc();
7059         if (!msg)
7060                 return -ENOMEM;
7062         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
7064         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7065                     if_nametoindex(bss->ifname));
7066         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
7068         os_memset(&upd, 0, sizeof(upd));
7069         upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
7070         if (authorized)
7071                 upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
7072         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
7074         return send_and_recv_msgs(drv, msg, NULL, NULL);
7075  nla_put_failure:
7076         nlmsg_free(msg);
7077         return -ENOBUFS;
7081 /* Set kernel driver on given frequency (MHz) */
7082 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
7084         struct i802_bss *bss = priv;
7085         return wpa_driver_nl80211_set_freq(bss, freq->freq, freq->ht_enabled,
7086                                            freq->sec_channel_offset);
7090 #if defined(HOSTAPD) || defined(CONFIG_AP)
7092 static inline int min_int(int a, int b)
7094         if (a < b)
7095                 return a;
7096         return b;
7100 static int get_key_handler(struct nl_msg *msg, void *arg)
7102         struct nlattr *tb[NL80211_ATTR_MAX + 1];
7103         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7105         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7106                   genlmsg_attrlen(gnlh, 0), NULL);
7108         /*
7109          * TODO: validate the key index and mac address!
7110          * Otherwise, there's a race condition as soon as
7111          * the kernel starts sending key notifications.
7112          */
7114         if (tb[NL80211_ATTR_KEY_SEQ])
7115                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
7116                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
7117         return NL_SKIP;
7121 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
7122                            int idx, u8 *seq)
7124         struct i802_bss *bss = priv;
7125         struct wpa_driver_nl80211_data *drv = bss->drv;
7126         struct nl_msg *msg;
7128         msg = nlmsg_alloc();
7129         if (!msg)
7130                 return -ENOMEM;
7132         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_KEY);
7134         if (addr)
7135                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7136         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
7137         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
7139         memset(seq, 0, 6);
7141         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
7142  nla_put_failure:
7143         nlmsg_free(msg);
7144         return -ENOBUFS;
7148 static int i802_set_rts(void *priv, int rts)
7150         struct i802_bss *bss = priv;
7151         struct wpa_driver_nl80211_data *drv = bss->drv;
7152         struct nl_msg *msg;
7153         int ret = -ENOBUFS;
7154         u32 val;
7156         msg = nlmsg_alloc();
7157         if (!msg)
7158                 return -ENOMEM;
7160         if (rts >= 2347)
7161                 val = (u32) -1;
7162         else
7163                 val = rts;
7165         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7166         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7167         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
7169         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7170         msg = NULL;
7171         if (!ret)
7172                 return 0;
7173 nla_put_failure:
7174         nlmsg_free(msg);
7175         wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
7176                    "%d (%s)", rts, ret, strerror(-ret));
7177         return ret;
7181 static int i802_set_frag(void *priv, int frag)
7183         struct i802_bss *bss = priv;
7184         struct wpa_driver_nl80211_data *drv = bss->drv;
7185         struct nl_msg *msg;
7186         int ret = -ENOBUFS;
7187         u32 val;
7189         msg = nlmsg_alloc();
7190         if (!msg)
7191                 return -ENOMEM;
7193         if (frag >= 2346)
7194                 val = (u32) -1;
7195         else
7196                 val = frag;
7198         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7199         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7200         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
7202         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7203         msg = NULL;
7204         if (!ret)
7205                 return 0;
7206 nla_put_failure:
7207         nlmsg_free(msg);
7208         wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
7209                    "%d: %d (%s)", frag, ret, strerror(-ret));
7210         return ret;
7214 static int i802_flush(void *priv)
7216         struct i802_bss *bss = priv;
7217         struct wpa_driver_nl80211_data *drv = bss->drv;
7218         struct nl_msg *msg;
7219         int res;
7221         msg = nlmsg_alloc();
7222         if (!msg)
7223                 return -1;
7225         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
7227         /*
7228          * XXX: FIX! this needs to flush all VLANs too
7229          */
7230         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7231                     if_nametoindex(bss->ifname));
7233         res = send_and_recv_msgs(drv, msg, NULL, NULL);
7234         if (res) {
7235                 wpa_printf(MSG_DEBUG, "nl80211: Station flush failed: ret=%d "
7236                            "(%s)", res, strerror(-res));
7237         }
7238         return res;
7239  nla_put_failure:
7240         nlmsg_free(msg);
7241         return -ENOBUFS;
7245 static int get_sta_handler(struct nl_msg *msg, void *arg)
7247         struct nlattr *tb[NL80211_ATTR_MAX + 1];
7248         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7249         struct hostap_sta_driver_data *data = arg;
7250         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
7251         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
7252                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
7253                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
7254                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
7255                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
7256                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
7257         };
7259         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7260                   genlmsg_attrlen(gnlh, 0), NULL);
7262         /*
7263          * TODO: validate the interface and mac address!
7264          * Otherwise, there's a race condition as soon as
7265          * the kernel starts sending station notifications.
7266          */
7268         if (!tb[NL80211_ATTR_STA_INFO]) {
7269                 wpa_printf(MSG_DEBUG, "sta stats missing!");
7270                 return NL_SKIP;
7271         }
7272         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
7273                              tb[NL80211_ATTR_STA_INFO],
7274                              stats_policy)) {
7275                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
7276                 return NL_SKIP;
7277         }
7279         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
7280                 data->inactive_msec =
7281                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
7282         if (stats[NL80211_STA_INFO_RX_BYTES])
7283                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
7284         if (stats[NL80211_STA_INFO_TX_BYTES])
7285                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
7286         if (stats[NL80211_STA_INFO_RX_PACKETS])
7287                 data->rx_packets =
7288                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
7289         if (stats[NL80211_STA_INFO_TX_PACKETS])
7290                 data->tx_packets =
7291                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
7293         return NL_SKIP;
7296 static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
7297                               const u8 *addr)
7299         struct i802_bss *bss = priv;
7300         struct wpa_driver_nl80211_data *drv = bss->drv;
7301         struct nl_msg *msg;
7303         os_memset(data, 0, sizeof(*data));
7304         msg = nlmsg_alloc();
7305         if (!msg)
7306                 return -ENOMEM;
7308         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
7310         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7311         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7313         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
7314  nla_put_failure:
7315         nlmsg_free(msg);
7316         return -ENOBUFS;
7320 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
7321                                     int cw_min, int cw_max, int burst_time)
7323         struct i802_bss *bss = priv;
7324         struct wpa_driver_nl80211_data *drv = bss->drv;
7325         struct nl_msg *msg;
7326         struct nlattr *txq, *params;
7328         msg = nlmsg_alloc();
7329         if (!msg)
7330                 return -1;
7332         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7334         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7336         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
7337         if (!txq)
7338                 goto nla_put_failure;
7340         /* We are only sending parameters for a single TXQ at a time */
7341         params = nla_nest_start(msg, 1);
7342         if (!params)
7343                 goto nla_put_failure;
7345         switch (queue) {
7346         case 0:
7347                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
7348                 break;
7349         case 1:
7350                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
7351                 break;
7352         case 2:
7353                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
7354                 break;
7355         case 3:
7356                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
7357                 break;
7358         }
7359         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
7360          * 32 usec, so need to convert the value here. */
7361         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
7362         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
7363         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
7364         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
7366         nla_nest_end(msg, params);
7368         nla_nest_end(msg, txq);
7370         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
7371                 return 0;
7372         msg = NULL;
7373  nla_put_failure:
7374         nlmsg_free(msg);
7375         return -1;
7379 static int i802_set_sta_vlan(void *priv, const u8 *addr,
7380                              const char *ifname, int vlan_id)
7382         struct i802_bss *bss = priv;
7383         struct wpa_driver_nl80211_data *drv = bss->drv;
7384         struct nl_msg *msg;
7385         int ret = -ENOBUFS;
7387         msg = nlmsg_alloc();
7388         if (!msg)
7389                 return -ENOMEM;
7391         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
7393         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7394                     if_nametoindex(bss->ifname));
7395         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7396         NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
7397                     if_nametoindex(ifname));
7399         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7400         msg = NULL;
7401         if (ret < 0) {
7402                 wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
7403                            MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
7404                            MAC2STR(addr), ifname, vlan_id, ret,
7405                            strerror(-ret));
7406         }
7407  nla_put_failure:
7408         nlmsg_free(msg);
7409         return ret;
7413 static int i802_get_inact_sec(void *priv, const u8 *addr)
7415         struct hostap_sta_driver_data data;
7416         int ret;
7418         data.inactive_msec = (unsigned long) -1;
7419         ret = i802_read_sta_data(priv, &data, addr);
7420         if (ret || data.inactive_msec == (unsigned long) -1)
7421                 return -1;
7422         return data.inactive_msec / 1000;
7426 static int i802_sta_clear_stats(void *priv, const u8 *addr)
7428 #if 0
7429         /* TODO */
7430 #endif
7431         return 0;
7435 static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
7436                            int reason)
7438         struct i802_bss *bss = priv;
7439         struct ieee80211_mgmt mgmt;
7441         memset(&mgmt, 0, sizeof(mgmt));
7442         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
7443                                           WLAN_FC_STYPE_DEAUTH);
7444         memcpy(mgmt.da, addr, ETH_ALEN);
7445         memcpy(mgmt.sa, own_addr, ETH_ALEN);
7446         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
7447         mgmt.u.deauth.reason_code = host_to_le16(reason);
7448         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
7449                                             IEEE80211_HDRLEN +
7450                                             sizeof(mgmt.u.deauth), 0);
7454 static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
7455                              int reason)
7457         struct i802_bss *bss = priv;
7458         struct ieee80211_mgmt mgmt;
7460         memset(&mgmt, 0, sizeof(mgmt));
7461         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
7462                                           WLAN_FC_STYPE_DISASSOC);
7463         memcpy(mgmt.da, addr, ETH_ALEN);
7464         memcpy(mgmt.sa, own_addr, ETH_ALEN);
7465         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
7466         mgmt.u.disassoc.reason_code = host_to_le16(reason);
7467         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
7468                                             IEEE80211_HDRLEN +
7469                                             sizeof(mgmt.u.disassoc), 0);
7472 #endif /* HOSTAPD || CONFIG_AP */
7474 #ifdef HOSTAPD
7476 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7478         int i;
7479         int *old;
7481         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
7482                    ifidx);
7483         for (i = 0; i < drv->num_if_indices; i++) {
7484                 if (drv->if_indices[i] == 0) {
7485                         drv->if_indices[i] = ifidx;
7486                         return;
7487                 }
7488         }
7490         if (drv->if_indices != drv->default_if_indices)
7491                 old = drv->if_indices;
7492         else
7493                 old = NULL;
7495         drv->if_indices = os_realloc(old,
7496                                      sizeof(int) * (drv->num_if_indices + 1));
7497         if (!drv->if_indices) {
7498                 if (!old)
7499                         drv->if_indices = drv->default_if_indices;
7500                 else
7501                         drv->if_indices = old;
7502                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
7503                            "interfaces");
7504                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
7505                 return;
7506         } else if (!old)
7507                 os_memcpy(drv->if_indices, drv->default_if_indices,
7508                           sizeof(drv->default_if_indices));
7509         drv->if_indices[drv->num_if_indices] = ifidx;
7510         drv->num_if_indices++;
7514 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7516         int i;
7518         for (i = 0; i < drv->num_if_indices; i++) {
7519                 if (drv->if_indices[i] == ifidx) {
7520                         drv->if_indices[i] = 0;
7521                         break;
7522                 }
7523         }
7527 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7529         int i;
7531         for (i = 0; i < drv->num_if_indices; i++)
7532                 if (drv->if_indices[i] == ifidx)
7533                         return 1;
7535         return 0;
7539 static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
7540                             const char *bridge_ifname)
7542         struct i802_bss *bss = priv;
7543         struct wpa_driver_nl80211_data *drv = bss->drv;
7544         char name[IFNAMSIZ + 1];
7546         os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
7547         wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
7548                    " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
7549         if (val) {
7550                 if (!if_nametoindex(name)) {
7551                         if (nl80211_create_iface(drv, name,
7552                                                  NL80211_IFTYPE_AP_VLAN,
7553                                                  NULL, 1) < 0)
7554                                 return -1;
7555                         if (bridge_ifname &&
7556                             linux_br_add_if(drv->global->ioctl_sock,
7557                                             bridge_ifname, name) < 0)
7558                                 return -1;
7559                 }
7560                 linux_set_iface_flags(drv->global->ioctl_sock, name, 1);
7561                 return i802_set_sta_vlan(priv, addr, name, 0);
7562         } else {
7563                 i802_set_sta_vlan(priv, addr, bss->ifname, 0);
7564                 return wpa_driver_nl80211_if_remove(priv, WPA_IF_AP_VLAN,
7565                                                     name);
7566         }
7570 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
7572         struct wpa_driver_nl80211_data *drv = eloop_ctx;
7573         struct sockaddr_ll lladdr;
7574         unsigned char buf[3000];
7575         int len;
7576         socklen_t fromlen = sizeof(lladdr);
7578         len = recvfrom(sock, buf, sizeof(buf), 0,
7579                        (struct sockaddr *)&lladdr, &fromlen);
7580         if (len < 0) {
7581                 perror("recv");
7582                 return;
7583         }
7585         if (have_ifidx(drv, lladdr.sll_ifindex))
7586                 drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
7590 static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
7591                              struct i802_bss *bss,
7592                              const char *brname, const char *ifname)
7594         int ifindex;
7595         char in_br[IFNAMSIZ];
7597         os_strlcpy(bss->brname, brname, IFNAMSIZ);
7598         ifindex = if_nametoindex(brname);
7599         if (ifindex == 0) {
7600                 /*
7601                  * Bridge was configured, but the bridge device does
7602                  * not exist. Try to add it now.
7603                  */
7604                 if (linux_br_add(drv->global->ioctl_sock, brname) < 0) {
7605                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
7606                                    "bridge interface %s: %s",
7607                                    brname, strerror(errno));
7608                         return -1;
7609                 }
7610                 bss->added_bridge = 1;
7611                 add_ifidx(drv, if_nametoindex(brname));
7612         }
7614         if (linux_br_get(in_br, ifname) == 0) {
7615                 if (os_strcmp(in_br, brname) == 0)
7616                         return 0; /* already in the bridge */
7618                 wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
7619                            "bridge %s", ifname, in_br);
7620                 if (linux_br_del_if(drv->global->ioctl_sock, in_br, ifname) <
7621                     0) {
7622                         wpa_printf(MSG_ERROR, "nl80211: Failed to "
7623                                    "remove interface %s from bridge "
7624                                    "%s: %s",
7625                                    ifname, brname, strerror(errno));
7626                         return -1;
7627                 }
7628         }
7630         wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
7631                    ifname, brname);
7632         if (linux_br_add_if(drv->global->ioctl_sock, brname, ifname) < 0) {
7633                 wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
7634                            "into bridge %s: %s",
7635                            ifname, brname, strerror(errno));
7636                 return -1;
7637         }
7638         bss->added_if_into_bridge = 1;
7640         return 0;
7644 static void *i802_init(struct hostapd_data *hapd,
7645                        struct wpa_init_params *params)
7647         struct wpa_driver_nl80211_data *drv;
7648         struct i802_bss *bss;
7649         size_t i;
7650         char brname[IFNAMSIZ];
7651         int ifindex, br_ifindex;
7652         int br_added = 0;
7654         bss = wpa_driver_nl80211_init(hapd, params->ifname,
7655                                       params->global_priv);
7656         if (bss == NULL)
7657                 return NULL;
7659         drv = bss->drv;
7660         drv->nlmode = NL80211_IFTYPE_AP;
7661         drv->eapol_sock = -1;
7663         if (linux_br_get(brname, params->ifname) == 0) {
7664                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
7665                            params->ifname, brname);
7666                 br_ifindex = if_nametoindex(brname);
7667         } else {
7668                 brname[0] = '\0';
7669                 br_ifindex = 0;
7670         }
7672         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
7673         drv->if_indices = drv->default_if_indices;
7674         for (i = 0; i < params->num_bridge; i++) {
7675                 if (params->bridge[i]) {
7676                         ifindex = if_nametoindex(params->bridge[i]);
7677                         if (ifindex)
7678                                 add_ifidx(drv, ifindex);
7679                         if (ifindex == br_ifindex)
7680                                 br_added = 1;
7681                 }
7682         }
7683         if (!br_added && br_ifindex &&
7684             (params->num_bridge == 0 || !params->bridge[0]))
7685                 add_ifidx(drv, br_ifindex);
7687         /* start listening for EAPOL on the default AP interface */
7688         add_ifidx(drv, drv->ifindex);
7690         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0))
7691                 goto failed;
7693         if (params->bssid) {
7694                 if (linux_set_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7695                                        params->bssid))
7696                         goto failed;
7697         }
7699         if (wpa_driver_nl80211_set_mode(bss, drv->nlmode)) {
7700                 wpa_printf(MSG_ERROR, "nl80211: Failed to set interface %s "
7701                            "into AP mode", bss->ifname);
7702                 goto failed;
7703         }
7705         if (params->num_bridge && params->bridge[0] &&
7706             i802_check_bridge(drv, bss, params->bridge[0], params->ifname) < 0)
7707                 goto failed;
7709         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1))
7710                 goto failed;
7712         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
7713         if (drv->eapol_sock < 0) {
7714                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
7715                 goto failed;
7716         }
7718         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
7719         {
7720                 printf("Could not register read socket for eapol\n");
7721                 goto failed;
7722         }
7724         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7725                                params->own_addr))
7726                 goto failed;
7728         memcpy(bss->addr, params->own_addr, ETH_ALEN);
7730         return bss;
7732 failed:
7733         wpa_driver_nl80211_deinit(bss);
7734         return NULL;
7738 static void i802_deinit(void *priv)
7740         wpa_driver_nl80211_deinit(priv);
7743 #endif /* HOSTAPD */
7746 static enum nl80211_iftype wpa_driver_nl80211_if_type(
7747         enum wpa_driver_if_type type)
7749         switch (type) {
7750         case WPA_IF_STATION:
7751                 return NL80211_IFTYPE_STATION;
7752         case WPA_IF_P2P_CLIENT:
7753         case WPA_IF_P2P_GROUP:
7754                 return NL80211_IFTYPE_P2P_CLIENT;
7755         case WPA_IF_AP_VLAN:
7756                 return NL80211_IFTYPE_AP_VLAN;
7757         case WPA_IF_AP_BSS:
7758                 return NL80211_IFTYPE_AP;
7759         case WPA_IF_P2P_GO:
7760                 return NL80211_IFTYPE_P2P_GO;
7761         }
7762         return -1;
7766 #ifdef CONFIG_P2P
7768 static int nl80211_addr_in_use(struct nl80211_global *global, const u8 *addr)
7770         struct wpa_driver_nl80211_data *drv;
7771         dl_list_for_each(drv, &global->interfaces,
7772                          struct wpa_driver_nl80211_data, list) {
7773                 if (os_memcmp(addr, drv->first_bss.addr, ETH_ALEN) == 0)
7774                         return 1;
7775         }
7776         return 0;
7780 static int nl80211_p2p_interface_addr(struct wpa_driver_nl80211_data *drv,
7781                                       u8 *new_addr)
7783         unsigned int idx;
7785         if (!drv->global)
7786                 return -1;
7788         os_memcpy(new_addr, drv->first_bss.addr, ETH_ALEN);
7789         for (idx = 0; idx < 64; idx++) {
7790                 new_addr[0] = drv->first_bss.addr[0] | 0x02;
7791                 new_addr[0] ^= idx << 2;
7792                 if (!nl80211_addr_in_use(drv->global, new_addr))
7793                         break;
7794         }
7795         if (idx == 64)
7796                 return -1;
7798         wpa_printf(MSG_DEBUG, "nl80211: Assigned new P2P Interface Address "
7799                    MACSTR, MAC2STR(new_addr));
7801         return 0;
7804 #endif /* CONFIG_P2P */
7807 static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
7808                                      const char *ifname, const u8 *addr,
7809                                      void *bss_ctx, void **drv_priv,
7810                                      char *force_ifname, u8 *if_addr,
7811                                      const char *bridge)
7813         struct i802_bss *bss = priv;
7814         struct wpa_driver_nl80211_data *drv = bss->drv;
7815         int ifidx;
7816 #ifdef HOSTAPD
7817         struct i802_bss *new_bss = NULL;
7819         if (type == WPA_IF_AP_BSS) {
7820                 new_bss = os_zalloc(sizeof(*new_bss));
7821                 if (new_bss == NULL)
7822                         return -1;
7823         }
7824 #endif /* HOSTAPD */
7826         if (addr)
7827                 os_memcpy(if_addr, addr, ETH_ALEN);
7828         ifidx = nl80211_create_iface(drv, ifname,
7829                                      wpa_driver_nl80211_if_type(type), addr,
7830                                      0);
7831         if (ifidx < 0) {
7832 #ifdef HOSTAPD
7833                 os_free(new_bss);
7834 #endif /* HOSTAPD */
7835                 return -1;
7836         }
7838         if (!addr &&
7839             linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7840                                if_addr) < 0) {
7841                 nl80211_remove_iface(drv, ifidx);
7842                 return -1;
7843         }
7845 #ifdef CONFIG_P2P
7846         if (!addr &&
7847             (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
7848              type == WPA_IF_P2P_GO)) {
7849                 /* Enforce unique P2P Interface Address */
7850                 u8 new_addr[ETH_ALEN], own_addr[ETH_ALEN];
7852                 if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7853                                        own_addr) < 0 ||
7854                     linux_get_ifhwaddr(drv->global->ioctl_sock, ifname,
7855                                        new_addr) < 0) {
7856                         nl80211_remove_iface(drv, ifidx);
7857                         return -1;
7858                 }
7859                 if (os_memcmp(own_addr, new_addr, ETH_ALEN) == 0) {
7860                         wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
7861                                    "for P2P group interface");
7862                         if (nl80211_p2p_interface_addr(drv, new_addr) < 0) {
7863                                 nl80211_remove_iface(drv, ifidx);
7864                                 return -1;
7865                         }
7866                         if (linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
7867                                                new_addr) < 0) {
7868                                 nl80211_remove_iface(drv, ifidx);
7869                                 return -1;
7870                         }
7871                 }
7872                 os_memcpy(if_addr, new_addr, ETH_ALEN);
7873         }
7874 #endif /* CONFIG_P2P */
7876 #ifdef HOSTAPD
7877         if (bridge &&
7878             i802_check_bridge(drv, new_bss, bridge, ifname) < 0) {
7879                 wpa_printf(MSG_ERROR, "nl80211: Failed to add the new "
7880                            "interface %s to a bridge %s", ifname, bridge);
7881                 nl80211_remove_iface(drv, ifidx);
7882                 os_free(new_bss);
7883                 return -1;
7884         }
7886         if (type == WPA_IF_AP_BSS) {
7887                 if (linux_set_iface_flags(drv->global->ioctl_sock, ifname, 1))
7888                 {
7889                         nl80211_remove_iface(drv, ifidx);
7890                         os_free(new_bss);
7891                         return -1;
7892                 }
7893                 os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
7894                 os_memcpy(new_bss->addr, if_addr, ETH_ALEN);
7895                 new_bss->ifindex = ifidx;
7896                 new_bss->drv = drv;
7897                 new_bss->next = drv->first_bss.next;
7898                 new_bss->freq = drv->first_bss.freq;
7899                 drv->first_bss.next = new_bss;
7900                 if (drv_priv)
7901                         *drv_priv = new_bss;
7902                 nl80211_init_bss(new_bss);
7904                 /* Subscribe management frames for this WPA_IF_AP_BSS */
7905                 if (nl80211_setup_ap(new_bss))
7906                         return -1;
7907         }
7908 #endif /* HOSTAPD */
7910         if (drv->global)
7911                 drv->global->if_add_ifindex = ifidx;
7913         return 0;
7917 static int wpa_driver_nl80211_if_remove(void *priv,
7918                                         enum wpa_driver_if_type type,
7919                                         const char *ifname)
7921         struct i802_bss *bss = priv;
7922         struct wpa_driver_nl80211_data *drv = bss->drv;
7923         int ifindex = if_nametoindex(ifname);
7925         wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d",
7926                    __func__, type, ifname, ifindex);
7927         if (ifindex <= 0)
7928                 return -1;
7930 #ifdef HOSTAPD
7931         if (bss->added_if_into_bridge) {
7932                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
7933                                     bss->ifname) < 0)
7934                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
7935                                    "interface %s from bridge %s: %s",
7936                                    bss->ifname, bss->brname, strerror(errno));
7937         }
7938         if (bss->added_bridge) {
7939                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
7940                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
7941                                    "bridge %s: %s",
7942                                    bss->brname, strerror(errno));
7943         }
7944 #endif /* HOSTAPD */
7946         nl80211_remove_iface(drv, ifindex);
7948 #ifdef HOSTAPD
7949         if (type != WPA_IF_AP_BSS)
7950                 return 0;
7952         if (bss != &drv->first_bss) {
7953                 struct i802_bss *tbss;
7955                 for (tbss = &drv->first_bss; tbss; tbss = tbss->next) {
7956                         if (tbss->next == bss) {
7957                                 tbss->next = bss->next;
7958                                 /* Unsubscribe management frames */
7959                                 nl80211_teardown_ap(bss);
7960                                 nl80211_destroy_bss(bss);
7961                                 os_free(bss);
7962                                 bss = NULL;
7963                                 break;
7964                         }
7965                 }
7966                 if (bss)
7967                         wpa_printf(MSG_INFO, "nl80211: %s - could not find "
7968                                    "BSS %p in the list", __func__, bss);
7969         }
7970 #endif /* HOSTAPD */
7972         return 0;
7976 static int cookie_handler(struct nl_msg *msg, void *arg)
7978         struct nlattr *tb[NL80211_ATTR_MAX + 1];
7979         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7980         u64 *cookie = arg;
7981         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7982                   genlmsg_attrlen(gnlh, 0), NULL);
7983         if (tb[NL80211_ATTR_COOKIE])
7984                 *cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
7985         return NL_SKIP;
7989 static int nl80211_send_frame_cmd(struct i802_bss *bss,
7990                                   unsigned int freq, unsigned int wait,
7991                                   const u8 *buf, size_t buf_len,
7992                                   u64 *cookie_out, int no_cck, int no_ack,
7993                                   int offchanok)
7995         struct wpa_driver_nl80211_data *drv = bss->drv;
7996         struct nl_msg *msg;
7997         u64 cookie;
7998         int ret = -1;
8000         msg = nlmsg_alloc();
8001         if (!msg)
8002                 return -1;
8004         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME);
8006         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8007         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
8008 #ifndef ANDROID_BRCM_P2P_PATCH
8009         if (wait)
8010                 NLA_PUT_U32(msg, NL80211_ATTR_DURATION, wait);
8011 #endif /* ANDROID_BRCM_P2P_PATCH */
8012         if (offchanok && (drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX))
8013                 NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
8014         if (no_cck)
8015                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
8016         if (no_ack)
8017                 NLA_PUT_FLAG(msg, NL80211_ATTR_DONT_WAIT_FOR_ACK);
8019         NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
8021         cookie = 0;
8022         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
8023         msg = NULL;
8024         if (ret) {
8025                 wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
8026                            "(%s) (freq=%u wait=%u)", ret, strerror(-ret),
8027                            freq, wait);
8028                 goto nla_put_failure;
8029         }
8030         wpa_printf(MSG_DEBUG, "nl80211: Frame TX command accepted%s; "
8031                    "cookie 0x%llx", no_ack ? " (no ACK)" : "",
8032                    (long long unsigned int) cookie);
8034         if (cookie_out)
8035                 *cookie_out = no_ack ? (u64) -1 : cookie;
8037 nla_put_failure:
8038         nlmsg_free(msg);
8039         return ret;
8043 static int wpa_driver_nl80211_send_action(void *priv, unsigned int freq,
8044                                           unsigned int wait_time,
8045                                           const u8 *dst, const u8 *src,
8046                                           const u8 *bssid,
8047                                           const u8 *data, size_t data_len,
8048                                           int no_cck)
8050         struct i802_bss *bss = priv;
8051         struct wpa_driver_nl80211_data *drv = bss->drv;
8052         int ret = -1;
8053         u8 *buf;
8054         struct ieee80211_hdr *hdr;
8056         wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d, "
8057                    "freq=%u MHz wait=%d ms no_cck=%d)",
8058                    drv->ifindex, freq, wait_time, no_cck);
8060         buf = os_zalloc(24 + data_len);
8061         if (buf == NULL)
8062                 return ret;
8063         os_memcpy(buf + 24, data, data_len);
8064         hdr = (struct ieee80211_hdr *) buf;
8065         hdr->frame_control =
8066                 IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
8067         os_memcpy(hdr->addr1, dst, ETH_ALEN);
8068         os_memcpy(hdr->addr2, src, ETH_ALEN);
8069         os_memcpy(hdr->addr3, bssid, ETH_ALEN);
8071         if (is_ap_interface(drv->nlmode))
8072                 ret = wpa_driver_nl80211_send_mlme_freq(priv, buf,
8073                                                         24 + data_len,
8074                                                         0, freq, no_cck, 1,
8075                                                         wait_time);
8076         else
8077                 ret = nl80211_send_frame_cmd(bss, freq, wait_time, buf,
8078                                              24 + data_len,
8079                                              &drv->send_action_cookie,
8080                                              no_cck, 0, 1);
8082         os_free(buf);
8083         return ret;
8087 static void wpa_driver_nl80211_send_action_cancel_wait(void *priv)
8089         struct i802_bss *bss = priv;
8090         struct wpa_driver_nl80211_data *drv = bss->drv;
8091         struct nl_msg *msg;
8092         int ret;
8094         msg = nlmsg_alloc();
8095         if (!msg)
8096                 return;
8098         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME_WAIT_CANCEL);
8100         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8101         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->send_action_cookie);
8103         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8104         msg = NULL;
8105         if (ret)
8106                 wpa_printf(MSG_DEBUG, "nl80211: wait cancel failed: ret=%d "
8107                            "(%s)", ret, strerror(-ret));
8109  nla_put_failure:
8110         nlmsg_free(msg);
8114 static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
8115                                                 unsigned int duration)
8117         struct i802_bss *bss = priv;
8118         struct wpa_driver_nl80211_data *drv = bss->drv;
8119         struct nl_msg *msg;
8120         int ret;
8121         u64 cookie;
8123         msg = nlmsg_alloc();
8124         if (!msg)
8125                 return -1;
8127         nl80211_cmd(drv, msg, 0, NL80211_CMD_REMAIN_ON_CHANNEL);
8129         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8130         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
8131         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
8133         cookie = 0;
8134         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
8135         msg = NULL;
8136         if (ret == 0) {
8137                 wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
8138                            "0x%llx for freq=%u MHz duration=%u",
8139                            (long long unsigned int) cookie, freq, duration);
8140                 drv->remain_on_chan_cookie = cookie;
8141                 drv->pending_remain_on_chan = 1;
8142                 return 0;
8143         }
8144         wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
8145                    "(freq=%d duration=%u): %d (%s)",
8146                    freq, duration, ret, strerror(-ret));
8147 nla_put_failure:
8148         nlmsg_free(msg);
8149         return -1;
8153 static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
8155         struct i802_bss *bss = priv;
8156         struct wpa_driver_nl80211_data *drv = bss->drv;
8157         struct nl_msg *msg;
8158         int ret;
8160         if (!drv->pending_remain_on_chan) {
8161                 wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
8162                            "to cancel");
8163                 return -1;
8164         }
8166         wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
8167                    "0x%llx",
8168                    (long long unsigned int) drv->remain_on_chan_cookie);
8170         msg = nlmsg_alloc();
8171         if (!msg)
8172                 return -1;
8174         nl80211_cmd(drv, msg, 0, NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL);
8176         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8177         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
8179         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8180         msg = NULL;
8181         if (ret == 0)
8182                 return 0;
8183         wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
8184                    "%d (%s)", ret, strerror(-ret));
8185 nla_put_failure:
8186         nlmsg_free(msg);
8187         return -1;
8191 static int wpa_driver_nl80211_probe_req_report(void *priv, int report)
8193         struct i802_bss *bss = priv;
8194         struct wpa_driver_nl80211_data *drv = bss->drv;
8196         if (!report) {
8197                 if (bss->nl_preq && drv->device_ap_sme &&
8198                     is_ap_interface(drv->nlmode)) {
8199                         /*
8200                          * Do not disable Probe Request reporting that was
8201                          * enabled in nl80211_setup_ap().
8202                          */
8203                         wpa_printf(MSG_DEBUG, "nl80211: Skip disabling of "
8204                                    "Probe Request reporting nl_preq=%p while "
8205                                    "in AP mode", bss->nl_preq);
8206                 } else if (bss->nl_preq) {
8207                         wpa_printf(MSG_DEBUG, "nl80211: Disable Probe Request "
8208                                    "reporting nl_preq=%p", bss->nl_preq);
8209                         eloop_unregister_read_sock(
8210                                 nl_socket_get_fd(bss->nl_preq));
8211                         nl_destroy_handles(&bss->nl_preq);
8212                 }
8213                 return 0;
8214         }
8216         if (bss->nl_preq) {
8217                 wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
8218                            "already on! nl_preq=%p", bss->nl_preq);
8219                 return 0;
8220         }
8222         bss->nl_preq = nl_create_handle(drv->global->nl_cb, "preq");
8223         if (bss->nl_preq == NULL)
8224                 return -1;
8225         wpa_printf(MSG_DEBUG, "nl80211: Enable Probe Request "
8226                    "reporting nl_preq=%p", bss->nl_preq);
8228         if (nl80211_register_frame(bss, bss->nl_preq,
8229                                    (WLAN_FC_TYPE_MGMT << 2) |
8230                                    (WLAN_FC_STYPE_PROBE_REQ << 4),
8231                                    NULL, 0) < 0)
8232                 goto out_err;
8234         eloop_register_read_sock(nl_socket_get_fd(bss->nl_preq),
8235                                  wpa_driver_nl80211_event_receive, bss->nl_cb,
8236                                  bss->nl_preq);
8238         return 0;
8240  out_err:
8241         nl_destroy_handles(&bss->nl_preq);
8242         return -1;
8246 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
8247                                      int ifindex, int disabled)
8249         struct nl_msg *msg;
8250         struct nlattr *bands, *band;
8251         int ret;
8253         msg = nlmsg_alloc();
8254         if (!msg)
8255                 return -1;
8257         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_TX_BITRATE_MASK);
8258         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
8260         bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
8261         if (!bands)
8262                 goto nla_put_failure;
8264         /*
8265          * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
8266          * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
8267          * rates. All 5 GHz rates are left enabled.
8268          */
8269         band = nla_nest_start(msg, NL80211_BAND_2GHZ);
8270         if (!band)
8271                 goto nla_put_failure;
8272         if (disabled) {
8273                 NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
8274                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
8275         }
8276         nla_nest_end(msg, band);
8278         nla_nest_end(msg, bands);
8280         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8281         msg = NULL;
8282         if (ret) {
8283                 wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
8284                            "(%s)", ret, strerror(-ret));
8285         }
8287         return ret;
8289 nla_put_failure:
8290         nlmsg_free(msg);
8291         return -1;
8295 static int wpa_driver_nl80211_deinit_ap(void *priv)
8297         struct i802_bss *bss = priv;
8298         struct wpa_driver_nl80211_data *drv = bss->drv;
8299         if (!is_ap_interface(drv->nlmode))
8300                 return -1;
8301         wpa_driver_nl80211_del_beacon(drv);
8302         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
8306 static void wpa_driver_nl80211_resume(void *priv)
8308         struct i802_bss *bss = priv;
8309         struct wpa_driver_nl80211_data *drv = bss->drv;
8310         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
8311                 wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on "
8312                            "resume event");
8313         }
8317 static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
8318                                   const u8 *ies, size_t ies_len)
8320         struct i802_bss *bss = priv;
8321         struct wpa_driver_nl80211_data *drv = bss->drv;
8322         int ret;
8323         u8 *data, *pos;
8324         size_t data_len;
8325         const u8 *own_addr = bss->addr;
8327         if (action != 1) {
8328                 wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
8329                            "action %d", action);
8330                 return -1;
8331         }
8333         /*
8334          * Action frame payload:
8335          * Category[1] = 6 (Fast BSS Transition)
8336          * Action[1] = 1 (Fast BSS Transition Request)
8337          * STA Address
8338          * Target AP Address
8339          * FT IEs
8340          */
8342         data_len = 2 + 2 * ETH_ALEN + ies_len;
8343         data = os_malloc(data_len);
8344         if (data == NULL)
8345                 return -1;
8346         pos = data;
8347         *pos++ = 0x06; /* FT Action category */
8348         *pos++ = action;
8349         os_memcpy(pos, own_addr, ETH_ALEN);
8350         pos += ETH_ALEN;
8351         os_memcpy(pos, target_ap, ETH_ALEN);
8352         pos += ETH_ALEN;
8353         os_memcpy(pos, ies, ies_len);
8355         ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, 0,
8356                                              drv->bssid, own_addr, drv->bssid,
8357                                              data, data_len, 0);
8358         os_free(data);
8360         return ret;
8364 static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
8366         struct i802_bss *bss = priv;
8367         struct wpa_driver_nl80211_data *drv = bss->drv;
8368         struct nl_msg *msg, *cqm = NULL;
8370         wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
8371                    "hysteresis=%d", threshold, hysteresis);
8373         msg = nlmsg_alloc();
8374         if (!msg)
8375                 return -1;
8377         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_CQM);
8379         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8381         cqm = nlmsg_alloc();
8382         if (cqm == NULL)
8383                 return -1;
8385         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
8386         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
8387         nla_put_nested(msg, NL80211_ATTR_CQM, cqm);
8389         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
8390                 return 0;
8391         msg = NULL;
8393 nla_put_failure:
8394         nlmsg_free(cqm);
8395         nlmsg_free(msg);
8396         return -1;
8400 static int nl80211_signal_poll(void *priv, struct wpa_signal_info *si)
8402         struct i802_bss *bss = priv;
8403         struct wpa_driver_nl80211_data *drv = bss->drv;
8404         int res;
8406         os_memset(si, 0, sizeof(*si));
8407         res = nl80211_get_link_signal(drv, si);
8408         if (res != 0)
8409                 return res;
8411         return nl80211_get_link_noise(drv, si);
8415 static int wpa_driver_nl80211_shared_freq(void *priv)
8417         struct i802_bss *bss = priv;
8418         struct wpa_driver_nl80211_data *drv = bss->drv;
8419         struct wpa_driver_nl80211_data *driver;
8420         int freq = 0;
8422         /*
8423          * If the same PHY is in connected state with some other interface,
8424          * then retrieve the assoc freq.
8425          */
8426         wpa_printf(MSG_DEBUG, "nl80211: Get shared freq for PHY %s",
8427                    drv->phyname);
8429         dl_list_for_each(driver, &drv->global->interfaces,
8430                          struct wpa_driver_nl80211_data, list) {
8431                 if (drv == driver ||
8432                     os_strcmp(drv->phyname, driver->phyname) != 0 ||
8433                     !driver->associated)
8434                         continue;
8436                 wpa_printf(MSG_DEBUG, "nl80211: Found a match for PHY %s - %s "
8437                            MACSTR,
8438                            driver->phyname, driver->first_bss.ifname,
8439                            MAC2STR(driver->first_bss.addr));
8440                 freq = nl80211_get_assoc_freq(driver);
8441                 wpa_printf(MSG_DEBUG, "nl80211: Shared freq for PHY %s: %d",
8442                            drv->phyname, freq);
8443         }
8445         if (!freq)
8446                 wpa_printf(MSG_DEBUG, "nl80211: No shared interface for "
8447                            "PHY (%s) in associated state", drv->phyname);
8449         return freq;
8453 static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
8454                               int encrypt)
8456         struct i802_bss *bss = priv;
8457         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt, 0,
8458                                              0, 0, 0, 0);
8462 static int nl80211_set_param(void *priv, const char *param)
8464         wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
8465         if (param == NULL)
8466                 return 0;
8468 #ifdef CONFIG_P2P
8469         if (os_strstr(param, "use_p2p_group_interface=1")) {
8470                 struct i802_bss *bss = priv;
8471                 struct wpa_driver_nl80211_data *drv = bss->drv;
8473                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
8474                            "interface");
8475                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
8476                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
8477         }
8478 #endif /* CONFIG_P2P */
8480         return 0;
8484 static void * nl80211_global_init(void)
8486         struct nl80211_global *global;
8487         struct netlink_config *cfg;
8489         global = os_zalloc(sizeof(*global));
8490         if (global == NULL)
8491                 return NULL;
8492         global->ioctl_sock = -1;
8493         dl_list_init(&global->interfaces);
8494         global->if_add_ifindex = -1;
8496         cfg = os_zalloc(sizeof(*cfg));
8497         if (cfg == NULL)
8498                 goto err;
8500         cfg->ctx = global;
8501         cfg->newlink_cb = wpa_driver_nl80211_event_rtm_newlink;
8502         cfg->dellink_cb = wpa_driver_nl80211_event_rtm_dellink;
8503         global->netlink = netlink_init(cfg);
8504         if (global->netlink == NULL) {
8505                 os_free(cfg);
8506                 goto err;
8507         }
8509         if (wpa_driver_nl80211_init_nl_global(global) < 0)
8510                 goto err;
8512         global->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
8513         if (global->ioctl_sock < 0) {
8514                 perror("socket(PF_INET,SOCK_DGRAM)");
8515                 goto err;
8516         }
8518         return global;
8520 err:
8521         nl80211_global_deinit(global);
8522         return NULL;
8526 static void nl80211_global_deinit(void *priv)
8528         struct nl80211_global *global = priv;
8529         if (global == NULL)
8530                 return;
8531         if (!dl_list_empty(&global->interfaces)) {
8532                 wpa_printf(MSG_ERROR, "nl80211: %u interface(s) remain at "
8533                            "nl80211_global_deinit",
8534                            dl_list_len(&global->interfaces));
8535         }
8537         if (global->netlink)
8538                 netlink_deinit(global->netlink);
8540         nl_destroy_handles(&global->nl);
8542         if (global->nl_event) {
8543                 eloop_unregister_read_sock(
8544                         nl_socket_get_fd(global->nl_event));
8545                 nl_destroy_handles(&global->nl_event);
8546         }
8548         nl_cb_put(global->nl_cb);
8550         if (global->ioctl_sock >= 0)
8551                 close(global->ioctl_sock);
8553         os_free(global);
8557 static const char * nl80211_get_radio_name(void *priv)
8559         struct i802_bss *bss = priv;
8560         struct wpa_driver_nl80211_data *drv = bss->drv;
8561         return drv->phyname;
8565 static int nl80211_pmkid(struct i802_bss *bss, int cmd, const u8 *bssid,
8566                          const u8 *pmkid)
8568         struct nl_msg *msg;
8570         msg = nlmsg_alloc();
8571         if (!msg)
8572                 return -ENOMEM;
8574         nl80211_cmd(bss->drv, msg, 0, cmd);
8576         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
8577         if (pmkid)
8578                 NLA_PUT(msg, NL80211_ATTR_PMKID, 16, pmkid);
8579         if (bssid)
8580                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
8582         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
8583  nla_put_failure:
8584         nlmsg_free(msg);
8585         return -ENOBUFS;
8589 static int nl80211_add_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
8591         struct i802_bss *bss = priv;
8592         wpa_printf(MSG_DEBUG, "nl80211: Add PMKID for " MACSTR, MAC2STR(bssid));
8593         return nl80211_pmkid(bss, NL80211_CMD_SET_PMKSA, bssid, pmkid);
8597 static int nl80211_remove_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
8599         struct i802_bss *bss = priv;
8600         wpa_printf(MSG_DEBUG, "nl80211: Delete PMKID for " MACSTR,
8601                    MAC2STR(bssid));
8602         return nl80211_pmkid(bss, NL80211_CMD_DEL_PMKSA, bssid, pmkid);
8606 static int nl80211_flush_pmkid(void *priv)
8608         struct i802_bss *bss = priv;
8609         wpa_printf(MSG_DEBUG, "nl80211: Flush PMKIDs");
8610         return nl80211_pmkid(bss, NL80211_CMD_FLUSH_PMKSA, NULL, NULL);
8614 static void nl80211_set_rekey_info(void *priv, const u8 *kek, const u8 *kck,
8615                                    const u8 *replay_ctr)
8617         struct i802_bss *bss = priv;
8618         struct wpa_driver_nl80211_data *drv = bss->drv;
8619         struct nlattr *replay_nested;
8620         struct nl_msg *msg;
8622         msg = nlmsg_alloc();
8623         if (!msg)
8624                 return;
8626         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_REKEY_OFFLOAD);
8628         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8630         replay_nested = nla_nest_start(msg, NL80211_ATTR_REKEY_DATA);
8631         if (!replay_nested)
8632                 goto nla_put_failure;
8634         NLA_PUT(msg, NL80211_REKEY_DATA_KEK, NL80211_KEK_LEN, kek);
8635         NLA_PUT(msg, NL80211_REKEY_DATA_KCK, NL80211_KCK_LEN, kck);
8636         NLA_PUT(msg, NL80211_REKEY_DATA_REPLAY_CTR, NL80211_REPLAY_CTR_LEN,
8637                 replay_ctr);
8639         nla_nest_end(msg, replay_nested);
8641         send_and_recv_msgs(drv, msg, NULL, NULL);
8642         return;
8643  nla_put_failure:
8644         nlmsg_free(msg);
8648 static void nl80211_send_null_frame(struct i802_bss *bss, const u8 *own_addr,
8649                                     const u8 *addr, int qos)
8651         /* send data frame to poll STA and check whether
8652          * this frame is ACKed */
8653         struct {
8654                 struct ieee80211_hdr hdr;
8655                 u16 qos_ctl;
8656         } STRUCT_PACKED nulldata;
8657         size_t size;
8659         /* Send data frame to poll STA and check whether this frame is ACKed */
8661         os_memset(&nulldata, 0, sizeof(nulldata));
8663         if (qos) {
8664                 nulldata.hdr.frame_control =
8665                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
8666                                      WLAN_FC_STYPE_QOS_NULL);
8667                 size = sizeof(nulldata);
8668         } else {
8669                 nulldata.hdr.frame_control =
8670                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
8671                                      WLAN_FC_STYPE_NULLFUNC);
8672                 size = sizeof(struct ieee80211_hdr);
8673         }
8675         nulldata.hdr.frame_control |= host_to_le16(WLAN_FC_FROMDS);
8676         os_memcpy(nulldata.hdr.IEEE80211_DA_FROMDS, addr, ETH_ALEN);
8677         os_memcpy(nulldata.hdr.IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
8678         os_memcpy(nulldata.hdr.IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
8680         if (wpa_driver_nl80211_send_mlme(bss, (u8 *) &nulldata, size, 0) < 0)
8681                 wpa_printf(MSG_DEBUG, "nl80211_send_null_frame: Failed to "
8682                            "send poll frame");
8685 static void nl80211_poll_client(void *priv, const u8 *own_addr, const u8 *addr,
8686                                 int qos)
8688         struct i802_bss *bss = priv;
8689         struct wpa_driver_nl80211_data *drv = bss->drv;
8690         struct nl_msg *msg;
8692         if (!drv->poll_command_supported) {
8693                 nl80211_send_null_frame(bss, own_addr, addr, qos);
8694                 return;
8695         }
8697         msg = nlmsg_alloc();
8698         if (!msg)
8699                 return;
8701         nl80211_cmd(drv, msg, 0, NL80211_CMD_PROBE_CLIENT);
8703         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8704         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
8706         send_and_recv_msgs(drv, msg, NULL, NULL);
8707         return;
8708  nla_put_failure:
8709         nlmsg_free(msg);
8713 static int nl80211_set_power_save(struct i802_bss *bss, int enabled)
8715         struct nl_msg *msg;
8717         msg = nlmsg_alloc();
8718         if (!msg)
8719                 return -ENOMEM;
8721         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_SET_POWER_SAVE);
8722         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8723         NLA_PUT_U32(msg, NL80211_ATTR_PS_STATE,
8724                     enabled ? NL80211_PS_ENABLED : NL80211_PS_DISABLED);
8725         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
8726 nla_put_failure:
8727         nlmsg_free(msg);
8728         return -ENOBUFS;
8732 static int nl80211_set_p2p_powersave(void *priv, int legacy_ps, int opp_ps,
8733                                      int ctwindow)
8735         struct i802_bss *bss = priv;
8737         wpa_printf(MSG_DEBUG, "nl80211: set_p2p_powersave (legacy_ps=%d "
8738                    "opp_ps=%d ctwindow=%d)", legacy_ps, opp_ps, ctwindow);
8740         if (opp_ps != -1 || ctwindow != -1)
8741                 return -1; /* Not yet supported */
8743         if (legacy_ps == -1)
8744                 return 0;
8745         if (legacy_ps != 0 && legacy_ps != 1)
8746                 return -1; /* Not yet supported */
8748         return nl80211_set_power_save(bss, legacy_ps);
8752 #ifdef CONFIG_TDLS
8754 static int nl80211_send_tdls_mgmt(void *priv, const u8 *dst, u8 action_code,
8755                                   u8 dialog_token, u16 status_code,
8756                                   const u8 *buf, size_t len)
8758         struct i802_bss *bss = priv;
8759         struct wpa_driver_nl80211_data *drv = bss->drv;
8760         struct nl_msg *msg;
8762         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
8763                 return -EOPNOTSUPP;
8765         if (!dst)
8766                 return -EINVAL;
8768         msg = nlmsg_alloc();
8769         if (!msg)
8770                 return -ENOMEM;
8772         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_MGMT);
8773         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8774         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, dst);
8775         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_ACTION, action_code);
8776         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_DIALOG_TOKEN, dialog_token);
8777         NLA_PUT_U16(msg, NL80211_ATTR_STATUS_CODE, status_code);
8778         NLA_PUT(msg, NL80211_ATTR_IE, len, buf);
8780         return send_and_recv_msgs(drv, msg, NULL, NULL);
8782 nla_put_failure:
8783         nlmsg_free(msg);
8784         return -ENOBUFS;
8788 static int nl80211_tdls_oper(void *priv, enum tdls_oper oper, const u8 *peer)
8790         struct i802_bss *bss = priv;
8791         struct wpa_driver_nl80211_data *drv = bss->drv;
8792         struct nl_msg *msg;
8793         enum nl80211_tdls_operation nl80211_oper;
8795         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
8796                 return -EOPNOTSUPP;
8798         switch (oper) {
8799         case TDLS_DISCOVERY_REQ:
8800                 nl80211_oper = NL80211_TDLS_DISCOVERY_REQ;
8801                 break;
8802         case TDLS_SETUP:
8803                 nl80211_oper = NL80211_TDLS_SETUP;
8804                 break;
8805         case TDLS_TEARDOWN:
8806                 nl80211_oper = NL80211_TDLS_TEARDOWN;
8807                 break;
8808         case TDLS_ENABLE_LINK:
8809                 nl80211_oper = NL80211_TDLS_ENABLE_LINK;
8810                 break;
8811         case TDLS_DISABLE_LINK:
8812                 nl80211_oper = NL80211_TDLS_DISABLE_LINK;
8813                 break;
8814         case TDLS_ENABLE:
8815                 return 0;
8816         case TDLS_DISABLE:
8817                 return 0;
8818         default:
8819                 return -EINVAL;
8820         }
8822         msg = nlmsg_alloc();
8823         if (!msg)
8824                 return -ENOMEM;
8826         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_OPER);
8827         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_OPERATION, nl80211_oper);
8828         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8829         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, peer);
8831         return send_and_recv_msgs(drv, msg, NULL, NULL);
8833 nla_put_failure:
8834         nlmsg_free(msg);
8835         return -ENOBUFS;
8838 #endif /* CONFIG TDLS */
8841 #ifdef ANDROID
8843 typedef struct android_wifi_priv_cmd {
8844         char *buf;
8845         int used_len;
8846         int total_len;
8847 } android_wifi_priv_cmd;
8849 static int drv_errors = 0;
8851 static void wpa_driver_send_hang_msg(struct wpa_driver_nl80211_data *drv)
8853         drv_errors++;
8854         if (drv_errors > DRV_NUMBER_SEQUENTIAL_ERRORS) {
8855                 drv_errors = 0;
8856                 wpa_msg(drv->ctx, MSG_INFO, WPA_EVENT_DRIVER_STATE "HANGED");
8857         }
8861 #define WPA_PS_ENABLED          0
8862 #define WPA_PS_DISABLED         1
8864 static int wpa_driver_set_power_save(void *priv, int state)
8866         return nl80211_set_power_save(priv, state == WPA_PS_ENABLED);
8870 static int get_power_mode_handler(struct nl_msg *msg, void *arg)
8872         struct nlattr *tb[NL80211_ATTR_MAX + 1];
8873         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
8874         int *state = arg;
8876         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
8877                   genlmsg_attrlen(gnlh, 0), NULL);
8879         if (!tb[NL80211_ATTR_PS_STATE])
8880                 return NL_SKIP;
8882         if (state) {
8883                 int s = (int) nla_get_u32(tb[NL80211_ATTR_PS_STATE]);
8884                 wpa_printf(MSG_DEBUG, "nl80211: Get power mode = %d", s);
8885                 *state = (s == NL80211_PS_ENABLED) ?
8886                         WPA_PS_ENABLED : WPA_PS_DISABLED;
8887         }
8889         return NL_SKIP;
8893 static int wpa_driver_get_power_save(void *priv, int *state)
8895         struct i802_bss *bss = priv;
8896         struct wpa_driver_nl80211_data *drv = bss->drv;
8897         struct nl_msg *msg;
8898         int ret = -1;
8899         enum nl80211_ps_state ps_state;
8901         msg = nlmsg_alloc();
8902         if (!msg)
8903                 return -1;
8905         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_POWER_SAVE);
8907         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8909         ret = send_and_recv_msgs(drv, msg, get_power_mode_handler, state);
8910         msg = NULL;
8911         if (ret < 0)
8912                 wpa_printf(MSG_ERROR, "nl80211: Get power mode fail: %d", ret);
8913 nla_put_failure:
8914         nlmsg_free(msg);
8915         return ret;
8919 static int android_priv_cmd(struct i802_bss *bss, const char *cmd)
8921         struct wpa_driver_nl80211_data *drv = bss->drv;
8922         struct ifreq ifr;
8923         android_wifi_priv_cmd priv_cmd;
8924         char buf[MAX_DRV_CMD_SIZE];
8925         int ret;
8927         os_memset(&ifr, 0, sizeof(ifr));
8928         os_memset(&priv_cmd, 0, sizeof(priv_cmd));
8929         os_strlcpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
8931         os_memset(buf, 0, sizeof(buf));
8932         os_strlcpy(buf, cmd, sizeof(buf));
8934         priv_cmd.buf = buf;
8935         priv_cmd.used_len = sizeof(buf);
8936         priv_cmd.total_len = sizeof(buf);
8937         ifr.ifr_data = &priv_cmd;
8939         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
8940         if (ret < 0) {
8941                 wpa_printf(MSG_ERROR, "%s: failed to issue private commands",
8942                            __func__);
8943                 wpa_driver_send_hang_msg(drv);
8944                 return ret;
8945         }
8947         drv_errors = 0;
8948         return 0;
8952 static int android_pno_start(struct i802_bss *bss,
8953                              struct wpa_driver_scan_params *params)
8955         struct wpa_driver_nl80211_data *drv = bss->drv;
8956         struct ifreq ifr;
8957         android_wifi_priv_cmd priv_cmd;
8958         int ret = 0, i = 0, bp;
8959         char buf[WEXT_PNO_MAX_COMMAND_SIZE];
8961         bp = WEXT_PNOSETUP_HEADER_SIZE;
8962         os_memcpy(buf, WEXT_PNOSETUP_HEADER, bp);
8963         buf[bp++] = WEXT_PNO_TLV_PREFIX;
8964         buf[bp++] = WEXT_PNO_TLV_VERSION;
8965         buf[bp++] = WEXT_PNO_TLV_SUBVERSION;
8966         buf[bp++] = WEXT_PNO_TLV_RESERVED;
8968         while (i < WEXT_PNO_AMOUNT && (size_t) i < params->num_ssids) {
8969                 /* Check that there is enough space needed for 1 more SSID, the
8970                  * other sections and null termination */
8971                 if ((bp + WEXT_PNO_SSID_HEADER_SIZE + MAX_SSID_LEN +
8972                      WEXT_PNO_NONSSID_SECTIONS_SIZE + 1) >= (int) sizeof(buf))
8973                         break;
8974                 wpa_hexdump_ascii(MSG_DEBUG, "For PNO Scan",
8975                                   params->ssids[i].ssid,
8976                                   params->ssids[i].ssid_len);
8977                 buf[bp++] = WEXT_PNO_SSID_SECTION;
8978                 buf[bp++] = params->ssids[i].ssid_len;
8979                 os_memcpy(&buf[bp], params->ssids[i].ssid,
8980                           params->ssids[i].ssid_len);
8981                 bp += params->ssids[i].ssid_len;
8982                 i++;
8983         }
8985         buf[bp++] = WEXT_PNO_SCAN_INTERVAL_SECTION;
8986         os_snprintf(&buf[bp], WEXT_PNO_SCAN_INTERVAL_LENGTH + 1, "%x",
8987                     WEXT_PNO_SCAN_INTERVAL);
8988         bp += WEXT_PNO_SCAN_INTERVAL_LENGTH;
8990         buf[bp++] = WEXT_PNO_REPEAT_SECTION;
8991         os_snprintf(&buf[bp], WEXT_PNO_REPEAT_LENGTH + 1, "%x",
8992                     WEXT_PNO_REPEAT);
8993         bp += WEXT_PNO_REPEAT_LENGTH;
8995         buf[bp++] = WEXT_PNO_MAX_REPEAT_SECTION;
8996         os_snprintf(&buf[bp], WEXT_PNO_MAX_REPEAT_LENGTH + 1, "%x",
8997                     WEXT_PNO_MAX_REPEAT);
8998         bp += WEXT_PNO_MAX_REPEAT_LENGTH + 1;
9000         memset(&ifr, 0, sizeof(ifr));
9001         memset(&priv_cmd, 0, sizeof(priv_cmd));
9002         os_strncpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
9004         priv_cmd.buf = buf;
9005         priv_cmd.used_len = bp;
9006         priv_cmd.total_len = bp;
9007         ifr.ifr_data = &priv_cmd;
9009         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
9011         if (ret < 0) {
9012                 wpa_printf(MSG_ERROR, "ioctl[SIOCSIWPRIV] (pnosetup): %d",
9013                            ret);
9014                 wpa_driver_send_hang_msg(drv);
9015                 return ret;
9016         }
9018         drv_errors = 0;
9020         return android_priv_cmd(bss, "PNOFORCE 1");
9024 static int android_pno_stop(struct i802_bss *bss)
9026         return android_priv_cmd(bss, "PNOFORCE 0");
9030 static int wpa_driver_nl80211_driver_cmd(void *priv, char *cmd, char *buf,
9031                                          size_t buf_len)
9033         struct i802_bss *bss = priv;
9034         struct wpa_driver_nl80211_data *drv = bss->drv;
9035         struct ifreq ifr;
9036         android_wifi_priv_cmd priv_cmd;
9037         int ret = 0;
9039         if (os_strcasecmp(cmd, "STOP") == 0) {
9040                 linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0);
9041                 wpa_msg(drv->ctx, MSG_INFO, WPA_EVENT_DRIVER_STATE "STOPPED");
9042         } else if (os_strcasecmp(cmd, "START") == 0) {
9043                 linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1);
9044                 wpa_msg(drv->ctx, MSG_INFO, WPA_EVENT_DRIVER_STATE "STARTED");
9045         } else if (os_strcasecmp(cmd, "MACADDR") == 0) {
9046                 u8 macaddr[ETH_ALEN] = {};
9048                 ret = linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
9049                                          macaddr);
9050                 if (!ret)
9051                         ret = os_snprintf(buf, buf_len,
9052                                           "Macaddr = " MACSTR "\n",
9053                                           MAC2STR(macaddr));
9054         } else if (os_strcasecmp(cmd, "RELOAD") == 0) {
9055                 wpa_msg(drv->ctx, MSG_INFO, WPA_EVENT_DRIVER_STATE "HANGED");
9056         } else if (os_strncasecmp(cmd, "POWERMODE ", 10) == 0) {
9057                 int state = atoi(cmd + 10);
9058                 ret = wpa_driver_set_power_save(priv, state);
9059                 if (ret < 0)
9060                         wpa_driver_send_hang_msg(drv);
9061                 else
9062                         drv_errors = 0;
9063         } else if (os_strncasecmp(cmd, "GETPOWER", 8) == 0) {
9064                 int state = -1;
9065                 ret = wpa_driver_get_power_save(priv, &state);
9066                 if (!ret && (state != -1))
9067                         ret = os_snprintf(buf, buf_len, "POWERMODE = %d\n",
9068                                           state);
9069         } else { /* Use private command */
9070                 memset(&ifr, 0, sizeof(ifr));
9071                 memset(&priv_cmd, 0, sizeof(priv_cmd));
9072                 os_memcpy(buf, cmd, strlen(cmd) + 1);
9073                 os_strncpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
9075                 priv_cmd.buf = buf;
9076                 priv_cmd.used_len = buf_len;
9077                 priv_cmd.total_len = buf_len;
9078                 ifr.ifr_data = &priv_cmd;
9080                 if ((ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1,
9081                                  &ifr)) < 0) {
9082                         wpa_printf(MSG_ERROR, "%s: failed to issue private "
9083                                    "commands\n", __func__);
9084                         wpa_driver_send_hang_msg(drv);
9085                 } else {
9086                         drv_errors = 0;
9087                         ret = 0;
9088                         if ((os_strcasecmp(cmd, "LINKSPEED") == 0) ||
9089                             (os_strcasecmp(cmd, "RSSI") == 0) ||
9090                             (os_strcasecmp(cmd, "GETBAND") == 0))
9091                                 ret = strlen(buf);
9093                         wpa_printf(MSG_DEBUG, "%s %s len = %d, %d", __func__,
9094                                    buf, ret, strlen(buf));
9095                 }
9096         }
9098         return ret;
9101 #endif /* ANDROID */
9104 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
9105         .name = "nl80211",
9106         .desc = "Linux nl80211/cfg80211",
9107         .get_bssid = wpa_driver_nl80211_get_bssid,
9108         .get_ssid = wpa_driver_nl80211_get_ssid,
9109         .set_key = wpa_driver_nl80211_set_key,
9110         .scan2 = wpa_driver_nl80211_scan,
9111         .sched_scan = wpa_driver_nl80211_sched_scan,
9112         .stop_sched_scan = wpa_driver_nl80211_stop_sched_scan,
9113         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
9114         .deauthenticate = wpa_driver_nl80211_deauthenticate,
9115         .disassociate = wpa_driver_nl80211_disassociate,
9116         .authenticate = wpa_driver_nl80211_authenticate,
9117         .associate = wpa_driver_nl80211_associate,
9118         .global_init = nl80211_global_init,
9119         .global_deinit = nl80211_global_deinit,
9120         .init2 = wpa_driver_nl80211_init,
9121         .deinit = wpa_driver_nl80211_deinit,
9122         .get_capa = wpa_driver_nl80211_get_capa,
9123         .set_operstate = wpa_driver_nl80211_set_operstate,
9124         .set_supp_port = wpa_driver_nl80211_set_supp_port,
9125         .set_country = wpa_driver_nl80211_set_country,
9126         .set_ap = wpa_driver_nl80211_set_ap,
9127         .if_add = wpa_driver_nl80211_if_add,
9128         .if_remove = wpa_driver_nl80211_if_remove,
9129         .send_mlme = wpa_driver_nl80211_send_mlme,
9130         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
9131         .sta_add = wpa_driver_nl80211_sta_add,
9132         .sta_remove = wpa_driver_nl80211_sta_remove,
9133         .hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
9134         .sta_set_flags = wpa_driver_nl80211_sta_set_flags,
9135 #ifdef HOSTAPD
9136         .hapd_init = i802_init,
9137         .hapd_deinit = i802_deinit,
9138         .set_wds_sta = i802_set_wds_sta,
9139 #endif /* HOSTAPD */
9140 #if defined(HOSTAPD) || defined(CONFIG_AP)
9141         .get_seqnum = i802_get_seqnum,
9142         .flush = i802_flush,
9143         .read_sta_data = i802_read_sta_data,
9144         .get_inact_sec = i802_get_inact_sec,
9145         .sta_clear_stats = i802_sta_clear_stats,
9146         .set_rts = i802_set_rts,
9147         .set_frag = i802_set_frag,
9148         .set_tx_queue_params = i802_set_tx_queue_params,
9149         .set_sta_vlan = i802_set_sta_vlan,
9150         .sta_deauth = i802_sta_deauth,
9151         .sta_disassoc = i802_sta_disassoc,
9152 #endif /* HOSTAPD || CONFIG_AP */
9153         .set_freq = i802_set_freq,
9154         .send_action = wpa_driver_nl80211_send_action,
9155         .send_action_cancel_wait = wpa_driver_nl80211_send_action_cancel_wait,
9156         .remain_on_channel = wpa_driver_nl80211_remain_on_channel,
9157         .cancel_remain_on_channel =
9158         wpa_driver_nl80211_cancel_remain_on_channel,
9159         .probe_req_report = wpa_driver_nl80211_probe_req_report,
9160         .deinit_ap = wpa_driver_nl80211_deinit_ap,
9161         .resume = wpa_driver_nl80211_resume,
9162         .send_ft_action = nl80211_send_ft_action,
9163         .signal_monitor = nl80211_signal_monitor,
9164         .signal_poll = nl80211_signal_poll,
9165         .send_frame = nl80211_send_frame,
9166         .shared_freq = wpa_driver_nl80211_shared_freq,
9167         .set_param = nl80211_set_param,
9168         .get_radio_name = nl80211_get_radio_name,
9169         .add_pmkid = nl80211_add_pmkid,
9170         .remove_pmkid = nl80211_remove_pmkid,
9171         .flush_pmkid = nl80211_flush_pmkid,
9172         .set_rekey_info = nl80211_set_rekey_info,
9173         .poll_client = nl80211_poll_client,
9174         .set_p2p_powersave = nl80211_set_p2p_powersave,
9175 #ifdef CONFIG_TDLS
9176         .send_tdls_mgmt = nl80211_send_tdls_mgmt,
9177         .tdls_oper = nl80211_tdls_oper,
9178 #endif /* CONFIG_TDLS */
9179 #ifdef ANDROID
9180         .driver_cmd = wpa_driver_nl80211_driver_cmd,
9181 #endif /* ANDROID */
9182 };