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