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