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