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