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