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