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