nl80211: Add channel flags for DFS state information
[mech_eap.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  */
12
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"
27
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"
40
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
49
50 # define SCM_WIFI_STATUS        SO_WIFI_STATUS
51 #endif
52
53 #ifndef SO_EE_ORIGIN_TXSTATUS
54 #define SO_EE_ORIGIN_TXSTATUS   4
55 #endif
56
57 #ifndef PACKET_TX_TIMESTAMP
58 #define PACKET_TX_TIMESTAMP     16
59 #endif
60
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 };
78
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;
84
85         handle = nl_handle_alloc_cb(cb);
86
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         }
94
95         nl_socket_set_local_port(handle, pid);
96
97         return handle;
98 }
99
100 static void nl80211_handle_destroy(struct nl_handle *handle)
101 {
102         uint32_t port = nl_socket_get_local_port(handle);
103
104         port >>= 22;
105         port_bitmap[port / 32] &= ~(1 << (port % 32));
106
107         nl_handle_destroy(handle);
108 }
109 #endif /* CONFIG_LIBNL20 */
110
111
112 static struct nl_handle * nl_create_handle(struct nl_cb *cb, const char *dbg)
113 {
114         struct nl_handle *handle;
115
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         }
122
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         }
129
130         return handle;
131 }
132
133
134 static void nl_destroy_handles(struct nl_handle **handle)
135 {
136         if (*handle == NULL)
137                 return;
138         nl80211_handle_destroy(*handle);
139         *handle = NULL;
140 }
141
142
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
149
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
156
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 */
165
166         struct nl_handle *nl_event;
167 };
168
169 struct nl80211_wiphy_data {
170         struct dl_list list;
171         struct dl_list bsss;
172         struct dl_list drvs;
173
174         struct nl_handle *nl_beacons;
175         struct nl_cb *nl_cb;
176
177         int wiphy_idx;
178 };
179
180 static void nl80211_global_deinit(void *priv);
181
182 struct i802_bss {
183         struct wpa_driver_nl80211_data *drv;
184         struct i802_bss *next;
185         int ifindex;
186         char ifname[IFNAMSIZ + 1];
187         char brname[IFNAMSIZ];
188         unsigned int beacon_set:1;
189         unsigned int added_if_into_bridge:1;
190         unsigned int added_bridge:1;
191         unsigned int in_deinit:1;
192
193         u8 addr[ETH_ALEN];
194
195         int freq;
196
197         void *ctx;
198         struct nl_handle *nl_preq, *nl_mgmt;
199         struct nl_cb *nl_cb;
200
201         struct nl80211_wiphy_data *wiphy_data;
202         struct dl_list wiphy_list;
203 };
204
205 struct wpa_driver_nl80211_data {
206         struct nl80211_global *global;
207         struct dl_list list;
208         struct dl_list wiphy_list;
209         char phyname[32];
210         void *ctx;
211         int ifindex;
212         int if_removed;
213         int if_disabled;
214         int ignore_if_down_event;
215         struct rfkill_data *rfkill;
216         struct wpa_driver_capa capa;
217         u8 *extended_capa, *extended_capa_mask;
218         unsigned int extended_capa_len;
219         int has_capability;
220
221         int operstate;
222
223         int scan_complete_events;
224
225         struct nl_cb *nl_cb;
226
227         u8 auth_bssid[ETH_ALEN];
228         u8 bssid[ETH_ALEN];
229         int associated;
230         u8 ssid[32];
231         size_t ssid_len;
232         enum nl80211_iftype nlmode;
233         enum nl80211_iftype ap_scan_as_station;
234         unsigned int assoc_freq;
235
236         int monitor_sock;
237         int monitor_ifidx;
238         int monitor_refcount;
239
240         unsigned int disabled_11b_rates:1;
241         unsigned int pending_remain_on_chan:1;
242         unsigned int in_interface_list:1;
243         unsigned int device_ap_sme:1;
244         unsigned int poll_command_supported:1;
245         unsigned int data_tx_status:1;
246         unsigned int scan_for_auth:1;
247         unsigned int retry_auth:1;
248         unsigned int use_monitor:1;
249         unsigned int ignore_next_local_disconnect:1;
250
251         u64 remain_on_chan_cookie;
252         u64 send_action_cookie;
253
254         unsigned int last_mgmt_freq;
255
256         struct wpa_driver_scan_filter *filter_ssids;
257         size_t num_filter_ssids;
258
259         struct i802_bss first_bss;
260
261         int eapol_tx_sock;
262
263 #ifdef HOSTAPD
264         int eapol_sock; /* socket for EAPOL frames */
265
266         int default_if_indices[16];
267         int *if_indices;
268         int num_if_indices;
269
270         int last_freq;
271         int last_freq_ht;
272 #endif /* HOSTAPD */
273
274         /* From failed authentication command */
275         int auth_freq;
276         u8 auth_bssid_[ETH_ALEN];
277         u8 auth_ssid[32];
278         size_t auth_ssid_len;
279         int auth_alg;
280         u8 *auth_ie;
281         size_t auth_ie_len;
282         u8 auth_wep_key[4][16];
283         size_t auth_wep_key_len[4];
284         int auth_wep_tx_keyidx;
285         int auth_local_state_change;
286         int auth_p2p;
287 };
288
289
290 static void wpa_driver_nl80211_deinit(struct i802_bss *bss);
291 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx,
292                                             void *timeout_ctx);
293 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
294                                        enum nl80211_iftype nlmode);
295 static int
296 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv);
297 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
298                                    const u8 *addr, int cmd, u16 reason_code,
299                                    int local_state_change);
300 static void nl80211_remove_monitor_interface(
301         struct wpa_driver_nl80211_data *drv);
302 static int nl80211_send_frame_cmd(struct i802_bss *bss,
303                                   unsigned int freq, unsigned int wait,
304                                   const u8 *buf, size_t buf_len, u64 *cookie,
305                                   int no_cck, int no_ack, int offchanok);
306 static int wpa_driver_nl80211_probe_req_report(struct i802_bss *bss,
307                                                int report);
308 #ifdef ANDROID
309 static int android_pno_start(struct i802_bss *bss,
310                              struct wpa_driver_scan_params *params);
311 static int android_pno_stop(struct i802_bss *bss);
312 #endif /* ANDROID */
313
314 #ifdef HOSTAPD
315 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
316 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
317 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
318 static int wpa_driver_nl80211_if_remove(struct i802_bss *bss,
319                                         enum wpa_driver_if_type type,
320                                         const char *ifname);
321 #else /* HOSTAPD */
322 static inline void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
323 {
324 }
325
326 static inline void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
327 {
328 }
329
330 static inline int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
331 {
332         return 0;
333 }
334 #endif /* HOSTAPD */
335
336 static int wpa_driver_nl80211_set_freq(struct i802_bss *bss,
337                                        struct hostapd_freq_params *freq);
338 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
339                                      int ifindex, int disabled);
340
341 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv);
342 static int wpa_driver_nl80211_authenticate_retry(
343         struct wpa_driver_nl80211_data *drv);
344
345
346 static int is_ap_interface(enum nl80211_iftype nlmode)
347 {
348         return (nlmode == NL80211_IFTYPE_AP ||
349                 nlmode == NL80211_IFTYPE_P2P_GO);
350 }
351
352
353 static int is_sta_interface(enum nl80211_iftype nlmode)
354 {
355         return (nlmode == NL80211_IFTYPE_STATION ||
356                 nlmode == NL80211_IFTYPE_P2P_CLIENT);
357 }
358
359
360 static int is_p2p_interface(enum nl80211_iftype nlmode)
361 {
362         return (nlmode == NL80211_IFTYPE_P2P_CLIENT ||
363                 nlmode == NL80211_IFTYPE_P2P_GO);
364 }
365
366
367 struct nl80211_bss_info_arg {
368         struct wpa_driver_nl80211_data *drv;
369         struct wpa_scan_results *res;
370         unsigned int assoc_freq;
371         u8 assoc_bssid[ETH_ALEN];
372 };
373
374 static int bss_info_handler(struct nl_msg *msg, void *arg);
375
376
377 /* nl80211 code */
378 static int ack_handler(struct nl_msg *msg, void *arg)
379 {
380         int *err = arg;
381         *err = 0;
382         return NL_STOP;
383 }
384
385 static int finish_handler(struct nl_msg *msg, void *arg)
386 {
387         int *ret = arg;
388         *ret = 0;
389         return NL_SKIP;
390 }
391
392 static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err,
393                          void *arg)
394 {
395         int *ret = arg;
396         *ret = err->error;
397         return NL_SKIP;
398 }
399
400
401 static int no_seq_check(struct nl_msg *msg, void *arg)
402 {
403         return NL_OK;
404 }
405
406
407 static int send_and_recv(struct nl80211_global *global,
408                          struct nl_handle *nl_handle, struct nl_msg *msg,
409                          int (*valid_handler)(struct nl_msg *, void *),
410                          void *valid_data)
411 {
412         struct nl_cb *cb;
413         int err = -ENOMEM;
414
415         cb = nl_cb_clone(global->nl_cb);
416         if (!cb)
417                 goto out;
418
419         err = nl_send_auto_complete(nl_handle, msg);
420         if (err < 0)
421                 goto out;
422
423         err = 1;
424
425         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
426         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
427         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
428
429         if (valid_handler)
430                 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM,
431                           valid_handler, valid_data);
432
433         while (err > 0)
434                 nl_recvmsgs(nl_handle, cb);
435  out:
436         nl_cb_put(cb);
437         nlmsg_free(msg);
438         return err;
439 }
440
441
442 static int send_and_recv_msgs_global(struct nl80211_global *global,
443                                      struct nl_msg *msg,
444                                      int (*valid_handler)(struct nl_msg *, void *),
445                                      void *valid_data)
446 {
447         return send_and_recv(global, global->nl, msg, valid_handler,
448                              valid_data);
449 }
450
451
452 static int send_and_recv_msgs(struct wpa_driver_nl80211_data *drv,
453                               struct nl_msg *msg,
454                               int (*valid_handler)(struct nl_msg *, void *),
455                               void *valid_data)
456 {
457         return send_and_recv(drv->global, drv->global->nl, msg,
458                              valid_handler, valid_data);
459 }
460
461
462 struct family_data {
463         const char *group;
464         int id;
465 };
466
467
468 static int family_handler(struct nl_msg *msg, void *arg)
469 {
470         struct family_data *res = arg;
471         struct nlattr *tb[CTRL_ATTR_MAX + 1];
472         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
473         struct nlattr *mcgrp;
474         int i;
475
476         nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
477                   genlmsg_attrlen(gnlh, 0), NULL);
478         if (!tb[CTRL_ATTR_MCAST_GROUPS])
479                 return NL_SKIP;
480
481         nla_for_each_nested(mcgrp, tb[CTRL_ATTR_MCAST_GROUPS], i) {
482                 struct nlattr *tb2[CTRL_ATTR_MCAST_GRP_MAX + 1];
483                 nla_parse(tb2, CTRL_ATTR_MCAST_GRP_MAX, nla_data(mcgrp),
484                           nla_len(mcgrp), NULL);
485                 if (!tb2[CTRL_ATTR_MCAST_GRP_NAME] ||
486                     !tb2[CTRL_ATTR_MCAST_GRP_ID] ||
487                     os_strncmp(nla_data(tb2[CTRL_ATTR_MCAST_GRP_NAME]),
488                                res->group,
489                                nla_len(tb2[CTRL_ATTR_MCAST_GRP_NAME])) != 0)
490                         continue;
491                 res->id = nla_get_u32(tb2[CTRL_ATTR_MCAST_GRP_ID]);
492                 break;
493         };
494
495         return NL_SKIP;
496 }
497
498
499 static int nl_get_multicast_id(struct nl80211_global *global,
500                                const char *family, const char *group)
501 {
502         struct nl_msg *msg;
503         int ret = -1;
504         struct family_data res = { group, -ENOENT };
505
506         msg = nlmsg_alloc();
507         if (!msg)
508                 return -ENOMEM;
509         genlmsg_put(msg, 0, 0, genl_ctrl_resolve(global->nl, "nlctrl"),
510                     0, 0, CTRL_CMD_GETFAMILY, 0);
511         NLA_PUT_STRING(msg, CTRL_ATTR_FAMILY_NAME, family);
512
513         ret = send_and_recv_msgs_global(global, msg, family_handler, &res);
514         msg = NULL;
515         if (ret == 0)
516                 ret = res.id;
517
518 nla_put_failure:
519         nlmsg_free(msg);
520         return ret;
521 }
522
523
524 static void * nl80211_cmd(struct wpa_driver_nl80211_data *drv,
525                           struct nl_msg *msg, int flags, uint8_t cmd)
526 {
527         return genlmsg_put(msg, 0, 0, drv->global->nl80211_id,
528                            0, flags, cmd, 0);
529 }
530
531
532 struct wiphy_idx_data {
533         int wiphy_idx;
534 };
535
536
537 static int netdev_info_handler(struct nl_msg *msg, void *arg)
538 {
539         struct nlattr *tb[NL80211_ATTR_MAX + 1];
540         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
541         struct wiphy_idx_data *info = arg;
542
543         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
544                   genlmsg_attrlen(gnlh, 0), NULL);
545
546         if (tb[NL80211_ATTR_WIPHY])
547                 info->wiphy_idx = nla_get_u32(tb[NL80211_ATTR_WIPHY]);
548
549         return NL_SKIP;
550 }
551
552
553 static int nl80211_get_wiphy_index(struct i802_bss *bss)
554 {
555         struct nl_msg *msg;
556         struct wiphy_idx_data data = {
557                 .wiphy_idx = -1,
558         };
559
560         msg = nlmsg_alloc();
561         if (!msg)
562                 return -1;
563
564         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_GET_INTERFACE);
565
566         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
567
568         if (send_and_recv_msgs(bss->drv, msg, netdev_info_handler, &data) == 0)
569                 return data.wiphy_idx;
570         msg = NULL;
571 nla_put_failure:
572         nlmsg_free(msg);
573         return -1;
574 }
575
576
577 static int nl80211_register_beacons(struct wpa_driver_nl80211_data *drv,
578                                     struct nl80211_wiphy_data *w)
579 {
580         struct nl_msg *msg;
581         int ret = -1;
582
583         msg = nlmsg_alloc();
584         if (!msg)
585                 return -1;
586
587         nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_BEACONS);
588
589         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, w->wiphy_idx);
590
591         ret = send_and_recv(drv->global, w->nl_beacons, msg, NULL, NULL);
592         msg = NULL;
593         if (ret) {
594                 wpa_printf(MSG_DEBUG, "nl80211: Register beacons command "
595                            "failed: ret=%d (%s)",
596                            ret, strerror(-ret));
597                 goto nla_put_failure;
598         }
599         ret = 0;
600 nla_put_failure:
601         nlmsg_free(msg);
602         return ret;
603 }
604
605
606 static void nl80211_recv_beacons(int sock, void *eloop_ctx, void *handle)
607 {
608         struct nl80211_wiphy_data *w = eloop_ctx;
609
610         wpa_printf(MSG_EXCESSIVE, "nl80211: Beacon event message available");
611
612         nl_recvmsgs(handle, w->nl_cb);
613 }
614
615
616 static int process_beacon_event(struct nl_msg *msg, void *arg)
617 {
618         struct nl80211_wiphy_data *w = arg;
619         struct wpa_driver_nl80211_data *drv;
620         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
621         struct nlattr *tb[NL80211_ATTR_MAX + 1];
622         union wpa_event_data event;
623
624         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
625                   genlmsg_attrlen(gnlh, 0), NULL);
626
627         if (gnlh->cmd != NL80211_CMD_FRAME) {
628                 wpa_printf(MSG_DEBUG, "nl80211: Unexpected beacon event? (%d)",
629                            gnlh->cmd);
630                 return NL_SKIP;
631         }
632
633         if (!tb[NL80211_ATTR_FRAME])
634                 return NL_SKIP;
635
636         dl_list_for_each(drv, &w->drvs, struct wpa_driver_nl80211_data,
637                          wiphy_list) {
638                 os_memset(&event, 0, sizeof(event));
639                 event.rx_mgmt.frame = nla_data(tb[NL80211_ATTR_FRAME]);
640                 event.rx_mgmt.frame_len = nla_len(tb[NL80211_ATTR_FRAME]);
641                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
642         }
643
644         return NL_SKIP;
645 }
646
647
648 static struct nl80211_wiphy_data *
649 nl80211_get_wiphy_data_ap(struct i802_bss *bss)
650 {
651         static DEFINE_DL_LIST(nl80211_wiphys);
652         struct nl80211_wiphy_data *w;
653         int wiphy_idx, found = 0;
654         struct i802_bss *tmp_bss;
655
656         if (bss->wiphy_data != NULL)
657                 return bss->wiphy_data;
658
659         wiphy_idx = nl80211_get_wiphy_index(bss);
660
661         dl_list_for_each(w, &nl80211_wiphys, struct nl80211_wiphy_data, list) {
662                 if (w->wiphy_idx == wiphy_idx)
663                         goto add;
664         }
665
666         /* alloc new one */
667         w = os_zalloc(sizeof(*w));
668         if (w == NULL)
669                 return NULL;
670         w->wiphy_idx = wiphy_idx;
671         dl_list_init(&w->bsss);
672         dl_list_init(&w->drvs);
673
674         w->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
675         if (!w->nl_cb) {
676                 os_free(w);
677                 return NULL;
678         }
679         nl_cb_set(w->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, no_seq_check, NULL);
680         nl_cb_set(w->nl_cb, NL_CB_VALID, NL_CB_CUSTOM, process_beacon_event,
681                   w);
682
683         w->nl_beacons = nl_create_handle(bss->drv->global->nl_cb,
684                                          "wiphy beacons");
685         if (w->nl_beacons == NULL) {
686                 os_free(w);
687                 return NULL;
688         }
689
690         if (nl80211_register_beacons(bss->drv, w)) {
691                 nl_destroy_handles(&w->nl_beacons);
692                 os_free(w);
693                 return NULL;
694         }
695
696         eloop_register_read_sock(nl_socket_get_fd(w->nl_beacons),
697                                  nl80211_recv_beacons, w, w->nl_beacons);
698
699         dl_list_add(&nl80211_wiphys, &w->list);
700
701 add:
702         /* drv entry for this bss already there? */
703         dl_list_for_each(tmp_bss, &w->bsss, struct i802_bss, wiphy_list) {
704                 if (tmp_bss->drv == bss->drv) {
705                         found = 1;
706                         break;
707                 }
708         }
709         /* if not add it */
710         if (!found)
711                 dl_list_add(&w->drvs, &bss->drv->wiphy_list);
712
713         dl_list_add(&w->bsss, &bss->wiphy_list);
714         bss->wiphy_data = w;
715         return w;
716 }
717
718
719 static void nl80211_put_wiphy_data_ap(struct i802_bss *bss)
720 {
721         struct nl80211_wiphy_data *w = bss->wiphy_data;
722         struct i802_bss *tmp_bss;
723         int found = 0;
724
725         if (w == NULL)
726                 return;
727         bss->wiphy_data = NULL;
728         dl_list_del(&bss->wiphy_list);
729
730         /* still any for this drv present? */
731         dl_list_for_each(tmp_bss, &w->bsss, struct i802_bss, wiphy_list) {
732                 if (tmp_bss->drv == bss->drv) {
733                         found = 1;
734                         break;
735                 }
736         }
737         /* if not remove it */
738         if (!found)
739                 dl_list_del(&bss->drv->wiphy_list);
740
741         if (!dl_list_empty(&w->bsss))
742                 return;
743
744         eloop_unregister_read_sock(nl_socket_get_fd(w->nl_beacons));
745
746         nl_cb_put(w->nl_cb);
747         nl_destroy_handles(&w->nl_beacons);
748         dl_list_del(&w->list);
749         os_free(w);
750 }
751
752
753 static int wpa_driver_nl80211_get_bssid(void *priv, u8 *bssid)
754 {
755         struct i802_bss *bss = priv;
756         struct wpa_driver_nl80211_data *drv = bss->drv;
757         if (!drv->associated)
758                 return -1;
759         os_memcpy(bssid, drv->bssid, ETH_ALEN);
760         return 0;
761 }
762
763
764 static int wpa_driver_nl80211_get_ssid(void *priv, u8 *ssid)
765 {
766         struct i802_bss *bss = priv;
767         struct wpa_driver_nl80211_data *drv = bss->drv;
768         if (!drv->associated)
769                 return -1;
770         os_memcpy(ssid, drv->ssid, drv->ssid_len);
771         return drv->ssid_len;
772 }
773
774
775 static void wpa_driver_nl80211_event_link(struct wpa_driver_nl80211_data *drv,
776                                           char *buf, size_t len, int del)
777 {
778         union wpa_event_data event;
779
780         os_memset(&event, 0, sizeof(event));
781         if (len > sizeof(event.interface_status.ifname))
782                 len = sizeof(event.interface_status.ifname) - 1;
783         os_memcpy(event.interface_status.ifname, buf, len);
784         event.interface_status.ievent = del ? EVENT_INTERFACE_REMOVED :
785                 EVENT_INTERFACE_ADDED;
786
787         wpa_printf(MSG_DEBUG, "RTM_%sLINK, IFLA_IFNAME: Interface '%s' %s",
788                    del ? "DEL" : "NEW",
789                    event.interface_status.ifname,
790                    del ? "removed" : "added");
791
792         if (os_strcmp(drv->first_bss.ifname, event.interface_status.ifname) == 0) {
793                 if (del) {
794                         if (drv->if_removed) {
795                                 wpa_printf(MSG_DEBUG, "nl80211: if_removed "
796                                            "already set - ignore event");
797                                 return;
798                         }
799                         drv->if_removed = 1;
800                 } else {
801                         if (if_nametoindex(drv->first_bss.ifname) == 0) {
802                                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s "
803                                            "does not exist - ignore "
804                                            "RTM_NEWLINK",
805                                            drv->first_bss.ifname);
806                                 return;
807                         }
808                         if (!drv->if_removed) {
809                                 wpa_printf(MSG_DEBUG, "nl80211: if_removed "
810                                            "already cleared - ignore event");
811                                 return;
812                         }
813                         drv->if_removed = 0;
814                 }
815         }
816
817         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_STATUS, &event);
818 }
819
820
821 static int wpa_driver_nl80211_own_ifname(struct wpa_driver_nl80211_data *drv,
822                                          u8 *buf, size_t len)
823 {
824         int attrlen, rta_len;
825         struct rtattr *attr;
826
827         attrlen = len;
828         attr = (struct rtattr *) buf;
829
830         rta_len = RTA_ALIGN(sizeof(struct rtattr));
831         while (RTA_OK(attr, attrlen)) {
832                 if (attr->rta_type == IFLA_IFNAME) {
833                         if (os_strcmp(((char *) attr) + rta_len, drv->first_bss.ifname)
834                             == 0)
835                                 return 1;
836                         else
837                                 break;
838                 }
839                 attr = RTA_NEXT(attr, attrlen);
840         }
841
842         return 0;
843 }
844
845
846 static int wpa_driver_nl80211_own_ifindex(struct wpa_driver_nl80211_data *drv,
847                                           int ifindex, u8 *buf, size_t len)
848 {
849         if (drv->ifindex == ifindex)
850                 return 1;
851
852         if (drv->if_removed && wpa_driver_nl80211_own_ifname(drv, buf, len)) {
853                 drv->first_bss.ifindex = if_nametoindex(drv->first_bss.ifname);
854                 wpa_printf(MSG_DEBUG, "nl80211: Update ifindex for a removed "
855                            "interface");
856                 wpa_driver_nl80211_finish_drv_init(drv);
857                 return 1;
858         }
859
860         return 0;
861 }
862
863
864 static struct wpa_driver_nl80211_data *
865 nl80211_find_drv(struct nl80211_global *global, int idx, u8 *buf, size_t len)
866 {
867         struct wpa_driver_nl80211_data *drv;
868         dl_list_for_each(drv, &global->interfaces,
869                          struct wpa_driver_nl80211_data, list) {
870                 if (wpa_driver_nl80211_own_ifindex(drv, idx, buf, len) ||
871                     have_ifidx(drv, idx))
872                         return drv;
873         }
874         return NULL;
875 }
876
877
878 static void wpa_driver_nl80211_event_rtm_newlink(void *ctx,
879                                                  struct ifinfomsg *ifi,
880                                                  u8 *buf, size_t len)
881 {
882         struct nl80211_global *global = ctx;
883         struct wpa_driver_nl80211_data *drv;
884         int attrlen, rta_len;
885         struct rtattr *attr;
886         u32 brid = 0;
887         char namebuf[IFNAMSIZ];
888
889         drv = nl80211_find_drv(global, ifi->ifi_index, buf, len);
890         if (!drv) {
891                 wpa_printf(MSG_DEBUG, "nl80211: Ignore event for foreign "
892                            "ifindex %d", ifi->ifi_index);
893                 return;
894         }
895
896         wpa_printf(MSG_DEBUG, "RTM_NEWLINK: operstate=%d ifi_flags=0x%x "
897                    "(%s%s%s%s)",
898                    drv->operstate, ifi->ifi_flags,
899                    (ifi->ifi_flags & IFF_UP) ? "[UP]" : "",
900                    (ifi->ifi_flags & IFF_RUNNING) ? "[RUNNING]" : "",
901                    (ifi->ifi_flags & IFF_LOWER_UP) ? "[LOWER_UP]" : "",
902                    (ifi->ifi_flags & IFF_DORMANT) ? "[DORMANT]" : "");
903
904         if (!drv->if_disabled && !(ifi->ifi_flags & IFF_UP)) {
905                 if (if_indextoname(ifi->ifi_index, namebuf) &&
906                     linux_iface_up(drv->global->ioctl_sock,
907                                    drv->first_bss.ifname) > 0) {
908                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface down "
909                                    "event since interface %s is up", namebuf);
910                         return;
911                 }
912                 wpa_printf(MSG_DEBUG, "nl80211: Interface down");
913                 if (drv->ignore_if_down_event) {
914                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface down "
915                                    "event generated by mode change");
916                         drv->ignore_if_down_event = 0;
917                 } else {
918                         drv->if_disabled = 1;
919                         wpa_supplicant_event(drv->ctx,
920                                              EVENT_INTERFACE_DISABLED, NULL);
921                 }
922         }
923
924         if (drv->if_disabled && (ifi->ifi_flags & IFF_UP)) {
925                 if (if_indextoname(ifi->ifi_index, namebuf) &&
926                     linux_iface_up(drv->global->ioctl_sock,
927                                    drv->first_bss.ifname) == 0) {
928                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
929                                    "event since interface %s is down",
930                                    namebuf);
931                 } else if (if_nametoindex(drv->first_bss.ifname) == 0) {
932                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
933                                    "event since interface %s does not exist",
934                                    drv->first_bss.ifname);
935                 } else if (drv->if_removed) {
936                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
937                                    "event since interface %s is marked "
938                                    "removed", drv->first_bss.ifname);
939                 } else {
940                         wpa_printf(MSG_DEBUG, "nl80211: Interface up");
941                         drv->if_disabled = 0;
942                         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_ENABLED,
943                                              NULL);
944                 }
945         }
946
947         /*
948          * Some drivers send the association event before the operup event--in
949          * this case, lifting operstate in wpa_driver_nl80211_set_operstate()
950          * fails. This will hit us when wpa_supplicant does not need to do
951          * IEEE 802.1X authentication
952          */
953         if (drv->operstate == 1 &&
954             (ifi->ifi_flags & (IFF_LOWER_UP | IFF_DORMANT)) == IFF_LOWER_UP &&
955             !(ifi->ifi_flags & IFF_RUNNING))
956                 netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
957                                        -1, IF_OPER_UP);
958
959         attrlen = len;
960         attr = (struct rtattr *) buf;
961         rta_len = RTA_ALIGN(sizeof(struct rtattr));
962         while (RTA_OK(attr, attrlen)) {
963                 if (attr->rta_type == IFLA_IFNAME) {
964                         wpa_driver_nl80211_event_link(
965                                 drv,
966                                 ((char *) attr) + rta_len,
967                                 attr->rta_len - rta_len, 0);
968                 } else if (attr->rta_type == IFLA_MASTER)
969                         brid = nla_get_u32((struct nlattr *) attr);
970                 attr = RTA_NEXT(attr, attrlen);
971         }
972
973         if (ifi->ifi_family == AF_BRIDGE && brid) {
974                 /* device has been added to bridge */
975                 if_indextoname(brid, namebuf);
976                 wpa_printf(MSG_DEBUG, "nl80211: Add ifindex %u for bridge %s",
977                            brid, namebuf);
978                 add_ifidx(drv, brid);
979         }
980 }
981
982
983 static void wpa_driver_nl80211_event_rtm_dellink(void *ctx,
984                                                  struct ifinfomsg *ifi,
985                                                  u8 *buf, size_t len)
986 {
987         struct nl80211_global *global = ctx;
988         struct wpa_driver_nl80211_data *drv;
989         int attrlen, rta_len;
990         struct rtattr *attr;
991         u32 brid = 0;
992
993         drv = nl80211_find_drv(global, ifi->ifi_index, buf, len);
994         if (!drv) {
995                 wpa_printf(MSG_DEBUG, "nl80211: Ignore dellink event for "
996                            "foreign ifindex %d", ifi->ifi_index);
997                 return;
998         }
999
1000         attrlen = len;
1001         attr = (struct rtattr *) buf;
1002
1003         rta_len = RTA_ALIGN(sizeof(struct rtattr));
1004         while (RTA_OK(attr, attrlen)) {
1005                 if (attr->rta_type == IFLA_IFNAME) {
1006                         wpa_driver_nl80211_event_link(
1007                                 drv,
1008                                 ((char *) attr) + rta_len,
1009                                 attr->rta_len - rta_len, 1);
1010                 } else if (attr->rta_type == IFLA_MASTER)
1011                         brid = nla_get_u32((struct nlattr *) attr);
1012                 attr = RTA_NEXT(attr, attrlen);
1013         }
1014
1015         if (ifi->ifi_family == AF_BRIDGE && brid) {
1016                 /* device has been removed from bridge */
1017                 char namebuf[IFNAMSIZ];
1018                 if_indextoname(brid, namebuf);
1019                 wpa_printf(MSG_DEBUG, "nl80211: Remove ifindex %u for bridge "
1020                            "%s", brid, namebuf);
1021                 del_ifidx(drv, brid);
1022         }
1023 }
1024
1025
1026 static void mlme_event_auth(struct wpa_driver_nl80211_data *drv,
1027                             const u8 *frame, size_t len)
1028 {
1029         const struct ieee80211_mgmt *mgmt;
1030         union wpa_event_data event;
1031
1032         wpa_printf(MSG_DEBUG, "nl80211: Authenticate event");
1033         mgmt = (const struct ieee80211_mgmt *) frame;
1034         if (len < 24 + sizeof(mgmt->u.auth)) {
1035                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1036                            "frame");
1037                 return;
1038         }
1039
1040         os_memcpy(drv->auth_bssid, mgmt->sa, ETH_ALEN);
1041         os_memset(&event, 0, sizeof(event));
1042         os_memcpy(event.auth.peer, mgmt->sa, ETH_ALEN);
1043         event.auth.auth_type = le_to_host16(mgmt->u.auth.auth_alg);
1044         event.auth.auth_transaction =
1045                 le_to_host16(mgmt->u.auth.auth_transaction);
1046         event.auth.status_code = le_to_host16(mgmt->u.auth.status_code);
1047         if (len > 24 + sizeof(mgmt->u.auth)) {
1048                 event.auth.ies = mgmt->u.auth.variable;
1049                 event.auth.ies_len = len - 24 - sizeof(mgmt->u.auth);
1050         }
1051
1052         wpa_supplicant_event(drv->ctx, EVENT_AUTH, &event);
1053 }
1054
1055
1056 static unsigned int nl80211_get_assoc_freq(struct wpa_driver_nl80211_data *drv)
1057 {
1058         struct nl_msg *msg;
1059         int ret;
1060         struct nl80211_bss_info_arg arg;
1061
1062         os_memset(&arg, 0, sizeof(arg));
1063         msg = nlmsg_alloc();
1064         if (!msg)
1065                 goto nla_put_failure;
1066
1067         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
1068         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1069
1070         arg.drv = drv;
1071         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
1072         msg = NULL;
1073         if (ret == 0) {
1074                 wpa_printf(MSG_DEBUG, "nl80211: Operating frequency for the "
1075                            "associated BSS from scan results: %u MHz",
1076                            arg.assoc_freq);
1077                 return arg.assoc_freq ? arg.assoc_freq : drv->assoc_freq;
1078         }
1079         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
1080                    "(%s)", ret, strerror(-ret));
1081 nla_put_failure:
1082         nlmsg_free(msg);
1083         return drv->assoc_freq;
1084 }
1085
1086
1087 static void mlme_event_assoc(struct wpa_driver_nl80211_data *drv,
1088                             const u8 *frame, size_t len)
1089 {
1090         const struct ieee80211_mgmt *mgmt;
1091         union wpa_event_data event;
1092         u16 status;
1093
1094         wpa_printf(MSG_DEBUG, "nl80211: Associate event");
1095         mgmt = (const struct ieee80211_mgmt *) frame;
1096         if (len < 24 + sizeof(mgmt->u.assoc_resp)) {
1097                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1098                            "frame");
1099                 return;
1100         }
1101
1102         status = le_to_host16(mgmt->u.assoc_resp.status_code);
1103         if (status != WLAN_STATUS_SUCCESS) {
1104                 os_memset(&event, 0, sizeof(event));
1105                 event.assoc_reject.bssid = mgmt->bssid;
1106                 if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
1107                         event.assoc_reject.resp_ies =
1108                                 (u8 *) mgmt->u.assoc_resp.variable;
1109                         event.assoc_reject.resp_ies_len =
1110                                 len - 24 - sizeof(mgmt->u.assoc_resp);
1111                 }
1112                 event.assoc_reject.status_code = status;
1113
1114                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
1115                 return;
1116         }
1117
1118         drv->associated = 1;
1119         os_memcpy(drv->bssid, mgmt->sa, ETH_ALEN);
1120
1121         os_memset(&event, 0, sizeof(event));
1122         if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
1123                 event.assoc_info.resp_ies = (u8 *) mgmt->u.assoc_resp.variable;
1124                 event.assoc_info.resp_ies_len =
1125                         len - 24 - sizeof(mgmt->u.assoc_resp);
1126         }
1127
1128         event.assoc_info.freq = drv->assoc_freq;
1129
1130         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
1131 }
1132
1133
1134 static void mlme_event_connect(struct wpa_driver_nl80211_data *drv,
1135                                enum nl80211_commands cmd, struct nlattr *status,
1136                                struct nlattr *addr, struct nlattr *req_ie,
1137                                struct nlattr *resp_ie)
1138 {
1139         union wpa_event_data event;
1140
1141         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1142                 /*
1143                  * Avoid reporting two association events that would confuse
1144                  * the core code.
1145                  */
1146                 wpa_printf(MSG_DEBUG, "nl80211: Ignore connect event (cmd=%d) "
1147                            "when using userspace SME", cmd);
1148                 return;
1149         }
1150
1151         if (cmd == NL80211_CMD_CONNECT)
1152                 wpa_printf(MSG_DEBUG, "nl80211: Connect event");
1153         else if (cmd == NL80211_CMD_ROAM)
1154                 wpa_printf(MSG_DEBUG, "nl80211: Roam event");
1155
1156         os_memset(&event, 0, sizeof(event));
1157         if (cmd == NL80211_CMD_CONNECT &&
1158             nla_get_u16(status) != WLAN_STATUS_SUCCESS) {
1159                 if (addr)
1160                         event.assoc_reject.bssid = nla_data(addr);
1161                 if (resp_ie) {
1162                         event.assoc_reject.resp_ies = nla_data(resp_ie);
1163                         event.assoc_reject.resp_ies_len = nla_len(resp_ie);
1164                 }
1165                 event.assoc_reject.status_code = nla_get_u16(status);
1166                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
1167                 return;
1168         }
1169
1170         drv->associated = 1;
1171         if (addr)
1172                 os_memcpy(drv->bssid, nla_data(addr), ETH_ALEN);
1173
1174         if (req_ie) {
1175                 event.assoc_info.req_ies = nla_data(req_ie);
1176                 event.assoc_info.req_ies_len = nla_len(req_ie);
1177         }
1178         if (resp_ie) {
1179                 event.assoc_info.resp_ies = nla_data(resp_ie);
1180                 event.assoc_info.resp_ies_len = nla_len(resp_ie);
1181         }
1182
1183         event.assoc_info.freq = nl80211_get_assoc_freq(drv);
1184
1185         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
1186 }
1187
1188
1189 static void mlme_event_disconnect(struct wpa_driver_nl80211_data *drv,
1190                                   struct nlattr *reason, struct nlattr *addr,
1191                                   struct nlattr *by_ap)
1192 {
1193         union wpa_event_data data;
1194         unsigned int locally_generated = by_ap == NULL;
1195
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         }
1205
1206         if (drv->ignore_next_local_disconnect) {
1207                 drv->ignore_next_local_disconnect = 0;
1208                 if (locally_generated) {
1209                         wpa_printf(MSG_DEBUG, "nl80211: Ignore disconnect "
1210                                    "event triggered during reassociation");
1211                         return;
1212                 }
1213                 wpa_printf(MSG_WARNING, "nl80211: Was expecting local "
1214                            "disconnect but got another disconnect "
1215                            "event first");
1216         }
1217
1218         wpa_printf(MSG_DEBUG, "nl80211: Disconnect event");
1219         drv->associated = 0;
1220         os_memset(&data, 0, sizeof(data));
1221         if (reason)
1222                 data.deauth_info.reason_code = nla_get_u16(reason);
1223         data.deauth_info.locally_generated = by_ap == NULL;
1224         wpa_supplicant_event(drv->ctx, EVENT_DEAUTH, &data);
1225 }
1226
1227
1228 static void mlme_event_ch_switch(struct wpa_driver_nl80211_data *drv,
1229                                  struct nlattr *freq, struct nlattr *type)
1230 {
1231         union wpa_event_data data;
1232         int ht_enabled = 1;
1233         int chan_offset = 0;
1234
1235         wpa_printf(MSG_DEBUG, "nl80211: Channel switch event");
1236
1237         if (!freq || !type)
1238                 return;
1239
1240         switch (nla_get_u32(type)) {
1241         case NL80211_CHAN_NO_HT:
1242                 ht_enabled = 0;
1243                 break;
1244         case NL80211_CHAN_HT20:
1245                 break;
1246         case NL80211_CHAN_HT40PLUS:
1247                 chan_offset = 1;
1248                 break;
1249         case NL80211_CHAN_HT40MINUS:
1250                 chan_offset = -1;
1251                 break;
1252         }
1253
1254         data.ch_switch.freq = nla_get_u32(freq);
1255         data.ch_switch.ht_enabled = ht_enabled;
1256         data.ch_switch.ch_offset = chan_offset;
1257
1258         wpa_supplicant_event(drv->ctx, EVENT_CH_SWITCH, &data);
1259 }
1260
1261
1262 static void mlme_timeout_event(struct wpa_driver_nl80211_data *drv,
1263                                enum nl80211_commands cmd, struct nlattr *addr)
1264 {
1265         union wpa_event_data event;
1266         enum wpa_event_type ev;
1267
1268         if (nla_len(addr) != ETH_ALEN)
1269                 return;
1270
1271         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d; timeout with " MACSTR,
1272                    cmd, MAC2STR((u8 *) nla_data(addr)));
1273
1274         if (cmd == NL80211_CMD_AUTHENTICATE)
1275                 ev = EVENT_AUTH_TIMED_OUT;
1276         else if (cmd == NL80211_CMD_ASSOCIATE)
1277                 ev = EVENT_ASSOC_TIMED_OUT;
1278         else
1279                 return;
1280
1281         os_memset(&event, 0, sizeof(event));
1282         os_memcpy(event.timeout_event.addr, nla_data(addr), ETH_ALEN);
1283         wpa_supplicant_event(drv->ctx, ev, &event);
1284 }
1285
1286
1287 static void mlme_event_mgmt(struct wpa_driver_nl80211_data *drv,
1288                             struct nlattr *freq, struct nlattr *sig,
1289                             const u8 *frame, size_t len)
1290 {
1291         const struct ieee80211_mgmt *mgmt;
1292         union wpa_event_data event;
1293         u16 fc, stype;
1294         int ssi_signal = 0;
1295
1296         wpa_printf(MSG_MSGDUMP, "nl80211: Frame event");
1297         mgmt = (const struct ieee80211_mgmt *) frame;
1298         if (len < 24) {
1299                 wpa_printf(MSG_DEBUG, "nl80211: Too short action frame");
1300                 return;
1301         }
1302
1303         fc = le_to_host16(mgmt->frame_control);
1304         stype = WLAN_FC_GET_STYPE(fc);
1305
1306         if (sig)
1307                 ssi_signal = (s32) nla_get_u32(sig);
1308
1309         os_memset(&event, 0, sizeof(event));
1310         if (freq) {
1311                 event.rx_action.freq = nla_get_u32(freq);
1312                 drv->last_mgmt_freq = event.rx_action.freq;
1313         }
1314         if (stype == WLAN_FC_STYPE_ACTION) {
1315                 event.rx_action.da = mgmt->da;
1316                 event.rx_action.sa = mgmt->sa;
1317                 event.rx_action.bssid = mgmt->bssid;
1318                 event.rx_action.category = mgmt->u.action.category;
1319                 event.rx_action.data = &mgmt->u.action.category + 1;
1320                 event.rx_action.len = frame + len - event.rx_action.data;
1321                 wpa_supplicant_event(drv->ctx, EVENT_RX_ACTION, &event);
1322         } else {
1323                 event.rx_mgmt.frame = frame;
1324                 event.rx_mgmt.frame_len = len;
1325                 event.rx_mgmt.ssi_signal = ssi_signal;
1326                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
1327         }
1328 }
1329
1330
1331 static void mlme_event_mgmt_tx_status(struct wpa_driver_nl80211_data *drv,
1332                                       struct nlattr *cookie, const u8 *frame,
1333                                       size_t len, struct nlattr *ack)
1334 {
1335         union wpa_event_data event;
1336         const struct ieee80211_hdr *hdr;
1337         u16 fc;
1338
1339         wpa_printf(MSG_DEBUG, "nl80211: Frame TX status event");
1340         if (!is_ap_interface(drv->nlmode)) {
1341                 u64 cookie_val;
1342
1343                 if (!cookie)
1344                         return;
1345
1346                 cookie_val = nla_get_u64(cookie);
1347                 wpa_printf(MSG_DEBUG, "nl80211: Action TX status:"
1348                            " cookie=0%llx%s (ack=%d)",
1349                            (long long unsigned int) cookie_val,
1350                            cookie_val == drv->send_action_cookie ?
1351                            " (match)" : " (unknown)", ack != NULL);
1352                 if (cookie_val != drv->send_action_cookie)
1353                         return;
1354         }
1355
1356         hdr = (const struct ieee80211_hdr *) frame;
1357         fc = le_to_host16(hdr->frame_control);
1358
1359         os_memset(&event, 0, sizeof(event));
1360         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
1361         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
1362         event.tx_status.dst = hdr->addr1;
1363         event.tx_status.data = frame;
1364         event.tx_status.data_len = len;
1365         event.tx_status.ack = ack != NULL;
1366         wpa_supplicant_event(drv->ctx, EVENT_TX_STATUS, &event);
1367 }
1368
1369
1370 static void mlme_event_deauth_disassoc(struct wpa_driver_nl80211_data *drv,
1371                                        enum wpa_event_type type,
1372                                        const u8 *frame, size_t len)
1373 {
1374         const struct ieee80211_mgmt *mgmt;
1375         union wpa_event_data event;
1376         const u8 *bssid = NULL;
1377         u16 reason_code = 0;
1378
1379         if (type == EVENT_DEAUTH)
1380                 wpa_printf(MSG_DEBUG, "nl80211: Deauthenticate event");
1381         else
1382                 wpa_printf(MSG_DEBUG, "nl80211: Disassociate event");
1383
1384         mgmt = (const struct ieee80211_mgmt *) frame;
1385         if (len >= 24) {
1386                 bssid = mgmt->bssid;
1387
1388                 if (drv->associated != 0 &&
1389                     os_memcmp(bssid, drv->bssid, ETH_ALEN) != 0 &&
1390                     os_memcmp(bssid, drv->auth_bssid, ETH_ALEN) != 0) {
1391                         /*
1392                          * We have presumably received this deauth as a
1393                          * response to a clear_state_mismatch() outgoing
1394                          * deauth.  Don't let it take us offline!
1395                          */
1396                         wpa_printf(MSG_DEBUG, "nl80211: Deauth received "
1397                                    "from Unknown BSSID " MACSTR " -- ignoring",
1398                                    MAC2STR(bssid));
1399                         return;
1400                 }
1401         }
1402
1403         drv->associated = 0;
1404         os_memset(&event, 0, sizeof(event));
1405
1406         /* Note: Same offset for Reason Code in both frame subtypes */
1407         if (len >= 24 + sizeof(mgmt->u.deauth))
1408                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
1409
1410         if (type == EVENT_DISASSOC) {
1411                 event.disassoc_info.locally_generated =
1412                         !os_memcmp(mgmt->sa, drv->first_bss.addr, ETH_ALEN);
1413                 event.disassoc_info.addr = bssid;
1414                 event.disassoc_info.reason_code = reason_code;
1415                 if (frame + len > mgmt->u.disassoc.variable) {
1416                         event.disassoc_info.ie = mgmt->u.disassoc.variable;
1417                         event.disassoc_info.ie_len = frame + len -
1418                                 mgmt->u.disassoc.variable;
1419                 }
1420         } else {
1421                 event.deauth_info.locally_generated =
1422                         !os_memcmp(mgmt->sa, drv->first_bss.addr, ETH_ALEN);
1423                 event.deauth_info.addr = bssid;
1424                 event.deauth_info.reason_code = reason_code;
1425                 if (frame + len > mgmt->u.deauth.variable) {
1426                         event.deauth_info.ie = mgmt->u.deauth.variable;
1427                         event.deauth_info.ie_len = frame + len -
1428                                 mgmt->u.deauth.variable;
1429                 }
1430         }
1431
1432         wpa_supplicant_event(drv->ctx, type, &event);
1433 }
1434
1435
1436 static void mlme_event_unprot_disconnect(struct wpa_driver_nl80211_data *drv,
1437                                          enum wpa_event_type type,
1438                                          const u8 *frame, size_t len)
1439 {
1440         const struct ieee80211_mgmt *mgmt;
1441         union wpa_event_data event;
1442         u16 reason_code = 0;
1443
1444         if (type == EVENT_UNPROT_DEAUTH)
1445                 wpa_printf(MSG_DEBUG, "nl80211: Unprot Deauthenticate event");
1446         else
1447                 wpa_printf(MSG_DEBUG, "nl80211: Unprot Disassociate event");
1448
1449         if (len < 24)
1450                 return;
1451
1452         mgmt = (const struct ieee80211_mgmt *) frame;
1453
1454         os_memset(&event, 0, sizeof(event));
1455         /* Note: Same offset for Reason Code in both frame subtypes */
1456         if (len >= 24 + sizeof(mgmt->u.deauth))
1457                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
1458
1459         if (type == EVENT_UNPROT_DISASSOC) {
1460                 event.unprot_disassoc.sa = mgmt->sa;
1461                 event.unprot_disassoc.da = mgmt->da;
1462                 event.unprot_disassoc.reason_code = reason_code;
1463         } else {
1464                 event.unprot_deauth.sa = mgmt->sa;
1465                 event.unprot_deauth.da = mgmt->da;
1466                 event.unprot_deauth.reason_code = reason_code;
1467         }
1468
1469         wpa_supplicant_event(drv->ctx, type, &event);
1470 }
1471
1472
1473 static void mlme_event(struct i802_bss *bss,
1474                        enum nl80211_commands cmd, struct nlattr *frame,
1475                        struct nlattr *addr, struct nlattr *timed_out,
1476                        struct nlattr *freq, struct nlattr *ack,
1477                        struct nlattr *cookie, struct nlattr *sig)
1478 {
1479         struct wpa_driver_nl80211_data *drv = bss->drv;
1480         const u8 *data;
1481         size_t len;
1482
1483         if (timed_out && addr) {
1484                 mlme_timeout_event(drv, cmd, addr);
1485                 return;
1486         }
1487
1488         if (frame == NULL) {
1489                 wpa_printf(MSG_DEBUG, "nl80211: MLME event %d without frame "
1490                            "data", cmd);
1491                 return;
1492         }
1493
1494         data = nla_data(frame);
1495         len = nla_len(frame);
1496         if (len < 4 + ETH_ALEN) {
1497                 wpa_printf(MSG_MSGDUMP, "nl80211: MLME event %d on %s(" MACSTR
1498                            ") - too short",
1499                            cmd, bss->ifname, MAC2STR(bss->addr));
1500                 return;
1501         }
1502         wpa_printf(MSG_MSGDUMP, "nl80211: MLME event %d on %s(" MACSTR ") A1="
1503                    MACSTR, cmd, bss->ifname, MAC2STR(bss->addr),
1504                    MAC2STR(data + 4));
1505         if (cmd != NL80211_CMD_FRAME_TX_STATUS && !(data[4] & 0x01) &&
1506             os_memcmp(bss->addr, data + 4, ETH_ALEN) != 0) {
1507                 wpa_printf(MSG_MSGDUMP, "nl80211: %s: Ignore MLME frame event "
1508                            "for foreign address", bss->ifname);
1509                 return;
1510         }
1511         wpa_hexdump(MSG_MSGDUMP, "nl80211: MLME event frame",
1512                     nla_data(frame), nla_len(frame));
1513
1514         switch (cmd) {
1515         case NL80211_CMD_AUTHENTICATE:
1516                 mlme_event_auth(drv, nla_data(frame), nla_len(frame));
1517                 break;
1518         case NL80211_CMD_ASSOCIATE:
1519                 mlme_event_assoc(drv, nla_data(frame), nla_len(frame));
1520                 break;
1521         case NL80211_CMD_DEAUTHENTICATE:
1522                 mlme_event_deauth_disassoc(drv, EVENT_DEAUTH,
1523                                            nla_data(frame), nla_len(frame));
1524                 break;
1525         case NL80211_CMD_DISASSOCIATE:
1526                 mlme_event_deauth_disassoc(drv, EVENT_DISASSOC,
1527                                            nla_data(frame), nla_len(frame));
1528                 break;
1529         case NL80211_CMD_FRAME:
1530                 mlme_event_mgmt(drv, freq, sig, nla_data(frame),
1531                                 nla_len(frame));
1532                 break;
1533         case NL80211_CMD_FRAME_TX_STATUS:
1534                 mlme_event_mgmt_tx_status(drv, cookie, nla_data(frame),
1535                                           nla_len(frame), ack);
1536                 break;
1537         case NL80211_CMD_UNPROT_DEAUTHENTICATE:
1538                 mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DEAUTH,
1539                                              nla_data(frame), nla_len(frame));
1540                 break;
1541         case NL80211_CMD_UNPROT_DISASSOCIATE:
1542                 mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DISASSOC,
1543                                              nla_data(frame), nla_len(frame));
1544                 break;
1545         default:
1546                 break;
1547         }
1548 }
1549
1550
1551 static void mlme_event_michael_mic_failure(struct i802_bss *bss,
1552                                            struct nlattr *tb[])
1553 {
1554         union wpa_event_data data;
1555
1556         wpa_printf(MSG_DEBUG, "nl80211: MLME event Michael MIC failure");
1557         os_memset(&data, 0, sizeof(data));
1558         if (tb[NL80211_ATTR_MAC]) {
1559                 wpa_hexdump(MSG_DEBUG, "nl80211: Source MAC address",
1560                             nla_data(tb[NL80211_ATTR_MAC]),
1561                             nla_len(tb[NL80211_ATTR_MAC]));
1562                 data.michael_mic_failure.src = nla_data(tb[NL80211_ATTR_MAC]);
1563         }
1564         if (tb[NL80211_ATTR_KEY_SEQ]) {
1565                 wpa_hexdump(MSG_DEBUG, "nl80211: TSC",
1566                             nla_data(tb[NL80211_ATTR_KEY_SEQ]),
1567                             nla_len(tb[NL80211_ATTR_KEY_SEQ]));
1568         }
1569         if (tb[NL80211_ATTR_KEY_TYPE]) {
1570                 enum nl80211_key_type key_type =
1571                         nla_get_u32(tb[NL80211_ATTR_KEY_TYPE]);
1572                 wpa_printf(MSG_DEBUG, "nl80211: Key Type %d", key_type);
1573                 if (key_type == NL80211_KEYTYPE_PAIRWISE)
1574                         data.michael_mic_failure.unicast = 1;
1575         } else
1576                 data.michael_mic_failure.unicast = 1;
1577
1578         if (tb[NL80211_ATTR_KEY_IDX]) {
1579                 u8 key_id = nla_get_u8(tb[NL80211_ATTR_KEY_IDX]);
1580                 wpa_printf(MSG_DEBUG, "nl80211: Key Id %d", key_id);
1581         }
1582
1583         wpa_supplicant_event(bss->ctx, EVENT_MICHAEL_MIC_FAILURE, &data);
1584 }
1585
1586
1587 static void mlme_event_join_ibss(struct wpa_driver_nl80211_data *drv,
1588                                  struct nlattr *tb[])
1589 {
1590         if (tb[NL80211_ATTR_MAC] == NULL) {
1591                 wpa_printf(MSG_DEBUG, "nl80211: No address in IBSS joined "
1592                            "event");
1593                 return;
1594         }
1595         os_memcpy(drv->bssid, nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
1596         drv->associated = 1;
1597         wpa_printf(MSG_DEBUG, "nl80211: IBSS " MACSTR " joined",
1598                    MAC2STR(drv->bssid));
1599
1600         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, NULL);
1601 }
1602
1603
1604 static void mlme_event_remain_on_channel(struct wpa_driver_nl80211_data *drv,
1605                                          int cancel_event, struct nlattr *tb[])
1606 {
1607         unsigned int freq, chan_type, duration;
1608         union wpa_event_data data;
1609         u64 cookie;
1610
1611         if (tb[NL80211_ATTR_WIPHY_FREQ])
1612                 freq = nla_get_u32(tb[NL80211_ATTR_WIPHY_FREQ]);
1613         else
1614                 freq = 0;
1615
1616         if (tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE])
1617                 chan_type = nla_get_u32(tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
1618         else
1619                 chan_type = 0;
1620
1621         if (tb[NL80211_ATTR_DURATION])
1622                 duration = nla_get_u32(tb[NL80211_ATTR_DURATION]);
1623         else
1624                 duration = 0;
1625
1626         if (tb[NL80211_ATTR_COOKIE])
1627                 cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
1628         else
1629                 cookie = 0;
1630
1631         wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel event (cancel=%d "
1632                    "freq=%u channel_type=%u duration=%u cookie=0x%llx (%s))",
1633                    cancel_event, freq, chan_type, duration,
1634                    (long long unsigned int) cookie,
1635                    cookie == drv->remain_on_chan_cookie ? "match" : "unknown");
1636
1637         if (cookie != drv->remain_on_chan_cookie)
1638                 return; /* not for us */
1639
1640         if (cancel_event)
1641                 drv->pending_remain_on_chan = 0;
1642
1643         os_memset(&data, 0, sizeof(data));
1644         data.remain_on_channel.freq = freq;
1645         data.remain_on_channel.duration = duration;
1646         wpa_supplicant_event(drv->ctx, cancel_event ?
1647                              EVENT_CANCEL_REMAIN_ON_CHANNEL :
1648                              EVENT_REMAIN_ON_CHANNEL, &data);
1649 }
1650
1651
1652 static void mlme_event_ft_event(struct wpa_driver_nl80211_data *drv,
1653                                 struct nlattr *tb[])
1654 {
1655         union wpa_event_data data;
1656
1657         os_memset(&data, 0, sizeof(data));
1658
1659         if (tb[NL80211_ATTR_IE]) {
1660                 data.ft_ies.ies = nla_data(tb[NL80211_ATTR_IE]);
1661                 data.ft_ies.ies_len = nla_len(tb[NL80211_ATTR_IE]);
1662         }
1663
1664         if (tb[NL80211_ATTR_IE_RIC]) {
1665                 data.ft_ies.ric_ies = nla_data(tb[NL80211_ATTR_IE_RIC]);
1666                 data.ft_ies.ric_ies_len = nla_len(tb[NL80211_ATTR_IE_RIC]);
1667         }
1668
1669         if (tb[NL80211_ATTR_MAC])
1670                 os_memcpy(data.ft_ies.target_ap,
1671                           nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
1672
1673         wpa_printf(MSG_DEBUG, "nl80211: FT event target_ap " MACSTR,
1674                    MAC2STR(data.ft_ies.target_ap));
1675
1676         wpa_supplicant_event(drv->ctx, EVENT_FT_RESPONSE, &data);
1677 }
1678
1679
1680 static void send_scan_event(struct wpa_driver_nl80211_data *drv, int aborted,
1681                             struct nlattr *tb[])
1682 {
1683         union wpa_event_data event;
1684         struct nlattr *nl;
1685         int rem;
1686         struct scan_info *info;
1687 #define MAX_REPORT_FREQS 50
1688         int freqs[MAX_REPORT_FREQS];
1689         int num_freqs = 0;
1690
1691         if (drv->scan_for_auth) {
1692                 drv->scan_for_auth = 0;
1693                 wpa_printf(MSG_DEBUG, "nl80211: Scan results for missing "
1694                            "cfg80211 BSS entry");
1695                 wpa_driver_nl80211_authenticate_retry(drv);
1696                 return;
1697         }
1698
1699         os_memset(&event, 0, sizeof(event));
1700         info = &event.scan_info;
1701         info->aborted = aborted;
1702
1703         if (tb[NL80211_ATTR_SCAN_SSIDS]) {
1704                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_SSIDS], rem) {
1705                         struct wpa_driver_scan_ssid *s =
1706                                 &info->ssids[info->num_ssids];
1707                         s->ssid = nla_data(nl);
1708                         s->ssid_len = nla_len(nl);
1709                         info->num_ssids++;
1710                         if (info->num_ssids == WPAS_MAX_SCAN_SSIDS)
1711                                 break;
1712                 }
1713         }
1714         if (tb[NL80211_ATTR_SCAN_FREQUENCIES]) {
1715                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_FREQUENCIES], rem)
1716                 {
1717                         freqs[num_freqs] = nla_get_u32(nl);
1718                         num_freqs++;
1719                         if (num_freqs == MAX_REPORT_FREQS - 1)
1720                                 break;
1721                 }
1722                 info->freqs = freqs;
1723                 info->num_freqs = num_freqs;
1724         }
1725         wpa_supplicant_event(drv->ctx, EVENT_SCAN_RESULTS, &event);
1726 }
1727
1728
1729 static int get_link_signal(struct nl_msg *msg, void *arg)
1730 {
1731         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1732         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1733         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
1734         static struct nla_policy policy[NL80211_STA_INFO_MAX + 1] = {
1735                 [NL80211_STA_INFO_SIGNAL] = { .type = NLA_U8 },
1736         };
1737         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
1738         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
1739                 [NL80211_RATE_INFO_BITRATE] = { .type = NLA_U16 },
1740                 [NL80211_RATE_INFO_MCS] = { .type = NLA_U8 },
1741                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG },
1742                 [NL80211_RATE_INFO_SHORT_GI] = { .type = NLA_FLAG },
1743         };
1744         struct wpa_signal_info *sig_change = arg;
1745
1746         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1747                   genlmsg_attrlen(gnlh, 0), NULL);
1748         if (!tb[NL80211_ATTR_STA_INFO] ||
1749             nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
1750                              tb[NL80211_ATTR_STA_INFO], policy))
1751                 return NL_SKIP;
1752         if (!sinfo[NL80211_STA_INFO_SIGNAL])
1753                 return NL_SKIP;
1754
1755         sig_change->current_signal =
1756                 (s8) nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
1757
1758         if (sinfo[NL80211_STA_INFO_TX_BITRATE]) {
1759                 if (nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1760                                      sinfo[NL80211_STA_INFO_TX_BITRATE],
1761                                      rate_policy)) {
1762                         sig_change->current_txrate = 0;
1763                 } else {
1764                         if (rinfo[NL80211_RATE_INFO_BITRATE]) {
1765                                 sig_change->current_txrate =
1766                                         nla_get_u16(rinfo[
1767                                              NL80211_RATE_INFO_BITRATE]) * 100;
1768                         }
1769                 }
1770         }
1771
1772         return NL_SKIP;
1773 }
1774
1775
1776 static int nl80211_get_link_signal(struct wpa_driver_nl80211_data *drv,
1777                                    struct wpa_signal_info *sig)
1778 {
1779         struct nl_msg *msg;
1780
1781         sig->current_signal = -9999;
1782         sig->current_txrate = 0;
1783
1784         msg = nlmsg_alloc();
1785         if (!msg)
1786                 return -ENOMEM;
1787
1788         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
1789
1790         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1791         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
1792
1793         return send_and_recv_msgs(drv, msg, get_link_signal, sig);
1794  nla_put_failure:
1795         nlmsg_free(msg);
1796         return -ENOBUFS;
1797 }
1798
1799
1800 static int get_link_noise(struct nl_msg *msg, void *arg)
1801 {
1802         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1803         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1804         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1805         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1806                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1807                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
1808         };
1809         struct wpa_signal_info *sig_change = arg;
1810
1811         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1812                   genlmsg_attrlen(gnlh, 0), NULL);
1813
1814         if (!tb[NL80211_ATTR_SURVEY_INFO]) {
1815                 wpa_printf(MSG_DEBUG, "nl80211: survey data missing!");
1816                 return NL_SKIP;
1817         }
1818
1819         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1820                              tb[NL80211_ATTR_SURVEY_INFO],
1821                              survey_policy)) {
1822                 wpa_printf(MSG_DEBUG, "nl80211: failed to parse nested "
1823                            "attributes!");
1824                 return NL_SKIP;
1825         }
1826
1827         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1828                 return NL_SKIP;
1829
1830         if (nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
1831             sig_change->frequency)
1832                 return NL_SKIP;
1833
1834         if (!sinfo[NL80211_SURVEY_INFO_NOISE])
1835                 return NL_SKIP;
1836
1837         sig_change->current_noise =
1838                 (s8) nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1839
1840         return NL_SKIP;
1841 }
1842
1843
1844 static int nl80211_get_link_noise(struct wpa_driver_nl80211_data *drv,
1845                                   struct wpa_signal_info *sig_change)
1846 {
1847         struct nl_msg *msg;
1848
1849         sig_change->current_noise = 9999;
1850         sig_change->frequency = drv->assoc_freq;
1851
1852         msg = nlmsg_alloc();
1853         if (!msg)
1854                 return -ENOMEM;
1855
1856         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
1857
1858         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1859
1860         return send_and_recv_msgs(drv, msg, get_link_noise, sig_change);
1861  nla_put_failure:
1862         nlmsg_free(msg);
1863         return -ENOBUFS;
1864 }
1865
1866
1867 static int get_noise_for_scan_results(struct nl_msg *msg, void *arg)
1868 {
1869         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1870         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1871         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1872         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1873                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1874                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
1875         };
1876         struct wpa_scan_results *scan_results = arg;
1877         struct wpa_scan_res *scan_res;
1878         size_t i;
1879
1880         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1881                   genlmsg_attrlen(gnlh, 0), NULL);
1882
1883         if (!tb[NL80211_ATTR_SURVEY_INFO]) {
1884                 wpa_printf(MSG_DEBUG, "nl80211: Survey data missing");
1885                 return NL_SKIP;
1886         }
1887
1888         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1889                              tb[NL80211_ATTR_SURVEY_INFO],
1890                              survey_policy)) {
1891                 wpa_printf(MSG_DEBUG, "nl80211: Failed to parse nested "
1892                            "attributes");
1893                 return NL_SKIP;
1894         }
1895
1896         if (!sinfo[NL80211_SURVEY_INFO_NOISE])
1897                 return NL_SKIP;
1898
1899         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1900                 return NL_SKIP;
1901
1902         for (i = 0; i < scan_results->num; ++i) {
1903                 scan_res = scan_results->res[i];
1904                 if (!scan_res)
1905                         continue;
1906                 if ((int) nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
1907                     scan_res->freq)
1908                         continue;
1909                 if (!(scan_res->flags & WPA_SCAN_NOISE_INVALID))
1910                         continue;
1911                 scan_res->noise = (s8)
1912                         nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1913                 scan_res->flags &= ~WPA_SCAN_NOISE_INVALID;
1914         }
1915
1916         return NL_SKIP;
1917 }
1918
1919
1920 static int nl80211_get_noise_for_scan_results(
1921         struct wpa_driver_nl80211_data *drv,
1922         struct wpa_scan_results *scan_res)
1923 {
1924         struct nl_msg *msg;
1925
1926         msg = nlmsg_alloc();
1927         if (!msg)
1928                 return -ENOMEM;
1929
1930         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
1931
1932         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1933
1934         return send_and_recv_msgs(drv, msg, get_noise_for_scan_results,
1935                                   scan_res);
1936  nla_put_failure:
1937         nlmsg_free(msg);
1938         return -ENOBUFS;
1939 }
1940
1941
1942 static void nl80211_cqm_event(struct wpa_driver_nl80211_data *drv,
1943                               struct nlattr *tb[])
1944 {
1945         static struct nla_policy cqm_policy[NL80211_ATTR_CQM_MAX + 1] = {
1946                 [NL80211_ATTR_CQM_RSSI_THOLD] = { .type = NLA_U32 },
1947                 [NL80211_ATTR_CQM_RSSI_HYST] = { .type = NLA_U8 },
1948                 [NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] = { .type = NLA_U32 },
1949                 [NL80211_ATTR_CQM_PKT_LOSS_EVENT] = { .type = NLA_U32 },
1950         };
1951         struct nlattr *cqm[NL80211_ATTR_CQM_MAX + 1];
1952         enum nl80211_cqm_rssi_threshold_event event;
1953         union wpa_event_data ed;
1954         struct wpa_signal_info sig;
1955         int res;
1956
1957         if (tb[NL80211_ATTR_CQM] == NULL ||
1958             nla_parse_nested(cqm, NL80211_ATTR_CQM_MAX, tb[NL80211_ATTR_CQM],
1959                              cqm_policy)) {
1960                 wpa_printf(MSG_DEBUG, "nl80211: Ignore invalid CQM event");
1961                 return;
1962         }
1963
1964         os_memset(&ed, 0, sizeof(ed));
1965
1966         if (cqm[NL80211_ATTR_CQM_PKT_LOSS_EVENT]) {
1967                 if (!tb[NL80211_ATTR_MAC])
1968                         return;
1969                 os_memcpy(ed.low_ack.addr, nla_data(tb[NL80211_ATTR_MAC]),
1970                           ETH_ALEN);
1971                 wpa_supplicant_event(drv->ctx, EVENT_STATION_LOW_ACK, &ed);
1972                 return;
1973         }
1974
1975         if (cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] == NULL)
1976                 return;
1977         event = nla_get_u32(cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]);
1978
1979         if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH) {
1980                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1981                            "event: RSSI high");
1982                 ed.signal_change.above_threshold = 1;
1983         } else if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW) {
1984                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1985                            "event: RSSI low");
1986                 ed.signal_change.above_threshold = 0;
1987         } else
1988                 return;
1989
1990         res = nl80211_get_link_signal(drv, &sig);
1991         if (res == 0) {
1992                 ed.signal_change.current_signal = sig.current_signal;
1993                 ed.signal_change.current_txrate = sig.current_txrate;
1994                 wpa_printf(MSG_DEBUG, "nl80211: Signal: %d dBm  txrate: %d",
1995                            sig.current_signal, sig.current_txrate);
1996         }
1997
1998         res = nl80211_get_link_noise(drv, &sig);
1999         if (res == 0) {
2000                 ed.signal_change.current_noise = sig.current_noise;
2001                 wpa_printf(MSG_DEBUG, "nl80211: Noise: %d dBm",
2002                            sig.current_noise);
2003         }
2004
2005         wpa_supplicant_event(drv->ctx, EVENT_SIGNAL_CHANGE, &ed);
2006 }
2007
2008
2009 static void nl80211_new_station_event(struct wpa_driver_nl80211_data *drv,
2010                                       struct nlattr **tb)
2011 {
2012         u8 *addr;
2013         union wpa_event_data data;
2014
2015         if (tb[NL80211_ATTR_MAC] == NULL)
2016                 return;
2017         addr = nla_data(tb[NL80211_ATTR_MAC]);
2018         wpa_printf(MSG_DEBUG, "nl80211: New station " MACSTR, MAC2STR(addr));
2019
2020         if (is_ap_interface(drv->nlmode) && drv->device_ap_sme) {
2021                 u8 *ies = NULL;
2022                 size_t ies_len = 0;
2023                 if (tb[NL80211_ATTR_IE]) {
2024                         ies = nla_data(tb[NL80211_ATTR_IE]);
2025                         ies_len = nla_len(tb[NL80211_ATTR_IE]);
2026                 }
2027                 wpa_hexdump(MSG_DEBUG, "nl80211: Assoc Req IEs", ies, ies_len);
2028                 drv_event_assoc(drv->ctx, addr, ies, ies_len, 0);
2029                 return;
2030         }
2031
2032         if (drv->nlmode != NL80211_IFTYPE_ADHOC)
2033                 return;
2034
2035         os_memset(&data, 0, sizeof(data));
2036         os_memcpy(data.ibss_rsn_start.peer, addr, ETH_ALEN);
2037         wpa_supplicant_event(drv->ctx, EVENT_IBSS_RSN_START, &data);
2038 }
2039
2040
2041 static void nl80211_del_station_event(struct wpa_driver_nl80211_data *drv,
2042                                       struct nlattr **tb)
2043 {
2044         u8 *addr;
2045         union wpa_event_data data;
2046
2047         if (tb[NL80211_ATTR_MAC] == NULL)
2048                 return;
2049         addr = nla_data(tb[NL80211_ATTR_MAC]);
2050         wpa_printf(MSG_DEBUG, "nl80211: Delete station " MACSTR,
2051                    MAC2STR(addr));
2052
2053         if (is_ap_interface(drv->nlmode) && drv->device_ap_sme) {
2054                 drv_event_disassoc(drv->ctx, addr);
2055                 return;
2056         }
2057
2058         if (drv->nlmode != NL80211_IFTYPE_ADHOC)
2059                 return;
2060
2061         os_memset(&data, 0, sizeof(data));
2062         os_memcpy(data.ibss_peer_lost.peer, addr, ETH_ALEN);
2063         wpa_supplicant_event(drv->ctx, EVENT_IBSS_PEER_LOST, &data);
2064 }
2065
2066
2067 static void nl80211_rekey_offload_event(struct wpa_driver_nl80211_data *drv,
2068                                         struct nlattr **tb)
2069 {
2070         struct nlattr *rekey_info[NUM_NL80211_REKEY_DATA];
2071         static struct nla_policy rekey_policy[NUM_NL80211_REKEY_DATA] = {
2072                 [NL80211_REKEY_DATA_KEK] = {
2073                         .minlen = NL80211_KEK_LEN,
2074                         .maxlen = NL80211_KEK_LEN,
2075                 },
2076                 [NL80211_REKEY_DATA_KCK] = {
2077                         .minlen = NL80211_KCK_LEN,
2078                         .maxlen = NL80211_KCK_LEN,
2079                 },
2080                 [NL80211_REKEY_DATA_REPLAY_CTR] = {
2081                         .minlen = NL80211_REPLAY_CTR_LEN,
2082                         .maxlen = NL80211_REPLAY_CTR_LEN,
2083                 },
2084         };
2085         union wpa_event_data data;
2086
2087         if (!tb[NL80211_ATTR_MAC])
2088                 return;
2089         if (!tb[NL80211_ATTR_REKEY_DATA])
2090                 return;
2091         if (nla_parse_nested(rekey_info, MAX_NL80211_REKEY_DATA,
2092                              tb[NL80211_ATTR_REKEY_DATA], rekey_policy))
2093                 return;
2094         if (!rekey_info[NL80211_REKEY_DATA_REPLAY_CTR])
2095                 return;
2096
2097         os_memset(&data, 0, sizeof(data));
2098         data.driver_gtk_rekey.bssid = nla_data(tb[NL80211_ATTR_MAC]);
2099         wpa_printf(MSG_DEBUG, "nl80211: Rekey offload event for BSSID " MACSTR,
2100                    MAC2STR(data.driver_gtk_rekey.bssid));
2101         data.driver_gtk_rekey.replay_ctr =
2102                 nla_data(rekey_info[NL80211_REKEY_DATA_REPLAY_CTR]);
2103         wpa_hexdump(MSG_DEBUG, "nl80211: Rekey offload - Replay Counter",
2104                     data.driver_gtk_rekey.replay_ctr, NL80211_REPLAY_CTR_LEN);
2105         wpa_supplicant_event(drv->ctx, EVENT_DRIVER_GTK_REKEY, &data);
2106 }
2107
2108
2109 static void nl80211_pmksa_candidate_event(struct wpa_driver_nl80211_data *drv,
2110                                           struct nlattr **tb)
2111 {
2112         struct nlattr *cand[NUM_NL80211_PMKSA_CANDIDATE];
2113         static struct nla_policy cand_policy[NUM_NL80211_PMKSA_CANDIDATE] = {
2114                 [NL80211_PMKSA_CANDIDATE_INDEX] = { .type = NLA_U32 },
2115                 [NL80211_PMKSA_CANDIDATE_BSSID] = {
2116                         .minlen = ETH_ALEN,
2117                         .maxlen = ETH_ALEN,
2118                 },
2119                 [NL80211_PMKSA_CANDIDATE_PREAUTH] = { .type = NLA_FLAG },
2120         };
2121         union wpa_event_data data;
2122
2123         wpa_printf(MSG_DEBUG, "nl80211: PMKSA candidate event");
2124
2125         if (!tb[NL80211_ATTR_PMKSA_CANDIDATE])
2126                 return;
2127         if (nla_parse_nested(cand, MAX_NL80211_PMKSA_CANDIDATE,
2128                              tb[NL80211_ATTR_PMKSA_CANDIDATE], cand_policy))
2129                 return;
2130         if (!cand[NL80211_PMKSA_CANDIDATE_INDEX] ||
2131             !cand[NL80211_PMKSA_CANDIDATE_BSSID])
2132                 return;
2133
2134         os_memset(&data, 0, sizeof(data));
2135         os_memcpy(data.pmkid_candidate.bssid,
2136                   nla_data(cand[NL80211_PMKSA_CANDIDATE_BSSID]), ETH_ALEN);
2137         data.pmkid_candidate.index =
2138                 nla_get_u32(cand[NL80211_PMKSA_CANDIDATE_INDEX]);
2139         data.pmkid_candidate.preauth =
2140                 cand[NL80211_PMKSA_CANDIDATE_PREAUTH] != NULL;
2141         wpa_supplicant_event(drv->ctx, EVENT_PMKID_CANDIDATE, &data);
2142 }
2143
2144
2145 static void nl80211_client_probe_event(struct wpa_driver_nl80211_data *drv,
2146                                        struct nlattr **tb)
2147 {
2148         union wpa_event_data data;
2149
2150         wpa_printf(MSG_DEBUG, "nl80211: Probe client event");
2151
2152         if (!tb[NL80211_ATTR_MAC] || !tb[NL80211_ATTR_ACK])
2153                 return;
2154
2155         os_memset(&data, 0, sizeof(data));
2156         os_memcpy(data.client_poll.addr,
2157                   nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2158
2159         wpa_supplicant_event(drv->ctx, EVENT_DRIVER_CLIENT_POLL_OK, &data);
2160 }
2161
2162
2163 static void nl80211_tdls_oper_event(struct wpa_driver_nl80211_data *drv,
2164                                     struct nlattr **tb)
2165 {
2166         union wpa_event_data data;
2167
2168         wpa_printf(MSG_DEBUG, "nl80211: TDLS operation event");
2169
2170         if (!tb[NL80211_ATTR_MAC] || !tb[NL80211_ATTR_TDLS_OPERATION])
2171                 return;
2172
2173         os_memset(&data, 0, sizeof(data));
2174         os_memcpy(data.tdls.peer, nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2175         switch (nla_get_u8(tb[NL80211_ATTR_TDLS_OPERATION])) {
2176         case NL80211_TDLS_SETUP:
2177                 wpa_printf(MSG_DEBUG, "nl80211: TDLS setup request for peer "
2178                            MACSTR, MAC2STR(data.tdls.peer));
2179                 data.tdls.oper = TDLS_REQUEST_SETUP;
2180                 break;
2181         case NL80211_TDLS_TEARDOWN:
2182                 wpa_printf(MSG_DEBUG, "nl80211: TDLS teardown request for peer "
2183                            MACSTR, MAC2STR(data.tdls.peer));
2184                 data.tdls.oper = TDLS_REQUEST_TEARDOWN;
2185                 break;
2186         default:
2187                 wpa_printf(MSG_DEBUG, "nl80211: Unsupported TDLS operatione "
2188                            "event");
2189                 return;
2190         }
2191         if (tb[NL80211_ATTR_REASON_CODE]) {
2192                 data.tdls.reason_code =
2193                         nla_get_u16(tb[NL80211_ATTR_REASON_CODE]);
2194         }
2195
2196         wpa_supplicant_event(drv->ctx, EVENT_TDLS, &data);
2197 }
2198
2199
2200 static void nl80211_connect_failed_event(struct wpa_driver_nl80211_data *drv,
2201                                          struct nlattr **tb)
2202 {
2203         union wpa_event_data data;
2204         u32 reason;
2205
2206         wpa_printf(MSG_DEBUG, "nl80211: Connect failed event");
2207
2208         if (!tb[NL80211_ATTR_MAC] || !tb[NL80211_ATTR_CONN_FAILED_REASON])
2209                 return;
2210
2211         os_memset(&data, 0, sizeof(data));
2212         os_memcpy(data.connect_failed_reason.addr,
2213                   nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2214
2215         reason = nla_get_u32(tb[NL80211_ATTR_CONN_FAILED_REASON]);
2216         switch (reason) {
2217         case NL80211_CONN_FAIL_MAX_CLIENTS:
2218                 wpa_printf(MSG_DEBUG, "nl80211: Max client reached");
2219                 data.connect_failed_reason.code = MAX_CLIENT_REACHED;
2220                 break;
2221         case NL80211_CONN_FAIL_BLOCKED_CLIENT:
2222                 wpa_printf(MSG_DEBUG, "nl80211: Blocked client " MACSTR
2223                            " tried to connect",
2224                            MAC2STR(data.connect_failed_reason.addr));
2225                 data.connect_failed_reason.code = BLOCKED_CLIENT;
2226                 break;
2227         default:
2228                 wpa_printf(MSG_DEBUG, "nl8021l: Unknown connect failed reason "
2229                            "%u", reason);
2230                 return;
2231         }
2232
2233         wpa_supplicant_event(drv->ctx, EVENT_CONNECT_FAILED_REASON, &data);
2234 }
2235
2236
2237 static void nl80211_radar_event(struct wpa_driver_nl80211_data *drv,
2238                                 struct nlattr **tb)
2239 {
2240         union wpa_event_data data;
2241         enum nl80211_radar_event event_type;
2242
2243         if (!tb[NL80211_ATTR_WIPHY_FREQ] || !tb[NL80211_ATTR_RADAR_EVENT])
2244                 return;
2245
2246         os_memset(&data, 0, sizeof(data));
2247         data.dfs_event.freq = nla_get_u16(tb[NL80211_ATTR_WIPHY_FREQ]);
2248         event_type = nla_get_u8(tb[NL80211_ATTR_RADAR_EVENT]);
2249
2250         wpa_printf(MSG_DEBUG, "nl80211: DFS event on freq %d MHz",
2251                    data.dfs_event.freq);
2252
2253         switch (event_type) {
2254         case NL80211_RADAR_DETECTED:
2255                 wpa_supplicant_event(drv->ctx, EVENT_DFS_RADAR_DETECTED, &data);
2256                 break;
2257         case NL80211_RADAR_CAC_FINISHED:
2258                 wpa_supplicant_event(drv->ctx, EVENT_DFS_CAC_FINISHED, &data);
2259                 break;
2260         case NL80211_RADAR_CAC_ABORTED:
2261                 wpa_supplicant_event(drv->ctx, EVENT_DFS_CAC_ABORTED, &data);
2262                 break;
2263         case NL80211_RADAR_NOP_FINISHED:
2264                 wpa_supplicant_event(drv->ctx, EVENT_DFS_NOP_FINISHED, &data);
2265                 break;
2266         default:
2267                 wpa_printf(MSG_DEBUG, "nl80211: Unknown radar event %d "
2268                            "received", event_type);
2269                 break;
2270         }
2271 }
2272
2273
2274 static void nl80211_spurious_frame(struct i802_bss *bss, struct nlattr **tb,
2275                                    int wds)
2276 {
2277         struct wpa_driver_nl80211_data *drv = bss->drv;
2278         union wpa_event_data event;
2279
2280         if (!tb[NL80211_ATTR_MAC])
2281                 return;
2282
2283         os_memset(&event, 0, sizeof(event));
2284         event.rx_from_unknown.bssid = bss->addr;
2285         event.rx_from_unknown.addr = nla_data(tb[NL80211_ATTR_MAC]);
2286         event.rx_from_unknown.wds = wds;
2287
2288         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
2289 }
2290
2291
2292 static void do_process_drv_event(struct i802_bss *bss, int cmd,
2293                                  struct nlattr **tb)
2294 {
2295         struct wpa_driver_nl80211_data *drv = bss->drv;
2296
2297         if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED &&
2298             (cmd == NL80211_CMD_NEW_SCAN_RESULTS ||
2299              cmd == NL80211_CMD_SCAN_ABORTED)) {
2300                 wpa_driver_nl80211_set_mode(&drv->first_bss,
2301                                             drv->ap_scan_as_station);
2302                 drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
2303         }
2304
2305         switch (cmd) {
2306         case NL80211_CMD_TRIGGER_SCAN:
2307                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Scan trigger");
2308                 break;
2309         case NL80211_CMD_START_SCHED_SCAN:
2310                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Sched scan started");
2311                 break;
2312         case NL80211_CMD_SCHED_SCAN_STOPPED:
2313                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Sched scan stopped");
2314                 wpa_supplicant_event(drv->ctx, EVENT_SCHED_SCAN_STOPPED, NULL);
2315                 break;
2316         case NL80211_CMD_NEW_SCAN_RESULTS:
2317                 wpa_dbg(drv->ctx, MSG_DEBUG,
2318                         "nl80211: New scan results available");
2319                 drv->scan_complete_events = 1;
2320                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
2321                                      drv->ctx);
2322                 send_scan_event(drv, 0, tb);
2323                 break;
2324         case NL80211_CMD_SCHED_SCAN_RESULTS:
2325                 wpa_dbg(drv->ctx, MSG_DEBUG,
2326                         "nl80211: New sched scan results available");
2327                 send_scan_event(drv, 0, tb);
2328                 break;
2329         case NL80211_CMD_SCAN_ABORTED:
2330                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Scan aborted");
2331                 /*
2332                  * Need to indicate that scan results are available in order
2333                  * not to make wpa_supplicant stop its scanning.
2334                  */
2335                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
2336                                      drv->ctx);
2337                 send_scan_event(drv, 1, tb);
2338                 break;
2339         case NL80211_CMD_AUTHENTICATE:
2340         case NL80211_CMD_ASSOCIATE:
2341         case NL80211_CMD_DEAUTHENTICATE:
2342         case NL80211_CMD_DISASSOCIATE:
2343         case NL80211_CMD_FRAME_TX_STATUS:
2344         case NL80211_CMD_UNPROT_DEAUTHENTICATE:
2345         case NL80211_CMD_UNPROT_DISASSOCIATE:
2346                 mlme_event(bss, cmd, tb[NL80211_ATTR_FRAME],
2347                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
2348                            tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
2349                            tb[NL80211_ATTR_COOKIE],
2350                            tb[NL80211_ATTR_RX_SIGNAL_DBM]);
2351                 break;
2352         case NL80211_CMD_CONNECT:
2353         case NL80211_CMD_ROAM:
2354                 mlme_event_connect(drv, cmd,
2355                                    tb[NL80211_ATTR_STATUS_CODE],
2356                                    tb[NL80211_ATTR_MAC],
2357                                    tb[NL80211_ATTR_REQ_IE],
2358                                    tb[NL80211_ATTR_RESP_IE]);
2359                 break;
2360         case NL80211_CMD_CH_SWITCH_NOTIFY:
2361                 mlme_event_ch_switch(drv, tb[NL80211_ATTR_WIPHY_FREQ],
2362                                      tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
2363                 break;
2364         case NL80211_CMD_DISCONNECT:
2365                 mlme_event_disconnect(drv, tb[NL80211_ATTR_REASON_CODE],
2366                                       tb[NL80211_ATTR_MAC],
2367                                       tb[NL80211_ATTR_DISCONNECTED_BY_AP]);
2368                 break;
2369         case NL80211_CMD_MICHAEL_MIC_FAILURE:
2370                 mlme_event_michael_mic_failure(bss, tb);
2371                 break;
2372         case NL80211_CMD_JOIN_IBSS:
2373                 mlme_event_join_ibss(drv, tb);
2374                 break;
2375         case NL80211_CMD_REMAIN_ON_CHANNEL:
2376                 mlme_event_remain_on_channel(drv, 0, tb);
2377                 break;
2378         case NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL:
2379                 mlme_event_remain_on_channel(drv, 1, tb);
2380                 break;
2381         case NL80211_CMD_NOTIFY_CQM:
2382                 nl80211_cqm_event(drv, tb);
2383                 break;
2384         case NL80211_CMD_REG_CHANGE:
2385                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory domain change");
2386                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
2387                                      NULL);
2388                 break;
2389         case NL80211_CMD_REG_BEACON_HINT:
2390                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory beacon hint");
2391                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
2392                                      NULL);
2393                 break;
2394         case NL80211_CMD_NEW_STATION:
2395                 nl80211_new_station_event(drv, tb);
2396                 break;
2397         case NL80211_CMD_DEL_STATION:
2398                 nl80211_del_station_event(drv, tb);
2399                 break;
2400         case NL80211_CMD_SET_REKEY_OFFLOAD:
2401                 nl80211_rekey_offload_event(drv, tb);
2402                 break;
2403         case NL80211_CMD_PMKSA_CANDIDATE:
2404                 nl80211_pmksa_candidate_event(drv, tb);
2405                 break;
2406         case NL80211_CMD_PROBE_CLIENT:
2407                 nl80211_client_probe_event(drv, tb);
2408                 break;
2409         case NL80211_CMD_TDLS_OPER:
2410                 nl80211_tdls_oper_event(drv, tb);
2411                 break;
2412         case NL80211_CMD_CONN_FAILED:
2413                 nl80211_connect_failed_event(drv, tb);
2414                 break;
2415         case NL80211_CMD_FT_EVENT:
2416                 mlme_event_ft_event(drv, tb);
2417                 break;
2418         case NL80211_CMD_RADAR_DETECT:
2419                 nl80211_radar_event(drv, tb);
2420                 break;
2421         default:
2422                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Ignored unknown event "
2423                         "(cmd=%d)", cmd);
2424                 break;
2425         }
2426 }
2427
2428
2429 static int process_drv_event(struct nl_msg *msg, void *arg)
2430 {
2431         struct wpa_driver_nl80211_data *drv = arg;
2432         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2433         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2434         struct i802_bss *bss;
2435         int ifidx = -1;
2436
2437         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2438                   genlmsg_attrlen(gnlh, 0), NULL);
2439
2440         if (tb[NL80211_ATTR_IFINDEX])
2441                 ifidx = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
2442
2443         for (bss = &drv->first_bss; bss; bss = bss->next) {
2444                 if (ifidx == -1 || ifidx == bss->ifindex) {
2445                         do_process_drv_event(bss, gnlh->cmd, tb);
2446                         return NL_SKIP;
2447                 }
2448         }
2449
2450         wpa_printf(MSG_DEBUG, "nl80211: Ignored event (cmd=%d) for foreign "
2451                    "interface (ifindex %d)", gnlh->cmd, ifidx);
2452
2453         return NL_SKIP;
2454 }
2455
2456
2457 static int process_global_event(struct nl_msg *msg, void *arg)
2458 {
2459         struct nl80211_global *global = arg;
2460         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2461         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2462         struct wpa_driver_nl80211_data *drv, *tmp;
2463         int ifidx = -1;
2464         struct i802_bss *bss;
2465
2466         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2467                   genlmsg_attrlen(gnlh, 0), NULL);
2468
2469         if (tb[NL80211_ATTR_IFINDEX])
2470                 ifidx = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
2471
2472         dl_list_for_each_safe(drv, tmp, &global->interfaces,
2473                               struct wpa_driver_nl80211_data, list) {
2474                 for (bss = &drv->first_bss; bss; bss = bss->next) {
2475                         if (ifidx == -1 || ifidx == bss->ifindex) {
2476                                 do_process_drv_event(bss, gnlh->cmd, tb);
2477                                 return NL_SKIP;
2478                         }
2479                 }
2480         }
2481
2482         return NL_SKIP;
2483 }
2484
2485
2486 static int process_bss_event(struct nl_msg *msg, void *arg)
2487 {
2488         struct i802_bss *bss = arg;
2489         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2490         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2491
2492         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2493                   genlmsg_attrlen(gnlh, 0), NULL);
2494
2495         switch (gnlh->cmd) {
2496         case NL80211_CMD_FRAME:
2497         case NL80211_CMD_FRAME_TX_STATUS:
2498                 mlme_event(bss, gnlh->cmd, tb[NL80211_ATTR_FRAME],
2499                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
2500                            tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
2501                            tb[NL80211_ATTR_COOKIE],
2502                            tb[NL80211_ATTR_RX_SIGNAL_DBM]);
2503                 break;
2504         case NL80211_CMD_UNEXPECTED_FRAME:
2505                 nl80211_spurious_frame(bss, tb, 0);
2506                 break;
2507         case NL80211_CMD_UNEXPECTED_4ADDR_FRAME:
2508                 nl80211_spurious_frame(bss, tb, 1);
2509                 break;
2510         default:
2511                 wpa_printf(MSG_DEBUG, "nl80211: Ignored unknown event "
2512                            "(cmd=%d)", gnlh->cmd);
2513                 break;
2514         }
2515
2516         return NL_SKIP;
2517 }
2518
2519
2520 static void wpa_driver_nl80211_event_receive(int sock, void *eloop_ctx,
2521                                              void *handle)
2522 {
2523         struct nl_cb *cb = eloop_ctx;
2524
2525         wpa_printf(MSG_MSGDUMP, "nl80211: Event message available");
2526
2527         nl_recvmsgs(handle, cb);
2528 }
2529
2530
2531 /**
2532  * wpa_driver_nl80211_set_country - ask nl80211 to set the regulatory domain
2533  * @priv: driver_nl80211 private data
2534  * @alpha2_arg: country to which to switch to
2535  * Returns: 0 on success, -1 on failure
2536  *
2537  * This asks nl80211 to set the regulatory domain for given
2538  * country ISO / IEC alpha2.
2539  */
2540 static int wpa_driver_nl80211_set_country(void *priv, const char *alpha2_arg)
2541 {
2542         struct i802_bss *bss = priv;
2543         struct wpa_driver_nl80211_data *drv = bss->drv;
2544         char alpha2[3];
2545         struct nl_msg *msg;
2546
2547         msg = nlmsg_alloc();
2548         if (!msg)
2549                 return -ENOMEM;
2550
2551         alpha2[0] = alpha2_arg[0];
2552         alpha2[1] = alpha2_arg[1];
2553         alpha2[2] = '\0';
2554
2555         nl80211_cmd(drv, msg, 0, NL80211_CMD_REQ_SET_REG);
2556
2557         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
2558         if (send_and_recv_msgs(drv, msg, NULL, NULL))
2559                 return -EINVAL;
2560         return 0;
2561 nla_put_failure:
2562         nlmsg_free(msg);
2563         return -EINVAL;
2564 }
2565
2566
2567 static int protocol_feature_handler(struct nl_msg *msg, void *arg)
2568 {
2569         u32 *feat = arg;
2570         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
2571         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2572
2573         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2574                   genlmsg_attrlen(gnlh, 0), NULL);
2575
2576         if (tb_msg[NL80211_ATTR_PROTOCOL_FEATURES])
2577                 *feat = nla_get_u32(tb_msg[NL80211_ATTR_PROTOCOL_FEATURES]);
2578
2579         return NL_SKIP;
2580 }
2581
2582
2583 static u32 get_nl80211_protocol_features(struct wpa_driver_nl80211_data *drv)
2584 {
2585         u32 feat = 0;
2586         struct nl_msg *msg;
2587
2588         msg = nlmsg_alloc();
2589         if (!msg)
2590                 goto nla_put_failure;
2591
2592         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_PROTOCOL_FEATURES);
2593         if (send_and_recv_msgs(drv, msg, protocol_feature_handler, &feat) == 0)
2594                 return feat;
2595
2596         msg = NULL;
2597 nla_put_failure:
2598         nlmsg_free(msg);
2599         return 0;
2600 }
2601
2602
2603 struct wiphy_info_data {
2604         struct wpa_driver_nl80211_data *drv;
2605         struct wpa_driver_capa *capa;
2606
2607         unsigned int error:1;
2608         unsigned int device_ap_sme:1;
2609         unsigned int poll_command_supported:1;
2610         unsigned int data_tx_status:1;
2611         unsigned int monitor_supported:1;
2612         unsigned int auth_supported:1;
2613         unsigned int connect_supported:1;
2614         unsigned int p2p_go_supported:1;
2615         unsigned int p2p_client_supported:1;
2616         unsigned int p2p_concurrent:1;
2617         unsigned int p2p_multichan_concurrent:1;
2618 };
2619
2620
2621 static unsigned int probe_resp_offload_support(int supp_protocols)
2622 {
2623         unsigned int prot = 0;
2624
2625         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS)
2626                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS;
2627         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2)
2628                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS2;
2629         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P)
2630                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_P2P;
2631         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_80211U)
2632                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_INTERWORKING;
2633
2634         return prot;
2635 }
2636
2637
2638 static void wiphy_info_supported_iftypes(struct wiphy_info_data *info,
2639                                          struct nlattr *tb)
2640 {
2641         struct nlattr *nl_mode;
2642         int i;
2643
2644         if (tb == NULL)
2645                 return;
2646
2647         nla_for_each_nested(nl_mode, tb, i) {
2648                 switch (nla_type(nl_mode)) {
2649                 case NL80211_IFTYPE_AP:
2650                         info->capa->flags |= WPA_DRIVER_FLAGS_AP;
2651                         break;
2652                 case NL80211_IFTYPE_ADHOC:
2653                         info->capa->flags |= WPA_DRIVER_FLAGS_IBSS;
2654                         break;
2655                 case NL80211_IFTYPE_P2P_GO:
2656                         info->p2p_go_supported = 1;
2657                         break;
2658                 case NL80211_IFTYPE_P2P_CLIENT:
2659                         info->p2p_client_supported = 1;
2660                         break;
2661                 case NL80211_IFTYPE_MONITOR:
2662                         info->monitor_supported = 1;
2663                         break;
2664                 }
2665         }
2666 }
2667
2668
2669 static int wiphy_info_iface_comb_process(struct wiphy_info_data *info,
2670                                          struct nlattr *nl_combi)
2671 {
2672         struct nlattr *tb_comb[NUM_NL80211_IFACE_COMB];
2673         struct nlattr *tb_limit[NUM_NL80211_IFACE_LIMIT];
2674         struct nlattr *nl_limit, *nl_mode;
2675         int err, rem_limit, rem_mode;
2676         int combination_has_p2p = 0, combination_has_mgd = 0;
2677         static struct nla_policy
2678         iface_combination_policy[NUM_NL80211_IFACE_COMB] = {
2679                 [NL80211_IFACE_COMB_LIMITS] = { .type = NLA_NESTED },
2680                 [NL80211_IFACE_COMB_MAXNUM] = { .type = NLA_U32 },
2681                 [NL80211_IFACE_COMB_STA_AP_BI_MATCH] = { .type = NLA_FLAG },
2682                 [NL80211_IFACE_COMB_NUM_CHANNELS] = { .type = NLA_U32 },
2683                 [NL80211_IFACE_COMB_RADAR_DETECT_WIDTHS] = { .type = NLA_U32 },
2684         },
2685         iface_limit_policy[NUM_NL80211_IFACE_LIMIT] = {
2686                 [NL80211_IFACE_LIMIT_TYPES] = { .type = NLA_NESTED },
2687                 [NL80211_IFACE_LIMIT_MAX] = { .type = NLA_U32 },
2688         };
2689
2690         err = nla_parse_nested(tb_comb, MAX_NL80211_IFACE_COMB,
2691                                nl_combi, iface_combination_policy);
2692         if (err || !tb_comb[NL80211_IFACE_COMB_LIMITS] ||
2693             !tb_comb[NL80211_IFACE_COMB_MAXNUM] ||
2694             !tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS])
2695                 return 0; /* broken combination */
2696
2697         if (tb_comb[NL80211_IFACE_COMB_RADAR_DETECT_WIDTHS])
2698                 info->capa->flags |= WPA_DRIVER_FLAGS_RADAR;
2699
2700         nla_for_each_nested(nl_limit, tb_comb[NL80211_IFACE_COMB_LIMITS],
2701                             rem_limit) {
2702                 err = nla_parse_nested(tb_limit, MAX_NL80211_IFACE_LIMIT,
2703                                        nl_limit, iface_limit_policy);
2704                 if (err || !tb_limit[NL80211_IFACE_LIMIT_TYPES])
2705                         return 0; /* broken combination */
2706
2707                 nla_for_each_nested(nl_mode,
2708                                     tb_limit[NL80211_IFACE_LIMIT_TYPES],
2709                                     rem_mode) {
2710                         int ift = nla_type(nl_mode);
2711                         if (ift == NL80211_IFTYPE_P2P_GO ||
2712                             ift == NL80211_IFTYPE_P2P_CLIENT)
2713                                 combination_has_p2p = 1;
2714                         if (ift == NL80211_IFTYPE_STATION)
2715                                 combination_has_mgd = 1;
2716                 }
2717                 if (combination_has_p2p && combination_has_mgd)
2718                         break;
2719         }
2720
2721         if (combination_has_p2p && combination_has_mgd) {
2722                 info->p2p_concurrent = 1;
2723                 if (nla_get_u32(tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS]) > 1)
2724                         info->p2p_multichan_concurrent = 1;
2725                 return 1;
2726         }
2727
2728         return 0;
2729 }
2730
2731
2732 static void wiphy_info_iface_comb(struct wiphy_info_data *info,
2733                                   struct nlattr *tb)
2734 {
2735         struct nlattr *nl_combi;
2736         int rem_combi;
2737
2738         if (tb == NULL)
2739                 return;
2740
2741         nla_for_each_nested(nl_combi, tb, rem_combi) {
2742                 if (wiphy_info_iface_comb_process(info, nl_combi) > 0)
2743                         break;
2744         }
2745 }
2746
2747
2748 static void wiphy_info_supp_cmds(struct wiphy_info_data *info,
2749                                  struct nlattr *tb)
2750 {
2751         struct nlattr *nl_cmd;
2752         int i;
2753
2754         if (tb == NULL)
2755                 return;
2756
2757         nla_for_each_nested(nl_cmd, tb, i) {
2758                 switch (nla_get_u32(nl_cmd)) {
2759                 case NL80211_CMD_AUTHENTICATE:
2760                         info->auth_supported = 1;
2761                         break;
2762                 case NL80211_CMD_CONNECT:
2763                         info->connect_supported = 1;
2764                         break;
2765                 case NL80211_CMD_START_SCHED_SCAN:
2766                         info->capa->sched_scan_supported = 1;
2767                         break;
2768                 case NL80211_CMD_PROBE_CLIENT:
2769                         info->poll_command_supported = 1;
2770                         break;
2771                 }
2772         }
2773 }
2774
2775
2776 static void wiphy_info_max_roc(struct wpa_driver_capa *capa,
2777                                struct nlattr *tb)
2778 {
2779         if (tb)
2780                 capa->max_remain_on_chan = nla_get_u32(tb);
2781 }
2782
2783
2784 static void wiphy_info_tdls(struct wpa_driver_capa *capa, struct nlattr *tdls,
2785                             struct nlattr *ext_setup)
2786 {
2787         if (tdls == NULL)
2788                 return;
2789
2790         wpa_printf(MSG_DEBUG, "nl80211: TDLS supported");
2791         capa->flags |= WPA_DRIVER_FLAGS_TDLS_SUPPORT;
2792
2793         if (ext_setup) {
2794                 wpa_printf(MSG_DEBUG, "nl80211: TDLS external setup");
2795                 capa->flags |= WPA_DRIVER_FLAGS_TDLS_EXTERNAL_SETUP;
2796         }
2797 }
2798
2799
2800 static void wiphy_info_feature_flags(struct wiphy_info_data *info,
2801                                      struct nlattr *tb)
2802 {
2803         u32 flags;
2804         struct wpa_driver_capa *capa = info->capa;
2805
2806         if (tb == NULL)
2807                 return;
2808
2809         flags = nla_get_u32(tb);
2810
2811         if (flags & NL80211_FEATURE_SK_TX_STATUS)
2812                 info->data_tx_status = 1;
2813
2814         if (flags & NL80211_FEATURE_INACTIVITY_TIMER)
2815                 capa->flags |= WPA_DRIVER_FLAGS_INACTIVITY_TIMER;
2816
2817         if (flags & NL80211_FEATURE_SAE)
2818                 capa->flags |= WPA_DRIVER_FLAGS_SAE;
2819
2820         if (flags & NL80211_FEATURE_NEED_OBSS_SCAN)
2821                 capa->flags |= WPA_DRIVER_FLAGS_OBSS_SCAN;
2822 }
2823
2824
2825 static void wiphy_info_probe_resp_offload(struct wpa_driver_capa *capa,
2826                                           struct nlattr *tb)
2827 {
2828         u32 protocols;
2829
2830         if (tb == NULL)
2831                 return;
2832
2833         protocols = nla_get_u32(tb);
2834         wpa_printf(MSG_DEBUG, "nl80211: Supports Probe Response offload in AP "
2835                    "mode");
2836         capa->flags |= WPA_DRIVER_FLAGS_PROBE_RESP_OFFLOAD;
2837         capa->probe_resp_offloads = probe_resp_offload_support(protocols);
2838 }
2839
2840
2841 static int wiphy_info_handler(struct nl_msg *msg, void *arg)
2842 {
2843         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2844         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2845         struct wiphy_info_data *info = arg;
2846         struct wpa_driver_capa *capa = info->capa;
2847         struct wpa_driver_nl80211_data *drv = info->drv;
2848
2849         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2850                   genlmsg_attrlen(gnlh, 0), NULL);
2851
2852         if (tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS])
2853                 capa->max_scan_ssids =
2854                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS]);
2855
2856         if (tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS])
2857                 capa->max_sched_scan_ssids =
2858                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS]);
2859
2860         if (tb[NL80211_ATTR_MAX_MATCH_SETS])
2861                 capa->max_match_sets =
2862                         nla_get_u8(tb[NL80211_ATTR_MAX_MATCH_SETS]);
2863
2864         wiphy_info_supported_iftypes(info, tb[NL80211_ATTR_SUPPORTED_IFTYPES]);
2865         wiphy_info_iface_comb(info, tb[NL80211_ATTR_INTERFACE_COMBINATIONS]);
2866         wiphy_info_supp_cmds(info, tb[NL80211_ATTR_SUPPORTED_COMMANDS]);
2867
2868         if (tb[NL80211_ATTR_OFFCHANNEL_TX_OK]) {
2869                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based "
2870                            "off-channel TX");
2871                 capa->flags |= WPA_DRIVER_FLAGS_OFFCHANNEL_TX;
2872         }
2873
2874         if (tb[NL80211_ATTR_ROAM_SUPPORT]) {
2875                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based roaming");
2876                 capa->flags |= WPA_DRIVER_FLAGS_BSS_SELECTION;
2877         }
2878
2879         wiphy_info_max_roc(capa,
2880                            tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION]);
2881
2882         if (tb[NL80211_ATTR_SUPPORT_AP_UAPSD])
2883                 capa->flags |= WPA_DRIVER_FLAGS_AP_UAPSD;
2884
2885         wiphy_info_tdls(capa, tb[NL80211_ATTR_TDLS_SUPPORT],
2886                         tb[NL80211_ATTR_TDLS_EXTERNAL_SETUP]);
2887
2888         if (tb[NL80211_ATTR_DEVICE_AP_SME])
2889                 info->device_ap_sme = 1;
2890
2891         wiphy_info_feature_flags(info, tb[NL80211_ATTR_FEATURE_FLAGS]);
2892         wiphy_info_probe_resp_offload(capa,
2893                                       tb[NL80211_ATTR_PROBE_RESP_OFFLOAD]);
2894
2895         if (tb[NL80211_ATTR_EXT_CAPA] && tb[NL80211_ATTR_EXT_CAPA_MASK] &&
2896             drv->extended_capa == NULL) {
2897                 drv->extended_capa =
2898                         os_malloc(nla_len(tb[NL80211_ATTR_EXT_CAPA]));
2899                 if (drv->extended_capa) {
2900                         os_memcpy(drv->extended_capa,
2901                                   nla_data(tb[NL80211_ATTR_EXT_CAPA]),
2902                                   nla_len(tb[NL80211_ATTR_EXT_CAPA]));
2903                         drv->extended_capa_len =
2904                                 nla_len(tb[NL80211_ATTR_EXT_CAPA]);
2905                 }
2906                 drv->extended_capa_mask =
2907                         os_malloc(nla_len(tb[NL80211_ATTR_EXT_CAPA]));
2908                 if (drv->extended_capa_mask) {
2909                         os_memcpy(drv->extended_capa_mask,
2910                                   nla_data(tb[NL80211_ATTR_EXT_CAPA]),
2911                                   nla_len(tb[NL80211_ATTR_EXT_CAPA]));
2912                 } else {
2913                         os_free(drv->extended_capa);
2914                         drv->extended_capa = NULL;
2915                         drv->extended_capa_len = 0;
2916                 }
2917         }
2918
2919         return NL_SKIP;
2920 }
2921
2922
2923 static int wpa_driver_nl80211_get_info(struct wpa_driver_nl80211_data *drv,
2924                                        struct wiphy_info_data *info)
2925 {
2926         u32 feat;
2927         struct nl_msg *msg;
2928
2929         os_memset(info, 0, sizeof(*info));
2930         info->capa = &drv->capa;
2931         info->drv = drv;
2932
2933         msg = nlmsg_alloc();
2934         if (!msg)
2935                 return -1;
2936
2937         feat = get_nl80211_protocol_features(drv);
2938         if (feat & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP)
2939                 nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_WIPHY);
2940         else
2941                 nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
2942
2943         NLA_PUT_FLAG(msg, NL80211_ATTR_SPLIT_WIPHY_DUMP);
2944         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->first_bss.ifindex);
2945
2946         if (send_and_recv_msgs(drv, msg, wiphy_info_handler, info))
2947                 return -1;
2948
2949         if (info->auth_supported)
2950                 drv->capa.flags |= WPA_DRIVER_FLAGS_SME;
2951         else if (!info->connect_supported) {
2952                 wpa_printf(MSG_INFO, "nl80211: Driver does not support "
2953                            "authentication/association or connect commands");
2954                 info->error = 1;
2955         }
2956
2957         if (info->p2p_go_supported && info->p2p_client_supported)
2958                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CAPABLE;
2959         if (info->p2p_concurrent) {
2960                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
2961                            "interface (driver advertised support)");
2962                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
2963                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
2964         }
2965         if (info->p2p_multichan_concurrent) {
2966                 wpa_printf(MSG_DEBUG, "nl80211: Enable multi-channel "
2967                            "concurrent (driver advertised support)");
2968                 drv->capa.flags |= WPA_DRIVER_FLAGS_MULTI_CHANNEL_CONCURRENT;
2969         }
2970
2971         /* default to 5000 since early versions of mac80211 don't set it */
2972         if (!drv->capa.max_remain_on_chan)
2973                 drv->capa.max_remain_on_chan = 5000;
2974
2975         return 0;
2976 nla_put_failure:
2977         nlmsg_free(msg);
2978         return -1;
2979 }
2980
2981
2982 static int wpa_driver_nl80211_capa(struct wpa_driver_nl80211_data *drv)
2983 {
2984         struct wiphy_info_data info;
2985         if (wpa_driver_nl80211_get_info(drv, &info))
2986                 return -1;
2987
2988         if (info.error)
2989                 return -1;
2990
2991         drv->has_capability = 1;
2992         /* For now, assume TKIP, CCMP, WPA, WPA2 are supported */
2993         drv->capa.key_mgmt = WPA_DRIVER_CAPA_KEY_MGMT_WPA |
2994                 WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK |
2995                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2 |
2996                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK;
2997         drv->capa.enc = WPA_DRIVER_CAPA_ENC_WEP40 |
2998                 WPA_DRIVER_CAPA_ENC_WEP104 |
2999                 WPA_DRIVER_CAPA_ENC_TKIP |
3000                 WPA_DRIVER_CAPA_ENC_CCMP;
3001         drv->capa.auth = WPA_DRIVER_AUTH_OPEN |
3002                 WPA_DRIVER_AUTH_SHARED |
3003                 WPA_DRIVER_AUTH_LEAP;
3004
3005         drv->capa.flags |= WPA_DRIVER_FLAGS_SANE_ERROR_CODES;
3006         drv->capa.flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE;
3007         drv->capa.flags |= WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
3008
3009         if (!info.device_ap_sme) {
3010                 drv->capa.flags |= WPA_DRIVER_FLAGS_DEAUTH_TX_STATUS;
3011
3012                 /*
3013                  * No AP SME is currently assumed to also indicate no AP MLME
3014                  * in the driver/firmware.
3015                  */
3016                 drv->capa.flags |= WPA_DRIVER_FLAGS_AP_MLME;
3017         }
3018
3019         drv->device_ap_sme = info.device_ap_sme;
3020         drv->poll_command_supported = info.poll_command_supported;
3021         drv->data_tx_status = info.data_tx_status;
3022
3023         /*
3024          * If poll command and tx status are supported, mac80211 is new enough
3025          * to have everything we need to not need monitor interfaces.
3026          */
3027         drv->use_monitor = !info.poll_command_supported || !info.data_tx_status;
3028
3029         if (drv->device_ap_sme && drv->use_monitor) {
3030                 /*
3031                  * Non-mac80211 drivers may not support monitor interface.
3032                  * Make sure we do not get stuck with incorrect capability here
3033                  * by explicitly testing this.
3034                  */
3035                 if (!info.monitor_supported) {
3036                         wpa_printf(MSG_DEBUG, "nl80211: Disable use_monitor "
3037                                    "with device_ap_sme since no monitor mode "
3038                                    "support detected");
3039                         drv->use_monitor = 0;
3040                 }
3041         }
3042
3043         /*
3044          * If we aren't going to use monitor interfaces, but the
3045          * driver doesn't support data TX status, we won't get TX
3046          * status for EAPOL frames.
3047          */
3048         if (!drv->use_monitor && !info.data_tx_status)
3049                 drv->capa.flags &= ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
3050
3051         return 0;
3052 }
3053
3054
3055 #ifdef ANDROID
3056 static int android_genl_ctrl_resolve(struct nl_handle *handle,
3057                                      const char *name)
3058 {
3059         /*
3060          * Android ICS has very minimal genl_ctrl_resolve() implementation, so
3061          * need to work around that.
3062          */
3063         struct nl_cache *cache = NULL;
3064         struct genl_family *nl80211 = NULL;
3065         int id = -1;
3066
3067         if (genl_ctrl_alloc_cache(handle, &cache) < 0) {
3068                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
3069                            "netlink cache");
3070                 goto fail;
3071         }
3072
3073         nl80211 = genl_ctrl_search_by_name(cache, name);
3074         if (nl80211 == NULL)
3075                 goto fail;
3076
3077         id = genl_family_get_id(nl80211);
3078
3079 fail:
3080         if (nl80211)
3081                 genl_family_put(nl80211);
3082         if (cache)
3083                 nl_cache_free(cache);
3084
3085         return id;
3086 }
3087 #define genl_ctrl_resolve android_genl_ctrl_resolve
3088 #endif /* ANDROID */
3089
3090
3091 static int wpa_driver_nl80211_init_nl_global(struct nl80211_global *global)
3092 {
3093         int ret;
3094
3095         global->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
3096         if (global->nl_cb == NULL) {
3097                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
3098                            "callbacks");
3099                 return -1;
3100         }
3101
3102         global->nl = nl_create_handle(global->nl_cb, "nl");
3103         if (global->nl == NULL)
3104                 goto err;
3105
3106         global->nl80211_id = genl_ctrl_resolve(global->nl, "nl80211");
3107         if (global->nl80211_id < 0) {
3108                 wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
3109                            "found");
3110                 goto err;
3111         }
3112
3113         global->nl_event = nl_create_handle(global->nl_cb, "event");
3114         if (global->nl_event == NULL)
3115                 goto err;
3116
3117         ret = nl_get_multicast_id(global, "nl80211", "scan");
3118         if (ret >= 0)
3119                 ret = nl_socket_add_membership(global->nl_event, ret);
3120         if (ret < 0) {
3121                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
3122                            "membership for scan events: %d (%s)",
3123                            ret, strerror(-ret));
3124                 goto err;
3125         }
3126
3127         ret = nl_get_multicast_id(global, "nl80211", "mlme");
3128         if (ret >= 0)
3129                 ret = nl_socket_add_membership(global->nl_event, ret);
3130         if (ret < 0) {
3131                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
3132                            "membership for mlme events: %d (%s)",
3133                            ret, strerror(-ret));
3134                 goto err;
3135         }
3136
3137         ret = nl_get_multicast_id(global, "nl80211", "regulatory");
3138         if (ret >= 0)
3139                 ret = nl_socket_add_membership(global->nl_event, ret);
3140         if (ret < 0) {
3141                 wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
3142                            "membership for regulatory events: %d (%s)",
3143                            ret, strerror(-ret));
3144                 /* Continue without regulatory events */
3145         }
3146
3147         nl_cb_set(global->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
3148                   no_seq_check, NULL);
3149         nl_cb_set(global->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
3150                   process_global_event, global);
3151
3152         eloop_register_read_sock(nl_socket_get_fd(global->nl_event),
3153                                  wpa_driver_nl80211_event_receive,
3154                                  global->nl_cb, global->nl_event);
3155
3156         return 0;
3157
3158 err:
3159         nl_destroy_handles(&global->nl_event);
3160         nl_destroy_handles(&global->nl);
3161         nl_cb_put(global->nl_cb);
3162         global->nl_cb = NULL;
3163         return -1;
3164 }
3165
3166
3167 static int wpa_driver_nl80211_init_nl(struct wpa_driver_nl80211_data *drv)
3168 {
3169         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
3170         if (!drv->nl_cb) {
3171                 wpa_printf(MSG_ERROR, "nl80211: Failed to alloc cb struct");
3172                 return -1;
3173         }
3174
3175         nl_cb_set(drv->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
3176                   no_seq_check, NULL);
3177         nl_cb_set(drv->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
3178                   process_drv_event, drv);
3179
3180         return 0;
3181 }
3182
3183
3184 static void wpa_driver_nl80211_rfkill_blocked(void *ctx)
3185 {
3186         wpa_printf(MSG_DEBUG, "nl80211: RFKILL blocked");
3187         /*
3188          * This may be for any interface; use ifdown event to disable
3189          * interface.
3190          */
3191 }
3192
3193
3194 static void wpa_driver_nl80211_rfkill_unblocked(void *ctx)
3195 {
3196         struct wpa_driver_nl80211_data *drv = ctx;
3197         wpa_printf(MSG_DEBUG, "nl80211: RFKILL unblocked");
3198         if (linux_set_iface_flags(drv->global->ioctl_sock,
3199                                   drv->first_bss.ifname, 1)) {
3200                 wpa_printf(MSG_DEBUG, "nl80211: Could not set interface UP "
3201                            "after rfkill unblock");
3202                 return;
3203         }
3204         /* rtnetlink ifup handler will report interface as enabled */
3205 }
3206
3207
3208 static void nl80211_get_phy_name(struct wpa_driver_nl80211_data *drv)
3209 {
3210         /* Find phy (radio) to which this interface belongs */
3211         char buf[90], *pos;
3212         int f, rv;
3213
3214         drv->phyname[0] = '\0';
3215         snprintf(buf, sizeof(buf) - 1, "/sys/class/net/%s/phy80211/name",
3216                  drv->first_bss.ifname);
3217         f = open(buf, O_RDONLY);
3218         if (f < 0) {
3219                 wpa_printf(MSG_DEBUG, "Could not open file %s: %s",
3220                            buf, strerror(errno));
3221                 return;
3222         }
3223
3224         rv = read(f, drv->phyname, sizeof(drv->phyname) - 1);
3225         close(f);
3226         if (rv < 0) {
3227                 wpa_printf(MSG_DEBUG, "Could not read file %s: %s",
3228                            buf, strerror(errno));
3229                 return;
3230         }
3231
3232         drv->phyname[rv] = '\0';
3233         pos = os_strchr(drv->phyname, '\n');
3234         if (pos)
3235                 *pos = '\0';
3236         wpa_printf(MSG_DEBUG, "nl80211: interface %s in phy %s",
3237                    drv->first_bss.ifname, drv->phyname);
3238 }
3239
3240
3241 static void wpa_driver_nl80211_handle_eapol_tx_status(int sock,
3242                                                       void *eloop_ctx,
3243                                                       void *handle)
3244 {
3245         struct wpa_driver_nl80211_data *drv = eloop_ctx;
3246         u8 data[2048];
3247         struct msghdr msg;
3248         struct iovec entry;
3249         u8 control[512];
3250         struct cmsghdr *cmsg;
3251         int res, found_ee = 0, found_wifi = 0, acked = 0;
3252         union wpa_event_data event;
3253
3254         memset(&msg, 0, sizeof(msg));
3255         msg.msg_iov = &entry;
3256         msg.msg_iovlen = 1;
3257         entry.iov_base = data;
3258         entry.iov_len = sizeof(data);
3259         msg.msg_control = &control;
3260         msg.msg_controllen = sizeof(control);
3261
3262         res = recvmsg(sock, &msg, MSG_ERRQUEUE);
3263         /* if error or not fitting 802.3 header, return */
3264         if (res < 14)
3265                 return;
3266
3267         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg))
3268         {
3269                 if (cmsg->cmsg_level == SOL_SOCKET &&
3270                     cmsg->cmsg_type == SCM_WIFI_STATUS) {
3271                         int *ack;
3272
3273                         found_wifi = 1;
3274                         ack = (void *)CMSG_DATA(cmsg);
3275                         acked = *ack;
3276                 }
3277
3278                 if (cmsg->cmsg_level == SOL_PACKET &&
3279                     cmsg->cmsg_type == PACKET_TX_TIMESTAMP) {
3280                         struct sock_extended_err *err =
3281                                 (struct sock_extended_err *)CMSG_DATA(cmsg);
3282
3283                         if (err->ee_origin == SO_EE_ORIGIN_TXSTATUS)
3284                                 found_ee = 1;
3285                 }
3286         }
3287
3288         if (!found_ee || !found_wifi)
3289                 return;
3290
3291         memset(&event, 0, sizeof(event));
3292         event.eapol_tx_status.dst = data;
3293         event.eapol_tx_status.data = data + 14;
3294         event.eapol_tx_status.data_len = res - 14;
3295         event.eapol_tx_status.ack = acked;
3296         wpa_supplicant_event(drv->ctx, EVENT_EAPOL_TX_STATUS, &event);
3297 }
3298
3299
3300 static int nl80211_init_bss(struct i802_bss *bss)
3301 {
3302         bss->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
3303         if (!bss->nl_cb)
3304                 return -1;
3305
3306         nl_cb_set(bss->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
3307                   no_seq_check, NULL);
3308         nl_cb_set(bss->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
3309                   process_bss_event, bss);
3310
3311         return 0;
3312 }
3313
3314
3315 static void nl80211_destroy_bss(struct i802_bss *bss)
3316 {
3317         nl_cb_put(bss->nl_cb);
3318         bss->nl_cb = NULL;
3319 }
3320
3321
3322 /**
3323  * wpa_driver_nl80211_init - Initialize nl80211 driver interface
3324  * @ctx: context to be used when calling wpa_supplicant functions,
3325  * e.g., wpa_supplicant_event()
3326  * @ifname: interface name, e.g., wlan0
3327  * @global_priv: private driver global data from global_init()
3328  * Returns: Pointer to private data, %NULL on failure
3329  */
3330 static void * wpa_driver_nl80211_init(void *ctx, const char *ifname,
3331                                       void *global_priv)
3332 {
3333         struct wpa_driver_nl80211_data *drv;
3334         struct rfkill_config *rcfg;
3335         struct i802_bss *bss;
3336
3337         if (global_priv == NULL)
3338                 return NULL;
3339         drv = os_zalloc(sizeof(*drv));
3340         if (drv == NULL)
3341                 return NULL;
3342         drv->global = global_priv;
3343         drv->ctx = ctx;
3344         bss = &drv->first_bss;
3345         bss->drv = drv;
3346         bss->ctx = ctx;
3347
3348         os_strlcpy(bss->ifname, ifname, sizeof(bss->ifname));
3349         drv->monitor_ifidx = -1;
3350         drv->monitor_sock = -1;
3351         drv->eapol_tx_sock = -1;
3352         drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
3353
3354         if (wpa_driver_nl80211_init_nl(drv)) {
3355                 os_free(drv);
3356                 return NULL;
3357         }
3358
3359         if (nl80211_init_bss(bss))
3360                 goto failed;
3361
3362         nl80211_get_phy_name(drv);
3363
3364         rcfg = os_zalloc(sizeof(*rcfg));
3365         if (rcfg == NULL)
3366                 goto failed;
3367         rcfg->ctx = drv;
3368         os_strlcpy(rcfg->ifname, ifname, sizeof(rcfg->ifname));
3369         rcfg->blocked_cb = wpa_driver_nl80211_rfkill_blocked;
3370         rcfg->unblocked_cb = wpa_driver_nl80211_rfkill_unblocked;
3371         drv->rfkill = rfkill_init(rcfg);
3372         if (drv->rfkill == NULL) {
3373                 wpa_printf(MSG_DEBUG, "nl80211: RFKILL status not available");
3374                 os_free(rcfg);
3375         }
3376
3377         if (wpa_driver_nl80211_finish_drv_init(drv))
3378                 goto failed;
3379
3380         drv->eapol_tx_sock = socket(PF_PACKET, SOCK_DGRAM, 0);
3381         if (drv->eapol_tx_sock < 0)
3382                 goto failed;
3383
3384         if (drv->data_tx_status) {
3385                 int enabled = 1;
3386
3387                 if (setsockopt(drv->eapol_tx_sock, SOL_SOCKET, SO_WIFI_STATUS,
3388                                &enabled, sizeof(enabled)) < 0) {
3389                         wpa_printf(MSG_DEBUG,
3390                                 "nl80211: wifi status sockopt failed\n");
3391                         drv->data_tx_status = 0;
3392                         if (!drv->use_monitor)
3393                                 drv->capa.flags &=
3394                                         ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
3395                 } else {
3396                         eloop_register_read_sock(drv->eapol_tx_sock,
3397                                 wpa_driver_nl80211_handle_eapol_tx_status,
3398                                 drv, NULL);
3399                 }
3400         }
3401
3402         if (drv->global) {
3403                 dl_list_add(&drv->global->interfaces, &drv->list);
3404                 drv->in_interface_list = 1;
3405         }
3406
3407         return bss;
3408
3409 failed:
3410         wpa_driver_nl80211_deinit(bss);
3411         return NULL;
3412 }
3413
3414
3415 static int nl80211_register_frame(struct i802_bss *bss,
3416                                   struct nl_handle *nl_handle,
3417                                   u16 type, const u8 *match, size_t match_len)
3418 {
3419         struct wpa_driver_nl80211_data *drv = bss->drv;
3420         struct nl_msg *msg;
3421         int ret = -1;
3422
3423         msg = nlmsg_alloc();
3424         if (!msg)
3425                 return -1;
3426
3427         wpa_printf(MSG_DEBUG, "nl80211: Register frame type=0x%x nl_handle=%p",
3428                    type, nl_handle);
3429         wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
3430                     match, match_len);
3431
3432         nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_ACTION);
3433
3434         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3435         NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE, type);
3436         NLA_PUT(msg, NL80211_ATTR_FRAME_MATCH, match_len, match);
3437
3438         ret = send_and_recv(drv->global, nl_handle, msg, NULL, NULL);
3439         msg = NULL;
3440         if (ret) {
3441                 wpa_printf(MSG_DEBUG, "nl80211: Register frame command "
3442                            "failed (type=%u): ret=%d (%s)",
3443                            type, ret, strerror(-ret));
3444                 wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
3445                             match, match_len);
3446                 goto nla_put_failure;
3447         }
3448         ret = 0;
3449 nla_put_failure:
3450         nlmsg_free(msg);
3451         return ret;
3452 }
3453
3454
3455 static int nl80211_alloc_mgmt_handle(struct i802_bss *bss)
3456 {
3457         struct wpa_driver_nl80211_data *drv = bss->drv;
3458
3459         if (bss->nl_mgmt) {
3460                 wpa_printf(MSG_DEBUG, "nl80211: Mgmt reporting "
3461                            "already on! (nl_mgmt=%p)", bss->nl_mgmt);
3462                 return -1;
3463         }
3464
3465         bss->nl_mgmt = nl_create_handle(drv->nl_cb, "mgmt");
3466         if (bss->nl_mgmt == NULL)
3467                 return -1;
3468
3469         eloop_register_read_sock(nl_socket_get_fd(bss->nl_mgmt),
3470                                  wpa_driver_nl80211_event_receive, bss->nl_cb,
3471                                  bss->nl_mgmt);
3472
3473         return 0;
3474 }
3475
3476
3477 static int nl80211_register_action_frame(struct i802_bss *bss,
3478                                          const u8 *match, size_t match_len)
3479 {
3480         u16 type = (WLAN_FC_TYPE_MGMT << 2) | (WLAN_FC_STYPE_ACTION << 4);
3481         return nl80211_register_frame(bss, bss->nl_mgmt,
3482                                       type, match, match_len);
3483 }
3484
3485
3486 static int nl80211_mgmt_subscribe_non_ap(struct i802_bss *bss)
3487 {
3488         struct wpa_driver_nl80211_data *drv = bss->drv;
3489
3490         if (nl80211_alloc_mgmt_handle(bss))
3491                 return -1;
3492         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with non-AP "
3493                    "handle %p", bss->nl_mgmt);
3494
3495 #if defined(CONFIG_P2P) || defined(CONFIG_INTERWORKING)
3496         /* GAS Initial Request */
3497         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0a", 2) < 0)
3498                 return -1;
3499         /* GAS Initial Response */
3500         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0b", 2) < 0)
3501                 return -1;
3502         /* GAS Comeback Request */
3503         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0c", 2) < 0)
3504                 return -1;
3505         /* GAS Comeback Response */
3506         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0d", 2) < 0)
3507                 return -1;
3508 #endif /* CONFIG_P2P || CONFIG_INTERWORKING */
3509 #ifdef CONFIG_P2P
3510         /* P2P Public Action */
3511         if (nl80211_register_action_frame(bss,
3512                                           (u8 *) "\x04\x09\x50\x6f\x9a\x09",
3513                                           6) < 0)
3514                 return -1;
3515         /* P2P Action */
3516         if (nl80211_register_action_frame(bss,
3517                                           (u8 *) "\x7f\x50\x6f\x9a\x09",
3518                                           5) < 0)
3519                 return -1;
3520 #endif /* CONFIG_P2P */
3521 #ifdef CONFIG_IEEE80211W
3522         /* SA Query Response */
3523         if (nl80211_register_action_frame(bss, (u8 *) "\x08\x01", 2) < 0)
3524                 return -1;
3525 #endif /* CONFIG_IEEE80211W */
3526 #ifdef CONFIG_TDLS
3527         if ((drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT)) {
3528                 /* TDLS Discovery Response */
3529                 if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0e", 2) <
3530                     0)
3531                         return -1;
3532         }
3533 #endif /* CONFIG_TDLS */
3534
3535         /* FT Action frames */
3536         if (nl80211_register_action_frame(bss, (u8 *) "\x06", 1) < 0)
3537                 return -1;
3538         else
3539                 drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_FT |
3540                         WPA_DRIVER_CAPA_KEY_MGMT_FT_PSK;
3541
3542         /* WNM - BSS Transition Management Request */
3543         if (nl80211_register_action_frame(bss, (u8 *) "\x0a\x07", 2) < 0)
3544                 return -1;
3545         /* WNM-Sleep Mode Response */
3546         if (nl80211_register_action_frame(bss, (u8 *) "\x0a\x11", 2) < 0)
3547                 return -1;
3548
3549         return 0;
3550 }
3551
3552
3553 static int nl80211_register_spurious_class3(struct i802_bss *bss)
3554 {
3555         struct wpa_driver_nl80211_data *drv = bss->drv;
3556         struct nl_msg *msg;
3557         int ret = -1;
3558
3559         msg = nlmsg_alloc();
3560         if (!msg)
3561                 return -1;
3562
3563         nl80211_cmd(drv, msg, 0, NL80211_CMD_UNEXPECTED_FRAME);
3564
3565         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3566
3567         ret = send_and_recv(drv->global, bss->nl_mgmt, msg, NULL, NULL);
3568         msg = NULL;
3569         if (ret) {
3570                 wpa_printf(MSG_DEBUG, "nl80211: Register spurious class3 "
3571                            "failed: ret=%d (%s)",
3572                            ret, strerror(-ret));
3573                 goto nla_put_failure;
3574         }
3575         ret = 0;
3576 nla_put_failure:
3577         nlmsg_free(msg);
3578         return ret;
3579 }
3580
3581
3582 static int nl80211_mgmt_subscribe_ap(struct i802_bss *bss)
3583 {
3584         static const int stypes[] = {
3585                 WLAN_FC_STYPE_AUTH,
3586                 WLAN_FC_STYPE_ASSOC_REQ,
3587                 WLAN_FC_STYPE_REASSOC_REQ,
3588                 WLAN_FC_STYPE_DISASSOC,
3589                 WLAN_FC_STYPE_DEAUTH,
3590                 WLAN_FC_STYPE_ACTION,
3591                 WLAN_FC_STYPE_PROBE_REQ,
3592 /* Beacon doesn't work as mac80211 doesn't currently allow
3593  * it, but it wouldn't really be the right thing anyway as
3594  * it isn't per interface ... maybe just dump the scan
3595  * results periodically for OLBC?
3596  */
3597 //              WLAN_FC_STYPE_BEACON,
3598         };
3599         unsigned int i;
3600
3601         if (nl80211_alloc_mgmt_handle(bss))
3602                 return -1;
3603         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3604                    "handle %p", bss->nl_mgmt);
3605
3606         for (i = 0; i < sizeof(stypes) / sizeof(stypes[0]); i++) {
3607                 if (nl80211_register_frame(bss, bss->nl_mgmt,
3608                                            (WLAN_FC_TYPE_MGMT << 2) |
3609                                            (stypes[i] << 4),
3610                                            NULL, 0) < 0) {
3611                         goto out_err;
3612                 }
3613         }
3614
3615         if (nl80211_register_spurious_class3(bss))
3616                 goto out_err;
3617
3618         if (nl80211_get_wiphy_data_ap(bss) == NULL)
3619                 goto out_err;
3620
3621         return 0;
3622
3623 out_err:
3624         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3625         nl_destroy_handles(&bss->nl_mgmt);
3626         return -1;
3627 }
3628
3629
3630 static int nl80211_mgmt_subscribe_ap_dev_sme(struct i802_bss *bss)
3631 {
3632         if (nl80211_alloc_mgmt_handle(bss))
3633                 return -1;
3634         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3635                    "handle %p (device SME)", bss->nl_mgmt);
3636
3637         if (nl80211_register_frame(bss, bss->nl_mgmt,
3638                                    (WLAN_FC_TYPE_MGMT << 2) |
3639                                    (WLAN_FC_STYPE_ACTION << 4),
3640                                    NULL, 0) < 0)
3641                 goto out_err;
3642
3643         return 0;
3644
3645 out_err:
3646         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3647         nl_destroy_handles(&bss->nl_mgmt);
3648         return -1;
3649 }
3650
3651
3652 static void nl80211_mgmt_unsubscribe(struct i802_bss *bss, const char *reason)
3653 {
3654         if (bss->nl_mgmt == NULL)
3655                 return;
3656         wpa_printf(MSG_DEBUG, "nl80211: Unsubscribe mgmt frames handle %p "
3657                    "(%s)", bss->nl_mgmt, reason);
3658         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3659         nl_destroy_handles(&bss->nl_mgmt);
3660
3661         nl80211_put_wiphy_data_ap(bss);
3662 }
3663
3664
3665 static void wpa_driver_nl80211_send_rfkill(void *eloop_ctx, void *timeout_ctx)
3666 {
3667         wpa_supplicant_event(timeout_ctx, EVENT_INTERFACE_DISABLED, NULL);
3668 }
3669
3670
3671 static int
3672 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv)
3673 {
3674         struct i802_bss *bss = &drv->first_bss;
3675         int send_rfkill_event = 0;
3676
3677         drv->ifindex = if_nametoindex(bss->ifname);
3678         drv->first_bss.ifindex = drv->ifindex;
3679
3680 #ifndef HOSTAPD
3681         /*
3682          * Make sure the interface starts up in station mode unless this is a
3683          * dynamically added interface (e.g., P2P) that was already configured
3684          * with proper iftype.
3685          */
3686         if (drv->ifindex != drv->global->if_add_ifindex &&
3687             wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION) < 0) {
3688                 wpa_printf(MSG_ERROR, "nl80211: Could not configure driver to "
3689                            "use managed mode");
3690                 return -1;
3691         }
3692
3693         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
3694                 if (rfkill_is_blocked(drv->rfkill)) {
3695                         wpa_printf(MSG_DEBUG, "nl80211: Could not yet enable "
3696                                    "interface '%s' due to rfkill",
3697                                    bss->ifname);
3698                         drv->if_disabled = 1;
3699                         send_rfkill_event = 1;
3700                 } else {
3701                         wpa_printf(MSG_ERROR, "nl80211: Could not set "
3702                                    "interface '%s' UP", bss->ifname);
3703                         return -1;
3704                 }
3705         }
3706
3707         netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
3708                                1, IF_OPER_DORMANT);
3709 #endif /* HOSTAPD */
3710
3711         if (wpa_driver_nl80211_capa(drv))
3712                 return -1;
3713
3714         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
3715                                bss->addr))
3716                 return -1;
3717
3718         if (send_rfkill_event) {
3719                 eloop_register_timeout(0, 0, wpa_driver_nl80211_send_rfkill,
3720                                        drv, drv->ctx);
3721         }
3722
3723         return 0;
3724 }
3725
3726
3727 static int wpa_driver_nl80211_del_beacon(struct wpa_driver_nl80211_data *drv)
3728 {
3729         struct nl_msg *msg;
3730
3731         msg = nlmsg_alloc();
3732         if (!msg)
3733                 return -ENOMEM;
3734
3735         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_BEACON);
3736         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3737
3738         return send_and_recv_msgs(drv, msg, NULL, NULL);
3739  nla_put_failure:
3740         nlmsg_free(msg);
3741         return -ENOBUFS;
3742 }
3743
3744
3745 /**
3746  * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
3747  * @bss: Pointer to private nl80211 data from wpa_driver_nl80211_init()
3748  *
3749  * Shut down driver interface and processing of driver events. Free
3750  * private data buffer if one was allocated in wpa_driver_nl80211_init().
3751  */
3752 static void wpa_driver_nl80211_deinit(struct i802_bss *bss)
3753 {
3754         struct wpa_driver_nl80211_data *drv = bss->drv;
3755
3756         bss->in_deinit = 1;
3757         if (drv->data_tx_status)
3758                 eloop_unregister_read_sock(drv->eapol_tx_sock);
3759         if (drv->eapol_tx_sock >= 0)
3760                 close(drv->eapol_tx_sock);
3761
3762         if (bss->nl_preq)
3763                 wpa_driver_nl80211_probe_req_report(bss, 0);
3764         if (bss->added_if_into_bridge) {
3765                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
3766                                     bss->ifname) < 0)
3767                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3768                                    "interface %s from bridge %s: %s",
3769                                    bss->ifname, bss->brname, strerror(errno));
3770         }
3771         if (bss->added_bridge) {
3772                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
3773                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3774                                    "bridge %s: %s",
3775                                    bss->brname, strerror(errno));
3776         }
3777
3778         nl80211_remove_monitor_interface(drv);
3779
3780         if (is_ap_interface(drv->nlmode))
3781                 wpa_driver_nl80211_del_beacon(drv);
3782
3783 #ifdef HOSTAPD
3784         if (drv->last_freq_ht) {
3785                 /* Clear HT flags from the driver */
3786                 struct hostapd_freq_params freq;
3787                 os_memset(&freq, 0, sizeof(freq));
3788                 freq.freq = drv->last_freq;
3789                 wpa_driver_nl80211_set_freq(bss, &freq);
3790         }
3791
3792         if (drv->eapol_sock >= 0) {
3793                 eloop_unregister_read_sock(drv->eapol_sock);
3794                 close(drv->eapol_sock);
3795         }
3796
3797         if (drv->if_indices != drv->default_if_indices)
3798                 os_free(drv->if_indices);
3799 #endif /* HOSTAPD */
3800
3801         if (drv->disabled_11b_rates)
3802                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
3803
3804         netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, 0,
3805                                IF_OPER_UP);
3806         rfkill_deinit(drv->rfkill);
3807
3808         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3809
3810         (void) linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0);
3811         wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION);
3812         nl80211_mgmt_unsubscribe(bss, "deinit");
3813
3814         nl_cb_put(drv->nl_cb);
3815
3816         nl80211_destroy_bss(&drv->first_bss);
3817
3818         os_free(drv->filter_ssids);
3819
3820         os_free(drv->auth_ie);
3821
3822         if (drv->in_interface_list)
3823                 dl_list_del(&drv->list);
3824
3825         os_free(drv->extended_capa);
3826         os_free(drv->extended_capa_mask);
3827         os_free(drv);
3828 }
3829
3830
3831 /**
3832  * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
3833  * @eloop_ctx: Driver private data
3834  * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
3835  *
3836  * This function can be used as registered timeout when starting a scan to
3837  * generate a scan completed event if the driver does not report this.
3838  */
3839 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
3840 {
3841         struct wpa_driver_nl80211_data *drv = eloop_ctx;
3842         if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED) {
3843                 wpa_driver_nl80211_set_mode(&drv->first_bss,
3844                                             drv->ap_scan_as_station);
3845                 drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
3846         }
3847         wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
3848         wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
3849 }
3850
3851
3852 static struct nl_msg *
3853 nl80211_scan_common(struct wpa_driver_nl80211_data *drv, u8 cmd,
3854                     struct wpa_driver_scan_params *params)
3855 {
3856         struct nl_msg *msg;
3857         size_t i;
3858
3859         msg = nlmsg_alloc();
3860         if (!msg)
3861                 return NULL;
3862
3863         nl80211_cmd(drv, msg, 0, cmd);
3864
3865         if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, drv->ifindex) < 0)
3866                 goto fail;
3867
3868         if (params->num_ssids) {
3869                 struct nlattr *ssids;
3870
3871                 ssids = nla_nest_start(msg, NL80211_ATTR_SCAN_SSIDS);
3872                 if (ssids == NULL)
3873                         goto fail;
3874                 for (i = 0; i < params->num_ssids; i++) {
3875                         wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan SSID",
3876                                           params->ssids[i].ssid,
3877                                           params->ssids[i].ssid_len);
3878                         if (nla_put(msg, i + 1, params->ssids[i].ssid_len,
3879                                     params->ssids[i].ssid) < 0)
3880                                 goto fail;
3881                 }
3882                 nla_nest_end(msg, ssids);
3883         }
3884
3885         if (params->extra_ies) {
3886                 wpa_hexdump(MSG_MSGDUMP, "nl80211: Scan extra IEs",
3887                             params->extra_ies, params->extra_ies_len);
3888                 if (nla_put(msg, NL80211_ATTR_IE, params->extra_ies_len,
3889                             params->extra_ies) < 0)
3890                         goto fail;
3891         }
3892
3893         if (params->freqs) {
3894                 struct nlattr *freqs;
3895                 freqs = nla_nest_start(msg, NL80211_ATTR_SCAN_FREQUENCIES);
3896                 if (freqs == NULL)
3897                         goto fail;
3898                 for (i = 0; params->freqs[i]; i++) {
3899                         wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
3900                                    "MHz", params->freqs[i]);
3901                         if (nla_put_u32(msg, i + 1, params->freqs[i]) < 0)
3902                                 goto fail;
3903                 }
3904                 nla_nest_end(msg, freqs);
3905         }
3906
3907         os_free(drv->filter_ssids);
3908         drv->filter_ssids = params->filter_ssids;
3909         params->filter_ssids = NULL;
3910         drv->num_filter_ssids = params->num_filter_ssids;
3911
3912         return msg;
3913
3914 fail:
3915         nlmsg_free(msg);
3916         return NULL;
3917 }
3918
3919
3920 /**
3921  * wpa_driver_nl80211_scan - Request the driver to initiate scan
3922  * @bss: Pointer to private driver data from wpa_driver_nl80211_init()
3923  * @params: Scan parameters
3924  * Returns: 0 on success, -1 on failure
3925  */
3926 static int wpa_driver_nl80211_scan(struct i802_bss *bss,
3927                                    struct wpa_driver_scan_params *params)
3928 {
3929         struct wpa_driver_nl80211_data *drv = bss->drv;
3930         int ret = -1, timeout;
3931         struct nl_msg *msg = NULL;
3932
3933         wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: scan request");
3934         drv->scan_for_auth = 0;
3935
3936         msg = nl80211_scan_common(drv, NL80211_CMD_TRIGGER_SCAN, params);
3937         if (!msg)
3938                 return -1;
3939
3940         if (params->p2p_probe) {
3941                 struct nlattr *rates;
3942
3943                 wpa_printf(MSG_DEBUG, "nl80211: P2P probe - mask SuppRates");
3944
3945                 rates = nla_nest_start(msg, NL80211_ATTR_SCAN_SUPP_RATES);
3946                 if (rates == NULL)
3947                         goto nla_put_failure;
3948
3949                 /*
3950                  * Remove 2.4 GHz rates 1, 2, 5.5, 11 Mbps from supported rates
3951                  * by masking out everything else apart from the OFDM rates 6,
3952                  * 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS rates. All 5 GHz
3953                  * rates are left enabled.
3954                  */
3955                 NLA_PUT(msg, NL80211_BAND_2GHZ, 8,
3956                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
3957                 nla_nest_end(msg, rates);
3958
3959                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
3960         }
3961
3962         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3963         msg = NULL;
3964         if (ret) {
3965                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
3966                            "(%s)", ret, strerror(-ret));
3967 #ifdef HOSTAPD
3968                 if (is_ap_interface(drv->nlmode)) {
3969                         /*
3970                          * mac80211 does not allow scan requests in AP mode, so
3971                          * try to do this in station mode.
3972                          */
3973                         if (wpa_driver_nl80211_set_mode(
3974                                     bss, NL80211_IFTYPE_STATION))
3975                                 goto nla_put_failure;
3976
3977                         if (wpa_driver_nl80211_scan(bss, params)) {
3978                                 wpa_driver_nl80211_set_mode(bss, drv->nlmode);
3979                                 goto nla_put_failure;
3980                         }
3981
3982                         /* Restore AP mode when processing scan results */
3983                         drv->ap_scan_as_station = drv->nlmode;
3984                         ret = 0;
3985                 } else
3986                         goto nla_put_failure;
3987 #else /* HOSTAPD */
3988                 goto nla_put_failure;
3989 #endif /* HOSTAPD */
3990         }
3991
3992         /* Not all drivers generate "scan completed" wireless event, so try to
3993          * read results after a timeout. */
3994         timeout = 10;
3995         if (drv->scan_complete_events) {
3996                 /*
3997                  * The driver seems to deliver events to notify when scan is
3998                  * complete, so use longer timeout to avoid race conditions
3999                  * with scanning and following association request.
4000                  */
4001                 timeout = 30;
4002         }
4003         wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
4004                    "seconds", ret, timeout);
4005         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
4006         eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
4007                                drv, drv->ctx);
4008
4009 nla_put_failure:
4010         nlmsg_free(msg);
4011         return ret;
4012 }
4013
4014
4015 /**
4016  * wpa_driver_nl80211_sched_scan - Initiate a scheduled scan
4017  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
4018  * @params: Scan parameters
4019  * @interval: Interval between scan cycles in milliseconds
4020  * Returns: 0 on success, -1 on failure or if not supported
4021  */
4022 static int wpa_driver_nl80211_sched_scan(void *priv,
4023                                          struct wpa_driver_scan_params *params,
4024                                          u32 interval)
4025 {
4026         struct i802_bss *bss = priv;
4027         struct wpa_driver_nl80211_data *drv = bss->drv;
4028         int ret = -1;
4029         struct nl_msg *msg;
4030         size_t i;
4031
4032         wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: sched_scan request");
4033
4034 #ifdef ANDROID
4035         if (!drv->capa.sched_scan_supported)
4036                 return android_pno_start(bss, params);
4037 #endif /* ANDROID */
4038
4039         msg = nl80211_scan_common(drv, NL80211_CMD_START_SCHED_SCAN, params);
4040         if (!msg)
4041                 goto nla_put_failure;
4042
4043         NLA_PUT_U32(msg, NL80211_ATTR_SCHED_SCAN_INTERVAL, interval);
4044
4045         if ((drv->num_filter_ssids &&
4046             (int) drv->num_filter_ssids <= drv->capa.max_match_sets) ||
4047             params->filter_rssi) {
4048                 struct nlattr *match_sets;
4049                 match_sets = nla_nest_start(msg, NL80211_ATTR_SCHED_SCAN_MATCH);
4050                 if (match_sets == NULL)
4051                         goto nla_put_failure;
4052
4053                 for (i = 0; i < drv->num_filter_ssids; i++) {
4054                         struct nlattr *match_set_ssid;
4055                         wpa_hexdump_ascii(MSG_MSGDUMP,
4056                                           "nl80211: Sched scan filter SSID",
4057                                           drv->filter_ssids[i].ssid,
4058                                           drv->filter_ssids[i].ssid_len);
4059
4060                         match_set_ssid = nla_nest_start(msg, i + 1);
4061                         if (match_set_ssid == NULL)
4062                                 goto nla_put_failure;
4063                         NLA_PUT(msg, NL80211_ATTR_SCHED_SCAN_MATCH_SSID,
4064                                 drv->filter_ssids[i].ssid_len,
4065                                 drv->filter_ssids[i].ssid);
4066
4067                         nla_nest_end(msg, match_set_ssid);
4068                 }
4069
4070                 if (params->filter_rssi) {
4071                         struct nlattr *match_set_rssi;
4072                         match_set_rssi = nla_nest_start(msg, 0);
4073                         if (match_set_rssi == NULL)
4074                                 goto nla_put_failure;
4075                         NLA_PUT_U32(msg, NL80211_SCHED_SCAN_MATCH_ATTR_RSSI,
4076                                     params->filter_rssi);
4077                         wpa_printf(MSG_MSGDUMP,
4078                                    "nl80211: Sched scan RSSI filter %d dBm",
4079                                    params->filter_rssi);
4080                         nla_nest_end(msg, match_set_rssi);
4081                 }
4082
4083                 nla_nest_end(msg, match_sets);
4084         }
4085
4086         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4087
4088         /* TODO: if we get an error here, we should fall back to normal scan */
4089
4090         msg = NULL;
4091         if (ret) {
4092                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan start failed: "
4093                            "ret=%d (%s)", ret, strerror(-ret));
4094                 goto nla_put_failure;
4095         }
4096
4097         wpa_printf(MSG_DEBUG, "nl80211: Sched scan requested (ret=%d) - "
4098                    "scan interval %d msec", ret, interval);
4099
4100 nla_put_failure:
4101         nlmsg_free(msg);
4102         return ret;
4103 }
4104
4105
4106 /**
4107  * wpa_driver_nl80211_stop_sched_scan - Stop a scheduled scan
4108  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
4109  * Returns: 0 on success, -1 on failure or if not supported
4110  */
4111 static int wpa_driver_nl80211_stop_sched_scan(void *priv)
4112 {
4113         struct i802_bss *bss = priv;
4114         struct wpa_driver_nl80211_data *drv = bss->drv;
4115         int ret = 0;
4116         struct nl_msg *msg;
4117
4118 #ifdef ANDROID
4119         if (!drv->capa.sched_scan_supported)
4120                 return android_pno_stop(bss);
4121 #endif /* ANDROID */
4122
4123         msg = nlmsg_alloc();
4124         if (!msg)
4125                 return -1;
4126
4127         nl80211_cmd(drv, msg, 0, NL80211_CMD_STOP_SCHED_SCAN);
4128
4129         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4130
4131         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4132         msg = NULL;
4133         if (ret) {
4134                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop failed: "
4135                            "ret=%d (%s)", ret, strerror(-ret));
4136                 goto nla_put_failure;
4137         }
4138
4139         wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop sent (ret=%d)", ret);
4140
4141 nla_put_failure:
4142         nlmsg_free(msg);
4143         return ret;
4144 }
4145
4146
4147 static const u8 * nl80211_get_ie(const u8 *ies, size_t ies_len, u8 ie)
4148 {
4149         const u8 *end, *pos;
4150
4151         if (ies == NULL)
4152                 return NULL;
4153
4154         pos = ies;
4155         end = ies + ies_len;
4156
4157         while (pos + 1 < end) {
4158                 if (pos + 2 + pos[1] > end)
4159                         break;
4160                 if (pos[0] == ie)
4161                         return pos;
4162                 pos += 2 + pos[1];
4163         }
4164
4165         return NULL;
4166 }
4167
4168
4169 static int nl80211_scan_filtered(struct wpa_driver_nl80211_data *drv,
4170                                  const u8 *ie, size_t ie_len)
4171 {
4172         const u8 *ssid;
4173         size_t i;
4174
4175         if (drv->filter_ssids == NULL)
4176                 return 0;
4177
4178         ssid = nl80211_get_ie(ie, ie_len, WLAN_EID_SSID);
4179         if (ssid == NULL)
4180                 return 1;
4181
4182         for (i = 0; i < drv->num_filter_ssids; i++) {
4183                 if (ssid[1] == drv->filter_ssids[i].ssid_len &&
4184                     os_memcmp(ssid + 2, drv->filter_ssids[i].ssid, ssid[1]) ==
4185                     0)
4186                         return 0;
4187         }
4188
4189         return 1;
4190 }
4191
4192
4193 static int bss_info_handler(struct nl_msg *msg, void *arg)
4194 {
4195         struct nlattr *tb[NL80211_ATTR_MAX + 1];
4196         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
4197         struct nlattr *bss[NL80211_BSS_MAX + 1];
4198         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
4199                 [NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
4200                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
4201                 [NL80211_BSS_TSF] = { .type = NLA_U64 },
4202                 [NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
4203                 [NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
4204                 [NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
4205                 [NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
4206                 [NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
4207                 [NL80211_BSS_STATUS] = { .type = NLA_U32 },
4208                 [NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
4209                 [NL80211_BSS_BEACON_IES] = { .type = NLA_UNSPEC },
4210         };
4211         struct nl80211_bss_info_arg *_arg = arg;
4212         struct wpa_scan_results *res = _arg->res;
4213         struct wpa_scan_res **tmp;
4214         struct wpa_scan_res *r;
4215         const u8 *ie, *beacon_ie;
4216         size_t ie_len, beacon_ie_len;
4217         u8 *pos;
4218         size_t i;
4219
4220         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
4221                   genlmsg_attrlen(gnlh, 0), NULL);
4222         if (!tb[NL80211_ATTR_BSS])
4223                 return NL_SKIP;
4224         if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
4225                              bss_policy))
4226                 return NL_SKIP;
4227         if (bss[NL80211_BSS_STATUS]) {
4228                 enum nl80211_bss_status status;
4229                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
4230                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
4231                     bss[NL80211_BSS_FREQUENCY]) {
4232                         _arg->assoc_freq =
4233                                 nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
4234                         wpa_printf(MSG_DEBUG, "nl80211: Associated on %u MHz",
4235                                    _arg->assoc_freq);
4236                 }
4237                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
4238                     bss[NL80211_BSS_BSSID]) {
4239                         os_memcpy(_arg->assoc_bssid,
4240                                   nla_data(bss[NL80211_BSS_BSSID]), ETH_ALEN);
4241                         wpa_printf(MSG_DEBUG, "nl80211: Associated with "
4242                                    MACSTR, MAC2STR(_arg->assoc_bssid));
4243                 }
4244         }
4245         if (!res)
4246                 return NL_SKIP;
4247         if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
4248                 ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
4249                 ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
4250         } else {
4251                 ie = NULL;
4252                 ie_len = 0;
4253         }
4254         if (bss[NL80211_BSS_BEACON_IES]) {
4255                 beacon_ie = nla_data(bss[NL80211_BSS_BEACON_IES]);
4256                 beacon_ie_len = nla_len(bss[NL80211_BSS_BEACON_IES]);
4257         } else {
4258                 beacon_ie = NULL;
4259                 beacon_ie_len = 0;
4260         }
4261
4262         if (nl80211_scan_filtered(_arg->drv, ie ? ie : beacon_ie,
4263                                   ie ? ie_len : beacon_ie_len))
4264                 return NL_SKIP;
4265
4266         r = os_zalloc(sizeof(*r) + ie_len + beacon_ie_len);
4267         if (r == NULL)
4268                 return NL_SKIP;
4269         if (bss[NL80211_BSS_BSSID])
4270                 os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
4271                           ETH_ALEN);
4272         if (bss[NL80211_BSS_FREQUENCY])
4273                 r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
4274         if (bss[NL80211_BSS_BEACON_INTERVAL])
4275                 r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
4276         if (bss[NL80211_BSS_CAPABILITY])
4277                 r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
4278         r->flags |= WPA_SCAN_NOISE_INVALID;
4279         if (bss[NL80211_BSS_SIGNAL_MBM]) {
4280                 r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
4281                 r->level /= 100; /* mBm to dBm */
4282                 r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
4283         } else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
4284                 r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
4285                 r->flags |= WPA_SCAN_QUAL_INVALID;
4286         } else
4287                 r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
4288         if (bss[NL80211_BSS_TSF])
4289                 r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
4290         if (bss[NL80211_BSS_SEEN_MS_AGO])
4291                 r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
4292         r->ie_len = ie_len;
4293         pos = (u8 *) (r + 1);
4294         if (ie) {
4295                 os_memcpy(pos, ie, ie_len);
4296                 pos += ie_len;
4297         }
4298         r->beacon_ie_len = beacon_ie_len;
4299         if (beacon_ie)
4300                 os_memcpy(pos, beacon_ie, beacon_ie_len);
4301
4302         if (bss[NL80211_BSS_STATUS]) {
4303                 enum nl80211_bss_status status;
4304                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
4305                 switch (status) {
4306                 case NL80211_BSS_STATUS_AUTHENTICATED:
4307                         r->flags |= WPA_SCAN_AUTHENTICATED;
4308                         break;
4309                 case NL80211_BSS_STATUS_ASSOCIATED:
4310                         r->flags |= WPA_SCAN_ASSOCIATED;
4311                         break;
4312                 default:
4313                         break;
4314                 }
4315         }
4316
4317         /*
4318          * cfg80211 maintains separate BSS table entries for APs if the same
4319          * BSSID,SSID pair is seen on multiple channels. wpa_supplicant does
4320          * not use frequency as a separate key in the BSS table, so filter out
4321          * duplicated entries. Prefer associated BSS entry in such a case in
4322          * order to get the correct frequency into the BSS table.
4323          */
4324         for (i = 0; i < res->num; i++) {
4325                 const u8 *s1, *s2;
4326                 if (os_memcmp(res->res[i]->bssid, r->bssid, ETH_ALEN) != 0)
4327                         continue;
4328
4329                 s1 = nl80211_get_ie((u8 *) (res->res[i] + 1),
4330                                     res->res[i]->ie_len, WLAN_EID_SSID);
4331                 s2 = nl80211_get_ie((u8 *) (r + 1), r->ie_len, WLAN_EID_SSID);
4332                 if (s1 == NULL || s2 == NULL || s1[1] != s2[1] ||
4333                     os_memcmp(s1, s2, 2 + s1[1]) != 0)
4334                         continue;
4335
4336                 /* Same BSSID,SSID was already included in scan results */
4337                 wpa_printf(MSG_DEBUG, "nl80211: Remove duplicated scan result "
4338                            "for " MACSTR, MAC2STR(r->bssid));
4339
4340                 if ((r->flags & WPA_SCAN_ASSOCIATED) &&
4341                     !(res->res[i]->flags & WPA_SCAN_ASSOCIATED)) {
4342                         os_free(res->res[i]);
4343                         res->res[i] = r;
4344                 } else
4345                         os_free(r);
4346                 return NL_SKIP;
4347         }
4348
4349         tmp = os_realloc_array(res->res, res->num + 1,
4350                                sizeof(struct wpa_scan_res *));
4351         if (tmp == NULL) {
4352                 os_free(r);
4353                 return NL_SKIP;
4354         }
4355         tmp[res->num++] = r;
4356         res->res = tmp;
4357
4358         return NL_SKIP;
4359 }
4360
4361
4362 static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
4363                                  const u8 *addr)
4364 {
4365         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
4366                 wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
4367                            "mismatch (" MACSTR ")", MAC2STR(addr));
4368                 wpa_driver_nl80211_mlme(drv, addr,
4369                                         NL80211_CMD_DEAUTHENTICATE,
4370                                         WLAN_REASON_PREV_AUTH_NOT_VALID, 1);
4371         }
4372 }
4373
4374
4375 static void wpa_driver_nl80211_check_bss_status(
4376         struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
4377 {
4378         size_t i;
4379
4380         for (i = 0; i < res->num; i++) {
4381                 struct wpa_scan_res *r = res->res[i];
4382                 if (r->flags & WPA_SCAN_AUTHENTICATED) {
4383                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
4384                                    "indicates BSS status with " MACSTR
4385                                    " as authenticated",
4386                                    MAC2STR(r->bssid));
4387                         if (is_sta_interface(drv->nlmode) &&
4388                             os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
4389                             os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
4390                             0) {
4391                                 wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
4392                                            " in local state (auth=" MACSTR
4393                                            " assoc=" MACSTR ")",
4394                                            MAC2STR(drv->auth_bssid),
4395                                            MAC2STR(drv->bssid));
4396                                 clear_state_mismatch(drv, r->bssid);
4397                         }
4398                 }
4399
4400                 if (r->flags & WPA_SCAN_ASSOCIATED) {
4401                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
4402                                    "indicate BSS status with " MACSTR
4403                                    " as associated",
4404                                    MAC2STR(r->bssid));
4405                         if (is_sta_interface(drv->nlmode) &&
4406                             !drv->associated) {
4407                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
4408                                            "(not associated) does not match "
4409                                            "with BSS state");
4410                                 clear_state_mismatch(drv, r->bssid);
4411                         } else if (is_sta_interface(drv->nlmode) &&
4412                                    os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
4413                                    0) {
4414                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
4415                                            "(associated with " MACSTR ") does "
4416                                            "not match with BSS state",
4417                                            MAC2STR(drv->bssid));
4418                                 clear_state_mismatch(drv, r->bssid);
4419                                 clear_state_mismatch(drv, drv->bssid);
4420                         }
4421                 }
4422         }
4423 }
4424
4425
4426 static struct wpa_scan_results *
4427 nl80211_get_scan_results(struct wpa_driver_nl80211_data *drv)
4428 {
4429         struct nl_msg *msg;
4430         struct wpa_scan_results *res;
4431         int ret;
4432         struct nl80211_bss_info_arg arg;
4433
4434         res = os_zalloc(sizeof(*res));
4435         if (res == NULL)
4436                 return NULL;
4437         msg = nlmsg_alloc();
4438         if (!msg)
4439                 goto nla_put_failure;
4440
4441         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
4442         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4443
4444         arg.drv = drv;
4445         arg.res = res;
4446         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
4447         msg = NULL;
4448         if (ret == 0) {
4449                 wpa_printf(MSG_DEBUG, "nl80211: Received scan results (%lu "
4450                            "BSSes)", (unsigned long) res->num);
4451                 nl80211_get_noise_for_scan_results(drv, res);
4452                 return res;
4453         }
4454         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
4455                    "(%s)", ret, strerror(-ret));
4456 nla_put_failure:
4457         nlmsg_free(msg);
4458         wpa_scan_results_free(res);
4459         return NULL;
4460 }
4461
4462
4463 /**
4464  * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
4465  * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
4466  * Returns: Scan results on success, -1 on failure
4467  */
4468 static struct wpa_scan_results *
4469 wpa_driver_nl80211_get_scan_results(void *priv)
4470 {
4471         struct i802_bss *bss = priv;
4472         struct wpa_driver_nl80211_data *drv = bss->drv;
4473         struct wpa_scan_results *res;
4474
4475         res = nl80211_get_scan_results(drv);
4476         if (res)
4477                 wpa_driver_nl80211_check_bss_status(drv, res);
4478         return res;
4479 }
4480
4481
4482 static void nl80211_dump_scan(struct wpa_driver_nl80211_data *drv)
4483 {
4484         struct wpa_scan_results *res;
4485         size_t i;
4486
4487         res = nl80211_get_scan_results(drv);
4488         if (res == NULL) {
4489                 wpa_printf(MSG_DEBUG, "nl80211: Failed to get scan results");
4490                 return;
4491         }
4492
4493         wpa_printf(MSG_DEBUG, "nl80211: Scan result dump");
4494         for (i = 0; i < res->num; i++) {
4495                 struct wpa_scan_res *r = res->res[i];
4496                 wpa_printf(MSG_DEBUG, "nl80211: %d/%d " MACSTR "%s%s",
4497                            (int) i, (int) res->num, MAC2STR(r->bssid),
4498                            r->flags & WPA_SCAN_AUTHENTICATED ? " [auth]" : "",
4499                            r->flags & WPA_SCAN_ASSOCIATED ? " [assoc]" : "");
4500         }
4501
4502         wpa_scan_results_free(res);
4503 }
4504
4505
4506 static int wpa_driver_nl80211_set_key(const char *ifname, struct i802_bss *bss,
4507                                       enum wpa_alg alg, const u8 *addr,
4508                                       int key_idx, int set_tx,
4509                                       const u8 *seq, size_t seq_len,
4510                                       const u8 *key, size_t key_len)
4511 {
4512         struct wpa_driver_nl80211_data *drv = bss->drv;
4513         int ifindex = if_nametoindex(ifname);
4514         struct nl_msg *msg;
4515         int ret;
4516
4517         wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
4518                    "set_tx=%d seq_len=%lu key_len=%lu",
4519                    __func__, ifindex, alg, addr, key_idx, set_tx,
4520                    (unsigned long) seq_len, (unsigned long) key_len);
4521 #ifdef CONFIG_TDLS
4522         if (key_idx == -1)
4523                 key_idx = 0;
4524 #endif /* CONFIG_TDLS */
4525
4526         msg = nlmsg_alloc();
4527         if (!msg)
4528                 return -ENOMEM;
4529
4530         if (alg == WPA_ALG_NONE) {
4531                 nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_KEY);
4532         } else {
4533                 nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_KEY);
4534                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
4535                 switch (alg) {
4536                 case WPA_ALG_WEP:
4537                         if (key_len == 5)
4538                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4539                                             WLAN_CIPHER_SUITE_WEP40);
4540                         else
4541                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4542                                             WLAN_CIPHER_SUITE_WEP104);
4543                         break;
4544                 case WPA_ALG_TKIP:
4545                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4546                                     WLAN_CIPHER_SUITE_TKIP);
4547                         break;
4548                 case WPA_ALG_CCMP:
4549                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4550                                     WLAN_CIPHER_SUITE_CCMP);
4551                         break;
4552                 case WPA_ALG_GCMP:
4553                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4554                                     WLAN_CIPHER_SUITE_GCMP);
4555                         break;
4556                 case WPA_ALG_IGTK:
4557                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4558                                     WLAN_CIPHER_SUITE_AES_CMAC);
4559                         break;
4560                 case WPA_ALG_SMS4:
4561                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4562                                     WLAN_CIPHER_SUITE_SMS4);
4563                         break;
4564                 case WPA_ALG_KRK:
4565                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4566                                     WLAN_CIPHER_SUITE_KRK);
4567                         break;
4568                 default:
4569                         wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4570                                    "algorithm %d", __func__, alg);
4571                         nlmsg_free(msg);
4572                         return -1;
4573                 }
4574         }
4575
4576         if (seq && seq_len)
4577                 NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
4578
4579         if (addr && !is_broadcast_ether_addr(addr)) {
4580                 wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
4581                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4582
4583                 if (alg != WPA_ALG_WEP && key_idx && !set_tx) {
4584                         wpa_printf(MSG_DEBUG, "   RSN IBSS RX GTK");
4585                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_TYPE,
4586                                     NL80211_KEYTYPE_GROUP);
4587                 }
4588         } else if (addr && is_broadcast_ether_addr(addr)) {
4589                 struct nlattr *types;
4590
4591                 wpa_printf(MSG_DEBUG, "   broadcast key");
4592
4593                 types = nla_nest_start(msg, NL80211_ATTR_KEY_DEFAULT_TYPES);
4594                 if (!types)
4595                         goto nla_put_failure;
4596                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4597                 nla_nest_end(msg, types);
4598         }
4599         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4600         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4601
4602         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4603         if ((ret == -ENOENT || ret == -ENOLINK) && alg == WPA_ALG_NONE)
4604                 ret = 0;
4605         if (ret)
4606                 wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
4607                            ret, strerror(-ret));
4608
4609         /*
4610          * If we failed or don't need to set the default TX key (below),
4611          * we're done here.
4612          */
4613         if (ret || !set_tx || alg == WPA_ALG_NONE)
4614                 return ret;
4615         if (is_ap_interface(drv->nlmode) && addr &&
4616             !is_broadcast_ether_addr(addr))
4617                 return ret;
4618
4619         msg = nlmsg_alloc();
4620         if (!msg)
4621                 return -ENOMEM;
4622
4623         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_KEY);
4624         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4625         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4626         if (alg == WPA_ALG_IGTK)
4627                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
4628         else
4629                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
4630         if (addr && is_broadcast_ether_addr(addr)) {
4631                 struct nlattr *types;
4632
4633                 types = nla_nest_start(msg, NL80211_ATTR_KEY_DEFAULT_TYPES);
4634                 if (!types)
4635                         goto nla_put_failure;
4636                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4637                 nla_nest_end(msg, types);
4638         } else if (addr) {
4639                 struct nlattr *types;
4640
4641                 types = nla_nest_start(msg, NL80211_ATTR_KEY_DEFAULT_TYPES);
4642                 if (!types)
4643                         goto nla_put_failure;
4644                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_TYPE_UNICAST);
4645                 nla_nest_end(msg, types);
4646         }
4647
4648         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4649         if (ret == -ENOENT)
4650                 ret = 0;
4651         if (ret)
4652                 wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
4653                            "err=%d %s)", ret, strerror(-ret));
4654         return ret;
4655
4656 nla_put_failure:
4657         nlmsg_free(msg);
4658         return -ENOBUFS;
4659 }
4660
4661
4662 static int nl_add_key(struct nl_msg *msg, enum wpa_alg alg,
4663                       int key_idx, int defkey,
4664                       const u8 *seq, size_t seq_len,
4665                       const u8 *key, size_t key_len)
4666 {
4667         struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
4668         if (!key_attr)
4669                 return -1;
4670
4671         if (defkey && alg == WPA_ALG_IGTK)
4672                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
4673         else if (defkey)
4674                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4675
4676         NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
4677
4678         switch (alg) {
4679         case WPA_ALG_WEP:
4680                 if (key_len == 5)
4681                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4682                                     WLAN_CIPHER_SUITE_WEP40);
4683                 else
4684                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4685                                     WLAN_CIPHER_SUITE_WEP104);
4686                 break;
4687         case WPA_ALG_TKIP:
4688                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_TKIP);
4689                 break;
4690         case WPA_ALG_CCMP:
4691                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_CCMP);
4692                 break;
4693         case WPA_ALG_GCMP:
4694                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_GCMP);
4695                 break;
4696         case WPA_ALG_IGTK:
4697                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4698                             WLAN_CIPHER_SUITE_AES_CMAC);
4699                 break;
4700         default:
4701                 wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4702                            "algorithm %d", __func__, alg);
4703                 return -1;
4704         }
4705
4706         if (seq && seq_len)
4707                 NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
4708
4709         NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
4710
4711         nla_nest_end(msg, key_attr);
4712
4713         return 0;
4714  nla_put_failure:
4715         return -1;
4716 }
4717
4718
4719 static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
4720                                  struct nl_msg *msg)
4721 {
4722         int i, privacy = 0;
4723         struct nlattr *nl_keys, *nl_key;
4724
4725         for (i = 0; i < 4; i++) {
4726                 if (!params->wep_key[i])
4727                         continue;
4728                 privacy = 1;
4729                 break;
4730         }
4731         if (params->wps == WPS_MODE_PRIVACY)
4732                 privacy = 1;
4733         if (params->pairwise_suite &&
4734             params->pairwise_suite != WPA_CIPHER_NONE)
4735                 privacy = 1;
4736
4737         if (!privacy)
4738                 return 0;
4739
4740         NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
4741
4742         nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
4743         if (!nl_keys)
4744                 goto nla_put_failure;
4745
4746         for (i = 0; i < 4; i++) {
4747                 if (!params->wep_key[i])
4748                         continue;
4749
4750                 nl_key = nla_nest_start(msg, i);
4751                 if (!nl_key)
4752                         goto nla_put_failure;
4753
4754                 NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
4755                         params->wep_key[i]);
4756                 if (params->wep_key_len[i] == 5)
4757                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4758                                     WLAN_CIPHER_SUITE_WEP40);
4759                 else
4760                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4761                                     WLAN_CIPHER_SUITE_WEP104);
4762
4763                 NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
4764
4765                 if (i == params->wep_tx_keyidx)
4766                         NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4767
4768                 nla_nest_end(msg, nl_key);
4769         }
4770         nla_nest_end(msg, nl_keys);
4771
4772         return 0;
4773
4774 nla_put_failure:
4775         return -ENOBUFS;
4776 }
4777
4778
4779 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
4780                                    const u8 *addr, int cmd, u16 reason_code,
4781                                    int local_state_change)
4782 {
4783         int ret = -1;
4784         struct nl_msg *msg;
4785
4786         msg = nlmsg_alloc();
4787         if (!msg)
4788                 return -1;
4789
4790         nl80211_cmd(drv, msg, 0, cmd);
4791
4792         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4793         NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
4794         if (addr)
4795                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4796         if (local_state_change)
4797                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4798
4799         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4800         msg = NULL;
4801         if (ret) {
4802                 wpa_dbg(drv->ctx, MSG_DEBUG,
4803                         "nl80211: MLME command failed: reason=%u ret=%d (%s)",
4804                         reason_code, ret, strerror(-ret));
4805                 goto nla_put_failure;
4806         }
4807         ret = 0;
4808
4809 nla_put_failure:
4810         nlmsg_free(msg);
4811         return ret;
4812 }
4813
4814
4815 static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
4816                                          int reason_code)
4817 {
4818         wpa_printf(MSG_DEBUG, "%s(reason_code=%d)", __func__, reason_code);
4819         drv->associated = 0;
4820         drv->ignore_next_local_disconnect = 0;
4821         /* Disconnect command doesn't need BSSID - it uses cached value */
4822         return wpa_driver_nl80211_mlme(drv, NULL, NL80211_CMD_DISCONNECT,
4823                                        reason_code, 0);
4824 }
4825
4826
4827 static int wpa_driver_nl80211_deauthenticate(struct i802_bss *bss,
4828                                              const u8 *addr, int reason_code)
4829 {
4830         struct wpa_driver_nl80211_data *drv = bss->drv;
4831         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
4832                 return wpa_driver_nl80211_disconnect(drv, reason_code);
4833         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
4834                    __func__, MAC2STR(addr), reason_code);
4835         drv->associated = 0;
4836         if (drv->nlmode == NL80211_IFTYPE_ADHOC)
4837                 return nl80211_leave_ibss(drv);
4838         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
4839                                        reason_code, 0);
4840 }
4841
4842
4843 static void nl80211_copy_auth_params(struct wpa_driver_nl80211_data *drv,
4844                                      struct wpa_driver_auth_params *params)
4845 {
4846         int i;
4847
4848         drv->auth_freq = params->freq;
4849         drv->auth_alg = params->auth_alg;
4850         drv->auth_wep_tx_keyidx = params->wep_tx_keyidx;
4851         drv->auth_local_state_change = params->local_state_change;
4852         drv->auth_p2p = params->p2p;
4853
4854         if (params->bssid)
4855                 os_memcpy(drv->auth_bssid_, params->bssid, ETH_ALEN);
4856         else
4857                 os_memset(drv->auth_bssid_, 0, ETH_ALEN);
4858
4859         if (params->ssid) {
4860                 os_memcpy(drv->auth_ssid, params->ssid, params->ssid_len);
4861                 drv->auth_ssid_len = params->ssid_len;
4862         } else
4863                 drv->auth_ssid_len = 0;
4864
4865
4866         os_free(drv->auth_ie);
4867         drv->auth_ie = NULL;
4868         drv->auth_ie_len = 0;
4869         if (params->ie) {
4870                 drv->auth_ie = os_malloc(params->ie_len);
4871                 if (drv->auth_ie) {
4872                         os_memcpy(drv->auth_ie, params->ie, params->ie_len);
4873                         drv->auth_ie_len = params->ie_len;
4874                 }
4875         }
4876
4877         for (i = 0; i < 4; i++) {
4878                 if (params->wep_key[i] && params->wep_key_len[i] &&
4879                     params->wep_key_len[i] <= 16) {
4880                         os_memcpy(drv->auth_wep_key[i], params->wep_key[i],
4881                                   params->wep_key_len[i]);
4882                         drv->auth_wep_key_len[i] = params->wep_key_len[i];
4883                 } else
4884                         drv->auth_wep_key_len[i] = 0;
4885         }
4886 }
4887
4888
4889 static int wpa_driver_nl80211_authenticate(
4890         struct i802_bss *bss, struct wpa_driver_auth_params *params)
4891 {
4892         struct wpa_driver_nl80211_data *drv = bss->drv;
4893         int ret = -1, i;
4894         struct nl_msg *msg;
4895         enum nl80211_auth_type type;
4896         enum nl80211_iftype nlmode;
4897         int count = 0;
4898         int is_retry;
4899
4900         is_retry = drv->retry_auth;
4901         drv->retry_auth = 0;
4902
4903         drv->associated = 0;
4904         os_memset(drv->auth_bssid, 0, ETH_ALEN);
4905         /* FIX: IBSS mode */
4906         nlmode = params->p2p ?
4907                 NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
4908         if (drv->nlmode != nlmode &&
4909             wpa_driver_nl80211_set_mode(bss, nlmode) < 0)
4910                 return -1;
4911
4912 retry:
4913         msg = nlmsg_alloc();
4914         if (!msg)
4915                 return -1;
4916
4917         wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
4918                    drv->ifindex);
4919
4920         nl80211_cmd(drv, msg, 0, NL80211_CMD_AUTHENTICATE);
4921
4922         for (i = 0; i < 4; i++) {
4923                 if (!params->wep_key[i])
4924                         continue;
4925                 wpa_driver_nl80211_set_key(bss->ifname, bss, WPA_ALG_WEP,
4926                                            NULL, i,
4927                                            i == params->wep_tx_keyidx, NULL, 0,
4928                                            params->wep_key[i],
4929                                            params->wep_key_len[i]);
4930                 if (params->wep_tx_keyidx != i)
4931                         continue;
4932                 if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
4933                                params->wep_key[i], params->wep_key_len[i])) {
4934                         nlmsg_free(msg);
4935                         return -1;
4936                 }
4937         }
4938
4939         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4940         if (params->bssid) {
4941                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4942                            MAC2STR(params->bssid));
4943                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4944         }
4945         if (params->freq) {
4946                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4947                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4948         }
4949         if (params->ssid) {
4950                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4951                                   params->ssid, params->ssid_len);
4952                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4953                         params->ssid);
4954         }
4955         wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
4956         if (params->ie)
4957                 NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
4958         if (params->sae_data) {
4959                 wpa_hexdump(MSG_DEBUG, "  * SAE data", params->sae_data,
4960                             params->sae_data_len);
4961                 NLA_PUT(msg, NL80211_ATTR_SAE_DATA, params->sae_data_len,
4962                         params->sae_data);
4963         }
4964         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
4965                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
4966         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
4967                 type = NL80211_AUTHTYPE_SHARED_KEY;
4968         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
4969                 type = NL80211_AUTHTYPE_NETWORK_EAP;
4970         else if (params->auth_alg & WPA_AUTH_ALG_FT)
4971                 type = NL80211_AUTHTYPE_FT;
4972         else if (params->auth_alg & WPA_AUTH_ALG_SAE)
4973                 type = NL80211_AUTHTYPE_SAE;
4974         else
4975                 goto nla_put_failure;
4976         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
4977         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
4978         if (params->local_state_change) {
4979                 wpa_printf(MSG_DEBUG, "  * Local state change only");
4980                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4981         }
4982
4983         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4984         msg = NULL;
4985         if (ret) {
4986                 wpa_dbg(drv->ctx, MSG_DEBUG,
4987                         "nl80211: MLME command failed (auth): ret=%d (%s)",
4988                         ret, strerror(-ret));
4989                 count++;
4990                 if (ret == -EALREADY && count == 1 && params->bssid &&
4991                     !params->local_state_change) {
4992                         /*
4993                          * mac80211 does not currently accept new
4994                          * authentication if we are already authenticated. As a
4995                          * workaround, force deauthentication and try again.
4996                          */
4997                         wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
4998                                    "after forced deauthentication");
4999                         wpa_driver_nl80211_deauthenticate(
5000                                 bss, params->bssid,
5001                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
5002                         nlmsg_free(msg);
5003                         goto retry;
5004                 }
5005
5006                 if (ret == -ENOENT && params->freq && !is_retry) {
5007                         /*
5008                          * cfg80211 has likely expired the BSS entry even
5009                          * though it was previously available in our internal
5010                          * BSS table. To recover quickly, start a single
5011                          * channel scan on the specified channel.
5012                          */
5013                         struct wpa_driver_scan_params scan;
5014                         int freqs[2];
5015
5016                         os_memset(&scan, 0, sizeof(scan));
5017                         scan.num_ssids = 1;
5018                         if (params->ssid) {
5019                                 scan.ssids[0].ssid = params->ssid;
5020                                 scan.ssids[0].ssid_len = params->ssid_len;
5021                         }
5022                         freqs[0] = params->freq;
5023                         freqs[1] = 0;
5024                         scan.freqs = freqs;
5025                         wpa_printf(MSG_DEBUG, "nl80211: Trigger single "
5026                                    "channel scan to refresh cfg80211 BSS "
5027                                    "entry");
5028                         ret = wpa_driver_nl80211_scan(bss, &scan);
5029                         if (ret == 0) {
5030                                 nl80211_copy_auth_params(drv, params);
5031                                 drv->scan_for_auth = 1;
5032                         }
5033                 } else if (is_retry) {
5034                         /*
5035                          * Need to indicate this with an event since the return
5036                          * value from the retry is not delivered to core code.
5037                          */
5038                         union wpa_event_data event;
5039                         wpa_printf(MSG_DEBUG, "nl80211: Authentication retry "
5040                                    "failed");
5041                         os_memset(&event, 0, sizeof(event));
5042                         os_memcpy(event.timeout_event.addr, drv->auth_bssid_,
5043                                   ETH_ALEN);
5044                         wpa_supplicant_event(drv->ctx, EVENT_AUTH_TIMED_OUT,
5045                                              &event);
5046                 }
5047
5048                 goto nla_put_failure;
5049         }
5050         ret = 0;
5051         wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
5052                    "successfully");
5053
5054 nla_put_failure:
5055         nlmsg_free(msg);
5056         return ret;
5057 }
5058
5059
5060 static int wpa_driver_nl80211_authenticate_retry(
5061         struct wpa_driver_nl80211_data *drv)
5062 {
5063         struct wpa_driver_auth_params params;
5064         struct i802_bss *bss = &drv->first_bss;
5065         int i;
5066
5067         wpa_printf(MSG_DEBUG, "nl80211: Try to authenticate again");
5068
5069         os_memset(&params, 0, sizeof(params));
5070         params.freq = drv->auth_freq;
5071         params.auth_alg = drv->auth_alg;
5072         params.wep_tx_keyidx = drv->auth_wep_tx_keyidx;
5073         params.local_state_change = drv->auth_local_state_change;
5074         params.p2p = drv->auth_p2p;
5075
5076         if (!is_zero_ether_addr(drv->auth_bssid_))
5077                 params.bssid = drv->auth_bssid_;
5078
5079         if (drv->auth_ssid_len) {
5080                 params.ssid = drv->auth_ssid;
5081                 params.ssid_len = drv->auth_ssid_len;
5082         }
5083
5084         params.ie = drv->auth_ie;
5085         params.ie_len = drv->auth_ie_len;
5086
5087         for (i = 0; i < 4; i++) {
5088                 if (drv->auth_wep_key_len[i]) {
5089                         params.wep_key[i] = drv->auth_wep_key[i];
5090                         params.wep_key_len[i] = drv->auth_wep_key_len[i];
5091                 }
5092         }
5093
5094         drv->retry_auth = 1;
5095         return wpa_driver_nl80211_authenticate(bss, &params);
5096 }
5097
5098
5099 struct phy_info_arg {
5100         u16 *num_modes;
5101         struct hostapd_hw_modes *modes;
5102         int last_mode, last_chan_idx;
5103 };
5104
5105 static void phy_info_ht_capa(struct hostapd_hw_modes *mode, struct nlattr *capa,
5106                              struct nlattr *ampdu_factor,
5107                              struct nlattr *ampdu_density,
5108                              struct nlattr *mcs_set)
5109 {
5110         if (capa)
5111                 mode->ht_capab = nla_get_u16(capa);
5112
5113         if (ampdu_factor)
5114                 mode->a_mpdu_params |= nla_get_u8(ampdu_factor) & 0x03;
5115
5116         if (ampdu_density)
5117                 mode->a_mpdu_params |= nla_get_u8(ampdu_density) << 2;
5118
5119         if (mcs_set && nla_len(mcs_set) >= 16) {
5120                 u8 *mcs;
5121                 mcs = nla_data(mcs_set);
5122                 os_memcpy(mode->mcs_set, mcs, 16);
5123         }
5124 }
5125
5126
5127 static void phy_info_vht_capa(struct hostapd_hw_modes *mode,
5128                               struct nlattr *capa,
5129                               struct nlattr *mcs_set)
5130 {
5131         if (capa)
5132                 mode->vht_capab = nla_get_u32(capa);
5133
5134         if (mcs_set && nla_len(mcs_set) >= 8) {
5135                 u8 *mcs;
5136                 mcs = nla_data(mcs_set);
5137                 os_memcpy(mode->vht_mcs_set, mcs, 8);
5138         }
5139 }
5140
5141
5142 static void phy_info_freq(struct hostapd_hw_modes *mode,
5143                           struct hostapd_channel_data *chan,
5144                           struct nlattr *tb_freq[])
5145 {
5146         u8 channel;
5147         chan->freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
5148         chan->flag = 0;
5149         if (ieee80211_freq_to_chan(chan->freq, &channel) != NUM_HOSTAPD_MODES)
5150                 chan->chan = channel;
5151
5152         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
5153                 chan->flag |= HOSTAPD_CHAN_DISABLED;
5154         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
5155                 chan->flag |= HOSTAPD_CHAN_PASSIVE_SCAN;
5156         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
5157                 chan->flag |= HOSTAPD_CHAN_NO_IBSS;
5158         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
5159                 chan->flag |= HOSTAPD_CHAN_RADAR;
5160
5161         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
5162             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
5163                 chan->max_tx_power = nla_get_u32(
5164                         tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
5165         if (tb_freq[NL80211_FREQUENCY_ATTR_DFS_STATE]) {
5166                 enum nl80211_dfs_state state =
5167                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_DFS_STATE]);
5168
5169                 switch (state) {
5170                 case NL80211_DFS_USABLE:
5171                         chan->flag |= HOSTAPD_CHAN_DFS_USABLE;
5172                         break;
5173                 case NL80211_DFS_AVAILABLE:
5174                         chan->flag |= HOSTAPD_CHAN_DFS_AVAILABLE;
5175                         break;
5176                 case NL80211_DFS_UNAVAILABLE:
5177                         chan->flag |= HOSTAPD_CHAN_DFS_UNAVAILABLE;
5178                         break;
5179                 }
5180         }
5181 }
5182
5183
5184 static int phy_info_freqs(struct phy_info_arg *phy_info,
5185                           struct hostapd_hw_modes *mode, struct nlattr *tb)
5186 {
5187         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
5188                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
5189                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
5190                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
5191                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
5192                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
5193                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
5194                 [NL80211_FREQUENCY_ATTR_DFS_STATE] = { .type = NLA_U32 },
5195         };
5196         int new_channels = 0;
5197         struct hostapd_channel_data *channel;
5198         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
5199         struct nlattr *nl_freq;
5200         int rem_freq, idx;
5201
5202         if (tb == NULL)
5203                 return NL_OK;
5204
5205         nla_for_each_nested(nl_freq, tb, rem_freq) {
5206                 nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX,
5207                           nla_data(nl_freq), nla_len(nl_freq), freq_policy);
5208                 if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
5209                         continue;
5210                 new_channels++;
5211         }
5212
5213         channel = os_realloc_array(mode->channels,
5214                                    mode->num_channels + new_channels,
5215                                    sizeof(struct hostapd_channel_data));
5216         if (!channel)
5217                 return NL_SKIP;
5218
5219         mode->channels = channel;
5220         mode->num_channels += new_channels;
5221
5222         idx = phy_info->last_chan_idx;
5223
5224         nla_for_each_nested(nl_freq, tb, rem_freq) {
5225                 nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX,
5226                           nla_data(nl_freq), nla_len(nl_freq), freq_policy);
5227                 if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
5228                         continue;
5229                 phy_info_freq(mode, &mode->channels[idx], tb_freq);
5230                 idx++;
5231         }
5232         phy_info->last_chan_idx = idx;
5233
5234         return NL_OK;
5235 }
5236
5237
5238 static int phy_info_rates(struct hostapd_hw_modes *mode, struct nlattr *tb)
5239 {
5240         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
5241                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
5242                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] =
5243                 { .type = NLA_FLAG },
5244         };
5245         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
5246         struct nlattr *nl_rate;
5247         int rem_rate, idx;
5248
5249         if (tb == NULL)
5250                 return NL_OK;
5251
5252         nla_for_each_nested(nl_rate, tb, rem_rate) {
5253                 nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX,
5254                           nla_data(nl_rate), nla_len(nl_rate),
5255                           rate_policy);
5256                 if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
5257                         continue;
5258                 mode->num_rates++;
5259         }
5260
5261         mode->rates = os_calloc(mode->num_rates, sizeof(int));
5262         if (!mode->rates)
5263                 return NL_SKIP;
5264
5265         idx = 0;
5266
5267         nla_for_each_nested(nl_rate, tb, rem_rate) {
5268                 nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX,
5269                           nla_data(nl_rate), nla_len(nl_rate),
5270                           rate_policy);
5271                 if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
5272                         continue;
5273                 mode->rates[idx] = nla_get_u32(
5274                         tb_rate[NL80211_BITRATE_ATTR_RATE]);
5275                 idx++;
5276         }
5277
5278         return NL_OK;
5279 }
5280
5281
5282 static int phy_info_band(struct phy_info_arg *phy_info, struct nlattr *nl_band)
5283 {
5284         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
5285         struct hostapd_hw_modes *mode;
5286         int ret;
5287
5288         if (phy_info->last_mode != nl_band->nla_type) {
5289                 mode = os_realloc_array(phy_info->modes,
5290                                         *phy_info->num_modes + 1,
5291                                         sizeof(*mode));
5292                 if (!mode)
5293                         return NL_SKIP;
5294                 phy_info->modes = mode;
5295
5296                 mode = &phy_info->modes[*(phy_info->num_modes)];
5297                 os_memset(mode, 0, sizeof(*mode));
5298                 mode->mode = NUM_HOSTAPD_MODES;
5299                 mode->flags = HOSTAPD_MODE_FLAG_HT_INFO_KNOWN;
5300                 *(phy_info->num_modes) += 1;
5301                 phy_info->last_mode = nl_band->nla_type;
5302                 phy_info->last_chan_idx = 0;
5303         } else
5304                 mode = &phy_info->modes[*(phy_info->num_modes) - 1];
5305
5306         nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
5307                   nla_len(nl_band), NULL);
5308
5309         phy_info_ht_capa(mode, tb_band[NL80211_BAND_ATTR_HT_CAPA],
5310                          tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR],
5311                          tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY],
5312                          tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
5313         phy_info_vht_capa(mode, tb_band[NL80211_BAND_ATTR_VHT_CAPA],
5314                           tb_band[NL80211_BAND_ATTR_VHT_MCS_SET]);
5315         ret = phy_info_freqs(phy_info, mode, tb_band[NL80211_BAND_ATTR_FREQS]);
5316         if (ret != NL_OK)
5317                 return ret;
5318         ret = phy_info_rates(mode, tb_band[NL80211_BAND_ATTR_RATES]);
5319         if (ret != NL_OK)
5320                 return ret;
5321
5322         return NL_OK;
5323 }
5324
5325
5326 static int phy_info_handler(struct nl_msg *msg, void *arg)
5327 {
5328         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
5329         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5330         struct phy_info_arg *phy_info = arg;
5331         struct nlattr *nl_band;
5332         int rem_band;
5333
5334         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5335                   genlmsg_attrlen(gnlh, 0), NULL);
5336
5337         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
5338                 return NL_SKIP;
5339
5340         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band)
5341         {
5342                 int res = phy_info_band(phy_info, nl_band);
5343                 if (res != NL_OK)
5344                         return res;
5345         }
5346
5347         return NL_SKIP;
5348 }
5349
5350
5351 static struct hostapd_hw_modes *
5352 wpa_driver_nl80211_postprocess_modes(struct hostapd_hw_modes *modes,
5353                                      u16 *num_modes)
5354 {
5355         u16 m;
5356         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
5357         int i, mode11g_idx = -1;
5358
5359         /* heuristic to set up modes */
5360         for (m = 0; m < *num_modes; m++) {
5361                 if (!modes[m].num_channels)
5362                         continue;
5363                 if (modes[m].channels[0].freq < 4000) {
5364                         modes[m].mode = HOSTAPD_MODE_IEEE80211B;
5365                         for (i = 0; i < modes[m].num_rates; i++) {
5366                                 if (modes[m].rates[i] > 200) {
5367                                         modes[m].mode = HOSTAPD_MODE_IEEE80211G;
5368                                         break;
5369                                 }
5370                         }
5371                 } else if (modes[m].channels[0].freq > 50000)
5372                         modes[m].mode = HOSTAPD_MODE_IEEE80211AD;
5373                 else
5374                         modes[m].mode = HOSTAPD_MODE_IEEE80211A;
5375         }
5376
5377         /* If only 802.11g mode is included, use it to construct matching
5378          * 802.11b mode data. */
5379
5380         for (m = 0; m < *num_modes; m++) {
5381                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
5382                         return modes; /* 802.11b already included */
5383                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
5384                         mode11g_idx = m;
5385         }
5386
5387         if (mode11g_idx < 0)
5388                 return modes; /* 2.4 GHz band not supported at all */
5389
5390         nmodes = os_realloc_array(modes, *num_modes + 1, sizeof(*nmodes));
5391         if (nmodes == NULL)
5392                 return modes; /* Could not add 802.11b mode */
5393
5394         mode = &nmodes[*num_modes];
5395         os_memset(mode, 0, sizeof(*mode));
5396         (*num_modes)++;
5397         modes = nmodes;
5398
5399         mode->mode = HOSTAPD_MODE_IEEE80211B;
5400
5401         mode11g = &modes[mode11g_idx];
5402         mode->num_channels = mode11g->num_channels;
5403         mode->channels = os_malloc(mode11g->num_channels *
5404                                    sizeof(struct hostapd_channel_data));
5405         if (mode->channels == NULL) {
5406                 (*num_modes)--;
5407                 return modes; /* Could not add 802.11b mode */
5408         }
5409         os_memcpy(mode->channels, mode11g->channels,
5410                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
5411
5412         mode->num_rates = 0;
5413         mode->rates = os_malloc(4 * sizeof(int));
5414         if (mode->rates == NULL) {
5415                 os_free(mode->channels);
5416                 (*num_modes)--;
5417                 return modes; /* Could not add 802.11b mode */
5418         }
5419
5420         for (i = 0; i < mode11g->num_rates; i++) {
5421                 if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 &&
5422                     mode11g->rates[i] != 55 && mode11g->rates[i] != 110)
5423                         continue;
5424                 mode->rates[mode->num_rates] = mode11g->rates[i];
5425                 mode->num_rates++;
5426                 if (mode->num_rates == 4)
5427                         break;
5428         }
5429
5430         if (mode->num_rates == 0) {
5431                 os_free(mode->channels);
5432                 os_free(mode->rates);
5433                 (*num_modes)--;
5434                 return modes; /* No 802.11b rates */
5435         }
5436
5437         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
5438                    "information");
5439
5440         return modes;
5441 }
5442
5443
5444 static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start,
5445                                   int end)
5446 {
5447         int c;
5448
5449         for (c = 0; c < mode->num_channels; c++) {
5450                 struct hostapd_channel_data *chan = &mode->channels[c];
5451                 if (chan->freq - 10 >= start && chan->freq + 10 <= end)
5452                         chan->flag |= HOSTAPD_CHAN_HT40;
5453         }
5454 }
5455
5456
5457 static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start,
5458                                       int end)
5459 {
5460         int c;
5461
5462         for (c = 0; c < mode->num_channels; c++) {
5463                 struct hostapd_channel_data *chan = &mode->channels[c];
5464                 if (!(chan->flag & HOSTAPD_CHAN_HT40))
5465                         continue;
5466                 if (chan->freq - 30 >= start && chan->freq - 10 <= end)
5467                         chan->flag |= HOSTAPD_CHAN_HT40MINUS;
5468                 if (chan->freq + 10 >= start && chan->freq + 30 <= end)
5469                         chan->flag |= HOSTAPD_CHAN_HT40PLUS;
5470         }
5471 }
5472
5473
5474 static void nl80211_reg_rule_ht40(struct nlattr *tb[],
5475                                   struct phy_info_arg *results)
5476 {
5477         u32 start, end, max_bw;
5478         u16 m;
5479
5480         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
5481             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
5482             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
5483                 return;
5484
5485         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
5486         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
5487         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
5488
5489         wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz",
5490                    start, end, max_bw);
5491         if (max_bw < 40)
5492                 return;
5493
5494         for (m = 0; m < *results->num_modes; m++) {
5495                 if (!(results->modes[m].ht_capab &
5496                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
5497                         continue;
5498                 nl80211_set_ht40_mode(&results->modes[m], start, end);
5499         }
5500 }
5501
5502
5503 static void nl80211_reg_rule_sec(struct nlattr *tb[],
5504                                  struct phy_info_arg *results)
5505 {
5506         u32 start, end, max_bw;
5507         u16 m;
5508
5509         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
5510             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
5511             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
5512                 return;
5513
5514         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
5515         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
5516         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
5517
5518         if (max_bw < 20)
5519                 return;
5520
5521         for (m = 0; m < *results->num_modes; m++) {
5522                 if (!(results->modes[m].ht_capab &
5523                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
5524                         continue;
5525                 nl80211_set_ht40_mode_sec(&results->modes[m], start, end);
5526         }
5527 }
5528
5529
5530 static int nl80211_get_reg(struct nl_msg *msg, void *arg)
5531 {
5532         struct phy_info_arg *results = arg;
5533         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
5534         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5535         struct nlattr *nl_rule;
5536         struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1];
5537         int rem_rule;
5538         static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
5539                 [NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
5540                 [NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
5541                 [NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
5542                 [NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
5543                 [NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
5544                 [NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
5545         };
5546
5547         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5548                   genlmsg_attrlen(gnlh, 0), NULL);
5549         if (!tb_msg[NL80211_ATTR_REG_ALPHA2] ||
5550             !tb_msg[NL80211_ATTR_REG_RULES]) {
5551                 wpa_printf(MSG_DEBUG, "nl80211: No regulatory information "
5552                            "available");
5553                 return NL_SKIP;
5554         }
5555
5556         wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s",
5557                    (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]));
5558
5559         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5560         {
5561                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5562                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5563                 nl80211_reg_rule_ht40(tb_rule, results);
5564         }
5565
5566         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5567         {
5568                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5569                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5570                 nl80211_reg_rule_sec(tb_rule, results);
5571         }
5572
5573         return NL_SKIP;
5574 }
5575
5576
5577 static int nl80211_set_ht40_flags(struct wpa_driver_nl80211_data *drv,
5578                                   struct phy_info_arg *results)
5579 {
5580         struct nl_msg *msg;
5581
5582         msg = nlmsg_alloc();
5583         if (!msg)
5584                 return -ENOMEM;
5585
5586         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_REG);
5587         return send_and_recv_msgs(drv, msg, nl80211_get_reg, results);
5588 }
5589
5590
5591 static struct hostapd_hw_modes *
5592 wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
5593 {
5594         u32 feat;
5595         struct i802_bss *bss = priv;
5596         struct wpa_driver_nl80211_data *drv = bss->drv;
5597         struct nl_msg *msg;
5598         struct phy_info_arg result = {
5599                 .num_modes = num_modes,
5600                 .modes = NULL,
5601                 .last_mode = -1,
5602         };
5603
5604         *num_modes = 0;
5605         *flags = 0;
5606
5607         msg = nlmsg_alloc();
5608         if (!msg)
5609                 return NULL;
5610
5611         feat = get_nl80211_protocol_features(drv);
5612         if (feat & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP)
5613                 nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_WIPHY);
5614         else
5615                 nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
5616
5617         NLA_PUT_FLAG(msg, NL80211_ATTR_SPLIT_WIPHY_DUMP);
5618         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5619
5620         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) {
5621                 nl80211_set_ht40_flags(drv, &result);
5622                 return wpa_driver_nl80211_postprocess_modes(result.modes,
5623                                                             num_modes);
5624         }
5625         msg = NULL;
5626  nla_put_failure:
5627         nlmsg_free(msg);
5628         return NULL;
5629 }
5630
5631
5632 static int wpa_driver_nl80211_send_mntr(struct wpa_driver_nl80211_data *drv,
5633                                         const void *data, size_t len,
5634                                         int encrypt, int noack)
5635 {
5636         __u8 rtap_hdr[] = {
5637                 0x00, 0x00, /* radiotap version */
5638                 0x0e, 0x00, /* radiotap length */
5639                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
5640                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
5641                 0x00,       /* padding */
5642                 0x00, 0x00, /* RX and TX flags to indicate that */
5643                 0x00, 0x00, /* this is the injected frame directly */
5644         };
5645         struct iovec iov[2] = {
5646                 {
5647                         .iov_base = &rtap_hdr,
5648                         .iov_len = sizeof(rtap_hdr),
5649                 },
5650                 {
5651                         .iov_base = (void *) data,
5652                         .iov_len = len,
5653                 }
5654         };
5655         struct msghdr msg = {
5656                 .msg_name = NULL,
5657                 .msg_namelen = 0,
5658                 .msg_iov = iov,
5659                 .msg_iovlen = 2,
5660                 .msg_control = NULL,
5661                 .msg_controllen = 0,
5662                 .msg_flags = 0,
5663         };
5664         int res;
5665         u16 txflags = 0;
5666
5667         if (encrypt)
5668                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
5669
5670         if (drv->monitor_sock < 0) {
5671                 wpa_printf(MSG_DEBUG, "nl80211: No monitor socket available "
5672                            "for %s", __func__);
5673                 return -1;
5674         }
5675
5676         if (noack)
5677                 txflags |= IEEE80211_RADIOTAP_F_TX_NOACK;
5678         WPA_PUT_LE16(&rtap_hdr[12], txflags);
5679
5680         res = sendmsg(drv->monitor_sock, &msg, 0);
5681         if (res < 0) {
5682                 wpa_printf(MSG_INFO, "nl80211: sendmsg: %s", strerror(errno));
5683                 return -1;
5684         }
5685         return 0;
5686 }
5687
5688
5689 static int wpa_driver_nl80211_send_frame(struct i802_bss *bss,
5690                                          const void *data, size_t len,
5691                                          int encrypt, int noack,
5692                                          unsigned int freq, int no_cck,
5693                                          int offchanok, unsigned int wait_time)
5694 {
5695         struct wpa_driver_nl80211_data *drv = bss->drv;
5696         u64 cookie;
5697
5698         if (freq == 0)
5699                 freq = bss->freq;
5700
5701         if (drv->use_monitor)
5702                 return wpa_driver_nl80211_send_mntr(drv, data, len,
5703                                                     encrypt, noack);
5704
5705         return nl80211_send_frame_cmd(bss, freq, wait_time, data, len,
5706                                       &cookie, no_cck, noack, offchanok);
5707 }
5708
5709
5710 static int wpa_driver_nl80211_send_mlme(struct i802_bss *bss, const u8 *data,
5711                                         size_t data_len, int noack,
5712                                         unsigned int freq, int no_cck,
5713                                         int offchanok,
5714                                         unsigned int wait_time)
5715 {
5716         struct wpa_driver_nl80211_data *drv = bss->drv;
5717         struct ieee80211_mgmt *mgmt;
5718         int encrypt = 1;
5719         u16 fc;
5720
5721         mgmt = (struct ieee80211_mgmt *) data;
5722         fc = le_to_host16(mgmt->frame_control);
5723
5724         if (is_sta_interface(drv->nlmode) &&
5725             WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5726             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_PROBE_RESP) {
5727                 /*
5728                  * The use of last_mgmt_freq is a bit of a hack,
5729                  * but it works due to the single-threaded nature
5730                  * of wpa_supplicant.
5731                  */
5732                 if (freq == 0)
5733                         freq = drv->last_mgmt_freq;
5734                 return nl80211_send_frame_cmd(bss, freq, 0,
5735                                               data, data_len, NULL, 1, noack,
5736                                               1);
5737         }
5738
5739         if (drv->device_ap_sme && is_ap_interface(drv->nlmode)) {
5740                 if (freq == 0)
5741                         freq = bss->freq;
5742                 return nl80211_send_frame_cmd(bss, freq,
5743                                               (int) freq == bss->freq ? 0 :
5744                                               wait_time,
5745                                               data, data_len,
5746                                               &drv->send_action_cookie,
5747                                               no_cck, noack, offchanok);
5748         }
5749
5750         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5751             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
5752                 /*
5753                  * Only one of the authentication frame types is encrypted.
5754                  * In order for static WEP encryption to work properly (i.e.,
5755                  * to not encrypt the frame), we need to tell mac80211 about
5756                  * the frames that must not be encrypted.
5757                  */
5758                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
5759                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
5760                 if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
5761                         encrypt = 0;
5762         }
5763
5764         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt,
5765                                              noack, freq, no_cck, offchanok,
5766                                              wait_time);
5767 }
5768
5769
5770 static int nl80211_set_bss(struct i802_bss *bss, int cts, int preamble,
5771                            int slot, int ht_opmode, int ap_isolate,
5772                            int *basic_rates)
5773 {
5774         struct wpa_driver_nl80211_data *drv = bss->drv;
5775         struct nl_msg *msg;
5776
5777         msg = nlmsg_alloc();
5778         if (!msg)
5779                 return -ENOMEM;
5780
5781         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_BSS);
5782
5783         if (cts >= 0)
5784                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
5785         if (preamble >= 0)
5786                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
5787         if (slot >= 0)
5788                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
5789         if (ht_opmode >= 0)
5790                 NLA_PUT_U16(msg, NL80211_ATTR_BSS_HT_OPMODE, ht_opmode);
5791         if (ap_isolate >= 0)
5792                 NLA_PUT_U8(msg, NL80211_ATTR_AP_ISOLATE, ap_isolate);
5793
5794         if (basic_rates) {
5795                 u8 rates[NL80211_MAX_SUPP_RATES];
5796                 u8 rates_len = 0;
5797                 int i;
5798
5799                 for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0;
5800                      i++)
5801                         rates[rates_len++] = basic_rates[i] / 5;
5802
5803                 NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
5804         }
5805
5806         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5807
5808         return send_and_recv_msgs(drv, msg, NULL, NULL);
5809  nla_put_failure:
5810         nlmsg_free(msg);
5811         return -ENOBUFS;
5812 }
5813
5814
5815 static int wpa_driver_nl80211_set_ap(void *priv,
5816                                      struct wpa_driver_ap_params *params)
5817 {
5818         struct i802_bss *bss = priv;
5819         struct wpa_driver_nl80211_data *drv = bss->drv;
5820         struct nl_msg *msg;
5821         u8 cmd = NL80211_CMD_NEW_BEACON;
5822         int ret;
5823         int beacon_set;
5824         int ifindex = if_nametoindex(bss->ifname);
5825         int num_suites;
5826         u32 suites[10];
5827         u32 ver;
5828
5829         beacon_set = bss->beacon_set;
5830
5831         msg = nlmsg_alloc();
5832         if (!msg)
5833                 return -ENOMEM;
5834
5835         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
5836                    beacon_set);
5837         if (beacon_set)
5838                 cmd = NL80211_CMD_SET_BEACON;
5839
5840         nl80211_cmd(drv, msg, 0, cmd);
5841         wpa_hexdump(MSG_DEBUG, "nl80211: Beacon head",
5842                     params->head, params->head_len);
5843         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, params->head_len, params->head);
5844         wpa_hexdump(MSG_DEBUG, "nl80211: Beacon tail",
5845                     params->tail, params->tail_len);
5846         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, params->tail_len, params->tail);
5847         wpa_printf(MSG_DEBUG, "nl80211: ifindex=%d", ifindex);
5848         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
5849         wpa_printf(MSG_DEBUG, "nl80211: beacon_int=%d", params->beacon_int);
5850         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, params->beacon_int);
5851         wpa_printf(MSG_DEBUG, "nl80211: dtim_period=%d", params->dtim_period);
5852         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, params->dtim_period);
5853         wpa_hexdump_ascii(MSG_DEBUG, "nl80211: ssid",
5854                           params->ssid, params->ssid_len);
5855         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
5856                 params->ssid);
5857         if (params->proberesp && params->proberesp_len) {
5858                 wpa_hexdump(MSG_DEBUG, "nl80211: proberesp (offload)",
5859                             params->proberesp, params->proberesp_len);
5860                 NLA_PUT(msg, NL80211_ATTR_PROBE_RESP, params->proberesp_len,
5861                         params->proberesp);
5862         }
5863         switch (params->hide_ssid) {
5864         case NO_SSID_HIDING:
5865                 wpa_printf(MSG_DEBUG, "nl80211: hidden SSID not in use");
5866                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5867                             NL80211_HIDDEN_SSID_NOT_IN_USE);
5868                 break;
5869         case HIDDEN_SSID_ZERO_LEN:
5870                 wpa_printf(MSG_DEBUG, "nl80211: hidden SSID zero len");
5871                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5872                             NL80211_HIDDEN_SSID_ZERO_LEN);
5873                 break;
5874         case HIDDEN_SSID_ZERO_CONTENTS:
5875                 wpa_printf(MSG_DEBUG, "nl80211: hidden SSID zero contents");
5876                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5877                             NL80211_HIDDEN_SSID_ZERO_CONTENTS);
5878                 break;
5879         }
5880         wpa_printf(MSG_DEBUG, "nl80211: privacy=%d", params->privacy);
5881         if (params->privacy)
5882                 NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
5883         wpa_printf(MSG_DEBUG, "nl80211: auth_algs=0x%x", params->auth_algs);
5884         if ((params->auth_algs & (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) ==
5885             (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) {
5886                 /* Leave out the attribute */
5887         } else if (params->auth_algs & WPA_AUTH_ALG_SHARED)
5888                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5889                             NL80211_AUTHTYPE_SHARED_KEY);
5890         else
5891                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5892                             NL80211_AUTHTYPE_OPEN_SYSTEM);
5893
5894         wpa_printf(MSG_DEBUG, "nl80211: wpa_version=0x%x", params->wpa_version);
5895         ver = 0;
5896         if (params->wpa_version & WPA_PROTO_WPA)
5897                 ver |= NL80211_WPA_VERSION_1;
5898         if (params->wpa_version & WPA_PROTO_RSN)
5899                 ver |= NL80211_WPA_VERSION_2;
5900         if (ver)
5901                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
5902
5903         wpa_printf(MSG_DEBUG, "nl80211: key_mgmt_suites=0x%x",
5904                    params->key_mgmt_suites);
5905         num_suites = 0;
5906         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X)
5907                 suites[num_suites++] = WLAN_AKM_SUITE_8021X;
5908         if (params->key_mgmt_suites & WPA_KEY_MGMT_PSK)
5909                 suites[num_suites++] = WLAN_AKM_SUITE_PSK;
5910         if (num_suites) {
5911                 NLA_PUT(msg, NL80211_ATTR_AKM_SUITES,
5912                         num_suites * sizeof(u32), suites);
5913         }
5914
5915         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X &&
5916             params->pairwise_ciphers & (WPA_CIPHER_WEP104 | WPA_CIPHER_WEP40))
5917                 NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT);
5918
5919         wpa_printf(MSG_DEBUG, "nl80211: pairwise_ciphers=0x%x",
5920                    params->pairwise_ciphers);
5921         num_suites = 0;
5922         if (params->pairwise_ciphers & WPA_CIPHER_CCMP)
5923                 suites[num_suites++] = WLAN_CIPHER_SUITE_CCMP;
5924         if (params->pairwise_ciphers & WPA_CIPHER_GCMP)
5925                 suites[num_suites++] = WLAN_CIPHER_SUITE_GCMP;
5926         if (params->pairwise_ciphers & WPA_CIPHER_TKIP)
5927                 suites[num_suites++] = WLAN_CIPHER_SUITE_TKIP;
5928         if (params->pairwise_ciphers & WPA_CIPHER_WEP104)
5929                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP104;
5930         if (params->pairwise_ciphers & WPA_CIPHER_WEP40)
5931                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP40;
5932         if (num_suites) {
5933                 NLA_PUT(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE,
5934                         num_suites * sizeof(u32), suites);
5935         }
5936
5937         wpa_printf(MSG_DEBUG, "nl80211: group_cipher=0x%x",
5938                    params->group_cipher);
5939         switch (params->group_cipher) {
5940         case WPA_CIPHER_CCMP:
5941                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5942                             WLAN_CIPHER_SUITE_CCMP);
5943                 break;
5944         case WPA_CIPHER_GCMP:
5945                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5946                             WLAN_CIPHER_SUITE_GCMP);
5947                 break;
5948         case WPA_CIPHER_TKIP:
5949                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5950                             WLAN_CIPHER_SUITE_TKIP);
5951                 break;
5952         case WPA_CIPHER_WEP104:
5953                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5954                             WLAN_CIPHER_SUITE_WEP104);
5955                 break;
5956         case WPA_CIPHER_WEP40:
5957                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5958                             WLAN_CIPHER_SUITE_WEP40);
5959                 break;
5960         }
5961
5962         if (params->beacon_ies) {
5963                 wpa_hexdump_buf(MSG_DEBUG, "nl80211: beacon_ies",
5964                                 params->beacon_ies);
5965                 NLA_PUT(msg, NL80211_ATTR_IE, wpabuf_len(params->beacon_ies),
5966                         wpabuf_head(params->beacon_ies));
5967         }
5968         if (params->proberesp_ies) {
5969                 wpa_hexdump_buf(MSG_DEBUG, "nl80211: proberesp_ies",
5970                                 params->proberesp_ies);
5971                 NLA_PUT(msg, NL80211_ATTR_IE_PROBE_RESP,
5972                         wpabuf_len(params->proberesp_ies),
5973                         wpabuf_head(params->proberesp_ies));
5974         }
5975         if (params->assocresp_ies) {
5976                 wpa_hexdump_buf(MSG_DEBUG, "nl80211: assocresp_ies",
5977                                 params->assocresp_ies);
5978                 NLA_PUT(msg, NL80211_ATTR_IE_ASSOC_RESP,
5979                         wpabuf_len(params->assocresp_ies),
5980                         wpabuf_head(params->assocresp_ies));
5981         }
5982
5983         if (drv->capa.flags & WPA_DRIVER_FLAGS_INACTIVITY_TIMER)  {
5984                 wpa_printf(MSG_DEBUG, "nl80211: ap_max_inactivity=%d",
5985                            params->ap_max_inactivity);
5986                 NLA_PUT_U16(msg, NL80211_ATTR_INACTIVITY_TIMEOUT,
5987                             params->ap_max_inactivity);
5988         }
5989
5990         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5991         if (ret) {
5992                 wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
5993                            ret, strerror(-ret));
5994         } else {
5995                 bss->beacon_set = 1;
5996                 nl80211_set_bss(bss, params->cts_protect, params->preamble,
5997                                 params->short_slot_time, params->ht_opmode,
5998                                 params->isolate, params->basic_rates);
5999         }
6000         return ret;
6001  nla_put_failure:
6002         nlmsg_free(msg);
6003         return -ENOBUFS;
6004 }
6005
6006
6007 static int wpa_driver_nl80211_set_freq(struct i802_bss *bss,
6008                                        struct hostapd_freq_params *freq)
6009 {
6010         struct wpa_driver_nl80211_data *drv = bss->drv;
6011         struct nl_msg *msg;
6012         int ret;
6013
6014         wpa_printf(MSG_DEBUG, "nl80211: Set freq %d (ht_enabled=%d, vht_enabled=%d,"
6015                    " bandwidth=%d MHz, cf1=%d MHz, cf2=%d MHz)",
6016                    freq->freq, freq->ht_enabled, freq->vht_enabled,
6017                    freq->bandwidth, freq->center_freq1, freq->center_freq2);
6018         msg = nlmsg_alloc();
6019         if (!msg)
6020                 return -1;
6021
6022         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
6023
6024         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6025         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq->freq);
6026         if (freq->vht_enabled) {
6027                 switch (freq->bandwidth) {
6028                 case 20:
6029                         NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
6030                                     NL80211_CHAN_WIDTH_20);
6031                         break;
6032                 case 40:
6033                         NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
6034                                     NL80211_CHAN_WIDTH_40);
6035                         break;
6036                 case 80:
6037                         if (freq->center_freq2)
6038                                 NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
6039                                             NL80211_CHAN_WIDTH_80P80);
6040                         else
6041                                 NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
6042                                             NL80211_CHAN_WIDTH_80);
6043                         break;
6044                 case 160:
6045                         NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
6046                                     NL80211_CHAN_WIDTH_160);
6047                         break;
6048                 default:
6049                         return -1;
6050                 }
6051                 NLA_PUT_U32(msg, NL80211_ATTR_CENTER_FREQ1, freq->center_freq1);
6052                 if (freq->center_freq2)
6053                         NLA_PUT_U32(msg, NL80211_ATTR_CENTER_FREQ2,
6054                                     freq->center_freq2);
6055         } else if (freq->ht_enabled) {
6056                 switch (freq->sec_channel_offset) {
6057                 case -1:
6058                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
6059                                     NL80211_CHAN_HT40MINUS);
6060                         break;
6061                 case 1:
6062                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
6063                                     NL80211_CHAN_HT40PLUS);
6064                         break;
6065                 default:
6066                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
6067                                     NL80211_CHAN_HT20);
6068                         break;
6069                 }
6070         }
6071
6072         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6073         msg = NULL;
6074         if (ret == 0) {
6075                 bss->freq = freq->freq;
6076                 return 0;
6077         }
6078         wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
6079                    "%d (%s)", freq->freq, ret, strerror(-ret));
6080 nla_put_failure:
6081         nlmsg_free(msg);
6082         return -1;
6083 }
6084
6085
6086 static u32 sta_flags_nl80211(int flags)
6087 {
6088         u32 f = 0;
6089
6090         if (flags & WPA_STA_AUTHORIZED)
6091                 f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
6092         if (flags & WPA_STA_WMM)
6093                 f |= BIT(NL80211_STA_FLAG_WME);
6094         if (flags & WPA_STA_SHORT_PREAMBLE)
6095                 f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
6096         if (flags & WPA_STA_MFP)
6097                 f |= BIT(NL80211_STA_FLAG_MFP);
6098         if (flags & WPA_STA_TDLS_PEER)
6099                 f |= BIT(NL80211_STA_FLAG_TDLS_PEER);
6100
6101         return f;
6102 }
6103
6104
6105 static int wpa_driver_nl80211_sta_add(void *priv,
6106                                       struct hostapd_sta_add_params *params)
6107 {
6108         struct i802_bss *bss = priv;
6109         struct wpa_driver_nl80211_data *drv = bss->drv;
6110         struct nl_msg *msg;
6111         struct nl80211_sta_flag_update upd;
6112         int ret = -ENOBUFS;
6113
6114         if ((params->flags & WPA_STA_TDLS_PEER) &&
6115             !(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
6116                 return -EOPNOTSUPP;
6117
6118         msg = nlmsg_alloc();
6119         if (!msg)
6120                 return -ENOMEM;
6121
6122         wpa_printf(MSG_DEBUG, "nl80211: %s STA " MACSTR,
6123                    params->set ? "Set" : "Add", MAC2STR(params->addr));
6124         nl80211_cmd(drv, msg, 0, params->set ? NL80211_CMD_SET_STATION :
6125                     NL80211_CMD_NEW_STATION);
6126
6127         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
6128         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
6129         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
6130                 params->supp_rates);
6131         wpa_hexdump(MSG_DEBUG, "  * supported rates", params->supp_rates,
6132                     params->supp_rates_len);
6133         if (!params->set) {
6134                 if (params->aid) {
6135                         wpa_printf(MSG_DEBUG, "  * aid=%u", params->aid);
6136                         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
6137                 } else {
6138                         /*
6139                          * cfg80211 validates that AID is non-zero, so we have
6140                          * to make this a non-zero value for the TDLS case where
6141                          * a dummy STA entry is used for now.
6142                          */
6143                         wpa_printf(MSG_DEBUG, "  * aid=1 (TDLS workaround)");
6144                         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, 1);
6145                 }
6146                 wpa_printf(MSG_DEBUG, "  * listen_interval=%u",
6147                            params->listen_interval);
6148                 NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
6149                             params->listen_interval);
6150         }
6151         if (params->ht_capabilities) {
6152                 wpa_hexdump(MSG_DEBUG, "  * ht_capabilities",
6153                             (u8 *) params->ht_capabilities,
6154                             sizeof(*params->ht_capabilities));
6155                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
6156                         sizeof(*params->ht_capabilities),
6157                         params->ht_capabilities);
6158         }
6159
6160         if (params->vht_capabilities) {
6161                 wpa_hexdump(MSG_DEBUG, "  * vht_capabilities",
6162                             (u8 *) params->vht_capabilities,
6163                             sizeof(*params->vht_capabilities));
6164                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY,
6165                         sizeof(*params->vht_capabilities),
6166                         params->vht_capabilities);
6167         }
6168
6169         wpa_printf(MSG_DEBUG, "  * capability=0x%x", params->capability);
6170         NLA_PUT_U16(msg, NL80211_ATTR_STA_CAPABILITY, params->capability);
6171
6172         if (params->ext_capab) {
6173                 wpa_hexdump(MSG_DEBUG, "  * ext_capab",
6174                             params->ext_capab, params->ext_capab_len);
6175                 NLA_PUT(msg, NL80211_ATTR_STA_EXT_CAPABILITY,
6176                         params->ext_capab_len, params->ext_capab);
6177         }
6178
6179         os_memset(&upd, 0, sizeof(upd));
6180         upd.mask = sta_flags_nl80211(params->flags);
6181         upd.set = upd.mask;
6182         wpa_printf(MSG_DEBUG, "  * flags set=0x%x mask=0x%x",
6183                    upd.set, upd.mask);
6184         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
6185
6186         if (params->flags & WPA_STA_WMM) {
6187                 struct nlattr *wme = nla_nest_start(msg, NL80211_ATTR_STA_WME);
6188
6189                 if (!wme)
6190                         goto nla_put_failure;
6191
6192                 wpa_printf(MSG_DEBUG, "  * qosinfo=0x%x", params->qosinfo);
6193                 NLA_PUT_U8(msg, NL80211_STA_WME_UAPSD_QUEUES,
6194                                 params->qosinfo & WMM_QOSINFO_STA_AC_MASK);
6195                 NLA_PUT_U8(msg, NL80211_STA_WME_MAX_SP,
6196                                 (params->qosinfo >> WMM_QOSINFO_STA_SP_SHIFT) &
6197                                 WMM_QOSINFO_STA_SP_MASK);
6198                 nla_nest_end(msg, wme);
6199         }
6200
6201         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6202         msg = NULL;
6203         if (ret)
6204                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_%s_STATION "
6205                            "result: %d (%s)", params->set ? "SET" : "NEW", ret,
6206                            strerror(-ret));
6207         if (ret == -EEXIST)
6208                 ret = 0;
6209  nla_put_failure:
6210         nlmsg_free(msg);
6211         return ret;
6212 }
6213
6214
6215 static int wpa_driver_nl80211_sta_remove(struct i802_bss *bss, const u8 *addr)
6216 {
6217         struct wpa_driver_nl80211_data *drv = bss->drv;
6218         struct nl_msg *msg;
6219         int ret;
6220
6221         msg = nlmsg_alloc();
6222         if (!msg)
6223                 return -ENOMEM;
6224
6225         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
6226
6227         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
6228                     if_nametoindex(bss->ifname));
6229         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
6230
6231         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6232         if (ret == -ENOENT)
6233                 return 0;
6234         return ret;
6235  nla_put_failure:
6236         nlmsg_free(msg);
6237         return -ENOBUFS;
6238 }
6239
6240
6241 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
6242                                  int ifidx)
6243 {
6244         struct nl_msg *msg;
6245
6246         wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
6247
6248         /* stop listening for EAPOL on this interface */
6249         del_ifidx(drv, ifidx);
6250
6251         msg = nlmsg_alloc();
6252         if (!msg)
6253                 goto nla_put_failure;
6254
6255         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_INTERFACE);
6256         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
6257
6258         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
6259                 return;
6260         msg = NULL;
6261  nla_put_failure:
6262         nlmsg_free(msg);
6263         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
6264 }
6265
6266
6267 static const char * nl80211_iftype_str(enum nl80211_iftype mode)
6268 {
6269         switch (mode) {
6270         case NL80211_IFTYPE_ADHOC:
6271                 return "ADHOC";
6272         case NL80211_IFTYPE_STATION:
6273                 return "STATION";
6274         case NL80211_IFTYPE_AP:
6275                 return "AP";
6276         case NL80211_IFTYPE_MONITOR:
6277                 return "MONITOR";
6278         case NL80211_IFTYPE_P2P_CLIENT:
6279                 return "P2P_CLIENT";
6280         case NL80211_IFTYPE_P2P_GO:
6281                 return "P2P_GO";
6282         default:
6283                 return "unknown";
6284         }
6285 }
6286
6287
6288 static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
6289                                      const char *ifname,
6290                                      enum nl80211_iftype iftype,
6291                                      const u8 *addr, int wds)
6292 {
6293         struct nl_msg *msg;
6294         int ifidx;
6295         int ret = -ENOBUFS;
6296
6297         wpa_printf(MSG_DEBUG, "nl80211: Create interface iftype %d (%s)",
6298                    iftype, nl80211_iftype_str(iftype));
6299
6300         msg = nlmsg_alloc();
6301         if (!msg)
6302                 return -1;
6303
6304         nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_INTERFACE);
6305         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6306         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
6307         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
6308
6309         if (iftype == NL80211_IFTYPE_MONITOR) {
6310                 struct nlattr *flags;
6311
6312                 flags = nla_nest_start(msg, NL80211_ATTR_MNTR_FLAGS);
6313                 if (!flags)
6314                         goto nla_put_failure;
6315
6316                 NLA_PUT_FLAG(msg, NL80211_MNTR_FLAG_COOK_FRAMES);
6317
6318                 nla_nest_end(msg, flags);
6319         } else if (wds) {
6320                 NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
6321         }
6322
6323         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6324         msg = NULL;
6325         if (ret) {
6326  nla_put_failure:
6327                 nlmsg_free(msg);
6328                 wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
6329                            ifname, ret, strerror(-ret));
6330                 return ret;
6331         }
6332
6333         ifidx = if_nametoindex(ifname);
6334         wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
6335                    ifname, ifidx);
6336
6337         if (ifidx <= 0)
6338                 return -1;
6339
6340         /* start listening for EAPOL on this interface */
6341         add_ifidx(drv, ifidx);
6342
6343         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
6344             linux_set_ifhwaddr(drv->global->ioctl_sock, ifname, addr)) {
6345                 nl80211_remove_iface(drv, ifidx);
6346                 return -1;
6347         }
6348
6349         return ifidx;
6350 }
6351
6352
6353 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
6354                                 const char *ifname, enum nl80211_iftype iftype,
6355                                 const u8 *addr, int wds)
6356 {
6357         int ret;
6358
6359         ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds);
6360
6361         /* if error occurred and interface exists already */
6362         if (ret == -ENFILE && if_nametoindex(ifname)) {
6363                 wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
6364
6365                 /* Try to remove the interface that was already there. */
6366                 nl80211_remove_iface(drv, if_nametoindex(ifname));
6367
6368                 /* Try to create the interface again */
6369                 ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
6370                                                 wds);
6371         }
6372
6373         if (ret >= 0 && is_p2p_interface(iftype))
6374                 nl80211_disable_11b_rates(drv, ret, 1);
6375
6376         return ret;
6377 }
6378
6379
6380 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
6381 {
6382         struct ieee80211_hdr *hdr;
6383         u16 fc;
6384         union wpa_event_data event;
6385
6386         hdr = (struct ieee80211_hdr *) buf;
6387         fc = le_to_host16(hdr->frame_control);
6388
6389         os_memset(&event, 0, sizeof(event));
6390         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
6391         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
6392         event.tx_status.dst = hdr->addr1;
6393         event.tx_status.data = buf;
6394         event.tx_status.data_len = len;
6395         event.tx_status.ack = ok;
6396         wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
6397 }
6398
6399
6400 static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
6401                              u8 *buf, size_t len)
6402 {
6403         struct ieee80211_hdr *hdr = (void *)buf;
6404         u16 fc;
6405         union wpa_event_data event;
6406
6407         if (len < sizeof(*hdr))
6408                 return;
6409
6410         fc = le_to_host16(hdr->frame_control);
6411
6412         os_memset(&event, 0, sizeof(event));
6413         event.rx_from_unknown.bssid = get_hdr_bssid(hdr, len);
6414         event.rx_from_unknown.addr = hdr->addr2;
6415         event.rx_from_unknown.wds = (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) ==
6416                 (WLAN_FC_FROMDS | WLAN_FC_TODS);
6417         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
6418 }
6419
6420
6421 static void handle_frame(struct wpa_driver_nl80211_data *drv,
6422                          u8 *buf, size_t len, int datarate, int ssi_signal)
6423 {
6424         struct ieee80211_hdr *hdr;
6425         u16 fc;
6426         union wpa_event_data event;
6427
6428         hdr = (struct ieee80211_hdr *) buf;
6429         fc = le_to_host16(hdr->frame_control);
6430
6431         switch (WLAN_FC_GET_TYPE(fc)) {
6432         case WLAN_FC_TYPE_MGMT:
6433                 os_memset(&event, 0, sizeof(event));
6434                 event.rx_mgmt.frame = buf;
6435                 event.rx_mgmt.frame_len = len;
6436                 event.rx_mgmt.datarate = datarate;
6437                 event.rx_mgmt.ssi_signal = ssi_signal;
6438                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
6439                 break;
6440         case WLAN_FC_TYPE_CTRL:
6441                 /* can only get here with PS-Poll frames */
6442                 wpa_printf(MSG_DEBUG, "CTRL");
6443                 from_unknown_sta(drv, buf, len);
6444                 break;
6445         case WLAN_FC_TYPE_DATA:
6446                 from_unknown_sta(drv, buf, len);
6447                 break;
6448         }
6449 }
6450
6451
6452 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
6453 {
6454         struct wpa_driver_nl80211_data *drv = eloop_ctx;
6455         int len;
6456         unsigned char buf[3000];
6457         struct ieee80211_radiotap_iterator iter;
6458         int ret;
6459         int datarate = 0, ssi_signal = 0;
6460         int injected = 0, failed = 0, rxflags = 0;
6461
6462         len = recv(sock, buf, sizeof(buf), 0);
6463         if (len < 0) {
6464                 perror("recv");
6465                 return;
6466         }
6467
6468         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
6469                 printf("received invalid radiotap frame\n");
6470                 return;
6471         }
6472
6473         while (1) {
6474                 ret = ieee80211_radiotap_iterator_next(&iter);
6475                 if (ret == -ENOENT)
6476                         break;
6477                 if (ret) {
6478                         printf("received invalid radiotap frame (%d)\n", ret);
6479                         return;
6480                 }
6481                 switch (iter.this_arg_index) {
6482                 case IEEE80211_RADIOTAP_FLAGS:
6483                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
6484                                 len -= 4;
6485                         break;
6486                 case IEEE80211_RADIOTAP_RX_FLAGS:
6487                         rxflags = 1;
6488                         break;
6489                 case IEEE80211_RADIOTAP_TX_FLAGS:
6490                         injected = 1;
6491                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
6492                                         IEEE80211_RADIOTAP_F_TX_FAIL;
6493                         break;
6494                 case IEEE80211_RADIOTAP_DATA_RETRIES:
6495                         break;
6496                 case IEEE80211_RADIOTAP_CHANNEL:
6497                         /* TODO: convert from freq/flags to channel number */
6498                         break;
6499                 case IEEE80211_RADIOTAP_RATE:
6500                         datarate = *iter.this_arg * 5;
6501                         break;
6502                 case IEEE80211_RADIOTAP_DBM_ANTSIGNAL:
6503                         ssi_signal = (s8) *iter.this_arg;
6504                         break;
6505                 }
6506         }
6507
6508         if (rxflags && injected)
6509                 return;
6510
6511         if (!injected)
6512                 handle_frame(drv, buf + iter.max_length,
6513                              len - iter.max_length, datarate, ssi_signal);
6514         else
6515                 handle_tx_callback(drv->ctx, buf + iter.max_length,
6516                                    len - iter.max_length, !failed);
6517 }
6518
6519
6520 /*
6521  * we post-process the filter code later and rewrite
6522  * this to the offset to the last instruction
6523  */
6524 #define PASS    0xFF
6525 #define FAIL    0xFE
6526
6527 static struct sock_filter msock_filter_insns[] = {
6528         /*
6529          * do a little-endian load of the radiotap length field
6530          */
6531         /* load lower byte into A */
6532         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
6533         /* put it into X (== index register) */
6534         BPF_STMT(BPF_MISC| BPF_TAX, 0),
6535         /* load upper byte into A */
6536         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
6537         /* left-shift it by 8 */
6538         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
6539         /* or with X */
6540         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
6541         /* put result into X */
6542         BPF_STMT(BPF_MISC| BPF_TAX, 0),
6543
6544         /*
6545          * Allow management frames through, this also gives us those
6546          * management frames that we sent ourselves with status
6547          */
6548         /* load the lower byte of the IEEE 802.11 frame control field */
6549         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
6550         /* mask off frame type and version */
6551         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
6552         /* accept frame if it's both 0, fall through otherwise */
6553         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
6554
6555         /*
6556          * TODO: add a bit to radiotap RX flags that indicates
6557          * that the sending station is not associated, then
6558          * add a filter here that filters on our DA and that flag
6559          * to allow us to deauth frames to that bad station.
6560          *
6561          * For now allow all To DS data frames through.
6562          */
6563         /* load the IEEE 802.11 frame control field */
6564         BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
6565         /* mask off frame type, version and DS status */
6566         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
6567         /* accept frame if version 0, type 2 and To DS, fall through otherwise
6568          */
6569         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
6570
6571 #if 0
6572         /*
6573          * drop non-data frames
6574          */
6575         /* load the lower byte of the frame control field */
6576         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
6577         /* mask off QoS bit */
6578         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
6579         /* drop non-data frames */
6580         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
6581 #endif
6582         /* load the upper byte of the frame control field */
6583         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
6584         /* mask off toDS/fromDS */
6585         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
6586         /* accept WDS frames */
6587         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
6588
6589         /*
6590          * add header length to index
6591          */
6592         /* load the lower byte of the frame control field */
6593         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
6594         /* mask off QoS bit */
6595         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
6596         /* right shift it by 6 to give 0 or 2 */
6597         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
6598         /* add data frame header length */
6599         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
6600         /* add index, was start of 802.11 header */
6601         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
6602         /* move to index, now start of LL header */
6603         BPF_STMT(BPF_MISC | BPF_TAX, 0),
6604
6605         /*
6606          * Accept empty data frames, we use those for
6607          * polling activity.
6608          */
6609         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
6610         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
6611
6612         /*
6613          * Accept EAPOL frames
6614          */
6615         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
6616         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
6617         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
6618         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
6619
6620         /* keep these last two statements or change the code below */
6621         /* return 0 == "DROP" */
6622         BPF_STMT(BPF_RET | BPF_K, 0),
6623         /* return ~0 == "keep all" */
6624         BPF_STMT(BPF_RET | BPF_K, ~0),
6625 };
6626
6627 static struct sock_fprog msock_filter = {
6628         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
6629         .filter = msock_filter_insns,
6630 };
6631
6632
6633 static int add_monitor_filter(int s)
6634 {
6635         int idx;
6636
6637         /* rewrite all PASS/FAIL jump offsets */
6638         for (idx = 0; idx < msock_filter.len; idx++) {
6639                 struct sock_filter *insn = &msock_filter_insns[idx];
6640
6641                 if (BPF_CLASS(insn->code) == BPF_JMP) {
6642                         if (insn->code == (BPF_JMP|BPF_JA)) {
6643                                 if (insn->k == PASS)
6644                                         insn->k = msock_filter.len - idx - 2;
6645                                 else if (insn->k == FAIL)
6646                                         insn->k = msock_filter.len - idx - 3;
6647                         }
6648
6649                         if (insn->jt == PASS)
6650                                 insn->jt = msock_filter.len - idx - 2;
6651                         else if (insn->jt == FAIL)
6652                                 insn->jt = msock_filter.len - idx - 3;
6653
6654                         if (insn->jf == PASS)
6655                                 insn->jf = msock_filter.len - idx - 2;
6656                         else if (insn->jf == FAIL)
6657                                 insn->jf = msock_filter.len - idx - 3;
6658                 }
6659         }
6660
6661         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
6662                        &msock_filter, sizeof(msock_filter))) {
6663                 perror("SO_ATTACH_FILTER");
6664                 return -1;
6665         }
6666
6667         return 0;
6668 }
6669
6670
6671 static void nl80211_remove_monitor_interface(
6672         struct wpa_driver_nl80211_data *drv)
6673 {
6674         drv->monitor_refcount--;
6675         if (drv->monitor_refcount > 0)
6676                 return;
6677
6678         if (drv->monitor_ifidx >= 0) {
6679                 nl80211_remove_iface(drv, drv->monitor_ifidx);
6680                 drv->monitor_ifidx = -1;
6681         }
6682         if (drv->monitor_sock >= 0) {
6683                 eloop_unregister_read_sock(drv->monitor_sock);
6684                 close(drv->monitor_sock);
6685                 drv->monitor_sock = -1;
6686         }
6687 }
6688
6689
6690 static int
6691 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
6692 {
6693         char buf[IFNAMSIZ];
6694         struct sockaddr_ll ll;
6695         int optval;
6696         socklen_t optlen;
6697
6698         if (drv->monitor_ifidx >= 0) {
6699                 drv->monitor_refcount++;
6700                 return 0;
6701         }
6702
6703         if (os_strncmp(drv->first_bss.ifname, "p2p-", 4) == 0) {
6704                 /*
6705                  * P2P interface name is of the format p2p-%s-%d. For monitor
6706                  * interface name corresponding to P2P GO, replace "p2p-" with
6707                  * "mon-" to retain the same interface name length and to
6708                  * indicate that it is a monitor interface.
6709                  */
6710                 snprintf(buf, IFNAMSIZ, "mon-%s", drv->first_bss.ifname + 4);
6711         } else {
6712                 /* Non-P2P interface with AP functionality. */
6713                 snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss.ifname);
6714         }
6715
6716         buf[IFNAMSIZ - 1] = '\0';
6717
6718         drv->monitor_ifidx =
6719                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
6720                                      0);
6721
6722         if (drv->monitor_ifidx == -EOPNOTSUPP) {
6723                 /*
6724                  * This is backward compatibility for a few versions of
6725                  * the kernel only that didn't advertise the right
6726                  * attributes for the only driver that then supported
6727                  * AP mode w/o monitor -- ath6kl.
6728                  */
6729                 wpa_printf(MSG_DEBUG, "nl80211: Driver does not support "
6730                            "monitor interface type - try to run without it");
6731                 drv->device_ap_sme = 1;
6732         }
6733
6734         if (drv->monitor_ifidx < 0)
6735                 return -1;
6736
6737         if (linux_set_iface_flags(drv->global->ioctl_sock, buf, 1))
6738                 goto error;
6739
6740         memset(&ll, 0, sizeof(ll));
6741         ll.sll_family = AF_PACKET;
6742         ll.sll_ifindex = drv->monitor_ifidx;
6743         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
6744         if (drv->monitor_sock < 0) {
6745                 perror("socket[PF_PACKET,SOCK_RAW]");
6746                 goto error;
6747         }
6748
6749         if (add_monitor_filter(drv->monitor_sock)) {
6750                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
6751                            "interface; do filtering in user space");
6752                 /* This works, but will cost in performance. */
6753         }
6754
6755         if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
6756                 perror("monitor socket bind");
6757                 goto error;
6758         }
6759
6760         optlen = sizeof(optval);
6761         optval = 20;
6762         if (setsockopt
6763             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
6764                 perror("Failed to set socket priority");
6765                 goto error;
6766         }
6767
6768         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
6769                                      drv, NULL)) {
6770                 printf("Could not register monitor read socket\n");
6771                 goto error;
6772         }
6773
6774         return 0;
6775  error:
6776         nl80211_remove_monitor_interface(drv);
6777         return -1;
6778 }
6779
6780
6781 static int nl80211_setup_ap(struct i802_bss *bss)
6782 {
6783         struct wpa_driver_nl80211_data *drv = bss->drv;
6784
6785         wpa_printf(MSG_DEBUG, "nl80211: Setup AP - device_ap_sme=%d "
6786                    "use_monitor=%d", drv->device_ap_sme, drv->use_monitor);
6787
6788         /*
6789          * Disable Probe Request reporting unless we need it in this way for
6790          * devices that include the AP SME, in the other case (unless using
6791          * monitor iface) we'll get it through the nl_mgmt socket instead.
6792          */
6793         if (!drv->device_ap_sme)
6794                 wpa_driver_nl80211_probe_req_report(bss, 0);
6795
6796         if (!drv->device_ap_sme && !drv->use_monitor)
6797                 if (nl80211_mgmt_subscribe_ap(bss))
6798                         return -1;
6799
6800         if (drv->device_ap_sme && !drv->use_monitor)
6801                 if (nl80211_mgmt_subscribe_ap_dev_sme(bss))
6802                         return -1;
6803
6804         if (!drv->device_ap_sme && drv->use_monitor &&
6805             nl80211_create_monitor_interface(drv) &&
6806             !drv->device_ap_sme)
6807                 return -1;
6808
6809         if (drv->device_ap_sme &&
6810             wpa_driver_nl80211_probe_req_report(bss, 1) < 0) {
6811                 wpa_printf(MSG_DEBUG, "nl80211: Failed to enable "
6812                            "Probe Request frame reporting in AP mode");
6813                 /* Try to survive without this */
6814         }
6815
6816         return 0;
6817 }
6818
6819
6820 static void nl80211_teardown_ap(struct i802_bss *bss)
6821 {
6822         struct wpa_driver_nl80211_data *drv = bss->drv;
6823
6824         if (drv->device_ap_sme) {
6825                 wpa_driver_nl80211_probe_req_report(bss, 0);
6826                 if (!drv->use_monitor)
6827                         nl80211_mgmt_unsubscribe(bss, "AP teardown (dev SME)");
6828         } else if (drv->use_monitor)
6829                 nl80211_remove_monitor_interface(drv);
6830         else
6831                 nl80211_mgmt_unsubscribe(bss, "AP teardown");
6832
6833         bss->beacon_set = 0;
6834 }
6835
6836
6837 static int nl80211_send_eapol_data(struct i802_bss *bss,
6838                                    const u8 *addr, const u8 *data,
6839                                    size_t data_len)
6840 {
6841         struct sockaddr_ll ll;
6842         int ret;
6843
6844         if (bss->drv->eapol_tx_sock < 0) {
6845                 wpa_printf(MSG_DEBUG, "nl80211: No socket to send EAPOL");
6846                 return -1;
6847         }
6848
6849         os_memset(&ll, 0, sizeof(ll));
6850         ll.sll_family = AF_PACKET;
6851         ll.sll_ifindex = bss->ifindex;
6852         ll.sll_protocol = htons(ETH_P_PAE);
6853         ll.sll_halen = ETH_ALEN;
6854         os_memcpy(ll.sll_addr, addr, ETH_ALEN);
6855         ret = sendto(bss->drv->eapol_tx_sock, data, data_len, 0,
6856                      (struct sockaddr *) &ll, sizeof(ll));
6857         if (ret < 0)
6858                 wpa_printf(MSG_ERROR, "nl80211: EAPOL TX: %s",
6859                            strerror(errno));
6860
6861         return ret;
6862 }
6863
6864
6865 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
6866
6867 static int wpa_driver_nl80211_hapd_send_eapol(
6868         void *priv, const u8 *addr, const u8 *data,
6869         size_t data_len, int encrypt, const u8 *own_addr, u32 flags)
6870 {
6871         struct i802_bss *bss = priv;
6872         struct wpa_driver_nl80211_data *drv = bss->drv;
6873         struct ieee80211_hdr *hdr;
6874         size_t len;
6875         u8 *pos;
6876         int res;
6877         int qos = flags & WPA_STA_WMM;
6878
6879         if (drv->device_ap_sme || !drv->use_monitor)
6880                 return nl80211_send_eapol_data(bss, addr, data, data_len);
6881
6882         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
6883                 data_len;
6884         hdr = os_zalloc(len);
6885         if (hdr == NULL) {
6886                 printf("malloc() failed for i802_send_data(len=%lu)\n",
6887                        (unsigned long) len);
6888                 return -1;
6889         }
6890
6891         hdr->frame_control =
6892                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
6893         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
6894         if (encrypt)
6895                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
6896         if (qos) {
6897                 hdr->frame_control |=
6898                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
6899         }
6900
6901         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
6902         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
6903         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
6904         pos = (u8 *) (hdr + 1);
6905
6906         if (qos) {
6907                 /* Set highest priority in QoS header */
6908                 pos[0] = 7;
6909                 pos[1] = 0;
6910                 pos += 2;
6911         }
6912
6913         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
6914         pos += sizeof(rfc1042_header);
6915         WPA_PUT_BE16(pos, ETH_P_PAE);
6916         pos += 2;
6917         memcpy(pos, data, data_len);
6918
6919         res = wpa_driver_nl80211_send_frame(bss, (u8 *) hdr, len, encrypt, 0,
6920                                             0, 0, 0, 0);
6921         if (res < 0) {
6922                 wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
6923                            "failed: %d (%s)",
6924                            (unsigned long) len, errno, strerror(errno));
6925         }
6926         os_free(hdr);
6927
6928         return res;
6929 }
6930
6931
6932 static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
6933                                             int total_flags,
6934                                             int flags_or, int flags_and)
6935 {
6936         struct i802_bss *bss = priv;
6937         struct wpa_driver_nl80211_data *drv = bss->drv;
6938         struct nl_msg *msg;
6939         struct nlattr *flags;
6940         struct nl80211_sta_flag_update upd;
6941
6942         msg = nlmsg_alloc();
6943         if (!msg)
6944                 return -ENOMEM;
6945
6946         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
6947
6948         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
6949                     if_nametoindex(bss->ifname));
6950         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
6951
6952         /*
6953          * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
6954          * can be removed eventually.
6955          */
6956         flags = nla_nest_start(msg, NL80211_ATTR_STA_FLAGS);
6957         if (!flags)
6958                 goto nla_put_failure;
6959         if (total_flags & WPA_STA_AUTHORIZED)
6960                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_AUTHORIZED);
6961
6962         if (total_flags & WPA_STA_WMM)
6963                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_WME);
6964
6965         if (total_flags & WPA_STA_SHORT_PREAMBLE)
6966                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_SHORT_PREAMBLE);
6967
6968         if (total_flags & WPA_STA_MFP)
6969                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_MFP);
6970
6971         if (total_flags & WPA_STA_TDLS_PEER)
6972                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_TDLS_PEER);
6973
6974         nla_nest_end(msg, flags);
6975
6976         os_memset(&upd, 0, sizeof(upd));
6977         upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
6978         upd.set = sta_flags_nl80211(flags_or);
6979         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
6980
6981         return send_and_recv_msgs(drv, msg, NULL, NULL);
6982  nla_put_failure:
6983         nlmsg_free(msg);
6984         return -ENOBUFS;
6985 }
6986
6987
6988 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
6989                                  struct wpa_driver_associate_params *params)
6990 {
6991         enum nl80211_iftype nlmode, old_mode;
6992         struct hostapd_freq_params freq = {
6993                 .freq = params->freq,
6994         };
6995
6996         if (params->p2p) {
6997                 wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
6998                            "group (GO)");
6999                 nlmode = NL80211_IFTYPE_P2P_GO;
7000         } else
7001                 nlmode = NL80211_IFTYPE_AP;
7002
7003         old_mode = drv->nlmode;
7004         if (wpa_driver_nl80211_set_mode(&drv->first_bss, nlmode)) {
7005                 nl80211_remove_monitor_interface(drv);
7006                 return -1;
7007         }
7008
7009         if (wpa_driver_nl80211_set_freq(&drv->first_bss, &freq)) {
7010                 if (old_mode != nlmode)
7011                         wpa_driver_nl80211_set_mode(&drv->first_bss, old_mode);
7012                 nl80211_remove_monitor_interface(drv);
7013                 return -1;
7014         }
7015
7016         return 0;
7017 }
7018
7019
7020 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
7021 {
7022         struct nl_msg *msg;
7023         int ret = -1;
7024
7025         msg = nlmsg_alloc();
7026         if (!msg)
7027                 return -1;
7028
7029         nl80211_cmd(drv, msg, 0, NL80211_CMD_LEAVE_IBSS);
7030         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7031         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7032         msg = NULL;
7033         if (ret) {
7034                 wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
7035                            "(%s)", ret, strerror(-ret));
7036                 goto nla_put_failure;
7037         }
7038
7039         ret = 0;
7040         wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
7041
7042 nla_put_failure:
7043         nlmsg_free(msg);
7044         return ret;
7045 }
7046
7047
7048 static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
7049                                    struct wpa_driver_associate_params *params)
7050 {
7051         struct nl_msg *msg;
7052         int ret = -1;
7053         int count = 0;
7054
7055         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
7056
7057         if (wpa_driver_nl80211_set_mode(&drv->first_bss,
7058                                         NL80211_IFTYPE_ADHOC)) {
7059                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
7060                            "IBSS mode");
7061                 return -1;
7062         }
7063
7064 retry:
7065         msg = nlmsg_alloc();
7066         if (!msg)
7067                 return -1;
7068
7069         nl80211_cmd(drv, msg, 0, NL80211_CMD_JOIN_IBSS);
7070         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7071
7072         if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
7073                 goto nla_put_failure;
7074
7075         wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
7076                           params->ssid, params->ssid_len);
7077         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
7078                 params->ssid);
7079         os_memcpy(drv->ssid, params->ssid, params->ssid_len);
7080         drv->ssid_len = params->ssid_len;
7081
7082         wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
7083         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
7084
7085         ret = nl80211_set_conn_keys(params, msg);
7086         if (ret)
7087                 goto nla_put_failure;
7088
7089         if (params->bssid && params->fixed_bssid) {
7090                 wpa_printf(MSG_DEBUG, "  * BSSID=" MACSTR,
7091                            MAC2STR(params->bssid));
7092                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
7093         }
7094
7095         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
7096             params->key_mgmt_suite == KEY_MGMT_PSK ||
7097             params->key_mgmt_suite == KEY_MGMT_802_1X_SHA256 ||
7098             params->key_mgmt_suite == KEY_MGMT_PSK_SHA256) {
7099                 wpa_printf(MSG_DEBUG, "  * control port");
7100                 NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
7101         }
7102
7103         if (params->wpa_ie) {
7104                 wpa_hexdump(MSG_DEBUG,
7105                             "  * Extra IEs for Beacon/Probe Response frames",
7106                             params->wpa_ie, params->wpa_ie_len);
7107                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
7108                         params->wpa_ie);
7109         }
7110
7111         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7112         msg = NULL;
7113         if (ret) {
7114                 wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
7115                            ret, strerror(-ret));
7116                 count++;
7117                 if (ret == -EALREADY && count == 1) {
7118                         wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
7119                                    "forced leave");
7120                         nl80211_leave_ibss(drv);
7121                         nlmsg_free(msg);
7122                         goto retry;
7123                 }
7124
7125                 goto nla_put_failure;
7126         }
7127         ret = 0;
7128         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
7129
7130 nla_put_failure:
7131         nlmsg_free(msg);
7132         return ret;
7133 }
7134
7135
7136 static int wpa_driver_nl80211_try_connect(
7137         struct wpa_driver_nl80211_data *drv,
7138         struct wpa_driver_associate_params *params)
7139 {
7140         struct nl_msg *msg;
7141         enum nl80211_auth_type type;
7142         int ret = 0;
7143         int algs;
7144
7145         msg = nlmsg_alloc();
7146         if (!msg)
7147                 return -1;
7148
7149         wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
7150         nl80211_cmd(drv, msg, 0, NL80211_CMD_CONNECT);
7151
7152         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7153         if (params->bssid) {
7154                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
7155                            MAC2STR(params->bssid));
7156                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
7157         }
7158         if (params->freq) {
7159                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
7160                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
7161         }
7162         if (params->bg_scan_period >= 0) {
7163                 wpa_printf(MSG_DEBUG, "  * bg scan period=%d",
7164                            params->bg_scan_period);
7165                 NLA_PUT_U16(msg, NL80211_ATTR_BG_SCAN_PERIOD,
7166                             params->bg_scan_period);
7167         }
7168         if (params->ssid) {
7169                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
7170                                   params->ssid, params->ssid_len);
7171                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
7172                         params->ssid);
7173                 if (params->ssid_len > sizeof(drv->ssid))
7174                         goto nla_put_failure;
7175                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
7176                 drv->ssid_len = params->ssid_len;
7177         }
7178         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
7179         if (params->wpa_ie)
7180                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
7181                         params->wpa_ie);
7182
7183         algs = 0;
7184         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
7185                 algs++;
7186         if (params->auth_alg & WPA_AUTH_ALG_SHARED)
7187                 algs++;
7188         if (params->auth_alg & WPA_AUTH_ALG_LEAP)
7189                 algs++;
7190         if (algs > 1) {
7191                 wpa_printf(MSG_DEBUG, "  * Leave out Auth Type for automatic "
7192                            "selection");
7193                 goto skip_auth_type;
7194         }
7195
7196         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
7197                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
7198         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
7199                 type = NL80211_AUTHTYPE_SHARED_KEY;
7200         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
7201                 type = NL80211_AUTHTYPE_NETWORK_EAP;
7202         else if (params->auth_alg & WPA_AUTH_ALG_FT)
7203                 type = NL80211_AUTHTYPE_FT;
7204         else
7205                 goto nla_put_failure;
7206
7207         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
7208         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
7209
7210 skip_auth_type:
7211         if (params->wpa_proto) {
7212                 enum nl80211_wpa_versions ver = 0;
7213
7214                 if (params->wpa_proto & WPA_PROTO_WPA)
7215                         ver |= NL80211_WPA_VERSION_1;
7216                 if (params->wpa_proto & WPA_PROTO_RSN)
7217                         ver |= NL80211_WPA_VERSION_2;
7218
7219                 wpa_printf(MSG_DEBUG, "  * WPA Versions 0x%x", ver);
7220                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
7221         }
7222
7223         if (params->pairwise_suite != CIPHER_NONE) {
7224                 int cipher;
7225
7226                 switch (params->pairwise_suite) {
7227                 case CIPHER_SMS4:
7228                         cipher = WLAN_CIPHER_SUITE_SMS4;
7229                         break;
7230                 case CIPHER_WEP40:
7231                         cipher = WLAN_CIPHER_SUITE_WEP40;
7232                         break;
7233                 case CIPHER_WEP104:
7234                         cipher = WLAN_CIPHER_SUITE_WEP104;
7235                         break;
7236                 case CIPHER_CCMP:
7237                         cipher = WLAN_CIPHER_SUITE_CCMP;
7238                         break;
7239                 case CIPHER_GCMP:
7240                         cipher = WLAN_CIPHER_SUITE_GCMP;
7241                         break;
7242                 case CIPHER_TKIP:
7243                 default:
7244                         cipher = WLAN_CIPHER_SUITE_TKIP;
7245                         break;
7246                 }
7247                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
7248         }
7249
7250         if (params->group_suite != CIPHER_NONE) {
7251                 int cipher;
7252
7253                 switch (params->group_suite) {
7254                 case CIPHER_SMS4:
7255                         cipher = WLAN_CIPHER_SUITE_SMS4;
7256                         break;
7257                 case CIPHER_WEP40:
7258                         cipher = WLAN_CIPHER_SUITE_WEP40;
7259                         break;
7260                 case CIPHER_WEP104:
7261                         cipher = WLAN_CIPHER_SUITE_WEP104;
7262                         break;
7263                 case CIPHER_CCMP:
7264                         cipher = WLAN_CIPHER_SUITE_CCMP;
7265                         break;
7266                 case CIPHER_GCMP:
7267                         cipher = WLAN_CIPHER_SUITE_GCMP;
7268                         break;
7269                 case CIPHER_TKIP:
7270                 default:
7271                         cipher = WLAN_CIPHER_SUITE_TKIP;
7272                         break;
7273                 }
7274                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
7275         }
7276
7277         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
7278             params->key_mgmt_suite == KEY_MGMT_PSK ||
7279             params->key_mgmt_suite == KEY_MGMT_FT_802_1X ||
7280             params->key_mgmt_suite == KEY_MGMT_FT_PSK ||
7281             params->key_mgmt_suite == KEY_MGMT_CCKM) {
7282                 int mgmt = WLAN_AKM_SUITE_PSK;
7283
7284                 switch (params->key_mgmt_suite) {
7285                 case KEY_MGMT_CCKM:
7286                         mgmt = WLAN_AKM_SUITE_CCKM;
7287                         break;
7288                 case KEY_MGMT_802_1X:
7289                         mgmt = WLAN_AKM_SUITE_8021X;
7290                         break;
7291                 case KEY_MGMT_FT_802_1X:
7292                         mgmt = WLAN_AKM_SUITE_FT_8021X;
7293                         break;
7294                 case KEY_MGMT_FT_PSK:
7295                         mgmt = WLAN_AKM_SUITE_FT_PSK;
7296                         break;
7297                 case KEY_MGMT_PSK:
7298                 default:
7299                         mgmt = WLAN_AKM_SUITE_PSK;
7300                         break;
7301                 }
7302                 NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
7303         }
7304
7305 #ifdef CONFIG_IEEE80211W
7306         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
7307                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
7308 #endif /* CONFIG_IEEE80211W */
7309
7310         if (params->disable_ht)
7311                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
7312
7313         if (params->htcaps && params->htcaps_mask) {
7314                 int sz = sizeof(struct ieee80211_ht_capabilities);
7315                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
7316                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
7317                         params->htcaps_mask);
7318         }
7319
7320 #ifdef CONFIG_VHT_OVERRIDES
7321         if (params->disable_vht) {
7322                 wpa_printf(MSG_DEBUG, "  * VHT disabled");
7323                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_VHT);
7324         }
7325
7326         if (params->vhtcaps && params->vhtcaps_mask) {
7327                 int sz = sizeof(struct ieee80211_vht_capabilities);
7328                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY, sz, params->vhtcaps);
7329                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY_MASK, sz,
7330                         params->vhtcaps_mask);
7331         }
7332 #endif /* CONFIG_VHT_OVERRIDES */
7333
7334         ret = nl80211_set_conn_keys(params, msg);
7335         if (ret)
7336                 goto nla_put_failure;
7337
7338         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7339         msg = NULL;
7340         if (ret) {
7341                 wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
7342                            "(%s)", ret, strerror(-ret));
7343                 goto nla_put_failure;
7344         }
7345         ret = 0;
7346         wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
7347
7348 nla_put_failure:
7349         nlmsg_free(msg);
7350         return ret;
7351
7352 }
7353
7354
7355 static int wpa_driver_nl80211_connect(
7356         struct wpa_driver_nl80211_data *drv,
7357         struct wpa_driver_associate_params *params)
7358 {
7359         int ret = wpa_driver_nl80211_try_connect(drv, params);
7360         if (ret == -EALREADY) {
7361                 /*
7362                  * cfg80211 does not currently accept new connections if
7363                  * we are already connected. As a workaround, force
7364                  * disconnection and try again.
7365                  */
7366                 wpa_printf(MSG_DEBUG, "nl80211: Explicitly "
7367                            "disconnecting before reassociation "
7368                            "attempt");
7369                 if (wpa_driver_nl80211_disconnect(
7370                             drv, WLAN_REASON_PREV_AUTH_NOT_VALID))
7371                         return -1;
7372                 /* Ignore the next local disconnect message. */
7373                 drv->ignore_next_local_disconnect = 1;
7374                 ret = wpa_driver_nl80211_try_connect(drv, params);
7375         }
7376         return ret;
7377 }
7378
7379
7380 static int wpa_driver_nl80211_associate(
7381         void *priv, struct wpa_driver_associate_params *params)
7382 {
7383         struct i802_bss *bss = priv;
7384         struct wpa_driver_nl80211_data *drv = bss->drv;
7385         int ret = -1;
7386         struct nl_msg *msg;
7387
7388         if (params->mode == IEEE80211_MODE_AP)
7389                 return wpa_driver_nl80211_ap(drv, params);
7390
7391         if (params->mode == IEEE80211_MODE_IBSS)
7392                 return wpa_driver_nl80211_ibss(drv, params);
7393
7394         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
7395                 enum nl80211_iftype nlmode = params->p2p ?
7396                         NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
7397
7398                 if (wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
7399                         return -1;
7400                 return wpa_driver_nl80211_connect(drv, params);
7401         }
7402
7403         drv->associated = 0;
7404
7405         msg = nlmsg_alloc();
7406         if (!msg)
7407                 return -1;
7408
7409         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
7410                    drv->ifindex);
7411         nl80211_cmd(drv, msg, 0, NL80211_CMD_ASSOCIATE);
7412
7413         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7414         if (params->bssid) {
7415                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
7416                            MAC2STR(params->bssid));
7417                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
7418         }
7419         if (params->freq) {
7420                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
7421                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
7422                 drv->assoc_freq = params->freq;
7423         } else
7424                 drv->assoc_freq = 0;
7425         if (params->bg_scan_period >= 0) {
7426                 wpa_printf(MSG_DEBUG, "  * bg scan period=%d",
7427                            params->bg_scan_period);
7428                 NLA_PUT_U16(msg, NL80211_ATTR_BG_SCAN_PERIOD,
7429                             params->bg_scan_period);
7430         }
7431         if (params->ssid) {
7432                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
7433                                   params->ssid, params->ssid_len);
7434                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
7435                         params->ssid);
7436                 if (params->ssid_len > sizeof(drv->ssid))
7437                         goto nla_put_failure;
7438                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
7439                 drv->ssid_len = params->ssid_len;
7440         }
7441         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
7442         if (params->wpa_ie)
7443                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
7444                         params->wpa_ie);
7445
7446         if (params->pairwise_suite != CIPHER_NONE) {
7447                 int cipher;
7448
7449                 switch (params->pairwise_suite) {
7450                 case CIPHER_WEP40:
7451                         cipher = WLAN_CIPHER_SUITE_WEP40;
7452                         break;
7453                 case CIPHER_WEP104:
7454                         cipher = WLAN_CIPHER_SUITE_WEP104;
7455                         break;
7456                 case CIPHER_CCMP:
7457                         cipher = WLAN_CIPHER_SUITE_CCMP;
7458                         break;
7459                 case CIPHER_GCMP:
7460                         cipher = WLAN_CIPHER_SUITE_GCMP;
7461                         break;
7462                 case CIPHER_TKIP:
7463                 default:
7464                         cipher = WLAN_CIPHER_SUITE_TKIP;
7465                         break;
7466                 }
7467                 wpa_printf(MSG_DEBUG, "  * pairwise=0x%x", cipher);
7468                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
7469         }
7470
7471         if (params->group_suite != CIPHER_NONE) {
7472                 int cipher;
7473
7474                 switch (params->group_suite) {
7475                 case CIPHER_WEP40:
7476                         cipher = WLAN_CIPHER_SUITE_WEP40;
7477                         break;
7478                 case CIPHER_WEP104:
7479                         cipher = WLAN_CIPHER_SUITE_WEP104;
7480                         break;
7481                 case CIPHER_CCMP:
7482                         cipher = WLAN_CIPHER_SUITE_CCMP;
7483                         break;
7484                 case CIPHER_GCMP:
7485                         cipher = WLAN_CIPHER_SUITE_GCMP;
7486                         break;
7487                 case CIPHER_TKIP:
7488                 default:
7489                         cipher = WLAN_CIPHER_SUITE_TKIP;
7490                         break;
7491                 }
7492                 wpa_printf(MSG_DEBUG, "  * group=0x%x", cipher);
7493                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
7494         }
7495
7496 #ifdef CONFIG_IEEE80211W
7497         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
7498                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
7499 #endif /* CONFIG_IEEE80211W */
7500
7501         NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
7502
7503         if (params->prev_bssid) {
7504                 wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
7505                            MAC2STR(params->prev_bssid));
7506                 NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
7507                         params->prev_bssid);
7508         }
7509
7510         if (params->disable_ht)
7511                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
7512
7513         if (params->htcaps && params->htcaps_mask) {
7514                 int sz = sizeof(struct ieee80211_ht_capabilities);
7515                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
7516                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
7517                         params->htcaps_mask);
7518         }
7519
7520 #ifdef CONFIG_VHT_OVERRIDES
7521         if (params->disable_vht) {
7522                 wpa_printf(MSG_DEBUG, "  * VHT disabled");
7523                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_VHT);
7524         }
7525
7526         if (params->vhtcaps && params->vhtcaps_mask) {
7527                 int sz = sizeof(struct ieee80211_vht_capabilities);
7528                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY, sz, params->vhtcaps);
7529                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY_MASK, sz,
7530                         params->vhtcaps_mask);
7531         }
7532 #endif /* CONFIG_VHT_OVERRIDES */
7533
7534         if (params->p2p)
7535                 wpa_printf(MSG_DEBUG, "  * P2P group");
7536
7537         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7538         msg = NULL;
7539         if (ret) {
7540                 wpa_dbg(drv->ctx, MSG_DEBUG,
7541                         "nl80211: MLME command failed (assoc): ret=%d (%s)",
7542                         ret, strerror(-ret));
7543                 nl80211_dump_scan(drv);
7544                 goto nla_put_failure;
7545         }
7546         ret = 0;
7547         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
7548                    "successfully");
7549
7550 nla_put_failure:
7551         nlmsg_free(msg);
7552         return ret;
7553 }
7554
7555
7556 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
7557                             int ifindex, enum nl80211_iftype mode)
7558 {
7559         struct nl_msg *msg;
7560         int ret = -ENOBUFS;
7561
7562         wpa_printf(MSG_DEBUG, "nl80211: Set mode ifindex %d iftype %d (%s)",
7563                    ifindex, mode, nl80211_iftype_str(mode));
7564
7565         msg = nlmsg_alloc();
7566         if (!msg)
7567                 return -ENOMEM;
7568
7569         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_INTERFACE);
7570         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
7571         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
7572
7573         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7574         msg = NULL;
7575         if (!ret)
7576                 return 0;
7577 nla_put_failure:
7578         nlmsg_free(msg);
7579         wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
7580                    " %d (%s)", ifindex, mode, ret, strerror(-ret));
7581         return ret;
7582 }
7583
7584
7585 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
7586                                        enum nl80211_iftype nlmode)
7587 {
7588         struct wpa_driver_nl80211_data *drv = bss->drv;
7589         int ret = -1;
7590         int i;
7591         int was_ap = is_ap_interface(drv->nlmode);
7592         int res;
7593
7594         res = nl80211_set_mode(drv, drv->ifindex, nlmode);
7595         if (res == 0) {
7596                 drv->nlmode = nlmode;
7597                 ret = 0;
7598                 goto done;
7599         }
7600
7601         if (res == -ENODEV)
7602                 return -1;
7603
7604         if (nlmode == drv->nlmode) {
7605                 wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
7606                            "requested mode - ignore error");
7607                 ret = 0;
7608                 goto done; /* Already in the requested mode */
7609         }
7610
7611         /* mac80211 doesn't allow mode changes while the device is up, so
7612          * take the device down, try to set the mode again, and bring the
7613          * device back up.
7614          */
7615         wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
7616                    "interface down");
7617         for (i = 0; i < 10; i++) {
7618                 res = linux_set_iface_flags(drv->global->ioctl_sock,
7619                                             bss->ifname, 0);
7620                 if (res == -EACCES || res == -ENODEV)
7621                         break;
7622                 if (res == 0) {
7623                         /* Try to set the mode again while the interface is
7624                          * down */
7625                         ret = nl80211_set_mode(drv, drv->ifindex, nlmode);
7626                         if (ret == -EACCES)
7627                                 break;
7628                         res = linux_set_iface_flags(drv->global->ioctl_sock,
7629                                                     bss->ifname, 1);
7630                         if (res && !ret)
7631                                 ret = -1;
7632                         else if (ret != -EBUSY)
7633                                 break;
7634                 } else
7635                         wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
7636                                    "interface down");
7637                 os_sleep(0, 100000);
7638         }
7639
7640         if (!ret) {
7641                 wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
7642                            "interface is down");
7643                 drv->nlmode = nlmode;
7644                 drv->ignore_if_down_event = 1;
7645         }
7646
7647 done:
7648         if (ret) {
7649                 wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
7650                            "from %d failed", nlmode, drv->nlmode);
7651                 return ret;
7652         }
7653
7654         if (is_p2p_interface(nlmode))
7655                 nl80211_disable_11b_rates(drv, drv->ifindex, 1);
7656         else if (drv->disabled_11b_rates)
7657                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
7658
7659         if (is_ap_interface(nlmode)) {
7660                 nl80211_mgmt_unsubscribe(bss, "start AP");
7661                 /* Setup additional AP mode functionality if needed */
7662                 if (nl80211_setup_ap(bss))
7663                         return -1;
7664         } else if (was_ap) {
7665                 /* Remove additional AP mode functionality */
7666                 nl80211_teardown_ap(bss);
7667         } else {
7668                 nl80211_mgmt_unsubscribe(bss, "mode change");
7669         }
7670
7671         if (!bss->in_deinit && !is_ap_interface(nlmode) &&
7672             nl80211_mgmt_subscribe_non_ap(bss) < 0)
7673                 wpa_printf(MSG_DEBUG, "nl80211: Failed to register Action "
7674                            "frame processing - ignore for now");
7675
7676         return 0;
7677 }
7678
7679
7680 static int wpa_driver_nl80211_get_capa(void *priv,
7681                                        struct wpa_driver_capa *capa)
7682 {
7683         struct i802_bss *bss = priv;
7684         struct wpa_driver_nl80211_data *drv = bss->drv;
7685         if (!drv->has_capability)
7686                 return -1;
7687         os_memcpy(capa, &drv->capa, sizeof(*capa));
7688         if (drv->extended_capa && drv->extended_capa_mask) {
7689                 capa->extended_capa = drv->extended_capa;
7690                 capa->extended_capa_mask = drv->extended_capa_mask;
7691                 capa->extended_capa_len = drv->extended_capa_len;
7692         }
7693         return 0;
7694 }
7695
7696
7697 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
7698 {
7699         struct i802_bss *bss = priv;
7700         struct wpa_driver_nl80211_data *drv = bss->drv;
7701
7702         wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
7703                    __func__, drv->operstate, state, state ? "UP" : "DORMANT");
7704         drv->operstate = state;
7705         return netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, -1,
7706                                       state ? IF_OPER_UP : IF_OPER_DORMANT);
7707 }
7708
7709
7710 static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
7711 {
7712         struct i802_bss *bss = priv;
7713         struct wpa_driver_nl80211_data *drv = bss->drv;
7714         struct nl_msg *msg;
7715         struct nl80211_sta_flag_update upd;
7716
7717         msg = nlmsg_alloc();
7718         if (!msg)
7719                 return -ENOMEM;
7720
7721         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
7722
7723         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7724                     if_nametoindex(bss->ifname));
7725         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
7726
7727         os_memset(&upd, 0, sizeof(upd));
7728         upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
7729         if (authorized)
7730                 upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
7731         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
7732
7733         return send_and_recv_msgs(drv, msg, NULL, NULL);
7734  nla_put_failure:
7735         nlmsg_free(msg);
7736         return -ENOBUFS;
7737 }
7738
7739
7740 /* Set kernel driver on given frequency (MHz) */
7741 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
7742 {
7743         struct i802_bss *bss = priv;
7744         return wpa_driver_nl80211_set_freq(bss, freq);
7745 }
7746
7747
7748 #if defined(HOSTAPD) || defined(CONFIG_AP)
7749
7750 static inline int min_int(int a, int b)
7751 {
7752         if (a < b)
7753                 return a;
7754         return b;
7755 }
7756
7757
7758 static int get_key_handler(struct nl_msg *msg, void *arg)
7759 {
7760         struct nlattr *tb[NL80211_ATTR_MAX + 1];
7761         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7762
7763         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7764                   genlmsg_attrlen(gnlh, 0), NULL);
7765
7766         /*
7767          * TODO: validate the key index and mac address!
7768          * Otherwise, there's a race condition as soon as
7769          * the kernel starts sending key notifications.
7770          */
7771
7772         if (tb[NL80211_ATTR_KEY_SEQ])
7773                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
7774                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
7775         return NL_SKIP;
7776 }
7777
7778
7779 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
7780                            int idx, u8 *seq)
7781 {
7782         struct i802_bss *bss = priv;
7783         struct wpa_driver_nl80211_data *drv = bss->drv;
7784         struct nl_msg *msg;
7785
7786         msg = nlmsg_alloc();
7787         if (!msg)
7788                 return -ENOMEM;
7789
7790         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_KEY);
7791
7792         if (addr)
7793                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7794         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
7795         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
7796
7797         memset(seq, 0, 6);
7798
7799         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
7800  nla_put_failure:
7801         nlmsg_free(msg);
7802         return -ENOBUFS;
7803 }
7804
7805
7806 static int i802_set_rts(void *priv, int rts)
7807 {
7808         struct i802_bss *bss = priv;
7809         struct wpa_driver_nl80211_data *drv = bss->drv;
7810         struct nl_msg *msg;
7811         int ret = -ENOBUFS;
7812         u32 val;
7813
7814         msg = nlmsg_alloc();
7815         if (!msg)
7816                 return -ENOMEM;
7817
7818         if (rts >= 2347)
7819                 val = (u32) -1;
7820         else
7821                 val = rts;
7822
7823         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7824         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7825         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
7826
7827         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7828         msg = NULL;
7829         if (!ret)
7830                 return 0;
7831 nla_put_failure:
7832         nlmsg_free(msg);
7833         wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
7834                    "%d (%s)", rts, ret, strerror(-ret));
7835         return ret;
7836 }
7837
7838
7839 static int i802_set_frag(void *priv, int frag)
7840 {
7841         struct i802_bss *bss = priv;
7842         struct wpa_driver_nl80211_data *drv = bss->drv;
7843         struct nl_msg *msg;
7844         int ret = -ENOBUFS;
7845         u32 val;
7846
7847         msg = nlmsg_alloc();
7848         if (!msg)
7849                 return -ENOMEM;
7850
7851         if (frag >= 2346)
7852                 val = (u32) -1;
7853         else
7854                 val = frag;
7855
7856         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7857         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7858         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
7859
7860         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7861         msg = NULL;
7862         if (!ret)
7863                 return 0;
7864 nla_put_failure:
7865         nlmsg_free(msg);
7866         wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
7867                    "%d: %d (%s)", frag, ret, strerror(-ret));
7868         return ret;
7869 }
7870
7871
7872 static int i802_flush(void *priv)
7873 {
7874         struct i802_bss *bss = priv;
7875         struct wpa_driver_nl80211_data *drv = bss->drv;
7876         struct nl_msg *msg;
7877         int res;
7878
7879         msg = nlmsg_alloc();
7880         if (!msg)
7881                 return -1;
7882
7883         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
7884
7885         /*
7886          * XXX: FIX! this needs to flush all VLANs too
7887          */
7888         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7889                     if_nametoindex(bss->ifname));
7890
7891         res = send_and_recv_msgs(drv, msg, NULL, NULL);
7892         if (res) {
7893                 wpa_printf(MSG_DEBUG, "nl80211: Station flush failed: ret=%d "
7894                            "(%s)", res, strerror(-res));
7895         }
7896         return res;
7897  nla_put_failure:
7898         nlmsg_free(msg);
7899         return -ENOBUFS;
7900 }
7901
7902 #endif /* HOSTAPD || CONFIG_AP */
7903
7904
7905 static int get_sta_handler(struct nl_msg *msg, void *arg)
7906 {
7907         struct nlattr *tb[NL80211_ATTR_MAX + 1];
7908         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7909         struct hostap_sta_driver_data *data = arg;
7910         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
7911         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
7912                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
7913                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
7914                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
7915                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
7916                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
7917                 [NL80211_STA_INFO_TX_FAILED] = { .type = NLA_U32 },
7918         };
7919
7920         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7921                   genlmsg_attrlen(gnlh, 0), NULL);
7922
7923         /*
7924          * TODO: validate the interface and mac address!
7925          * Otherwise, there's a race condition as soon as
7926          * the kernel starts sending station notifications.
7927          */
7928
7929         if (!tb[NL80211_ATTR_STA_INFO]) {
7930                 wpa_printf(MSG_DEBUG, "sta stats missing!");
7931                 return NL_SKIP;
7932         }
7933         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
7934                              tb[NL80211_ATTR_STA_INFO],
7935                              stats_policy)) {
7936                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
7937                 return NL_SKIP;
7938         }
7939
7940         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
7941                 data->inactive_msec =
7942                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
7943         if (stats[NL80211_STA_INFO_RX_BYTES])
7944                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
7945         if (stats[NL80211_STA_INFO_TX_BYTES])
7946                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
7947         if (stats[NL80211_STA_INFO_RX_PACKETS])
7948                 data->rx_packets =
7949                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
7950         if (stats[NL80211_STA_INFO_TX_PACKETS])
7951                 data->tx_packets =
7952                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
7953         if (stats[NL80211_STA_INFO_TX_FAILED])
7954                 data->tx_retry_failed =
7955                         nla_get_u32(stats[NL80211_STA_INFO_TX_FAILED]);
7956
7957         return NL_SKIP;
7958 }
7959
7960 static int i802_read_sta_data(struct i802_bss *bss,
7961                               struct hostap_sta_driver_data *data,
7962                               const u8 *addr)
7963 {
7964         struct wpa_driver_nl80211_data *drv = bss->drv;
7965         struct nl_msg *msg;
7966
7967         os_memset(data, 0, sizeof(*data));
7968         msg = nlmsg_alloc();
7969         if (!msg)
7970                 return -ENOMEM;
7971
7972         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
7973
7974         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7975         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7976
7977         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
7978  nla_put_failure:
7979         nlmsg_free(msg);
7980         return -ENOBUFS;
7981 }
7982
7983
7984 #if defined(HOSTAPD) || defined(CONFIG_AP)
7985
7986 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
7987                                     int cw_min, int cw_max, int burst_time)
7988 {
7989         struct i802_bss *bss = priv;
7990         struct wpa_driver_nl80211_data *drv = bss->drv;
7991         struct nl_msg *msg;
7992         struct nlattr *txq, *params;
7993
7994         msg = nlmsg_alloc();
7995         if (!msg)
7996                 return -1;
7997
7998         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7999
8000         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
8001
8002         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
8003         if (!txq)
8004                 goto nla_put_failure;
8005
8006         /* We are only sending parameters for a single TXQ at a time */
8007         params = nla_nest_start(msg, 1);
8008         if (!params)
8009                 goto nla_put_failure;
8010
8011         switch (queue) {
8012         case 0:
8013                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
8014                 break;
8015         case 1:
8016                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
8017                 break;
8018         case 2:
8019                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
8020                 break;
8021         case 3:
8022                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
8023                 break;
8024         }
8025         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
8026          * 32 usec, so need to convert the value here. */
8027         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
8028         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
8029         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
8030         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
8031
8032         nla_nest_end(msg, params);
8033
8034         nla_nest_end(msg, txq);
8035
8036         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
8037                 return 0;
8038         msg = NULL;
8039  nla_put_failure:
8040         nlmsg_free(msg);
8041         return -1;
8042 }
8043
8044
8045 static int i802_set_sta_vlan(struct i802_bss *bss, const u8 *addr,
8046                              const char *ifname, int vlan_id)
8047 {
8048         struct wpa_driver_nl80211_data *drv = bss->drv;
8049         struct nl_msg *msg;
8050         int ret = -ENOBUFS;
8051
8052         msg = nlmsg_alloc();
8053         if (!msg)
8054                 return -ENOMEM;
8055
8056         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
8057
8058         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
8059                     if_nametoindex(bss->ifname));
8060         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
8061         NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
8062                     if_nametoindex(ifname));
8063
8064         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8065         msg = NULL;
8066         if (ret < 0) {
8067                 wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
8068                            MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
8069                            MAC2STR(addr), ifname, vlan_id, ret,
8070                            strerror(-ret));
8071         }
8072  nla_put_failure:
8073         nlmsg_free(msg);
8074         return ret;
8075 }
8076
8077
8078 static int i802_get_inact_sec(void *priv, const u8 *addr)
8079 {
8080         struct hostap_sta_driver_data data;
8081         int ret;
8082
8083         data.inactive_msec = (unsigned long) -1;
8084         ret = i802_read_sta_data(priv, &data, addr);
8085         if (ret || data.inactive_msec == (unsigned long) -1)
8086                 return -1;
8087         return data.inactive_msec / 1000;
8088 }
8089
8090
8091 static int i802_sta_clear_stats(void *priv, const u8 *addr)
8092 {
8093 #if 0
8094         /* TODO */
8095 #endif
8096         return 0;
8097 }
8098
8099
8100 static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
8101                            int reason)
8102 {
8103         struct i802_bss *bss = priv;
8104         struct wpa_driver_nl80211_data *drv = bss->drv;
8105         struct ieee80211_mgmt mgmt;
8106
8107         if (drv->device_ap_sme)
8108                 return wpa_driver_nl80211_sta_remove(bss, addr);
8109
8110         memset(&mgmt, 0, sizeof(mgmt));
8111         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
8112                                           WLAN_FC_STYPE_DEAUTH);
8113         memcpy(mgmt.da, addr, ETH_ALEN);
8114         memcpy(mgmt.sa, own_addr, ETH_ALEN);
8115         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
8116         mgmt.u.deauth.reason_code = host_to_le16(reason);
8117         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
8118                                             IEEE80211_HDRLEN +
8119                                             sizeof(mgmt.u.deauth), 0, 0, 0, 0,
8120                                             0);
8121 }
8122
8123
8124 static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
8125                              int reason)
8126 {
8127         struct i802_bss *bss = priv;
8128         struct wpa_driver_nl80211_data *drv = bss->drv;
8129         struct ieee80211_mgmt mgmt;
8130
8131         if (drv->device_ap_sme)
8132                 return wpa_driver_nl80211_sta_remove(bss, addr);
8133
8134         memset(&mgmt, 0, sizeof(mgmt));
8135         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
8136                                           WLAN_FC_STYPE_DISASSOC);
8137         memcpy(mgmt.da, addr, ETH_ALEN);
8138         memcpy(mgmt.sa, own_addr, ETH_ALEN);
8139         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
8140         mgmt.u.disassoc.reason_code = host_to_le16(reason);
8141         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
8142                                             IEEE80211_HDRLEN +
8143                                             sizeof(mgmt.u.disassoc), 0, 0, 0, 0,
8144                                             0);
8145 }
8146
8147 #endif /* HOSTAPD || CONFIG_AP */
8148
8149 #ifdef HOSTAPD
8150
8151 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
8152 {
8153         int i;
8154         int *old;
8155
8156         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
8157                    ifidx);
8158         for (i = 0; i < drv->num_if_indices; i++) {
8159                 if (drv->if_indices[i] == 0) {
8160                         drv->if_indices[i] = ifidx;
8161                         return;
8162                 }
8163         }
8164
8165         if (drv->if_indices != drv->default_if_indices)
8166                 old = drv->if_indices;
8167         else
8168                 old = NULL;
8169
8170         drv->if_indices = os_realloc_array(old, drv->num_if_indices + 1,
8171                                            sizeof(int));
8172         if (!drv->if_indices) {
8173                 if (!old)
8174                         drv->if_indices = drv->default_if_indices;
8175                 else
8176                         drv->if_indices = old;
8177                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
8178                            "interfaces");
8179                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
8180                 return;
8181         } else if (!old)
8182                 os_memcpy(drv->if_indices, drv->default_if_indices,
8183                           sizeof(drv->default_if_indices));
8184         drv->if_indices[drv->num_if_indices] = ifidx;
8185         drv->num_if_indices++;
8186 }
8187
8188
8189 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
8190 {
8191         int i;
8192
8193         for (i = 0; i < drv->num_if_indices; i++) {
8194                 if (drv->if_indices[i] == ifidx) {
8195                         drv->if_indices[i] = 0;
8196                         break;
8197                 }
8198         }
8199 }
8200
8201
8202 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
8203 {
8204         int i;
8205
8206         for (i = 0; i < drv->num_if_indices; i++)
8207                 if (drv->if_indices[i] == ifidx)
8208                         return 1;
8209
8210         return 0;
8211 }
8212
8213
8214 static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
8215                             const char *bridge_ifname)
8216 {
8217         struct i802_bss *bss = priv;
8218         struct wpa_driver_nl80211_data *drv = bss->drv;
8219         char name[IFNAMSIZ + 1];
8220
8221         os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
8222         wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
8223                    " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
8224         if (val) {
8225                 if (!if_nametoindex(name)) {
8226                         if (nl80211_create_iface(drv, name,
8227                                                  NL80211_IFTYPE_AP_VLAN,
8228                                                  bss->addr, 1) < 0)
8229                                 return -1;
8230                         if (bridge_ifname &&
8231                             linux_br_add_if(drv->global->ioctl_sock,
8232                                             bridge_ifname, name) < 0)
8233                                 return -1;
8234                 }
8235                 if (linux_set_iface_flags(drv->global->ioctl_sock, name, 1)) {
8236                         wpa_printf(MSG_ERROR, "nl80211: Failed to set WDS STA "
8237                                    "interface %s up", name);
8238                 }
8239                 return i802_set_sta_vlan(priv, addr, name, 0);
8240         } else {
8241                 if (bridge_ifname)
8242                         linux_br_del_if(drv->global->ioctl_sock, bridge_ifname,
8243                                         name);
8244
8245                 i802_set_sta_vlan(priv, addr, bss->ifname, 0);
8246                 return wpa_driver_nl80211_if_remove(priv, WPA_IF_AP_VLAN,
8247                                                     name);
8248         }
8249 }
8250
8251
8252 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
8253 {
8254         struct wpa_driver_nl80211_data *drv = eloop_ctx;
8255         struct sockaddr_ll lladdr;
8256         unsigned char buf[3000];
8257         int len;
8258         socklen_t fromlen = sizeof(lladdr);
8259
8260         len = recvfrom(sock, buf, sizeof(buf), 0,
8261                        (struct sockaddr *)&lladdr, &fromlen);
8262         if (len < 0) {
8263                 perror("recv");
8264                 return;
8265         }
8266
8267         if (have_ifidx(drv, lladdr.sll_ifindex))
8268                 drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
8269 }
8270
8271
8272 static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
8273                              struct i802_bss *bss,
8274                              const char *brname, const char *ifname)
8275 {
8276         int ifindex;
8277         char in_br[IFNAMSIZ];
8278
8279         os_strlcpy(bss->brname, brname, IFNAMSIZ);
8280         ifindex = if_nametoindex(brname);
8281         if (ifindex == 0) {
8282                 /*
8283                  * Bridge was configured, but the bridge device does
8284                  * not exist. Try to add it now.
8285                  */
8286                 if (linux_br_add(drv->global->ioctl_sock, brname) < 0) {
8287                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
8288                                    "bridge interface %s: %s",
8289                                    brname, strerror(errno));
8290                         return -1;
8291                 }
8292                 bss->added_bridge = 1;
8293                 add_ifidx(drv, if_nametoindex(brname));
8294         }
8295
8296         if (linux_br_get(in_br, ifname) == 0) {
8297                 if (os_strcmp(in_br, brname) == 0)
8298                         return 0; /* already in the bridge */
8299
8300                 wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
8301                            "bridge %s", ifname, in_br);
8302                 if (linux_br_del_if(drv->global->ioctl_sock, in_br, ifname) <
8303                     0) {
8304                         wpa_printf(MSG_ERROR, "nl80211: Failed to "
8305                                    "remove interface %s from bridge "
8306                                    "%s: %s",
8307                                    ifname, brname, strerror(errno));
8308                         return -1;
8309                 }
8310         }
8311
8312         wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
8313                    ifname, brname);
8314         if (linux_br_add_if(drv->global->ioctl_sock, brname, ifname) < 0) {
8315                 wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
8316                            "into bridge %s: %s",
8317                            ifname, brname, strerror(errno));
8318                 return -1;
8319         }
8320         bss->added_if_into_bridge = 1;
8321
8322         return 0;
8323 }
8324
8325
8326 static void *i802_init(struct hostapd_data *hapd,
8327                        struct wpa_init_params *params)
8328 {
8329         struct wpa_driver_nl80211_data *drv;
8330         struct i802_bss *bss;
8331         size_t i;
8332         char brname[IFNAMSIZ];
8333         int ifindex, br_ifindex;
8334         int br_added = 0;
8335
8336         bss = wpa_driver_nl80211_init(hapd, params->ifname,
8337                                       params->global_priv);
8338         if (bss == NULL)
8339                 return NULL;
8340
8341         drv = bss->drv;
8342         drv->nlmode = NL80211_IFTYPE_AP;
8343         drv->eapol_sock = -1;
8344
8345         if (linux_br_get(brname, params->ifname) == 0) {
8346                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
8347                            params->ifname, brname);
8348                 br_ifindex = if_nametoindex(brname);
8349         } else {
8350                 brname[0] = '\0';
8351                 br_ifindex = 0;
8352         }
8353
8354         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
8355         drv->if_indices = drv->default_if_indices;
8356         for (i = 0; i < params->num_bridge; i++) {
8357                 if (params->bridge[i]) {
8358                         ifindex = if_nametoindex(params->bridge[i]);
8359                         if (ifindex)
8360                                 add_ifidx(drv, ifindex);
8361                         if (ifindex == br_ifindex)
8362                                 br_added = 1;
8363                 }
8364         }
8365         if (!br_added && br_ifindex &&
8366             (params->num_bridge == 0 || !params->bridge[0]))
8367                 add_ifidx(drv, br_ifindex);
8368
8369         /* start listening for EAPOL on the default AP interface */
8370         add_ifidx(drv, drv->ifindex);
8371
8372         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0))
8373                 goto failed;
8374
8375         if (params->bssid) {
8376                 if (linux_set_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
8377                                        params->bssid))
8378                         goto failed;
8379         }
8380
8381         if (wpa_driver_nl80211_set_mode(bss, drv->nlmode)) {
8382                 wpa_printf(MSG_ERROR, "nl80211: Failed to set interface %s "
8383                            "into AP mode", bss->ifname);
8384                 goto failed;
8385         }
8386
8387         if (params->num_bridge && params->bridge[0] &&
8388             i802_check_bridge(drv, bss, params->bridge[0], params->ifname) < 0)
8389                 goto failed;
8390
8391         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1))
8392                 goto failed;
8393
8394         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
8395         if (drv->eapol_sock < 0) {
8396                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
8397                 goto failed;
8398         }
8399
8400         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
8401         {
8402                 printf("Could not register read socket for eapol\n");
8403                 goto failed;
8404         }
8405
8406         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
8407                                params->own_addr))
8408                 goto failed;
8409
8410         memcpy(bss->addr, params->own_addr, ETH_ALEN);
8411
8412         return bss;
8413
8414 failed:
8415         wpa_driver_nl80211_deinit(bss);
8416         return NULL;
8417 }
8418
8419
8420 static void i802_deinit(void *priv)
8421 {
8422         struct i802_bss *bss = priv;
8423         wpa_driver_nl80211_deinit(bss);
8424 }
8425
8426 #endif /* HOSTAPD */
8427
8428
8429 static enum nl80211_iftype wpa_driver_nl80211_if_type(
8430         enum wpa_driver_if_type type)
8431 {
8432         switch (type) {
8433         case WPA_IF_STATION:
8434                 return NL80211_IFTYPE_STATION;
8435         case WPA_IF_P2P_CLIENT:
8436         case WPA_IF_P2P_GROUP:
8437                 return NL80211_IFTYPE_P2P_CLIENT;
8438         case WPA_IF_AP_VLAN:
8439                 return NL80211_IFTYPE_AP_VLAN;
8440         case WPA_IF_AP_BSS:
8441                 return NL80211_IFTYPE_AP;
8442         case WPA_IF_P2P_GO:
8443                 return NL80211_IFTYPE_P2P_GO;
8444         }
8445         return -1;
8446 }
8447
8448
8449 #ifdef CONFIG_P2P
8450
8451 static int nl80211_addr_in_use(struct nl80211_global *global, const u8 *addr)
8452 {
8453         struct wpa_driver_nl80211_data *drv;
8454         dl_list_for_each(drv, &global->interfaces,
8455                          struct wpa_driver_nl80211_data, list) {
8456                 if (os_memcmp(addr, drv->first_bss.addr, ETH_ALEN) == 0)
8457                         return 1;
8458         }
8459         return 0;
8460 }
8461
8462
8463 static int nl80211_p2p_interface_addr(struct wpa_driver_nl80211_data *drv,
8464                                       u8 *new_addr)
8465 {
8466         unsigned int idx;
8467
8468         if (!drv->global)
8469                 return -1;
8470
8471         os_memcpy(new_addr, drv->first_bss.addr, ETH_ALEN);
8472         for (idx = 0; idx < 64; idx++) {
8473                 new_addr[0] = drv->first_bss.addr[0] | 0x02;
8474                 new_addr[0] ^= idx << 2;
8475                 if (!nl80211_addr_in_use(drv->global, new_addr))
8476                         break;
8477         }
8478         if (idx == 64)
8479                 return -1;
8480
8481         wpa_printf(MSG_DEBUG, "nl80211: Assigned new P2P Interface Address "
8482                    MACSTR, MAC2STR(new_addr));
8483
8484         return 0;
8485 }
8486
8487 #endif /* CONFIG_P2P */
8488
8489
8490 static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
8491                                      const char *ifname, const u8 *addr,
8492                                      void *bss_ctx, void **drv_priv,
8493                                      char *force_ifname, u8 *if_addr,
8494                                      const char *bridge)
8495 {
8496         struct i802_bss *bss = priv;
8497         struct wpa_driver_nl80211_data *drv = bss->drv;
8498         int ifidx;
8499 #ifdef HOSTAPD
8500         struct i802_bss *new_bss = NULL;
8501
8502         if (type == WPA_IF_AP_BSS) {
8503                 new_bss = os_zalloc(sizeof(*new_bss));
8504                 if (new_bss == NULL)
8505                         return -1;
8506         }
8507 #endif /* HOSTAPD */
8508
8509         if (addr)
8510                 os_memcpy(if_addr, addr, ETH_ALEN);
8511         ifidx = nl80211_create_iface(drv, ifname,
8512                                      wpa_driver_nl80211_if_type(type), addr,
8513                                      0);
8514         if (ifidx < 0) {
8515 #ifdef HOSTAPD
8516                 os_free(new_bss);
8517 #endif /* HOSTAPD */
8518                 return -1;
8519         }
8520
8521         if (!addr &&
8522             linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
8523                                if_addr) < 0) {
8524                 nl80211_remove_iface(drv, ifidx);
8525                 return -1;
8526         }
8527
8528 #ifdef CONFIG_P2P
8529         if (!addr &&
8530             (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
8531              type == WPA_IF_P2P_GO)) {
8532                 /* Enforce unique P2P Interface Address */
8533                 u8 new_addr[ETH_ALEN], own_addr[ETH_ALEN];
8534
8535                 if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
8536                                        own_addr) < 0 ||
8537                     linux_get_ifhwaddr(drv->global->ioctl_sock, ifname,
8538                                        new_addr) < 0) {
8539                         nl80211_remove_iface(drv, ifidx);
8540                         return -1;
8541                 }
8542                 if (os_memcmp(own_addr, new_addr, ETH_ALEN) == 0) {
8543                         wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
8544                                    "for P2P group interface");
8545                         if (nl80211_p2p_interface_addr(drv, new_addr) < 0) {
8546                                 nl80211_remove_iface(drv, ifidx);
8547                                 return -1;
8548                         }
8549                         if (linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
8550                                                new_addr) < 0) {
8551                                 nl80211_remove_iface(drv, ifidx);
8552                                 return -1;
8553                         }
8554                 }
8555                 os_memcpy(if_addr, new_addr, ETH_ALEN);
8556         }
8557 #endif /* CONFIG_P2P */
8558
8559 #ifdef HOSTAPD
8560         if (bridge &&
8561             i802_check_bridge(drv, new_bss, bridge, ifname) < 0) {
8562                 wpa_printf(MSG_ERROR, "nl80211: Failed to add the new "
8563                            "interface %s to a bridge %s", ifname, bridge);
8564                 nl80211_remove_iface(drv, ifidx);
8565                 os_free(new_bss);
8566                 return -1;
8567         }
8568
8569         if (type == WPA_IF_AP_BSS) {
8570                 if (linux_set_iface_flags(drv->global->ioctl_sock, ifname, 1))
8571                 {
8572                         nl80211_remove_iface(drv, ifidx);
8573                         os_free(new_bss);
8574                         return -1;
8575                 }
8576                 os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
8577                 os_memcpy(new_bss->addr, if_addr, ETH_ALEN);
8578                 new_bss->ifindex = ifidx;
8579                 new_bss->drv = drv;
8580                 new_bss->next = drv->first_bss.next;
8581                 new_bss->freq = drv->first_bss.freq;
8582                 new_bss->ctx = bss_ctx;
8583                 drv->first_bss.next = new_bss;
8584                 if (drv_priv)
8585                         *drv_priv = new_bss;
8586                 nl80211_init_bss(new_bss);
8587
8588                 /* Subscribe management frames for this WPA_IF_AP_BSS */
8589                 if (nl80211_setup_ap(new_bss))
8590                         return -1;
8591         }
8592 #endif /* HOSTAPD */
8593
8594         if (drv->global)
8595                 drv->global->if_add_ifindex = ifidx;
8596
8597         return 0;
8598 }
8599
8600
8601 static int wpa_driver_nl80211_if_remove(struct i802_bss *bss,
8602                                         enum wpa_driver_if_type type,
8603                                         const char *ifname)
8604 {
8605         struct wpa_driver_nl80211_data *drv = bss->drv;
8606         int ifindex = if_nametoindex(ifname);
8607
8608         wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d",
8609                    __func__, type, ifname, ifindex);
8610         if (ifindex <= 0)
8611                 return -1;
8612
8613         nl80211_remove_iface(drv, ifindex);
8614
8615 #ifdef HOSTAPD
8616         if (type != WPA_IF_AP_BSS)
8617                 return 0;
8618
8619         if (bss->added_if_into_bridge) {
8620                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
8621                                     bss->ifname) < 0)
8622                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
8623                                    "interface %s from bridge %s: %s",
8624                                    bss->ifname, bss->brname, strerror(errno));
8625         }
8626         if (bss->added_bridge) {
8627                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
8628                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
8629                                    "bridge %s: %s",
8630                                    bss->brname, strerror(errno));
8631         }
8632
8633         if (bss != &drv->first_bss) {
8634                 struct i802_bss *tbss;
8635
8636                 for (tbss = &drv->first_bss; tbss; tbss = tbss->next) {
8637                         if (tbss->next == bss) {
8638                                 tbss->next = bss->next;
8639                                 /* Unsubscribe management frames */
8640                                 nl80211_teardown_ap(bss);
8641                                 nl80211_destroy_bss(bss);
8642                                 os_free(bss);
8643                                 bss = NULL;
8644                                 break;
8645                         }
8646                 }
8647                 if (bss)
8648                         wpa_printf(MSG_INFO, "nl80211: %s - could not find "
8649                                    "BSS %p in the list", __func__, bss);
8650         }
8651 #endif /* HOSTAPD */
8652
8653         return 0;
8654 }
8655
8656
8657 static int cookie_handler(struct nl_msg *msg, void *arg)
8658 {
8659         struct nlattr *tb[NL80211_ATTR_MAX + 1];
8660         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
8661         u64 *cookie = arg;
8662         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
8663                   genlmsg_attrlen(gnlh, 0), NULL);
8664         if (tb[NL80211_ATTR_COOKIE])
8665                 *cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
8666         return NL_SKIP;
8667 }
8668
8669
8670 static int nl80211_send_frame_cmd(struct i802_bss *bss,
8671                                   unsigned int freq, unsigned int wait,
8672                                   const u8 *buf, size_t buf_len,
8673                                   u64 *cookie_out, int no_cck, int no_ack,
8674                                   int offchanok)
8675 {
8676         struct wpa_driver_nl80211_data *drv = bss->drv;
8677         struct nl_msg *msg;
8678         u64 cookie;
8679         int ret = -1;
8680
8681         msg = nlmsg_alloc();
8682         if (!msg)
8683                 return -1;
8684
8685         wpa_printf(MSG_MSGDUMP, "nl80211: CMD_FRAME freq=%u wait=%u no_cck=%d "
8686                    "no_ack=%d offchanok=%d",
8687                    freq, wait, no_cck, no_ack, offchanok);
8688         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME);
8689
8690         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8691         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
8692         if (wait)
8693                 NLA_PUT_U32(msg, NL80211_ATTR_DURATION, wait);
8694         if (offchanok && (drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX))
8695                 NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
8696         if (no_cck)
8697                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
8698         if (no_ack)
8699                 NLA_PUT_FLAG(msg, NL80211_ATTR_DONT_WAIT_FOR_ACK);
8700
8701         NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
8702
8703         cookie = 0;
8704         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
8705         msg = NULL;
8706         if (ret) {
8707                 wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
8708                            "(%s) (freq=%u wait=%u)", ret, strerror(-ret),
8709                            freq, wait);
8710                 goto nla_put_failure;
8711         }
8712         wpa_printf(MSG_MSGDUMP, "nl80211: Frame TX command accepted%s; "
8713                    "cookie 0x%llx", no_ack ? " (no ACK)" : "",
8714                    (long long unsigned int) cookie);
8715
8716         if (cookie_out)
8717                 *cookie_out = no_ack ? (u64) -1 : cookie;
8718
8719 nla_put_failure:
8720         nlmsg_free(msg);
8721         return ret;
8722 }
8723
8724
8725 static int wpa_driver_nl80211_send_action(struct i802_bss *bss,
8726                                           unsigned int freq,
8727                                           unsigned int wait_time,
8728                                           const u8 *dst, const u8 *src,
8729                                           const u8 *bssid,
8730                                           const u8 *data, size_t data_len,
8731                                           int no_cck)
8732 {
8733         struct wpa_driver_nl80211_data *drv = bss->drv;
8734         int ret = -1;
8735         u8 *buf;
8736         struct ieee80211_hdr *hdr;
8737
8738         wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d, "
8739                    "freq=%u MHz wait=%d ms no_cck=%d)",
8740                    drv->ifindex, freq, wait_time, no_cck);
8741
8742         buf = os_zalloc(24 + data_len);
8743         if (buf == NULL)
8744                 return ret;
8745         os_memcpy(buf + 24, data, data_len);
8746         hdr = (struct ieee80211_hdr *) buf;
8747         hdr->frame_control =
8748                 IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
8749         os_memcpy(hdr->addr1, dst, ETH_ALEN);
8750         os_memcpy(hdr->addr2, src, ETH_ALEN);
8751         os_memcpy(hdr->addr3, bssid, ETH_ALEN);
8752
8753         if (is_ap_interface(drv->nlmode))
8754                 ret = wpa_driver_nl80211_send_mlme(bss, buf, 24 + data_len,
8755                                                    0, freq, no_cck, 1,
8756                                                    wait_time);
8757         else
8758                 ret = nl80211_send_frame_cmd(bss, freq, wait_time, buf,
8759                                              24 + data_len,
8760                                              &drv->send_action_cookie,
8761                                              no_cck, 0, 1);
8762
8763         os_free(buf);
8764         return ret;
8765 }
8766
8767
8768 static void wpa_driver_nl80211_send_action_cancel_wait(void *priv)
8769 {
8770         struct i802_bss *bss = priv;
8771         struct wpa_driver_nl80211_data *drv = bss->drv;
8772         struct nl_msg *msg;
8773         int ret;
8774
8775         msg = nlmsg_alloc();
8776         if (!msg)
8777                 return;
8778
8779         wpa_printf(MSG_DEBUG, "nl80211: Cancel TX frame wait: cookie=0x%llx",
8780                    (long long unsigned int) drv->send_action_cookie);
8781         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME_WAIT_CANCEL);
8782
8783         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8784         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->send_action_cookie);
8785
8786         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8787         msg = NULL;
8788         if (ret)
8789                 wpa_printf(MSG_DEBUG, "nl80211: wait cancel failed: ret=%d "
8790                            "(%s)", ret, strerror(-ret));
8791
8792  nla_put_failure:
8793         nlmsg_free(msg);
8794 }
8795
8796
8797 static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
8798                                                 unsigned int duration)
8799 {
8800         struct i802_bss *bss = priv;
8801         struct wpa_driver_nl80211_data *drv = bss->drv;
8802         struct nl_msg *msg;
8803         int ret;
8804         u64 cookie;
8805
8806         msg = nlmsg_alloc();
8807         if (!msg)
8808                 return -1;
8809
8810         nl80211_cmd(drv, msg, 0, NL80211_CMD_REMAIN_ON_CHANNEL);
8811
8812         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8813         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
8814         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
8815
8816         cookie = 0;
8817         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
8818         msg = NULL;
8819         if (ret == 0) {
8820                 wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
8821                            "0x%llx for freq=%u MHz duration=%u",
8822                            (long long unsigned int) cookie, freq, duration);
8823                 drv->remain_on_chan_cookie = cookie;
8824                 drv->pending_remain_on_chan = 1;
8825                 return 0;
8826         }
8827         wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
8828                    "(freq=%d duration=%u): %d (%s)",
8829                    freq, duration, ret, strerror(-ret));
8830 nla_put_failure:
8831         nlmsg_free(msg);
8832         return -1;
8833 }
8834
8835
8836 static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
8837 {
8838         struct i802_bss *bss = priv;
8839         struct wpa_driver_nl80211_data *drv = bss->drv;
8840         struct nl_msg *msg;
8841         int ret;
8842
8843         if (!drv->pending_remain_on_chan) {
8844                 wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
8845                            "to cancel");
8846                 return -1;
8847         }
8848
8849         wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
8850                    "0x%llx",
8851                    (long long unsigned int) drv->remain_on_chan_cookie);
8852
8853         msg = nlmsg_alloc();
8854         if (!msg)
8855                 return -1;
8856
8857         nl80211_cmd(drv, msg, 0, NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL);
8858
8859         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8860         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
8861
8862         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8863         msg = NULL;
8864         if (ret == 0)
8865                 return 0;
8866         wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
8867                    "%d (%s)", ret, strerror(-ret));
8868 nla_put_failure:
8869         nlmsg_free(msg);
8870         return -1;
8871 }
8872
8873
8874 static int wpa_driver_nl80211_probe_req_report(struct i802_bss *bss, int report)
8875 {
8876         struct wpa_driver_nl80211_data *drv = bss->drv;
8877
8878         if (!report) {
8879                 if (bss->nl_preq && drv->device_ap_sme &&
8880                     is_ap_interface(drv->nlmode)) {
8881                         /*
8882                          * Do not disable Probe Request reporting that was
8883                          * enabled in nl80211_setup_ap().
8884                          */
8885                         wpa_printf(MSG_DEBUG, "nl80211: Skip disabling of "
8886                                    "Probe Request reporting nl_preq=%p while "
8887                                    "in AP mode", bss->nl_preq);
8888                 } else if (bss->nl_preq) {
8889                         wpa_printf(MSG_DEBUG, "nl80211: Disable Probe Request "
8890                                    "reporting nl_preq=%p", bss->nl_preq);
8891                         eloop_unregister_read_sock(
8892                                 nl_socket_get_fd(bss->nl_preq));
8893                         nl_destroy_handles(&bss->nl_preq);
8894                 }
8895                 return 0;
8896         }
8897
8898         if (bss->nl_preq) {
8899                 wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
8900                            "already on! nl_preq=%p", bss->nl_preq);
8901                 return 0;
8902         }
8903
8904         bss->nl_preq = nl_create_handle(drv->global->nl_cb, "preq");
8905         if (bss->nl_preq == NULL)
8906                 return -1;
8907         wpa_printf(MSG_DEBUG, "nl80211: Enable Probe Request "
8908                    "reporting nl_preq=%p", bss->nl_preq);
8909
8910         if (nl80211_register_frame(bss, bss->nl_preq,
8911                                    (WLAN_FC_TYPE_MGMT << 2) |
8912                                    (WLAN_FC_STYPE_PROBE_REQ << 4),
8913                                    NULL, 0) < 0)
8914                 goto out_err;
8915
8916         eloop_register_read_sock(nl_socket_get_fd(bss->nl_preq),
8917                                  wpa_driver_nl80211_event_receive, bss->nl_cb,
8918                                  bss->nl_preq);
8919
8920         return 0;
8921
8922  out_err:
8923         nl_destroy_handles(&bss->nl_preq);
8924         return -1;
8925 }
8926
8927
8928 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
8929                                      int ifindex, int disabled)
8930 {
8931         struct nl_msg *msg;
8932         struct nlattr *bands, *band;
8933         int ret;
8934
8935         msg = nlmsg_alloc();
8936         if (!msg)
8937                 return -1;
8938
8939         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_TX_BITRATE_MASK);
8940         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
8941
8942         bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
8943         if (!bands)
8944                 goto nla_put_failure;
8945
8946         /*
8947          * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
8948          * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
8949          * rates. All 5 GHz rates are left enabled.
8950          */
8951         band = nla_nest_start(msg, NL80211_BAND_2GHZ);
8952         if (!band)
8953                 goto nla_put_failure;
8954         if (disabled) {
8955                 NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
8956                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
8957         }
8958         nla_nest_end(msg, band);
8959
8960         nla_nest_end(msg, bands);
8961
8962         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8963         msg = NULL;
8964         if (ret) {
8965                 wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
8966                            "(%s)", ret, strerror(-ret));
8967         } else
8968                 drv->disabled_11b_rates = disabled;
8969
8970         return ret;
8971
8972 nla_put_failure:
8973         nlmsg_free(msg);
8974         return -1;
8975 }
8976
8977
8978 static int wpa_driver_nl80211_deinit_ap(void *priv)
8979 {
8980         struct i802_bss *bss = priv;
8981         struct wpa_driver_nl80211_data *drv = bss->drv;
8982         if (!is_ap_interface(drv->nlmode))
8983                 return -1;
8984         wpa_driver_nl80211_del_beacon(drv);
8985         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
8986 }
8987
8988
8989 static int wpa_driver_nl80211_deinit_p2p_cli(void *priv)
8990 {
8991         struct i802_bss *bss = priv;
8992         struct wpa_driver_nl80211_data *drv = bss->drv;
8993         if (drv->nlmode != NL80211_IFTYPE_P2P_CLIENT)
8994                 return -1;
8995         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
8996 }
8997
8998
8999 static void wpa_driver_nl80211_resume(void *priv)
9000 {
9001         struct i802_bss *bss = priv;
9002         struct wpa_driver_nl80211_data *drv = bss->drv;
9003         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
9004                 wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on "
9005                            "resume event");
9006         }
9007 }
9008
9009
9010 static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
9011                                   const u8 *ies, size_t ies_len)
9012 {
9013         struct i802_bss *bss = priv;
9014         struct wpa_driver_nl80211_data *drv = bss->drv;
9015         int ret;
9016         u8 *data, *pos;
9017         size_t data_len;
9018         const u8 *own_addr = bss->addr;
9019
9020         if (action != 1) {
9021                 wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
9022                            "action %d", action);
9023                 return -1;
9024         }
9025
9026         /*
9027          * Action frame payload:
9028          * Category[1] = 6 (Fast BSS Transition)
9029          * Action[1] = 1 (Fast BSS Transition Request)
9030          * STA Address
9031          * Target AP Address
9032          * FT IEs
9033          */
9034
9035         data_len = 2 + 2 * ETH_ALEN + ies_len;
9036         data = os_malloc(data_len);
9037         if (data == NULL)
9038                 return -1;
9039         pos = data;
9040         *pos++ = 0x06; /* FT Action category */
9041         *pos++ = action;
9042         os_memcpy(pos, own_addr, ETH_ALEN);
9043         pos += ETH_ALEN;
9044         os_memcpy(pos, target_ap, ETH_ALEN);
9045         pos += ETH_ALEN;
9046         os_memcpy(pos, ies, ies_len);
9047
9048         ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, 0,
9049                                              drv->bssid, own_addr, drv->bssid,
9050                                              data, data_len, 0);
9051         os_free(data);
9052
9053         return ret;
9054 }
9055
9056
9057 static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
9058 {
9059         struct i802_bss *bss = priv;
9060         struct wpa_driver_nl80211_data *drv = bss->drv;
9061         struct nl_msg *msg;
9062         struct nlattr *cqm;
9063         int ret = -1;
9064
9065         wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
9066                    "hysteresis=%d", threshold, hysteresis);
9067
9068         msg = nlmsg_alloc();
9069         if (!msg)
9070                 return -1;
9071
9072         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_CQM);
9073
9074         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
9075
9076         cqm = nla_nest_start(msg, NL80211_ATTR_CQM);
9077         if (cqm == NULL)
9078                 goto nla_put_failure;
9079
9080         NLA_PUT_U32(msg, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
9081         NLA_PUT_U32(msg, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
9082         nla_nest_end(msg, cqm);
9083
9084         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9085         msg = NULL;
9086
9087 nla_put_failure:
9088         nlmsg_free(msg);
9089         return ret;
9090 }
9091
9092
9093 static int nl80211_signal_poll(void *priv, struct wpa_signal_info *si)
9094 {
9095         struct i802_bss *bss = priv;
9096         struct wpa_driver_nl80211_data *drv = bss->drv;
9097         int res;
9098
9099         os_memset(si, 0, sizeof(*si));
9100         res = nl80211_get_link_signal(drv, si);
9101         if (res != 0)
9102                 return res;
9103
9104         return nl80211_get_link_noise(drv, si);
9105 }
9106
9107
9108 static int wpa_driver_nl80211_shared_freq(void *priv)
9109 {
9110         struct i802_bss *bss = priv;
9111         struct wpa_driver_nl80211_data *drv = bss->drv;
9112         struct wpa_driver_nl80211_data *driver;
9113         int freq = 0;
9114
9115         /*
9116          * If the same PHY is in connected state with some other interface,
9117          * then retrieve the assoc freq.
9118          */
9119         wpa_printf(MSG_DEBUG, "nl80211: Get shared freq for PHY %s",
9120                    drv->phyname);
9121
9122         dl_list_for_each(driver, &drv->global->interfaces,
9123                          struct wpa_driver_nl80211_data, list) {
9124                 if (drv == driver ||
9125                     os_strcmp(drv->phyname, driver->phyname) != 0 ||
9126                     !driver->associated)
9127                         continue;
9128
9129                 wpa_printf(MSG_DEBUG, "nl80211: Found a match for PHY %s - %s "
9130                            MACSTR,
9131                            driver->phyname, driver->first_bss.ifname,
9132                            MAC2STR(driver->first_bss.addr));
9133                 if (is_ap_interface(driver->nlmode))
9134                         freq = driver->first_bss.freq;
9135                 else
9136                         freq = nl80211_get_assoc_freq(driver);
9137                 wpa_printf(MSG_DEBUG, "nl80211: Shared freq for PHY %s: %d",
9138                            drv->phyname, freq);
9139         }
9140
9141         if (!freq)
9142                 wpa_printf(MSG_DEBUG, "nl80211: No shared interface for "
9143                            "PHY (%s) in associated state", drv->phyname);
9144
9145         return freq;
9146 }
9147
9148
9149 static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
9150                               int encrypt)
9151 {
9152         struct i802_bss *bss = priv;
9153         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt, 0,
9154                                              0, 0, 0, 0);
9155 }
9156
9157
9158 static int nl80211_set_param(void *priv, const char *param)
9159 {
9160         wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
9161         if (param == NULL)
9162                 return 0;
9163
9164 #ifdef CONFIG_P2P
9165         if (os_strstr(param, "use_p2p_group_interface=1")) {
9166                 struct i802_bss *bss = priv;
9167                 struct wpa_driver_nl80211_data *drv = bss->drv;
9168
9169                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
9170                            "interface");
9171                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
9172                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
9173         }
9174 #endif /* CONFIG_P2P */
9175
9176         return 0;
9177 }
9178
9179
9180 static void * nl80211_global_init(void)
9181 {
9182         struct nl80211_global *global;
9183         struct netlink_config *cfg;
9184
9185         global = os_zalloc(sizeof(*global));
9186         if (global == NULL)
9187                 return NULL;
9188         global->ioctl_sock = -1;
9189         dl_list_init(&global->interfaces);
9190         global->if_add_ifindex = -1;
9191
9192         cfg = os_zalloc(sizeof(*cfg));
9193         if (cfg == NULL)
9194                 goto err;
9195
9196         cfg->ctx = global;
9197         cfg->newlink_cb = wpa_driver_nl80211_event_rtm_newlink;
9198         cfg->dellink_cb = wpa_driver_nl80211_event_rtm_dellink;
9199         global->netlink = netlink_init(cfg);
9200         if (global->netlink == NULL) {
9201                 os_free(cfg);
9202                 goto err;
9203         }
9204
9205         if (wpa_driver_nl80211_init_nl_global(global) < 0)
9206                 goto err;
9207
9208         global->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
9209         if (global->ioctl_sock < 0) {
9210                 perror("socket(PF_INET,SOCK_DGRAM)");
9211                 goto err;
9212         }
9213
9214         return global;
9215
9216 err:
9217         nl80211_global_deinit(global);
9218         return NULL;
9219 }
9220
9221
9222 static void nl80211_global_deinit(void *priv)
9223 {
9224         struct nl80211_global *global = priv;
9225         if (global == NULL)
9226                 return;
9227         if (!dl_list_empty(&global->interfaces)) {
9228                 wpa_printf(MSG_ERROR, "nl80211: %u interface(s) remain at "
9229                            "nl80211_global_deinit",
9230                            dl_list_len(&global->interfaces));
9231         }
9232
9233         if (global->netlink)
9234                 netlink_deinit(global->netlink);
9235
9236         nl_destroy_handles(&global->nl);
9237
9238         if (global->nl_event) {
9239                 eloop_unregister_read_sock(
9240                         nl_socket_get_fd(global->nl_event));
9241                 nl_destroy_handles(&global->nl_event);
9242         }
9243
9244         nl_cb_put(global->nl_cb);
9245
9246         if (global->ioctl_sock >= 0)
9247                 close(global->ioctl_sock);
9248
9249         os_free(global);
9250 }
9251
9252
9253 static const char * nl80211_get_radio_name(void *priv)
9254 {
9255         struct i802_bss *bss = priv;
9256         struct wpa_driver_nl80211_data *drv = bss->drv;
9257         return drv->phyname;
9258 }
9259
9260
9261 static int nl80211_pmkid(struct i802_bss *bss, int cmd, const u8 *bssid,
9262                          const u8 *pmkid)
9263 {
9264         struct nl_msg *msg;
9265
9266         msg = nlmsg_alloc();
9267         if (!msg)
9268                 return -ENOMEM;
9269
9270         nl80211_cmd(bss->drv, msg, 0, cmd);
9271
9272         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
9273         if (pmkid)
9274                 NLA_PUT(msg, NL80211_ATTR_PMKID, 16, pmkid);
9275         if (bssid)
9276                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
9277
9278         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
9279  nla_put_failure:
9280         nlmsg_free(msg);
9281         return -ENOBUFS;
9282 }
9283
9284
9285 static int nl80211_add_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
9286 {
9287         struct i802_bss *bss = priv;
9288         wpa_printf(MSG_DEBUG, "nl80211: Add PMKID for " MACSTR, MAC2STR(bssid));
9289         return nl80211_pmkid(bss, NL80211_CMD_SET_PMKSA, bssid, pmkid);
9290 }
9291
9292
9293 static int nl80211_remove_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
9294 {
9295         struct i802_bss *bss = priv;
9296         wpa_printf(MSG_DEBUG, "nl80211: Delete PMKID for " MACSTR,
9297                    MAC2STR(bssid));
9298         return nl80211_pmkid(bss, NL80211_CMD_DEL_PMKSA, bssid, pmkid);
9299 }
9300
9301
9302 static int nl80211_flush_pmkid(void *priv)
9303 {
9304         struct i802_bss *bss = priv;
9305         wpa_printf(MSG_DEBUG, "nl80211: Flush PMKIDs");
9306         return nl80211_pmkid(bss, NL80211_CMD_FLUSH_PMKSA, NULL, NULL);
9307 }
9308
9309
9310 static void nl80211_set_rekey_info(void *priv, const u8 *kek, const u8 *kck,
9311                                    const u8 *replay_ctr)
9312 {
9313         struct i802_bss *bss = priv;
9314         struct wpa_driver_nl80211_data *drv = bss->drv;
9315         struct nlattr *replay_nested;
9316         struct nl_msg *msg;
9317
9318         msg = nlmsg_alloc();
9319         if (!msg)
9320                 return;
9321
9322         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_REKEY_OFFLOAD);
9323
9324         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
9325
9326         replay_nested = nla_nest_start(msg, NL80211_ATTR_REKEY_DATA);
9327         if (!replay_nested)
9328                 goto nla_put_failure;
9329
9330         NLA_PUT(msg, NL80211_REKEY_DATA_KEK, NL80211_KEK_LEN, kek);
9331         NLA_PUT(msg, NL80211_REKEY_DATA_KCK, NL80211_KCK_LEN, kck);
9332         NLA_PUT(msg, NL80211_REKEY_DATA_REPLAY_CTR, NL80211_REPLAY_CTR_LEN,
9333                 replay_ctr);
9334
9335         nla_nest_end(msg, replay_nested);
9336
9337         send_and_recv_msgs(drv, msg, NULL, NULL);
9338         return;
9339  nla_put_failure:
9340         nlmsg_free(msg);
9341 }
9342
9343
9344 static void nl80211_send_null_frame(struct i802_bss *bss, const u8 *own_addr,
9345                                     const u8 *addr, int qos)
9346 {
9347         /* send data frame to poll STA and check whether
9348          * this frame is ACKed */
9349         struct {
9350                 struct ieee80211_hdr hdr;
9351                 u16 qos_ctl;
9352         } STRUCT_PACKED nulldata;
9353         size_t size;
9354
9355         /* Send data frame to poll STA and check whether this frame is ACKed */
9356
9357         os_memset(&nulldata, 0, sizeof(nulldata));
9358
9359         if (qos) {
9360                 nulldata.hdr.frame_control =
9361                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
9362                                      WLAN_FC_STYPE_QOS_NULL);
9363                 size = sizeof(nulldata);
9364         } else {
9365                 nulldata.hdr.frame_control =
9366                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
9367                                      WLAN_FC_STYPE_NULLFUNC);
9368                 size = sizeof(struct ieee80211_hdr);
9369         }
9370
9371         nulldata.hdr.frame_control |= host_to_le16(WLAN_FC_FROMDS);
9372         os_memcpy(nulldata.hdr.IEEE80211_DA_FROMDS, addr, ETH_ALEN);
9373         os_memcpy(nulldata.hdr.IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
9374         os_memcpy(nulldata.hdr.IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
9375
9376         if (wpa_driver_nl80211_send_mlme(bss, (u8 *) &nulldata, size, 0, 0, 0,
9377                                          0, 0) < 0)
9378                 wpa_printf(MSG_DEBUG, "nl80211_send_null_frame: Failed to "
9379                            "send poll frame");
9380 }
9381
9382 static void nl80211_poll_client(void *priv, const u8 *own_addr, const u8 *addr,
9383                                 int qos)
9384 {
9385         struct i802_bss *bss = priv;
9386         struct wpa_driver_nl80211_data *drv = bss->drv;
9387         struct nl_msg *msg;
9388
9389         if (!drv->poll_command_supported) {
9390                 nl80211_send_null_frame(bss, own_addr, addr, qos);
9391                 return;
9392         }
9393
9394         msg = nlmsg_alloc();
9395         if (!msg)
9396                 return;
9397
9398         nl80211_cmd(drv, msg, 0, NL80211_CMD_PROBE_CLIENT);
9399
9400         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
9401         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
9402
9403         send_and_recv_msgs(drv, msg, NULL, NULL);
9404         return;
9405  nla_put_failure:
9406         nlmsg_free(msg);
9407 }
9408
9409
9410 static int nl80211_set_power_save(struct i802_bss *bss, int enabled)
9411 {
9412         struct nl_msg *msg;
9413
9414         msg = nlmsg_alloc();
9415         if (!msg)
9416                 return -ENOMEM;
9417
9418         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_SET_POWER_SAVE);
9419         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
9420         NLA_PUT_U32(msg, NL80211_ATTR_PS_STATE,
9421                     enabled ? NL80211_PS_ENABLED : NL80211_PS_DISABLED);
9422         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
9423 nla_put_failure:
9424         nlmsg_free(msg);
9425         return -ENOBUFS;
9426 }
9427
9428
9429 static int nl80211_set_p2p_powersave(void *priv, int legacy_ps, int opp_ps,
9430                                      int ctwindow)
9431 {
9432         struct i802_bss *bss = priv;
9433
9434         wpa_printf(MSG_DEBUG, "nl80211: set_p2p_powersave (legacy_ps=%d "
9435                    "opp_ps=%d ctwindow=%d)", legacy_ps, opp_ps, ctwindow);
9436
9437         if (opp_ps != -1 || ctwindow != -1)
9438                 return -1; /* Not yet supported */
9439
9440         if (legacy_ps == -1)
9441                 return 0;
9442         if (legacy_ps != 0 && legacy_ps != 1)
9443                 return -1; /* Not yet supported */
9444
9445         return nl80211_set_power_save(bss, legacy_ps);
9446 }
9447
9448
9449 #ifdef CONFIG_TDLS
9450
9451 static int nl80211_send_tdls_mgmt(void *priv, const u8 *dst, u8 action_code,
9452                                   u8 dialog_token, u16 status_code,
9453                                   const u8 *buf, size_t len)
9454 {
9455         struct i802_bss *bss = priv;
9456         struct wpa_driver_nl80211_data *drv = bss->drv;
9457         struct nl_msg *msg;
9458
9459         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
9460                 return -EOPNOTSUPP;
9461
9462         if (!dst)
9463                 return -EINVAL;
9464
9465         msg = nlmsg_alloc();
9466         if (!msg)
9467                 return -ENOMEM;
9468
9469         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_MGMT);
9470         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9471         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, dst);
9472         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_ACTION, action_code);
9473         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_DIALOG_TOKEN, dialog_token);
9474         NLA_PUT_U16(msg, NL80211_ATTR_STATUS_CODE, status_code);
9475         NLA_PUT(msg, NL80211_ATTR_IE, len, buf);
9476
9477         return send_and_recv_msgs(drv, msg, NULL, NULL);
9478
9479 nla_put_failure:
9480         nlmsg_free(msg);
9481         return -ENOBUFS;
9482 }
9483
9484
9485 static int nl80211_tdls_oper(void *priv, enum tdls_oper oper, const u8 *peer)
9486 {
9487         struct i802_bss *bss = priv;
9488         struct wpa_driver_nl80211_data *drv = bss->drv;
9489         struct nl_msg *msg;
9490         enum nl80211_tdls_operation nl80211_oper;
9491
9492         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
9493                 return -EOPNOTSUPP;
9494
9495         switch (oper) {
9496         case TDLS_DISCOVERY_REQ:
9497                 nl80211_oper = NL80211_TDLS_DISCOVERY_REQ;
9498                 break;
9499         case TDLS_SETUP:
9500                 nl80211_oper = NL80211_TDLS_SETUP;
9501                 break;
9502         case TDLS_TEARDOWN:
9503                 nl80211_oper = NL80211_TDLS_TEARDOWN;
9504                 break;
9505         case TDLS_ENABLE_LINK:
9506                 nl80211_oper = NL80211_TDLS_ENABLE_LINK;
9507                 break;
9508         case TDLS_DISABLE_LINK:
9509                 nl80211_oper = NL80211_TDLS_DISABLE_LINK;
9510                 break;
9511         case TDLS_ENABLE:
9512                 return 0;
9513         case TDLS_DISABLE:
9514                 return 0;
9515         default:
9516                 return -EINVAL;
9517         }
9518
9519         msg = nlmsg_alloc();
9520         if (!msg)
9521                 return -ENOMEM;
9522
9523         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_OPER);
9524         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_OPERATION, nl80211_oper);
9525         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9526         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, peer);
9527
9528         return send_and_recv_msgs(drv, msg, NULL, NULL);
9529
9530 nla_put_failure:
9531         nlmsg_free(msg);
9532         return -ENOBUFS;
9533 }
9534
9535 #endif /* CONFIG TDLS */
9536
9537
9538 #ifdef ANDROID
9539
9540 typedef struct android_wifi_priv_cmd {
9541         char *buf;
9542         int used_len;
9543         int total_len;
9544 } android_wifi_priv_cmd;
9545
9546 static int drv_errors = 0;
9547
9548 static void wpa_driver_send_hang_msg(struct wpa_driver_nl80211_data *drv)
9549 {
9550         drv_errors++;
9551         if (drv_errors > DRV_NUMBER_SEQUENTIAL_ERRORS) {
9552                 drv_errors = 0;
9553                 wpa_msg(drv->ctx, MSG_INFO, WPA_EVENT_DRIVER_STATE "HANGED");
9554         }
9555 }
9556
9557
9558 static int android_priv_cmd(struct i802_bss *bss, const char *cmd)
9559 {
9560         struct wpa_driver_nl80211_data *drv = bss->drv;
9561         struct ifreq ifr;
9562         android_wifi_priv_cmd priv_cmd;
9563         char buf[MAX_DRV_CMD_SIZE];
9564         int ret;
9565
9566         os_memset(&ifr, 0, sizeof(ifr));
9567         os_memset(&priv_cmd, 0, sizeof(priv_cmd));
9568         os_strlcpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
9569
9570         os_memset(buf, 0, sizeof(buf));
9571         os_strlcpy(buf, cmd, sizeof(buf));
9572
9573         priv_cmd.buf = buf;
9574         priv_cmd.used_len = sizeof(buf);
9575         priv_cmd.total_len = sizeof(buf);
9576         ifr.ifr_data = &priv_cmd;
9577
9578         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
9579         if (ret < 0) {
9580                 wpa_printf(MSG_ERROR, "%s: failed to issue private commands",
9581                            __func__);
9582                 wpa_driver_send_hang_msg(drv);
9583                 return ret;
9584         }
9585
9586         drv_errors = 0;
9587         return 0;
9588 }
9589
9590
9591 static int android_pno_start(struct i802_bss *bss,
9592                              struct wpa_driver_scan_params *params)
9593 {
9594         struct wpa_driver_nl80211_data *drv = bss->drv;
9595         struct ifreq ifr;
9596         android_wifi_priv_cmd priv_cmd;
9597         int ret = 0, i = 0, bp;
9598         char buf[WEXT_PNO_MAX_COMMAND_SIZE];
9599
9600         bp = WEXT_PNOSETUP_HEADER_SIZE;
9601         os_memcpy(buf, WEXT_PNOSETUP_HEADER, bp);
9602         buf[bp++] = WEXT_PNO_TLV_PREFIX;
9603         buf[bp++] = WEXT_PNO_TLV_VERSION;
9604         buf[bp++] = WEXT_PNO_TLV_SUBVERSION;
9605         buf[bp++] = WEXT_PNO_TLV_RESERVED;
9606
9607         while (i < WEXT_PNO_AMOUNT && (size_t) i < params->num_ssids) {
9608                 /* Check that there is enough space needed for 1 more SSID, the
9609                  * other sections and null termination */
9610                 if ((bp + WEXT_PNO_SSID_HEADER_SIZE + MAX_SSID_LEN +
9611                      WEXT_PNO_NONSSID_SECTIONS_SIZE + 1) >= (int) sizeof(buf))
9612                         break;
9613                 wpa_hexdump_ascii(MSG_DEBUG, "For PNO Scan",
9614                                   params->ssids[i].ssid,
9615                                   params->ssids[i].ssid_len);
9616                 buf[bp++] = WEXT_PNO_SSID_SECTION;
9617                 buf[bp++] = params->ssids[i].ssid_len;
9618                 os_memcpy(&buf[bp], params->ssids[i].ssid,
9619                           params->ssids[i].ssid_len);
9620                 bp += params->ssids[i].ssid_len;
9621                 i++;
9622         }
9623
9624         buf[bp++] = WEXT_PNO_SCAN_INTERVAL_SECTION;
9625         os_snprintf(&buf[bp], WEXT_PNO_SCAN_INTERVAL_LENGTH + 1, "%x",
9626                     WEXT_PNO_SCAN_INTERVAL);
9627         bp += WEXT_PNO_SCAN_INTERVAL_LENGTH;
9628
9629         buf[bp++] = WEXT_PNO_REPEAT_SECTION;
9630         os_snprintf(&buf[bp], WEXT_PNO_REPEAT_LENGTH + 1, "%x",
9631                     WEXT_PNO_REPEAT);
9632         bp += WEXT_PNO_REPEAT_LENGTH;
9633
9634         buf[bp++] = WEXT_PNO_MAX_REPEAT_SECTION;
9635         os_snprintf(&buf[bp], WEXT_PNO_MAX_REPEAT_LENGTH + 1, "%x",
9636                     WEXT_PNO_MAX_REPEAT);
9637         bp += WEXT_PNO_MAX_REPEAT_LENGTH + 1;
9638
9639         memset(&ifr, 0, sizeof(ifr));
9640         memset(&priv_cmd, 0, sizeof(priv_cmd));
9641         os_strncpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
9642
9643         priv_cmd.buf = buf;
9644         priv_cmd.used_len = bp;
9645         priv_cmd.total_len = bp;
9646         ifr.ifr_data = &priv_cmd;
9647
9648         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
9649
9650         if (ret < 0) {
9651                 wpa_printf(MSG_ERROR, "ioctl[SIOCSIWPRIV] (pnosetup): %d",
9652                            ret);
9653                 wpa_driver_send_hang_msg(drv);
9654                 return ret;
9655         }
9656
9657         drv_errors = 0;
9658
9659         return android_priv_cmd(bss, "PNOFORCE 1");
9660 }
9661
9662
9663 static int android_pno_stop(struct i802_bss *bss)
9664 {
9665         return android_priv_cmd(bss, "PNOFORCE 0");
9666 }
9667
9668 #endif /* ANDROID */
9669
9670
9671 static int driver_nl80211_set_key(const char *ifname, void *priv,
9672                                   enum wpa_alg alg, const u8 *addr,
9673                                   int key_idx, int set_tx,
9674                                   const u8 *seq, size_t seq_len,
9675                                   const u8 *key, size_t key_len)
9676 {
9677         struct i802_bss *bss = priv;
9678         return wpa_driver_nl80211_set_key(ifname, bss, alg, addr, key_idx,
9679                                           set_tx, seq, seq_len, key, key_len);
9680 }
9681
9682
9683 static int driver_nl80211_scan2(void *priv,
9684                                 struct wpa_driver_scan_params *params)
9685 {
9686         struct i802_bss *bss = priv;
9687         return wpa_driver_nl80211_scan(bss, params);
9688 }
9689
9690
9691 static int driver_nl80211_deauthenticate(void *priv, const u8 *addr,
9692                                          int reason_code)
9693 {
9694         struct i802_bss *bss = priv;
9695         return wpa_driver_nl80211_deauthenticate(bss, addr, reason_code);
9696 }
9697
9698
9699 static int driver_nl80211_authenticate(void *priv,
9700                                        struct wpa_driver_auth_params *params)
9701 {
9702         struct i802_bss *bss = priv;
9703         return wpa_driver_nl80211_authenticate(bss, params);
9704 }
9705
9706
9707 static void driver_nl80211_deinit(void *priv)
9708 {
9709         struct i802_bss *bss = priv;
9710         wpa_driver_nl80211_deinit(bss);
9711 }
9712
9713
9714 static int driver_nl80211_if_remove(void *priv, enum wpa_driver_if_type type,
9715                                     const char *ifname)
9716 {
9717         struct i802_bss *bss = priv;
9718         return wpa_driver_nl80211_if_remove(bss, type, ifname);
9719 }
9720
9721
9722 static int driver_nl80211_send_mlme(void *priv, const u8 *data,
9723                                     size_t data_len, int noack)
9724 {
9725         struct i802_bss *bss = priv;
9726         return wpa_driver_nl80211_send_mlme(bss, data, data_len, noack,
9727                                             0, 0, 0, 0);
9728 }
9729
9730
9731 static int driver_nl80211_sta_remove(void *priv, const u8 *addr)
9732 {
9733         struct i802_bss *bss = priv;
9734         return wpa_driver_nl80211_sta_remove(bss, addr);
9735 }
9736
9737
9738 #if defined(HOSTAPD) || defined(CONFIG_AP)
9739 static int driver_nl80211_set_sta_vlan(void *priv, const u8 *addr,
9740                                        const char *ifname, int vlan_id)
9741 {
9742         struct i802_bss *bss = priv;
9743         return i802_set_sta_vlan(bss, addr, ifname, vlan_id);
9744 }
9745 #endif /* HOSTAPD || CONFIG_AP */
9746
9747
9748 static int driver_nl80211_read_sta_data(void *priv,
9749                                         struct hostap_sta_driver_data *data,
9750                                         const u8 *addr)
9751 {
9752         struct i802_bss *bss = priv;
9753         return i802_read_sta_data(bss, data, addr);
9754 }
9755
9756
9757 static int driver_nl80211_send_action(void *priv, unsigned int freq,
9758                                       unsigned int wait_time,
9759                                       const u8 *dst, const u8 *src,
9760                                       const u8 *bssid,
9761                                       const u8 *data, size_t data_len,
9762                                       int no_cck)
9763 {
9764         struct i802_bss *bss = priv;
9765         return wpa_driver_nl80211_send_action(bss, freq, wait_time, dst, src,
9766                                               bssid, data, data_len, no_cck);
9767 }
9768
9769
9770 static int driver_nl80211_probe_req_report(void *priv, int report)
9771 {
9772         struct i802_bss *bss = priv;
9773         return wpa_driver_nl80211_probe_req_report(bss, report);
9774 }
9775
9776
9777 static int wpa_driver_nl80211_update_ft_ies(void *priv, const u8 *md,
9778                                             const u8 *ies, size_t ies_len)
9779 {
9780         int ret;
9781         struct nl_msg *msg;
9782         struct i802_bss *bss = priv;
9783         struct wpa_driver_nl80211_data *drv = bss->drv;
9784         u16 mdid = WPA_GET_LE16(md);
9785
9786         msg = nlmsg_alloc();
9787         if (!msg)
9788                 return -ENOMEM;
9789
9790         wpa_printf(MSG_DEBUG, "nl80211: Updating FT IEs");
9791         nl80211_cmd(drv, msg, 0, NL80211_CMD_UPDATE_FT_IES);
9792         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9793         NLA_PUT(msg, NL80211_ATTR_IE, ies_len, ies);
9794         NLA_PUT_U16(msg, NL80211_ATTR_MDID, mdid);
9795
9796         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9797         if (ret) {
9798                 wpa_printf(MSG_DEBUG, "nl80211: update_ft_ies failed "
9799                            "err=%d (%s)", ret, strerror(-ret));
9800         }
9801
9802         return ret;
9803
9804 nla_put_failure:
9805         nlmsg_free(msg);
9806         return -ENOBUFS;
9807 }
9808
9809
9810 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
9811         .name = "nl80211",
9812         .desc = "Linux nl80211/cfg80211",
9813         .get_bssid = wpa_driver_nl80211_get_bssid,
9814         .get_ssid = wpa_driver_nl80211_get_ssid,
9815         .set_key = driver_nl80211_set_key,
9816         .scan2 = driver_nl80211_scan2,
9817         .sched_scan = wpa_driver_nl80211_sched_scan,
9818         .stop_sched_scan = wpa_driver_nl80211_stop_sched_scan,
9819         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
9820         .deauthenticate = driver_nl80211_deauthenticate,
9821         .authenticate = driver_nl80211_authenticate,
9822         .associate = wpa_driver_nl80211_associate,
9823         .global_init = nl80211_global_init,
9824         .global_deinit = nl80211_global_deinit,
9825         .init2 = wpa_driver_nl80211_init,
9826         .deinit = driver_nl80211_deinit,
9827         .get_capa = wpa_driver_nl80211_get_capa,
9828         .set_operstate = wpa_driver_nl80211_set_operstate,
9829         .set_supp_port = wpa_driver_nl80211_set_supp_port,
9830         .set_country = wpa_driver_nl80211_set_country,
9831         .set_ap = wpa_driver_nl80211_set_ap,
9832         .if_add = wpa_driver_nl80211_if_add,
9833         .if_remove = driver_nl80211_if_remove,
9834         .send_mlme = driver_nl80211_send_mlme,
9835         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
9836         .sta_add = wpa_driver_nl80211_sta_add,
9837         .sta_remove = driver_nl80211_sta_remove,
9838         .hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
9839         .sta_set_flags = wpa_driver_nl80211_sta_set_flags,
9840 #ifdef HOSTAPD
9841         .hapd_init = i802_init,
9842         .hapd_deinit = i802_deinit,
9843         .set_wds_sta = i802_set_wds_sta,
9844 #endif /* HOSTAPD */
9845 #if defined(HOSTAPD) || defined(CONFIG_AP)
9846         .get_seqnum = i802_get_seqnum,
9847         .flush = i802_flush,
9848         .get_inact_sec = i802_get_inact_sec,
9849         .sta_clear_stats = i802_sta_clear_stats,
9850         .set_rts = i802_set_rts,
9851         .set_frag = i802_set_frag,
9852         .set_tx_queue_params = i802_set_tx_queue_params,
9853         .set_sta_vlan = driver_nl80211_set_sta_vlan,
9854         .sta_deauth = i802_sta_deauth,
9855         .sta_disassoc = i802_sta_disassoc,
9856 #endif /* HOSTAPD || CONFIG_AP */
9857         .read_sta_data = driver_nl80211_read_sta_data,
9858         .set_freq = i802_set_freq,
9859         .send_action = driver_nl80211_send_action,
9860         .send_action_cancel_wait = wpa_driver_nl80211_send_action_cancel_wait,
9861         .remain_on_channel = wpa_driver_nl80211_remain_on_channel,
9862         .cancel_remain_on_channel =
9863         wpa_driver_nl80211_cancel_remain_on_channel,
9864         .probe_req_report = driver_nl80211_probe_req_report,
9865         .deinit_ap = wpa_driver_nl80211_deinit_ap,
9866         .deinit_p2p_cli = wpa_driver_nl80211_deinit_p2p_cli,
9867         .resume = wpa_driver_nl80211_resume,
9868         .send_ft_action = nl80211_send_ft_action,
9869         .signal_monitor = nl80211_signal_monitor,
9870         .signal_poll = nl80211_signal_poll,
9871         .send_frame = nl80211_send_frame,
9872         .shared_freq = wpa_driver_nl80211_shared_freq,
9873         .set_param = nl80211_set_param,
9874         .get_radio_name = nl80211_get_radio_name,
9875         .add_pmkid = nl80211_add_pmkid,
9876         .remove_pmkid = nl80211_remove_pmkid,
9877         .flush_pmkid = nl80211_flush_pmkid,
9878         .set_rekey_info = nl80211_set_rekey_info,
9879         .poll_client = nl80211_poll_client,
9880         .set_p2p_powersave = nl80211_set_p2p_powersave,
9881 #ifdef CONFIG_TDLS
9882         .send_tdls_mgmt = nl80211_send_tdls_mgmt,
9883         .tdls_oper = nl80211_tdls_oper,
9884 #endif /* CONFIG_TDLS */
9885         .update_ft_ies = wpa_driver_nl80211_update_ft_ies,
9886 };