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