nl80211: Fix netlink error paths in sched_scan() handler
[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                 /*
2638                  * No AP SME is currently assumed to also indicate no AP MLME
2639                  * in the driver/firmware.
2640                  */
2641                 drv->capa.flags |= WPA_DRIVER_FLAGS_AP_MLME;
2642         }
2643
2644         drv->device_ap_sme = info.device_ap_sme;
2645         drv->poll_command_supported = info.poll_command_supported;
2646         drv->data_tx_status = info.data_tx_status;
2647
2648         /*
2649          * If poll command is supported mac80211 is new enough to
2650          * have everything we need to not need monitor interfaces.
2651          */
2652         drv->use_monitor = !info.poll_command_supported;
2653
2654         if (drv->device_ap_sme && drv->use_monitor) {
2655                 /*
2656                  * Non-mac80211 drivers may not support monitor interface.
2657                  * Make sure we do not get stuck with incorrect capability here
2658                  * by explicitly testing this.
2659                  */
2660                 if (!info.monitor_supported) {
2661                         wpa_printf(MSG_DEBUG, "nl80211: Disable use_monitor "
2662                                    "with device_ap_sme since no monitor mode "
2663                                    "support detected");
2664                         drv->use_monitor = 0;
2665                 }
2666         }
2667
2668         /*
2669          * If we aren't going to use monitor interfaces, but the
2670          * driver doesn't support data TX status, we won't get TX
2671          * status for EAPOL frames.
2672          */
2673         if (!drv->use_monitor && !info.data_tx_status)
2674                 drv->capa.flags &= ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2675
2676         return 0;
2677 }
2678
2679
2680 #ifdef ANDROID
2681 static int android_genl_ctrl_resolve(struct nl_handle *handle,
2682                                      const char *name)
2683 {
2684         /*
2685          * Android ICS has very minimal genl_ctrl_resolve() implementation, so
2686          * need to work around that.
2687          */
2688         struct nl_cache *cache = NULL;
2689         struct genl_family *nl80211 = NULL;
2690         int id = -1;
2691
2692         if (genl_ctrl_alloc_cache(handle, &cache) < 0) {
2693                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
2694                            "netlink cache");
2695                 goto fail;
2696         }
2697
2698         nl80211 = genl_ctrl_search_by_name(cache, name);
2699         if (nl80211 == NULL)
2700                 goto fail;
2701
2702         id = genl_family_get_id(nl80211);
2703
2704 fail:
2705         if (nl80211)
2706                 genl_family_put(nl80211);
2707         if (cache)
2708                 nl_cache_free(cache);
2709
2710         return id;
2711 }
2712 #define genl_ctrl_resolve android_genl_ctrl_resolve
2713 #endif /* ANDROID */
2714
2715
2716 static int wpa_driver_nl80211_init_nl_global(struct nl80211_global *global)
2717 {
2718         int ret;
2719
2720         global->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2721         if (global->nl_cb == NULL) {
2722                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
2723                            "callbacks");
2724                 return -1;
2725         }
2726
2727         global->nl = nl_create_handle(global->nl_cb, "nl");
2728         if (global->nl == NULL)
2729                 goto err;
2730
2731         global->nl80211_id = genl_ctrl_resolve(global->nl, "nl80211");
2732         if (global->nl80211_id < 0) {
2733                 wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
2734                            "found");
2735                 goto err;
2736         }
2737
2738         global->nl_event = nl_create_handle(global->nl_cb, "event");
2739         if (global->nl_event == NULL)
2740                 goto err;
2741
2742         ret = nl_get_multicast_id(global, "nl80211", "scan");
2743         if (ret >= 0)
2744                 ret = nl_socket_add_membership(global->nl_event, ret);
2745         if (ret < 0) {
2746                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
2747                            "membership for scan events: %d (%s)",
2748                            ret, strerror(-ret));
2749                 goto err;
2750         }
2751
2752         ret = nl_get_multicast_id(global, "nl80211", "mlme");
2753         if (ret >= 0)
2754                 ret = nl_socket_add_membership(global->nl_event, ret);
2755         if (ret < 0) {
2756                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
2757                            "membership for mlme events: %d (%s)",
2758                            ret, strerror(-ret));
2759                 goto err;
2760         }
2761
2762         ret = nl_get_multicast_id(global, "nl80211", "regulatory");
2763         if (ret >= 0)
2764                 ret = nl_socket_add_membership(global->nl_event, ret);
2765         if (ret < 0) {
2766                 wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
2767                            "membership for regulatory events: %d (%s)",
2768                            ret, strerror(-ret));
2769                 /* Continue without regulatory events */
2770         }
2771
2772         nl_cb_set(global->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2773                   no_seq_check, NULL);
2774         nl_cb_set(global->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2775                   process_global_event, global);
2776
2777         eloop_register_read_sock(nl_socket_get_fd(global->nl_event),
2778                                  wpa_driver_nl80211_event_receive,
2779                                  global->nl_cb, global->nl_event);
2780
2781         return 0;
2782
2783 err:
2784         nl_destroy_handles(&global->nl_event);
2785         nl_destroy_handles(&global->nl);
2786         nl_cb_put(global->nl_cb);
2787         global->nl_cb = NULL;
2788         return -1;
2789 }
2790
2791
2792 static int wpa_driver_nl80211_init_nl(struct wpa_driver_nl80211_data *drv)
2793 {
2794         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2795         if (!drv->nl_cb) {
2796                 wpa_printf(MSG_ERROR, "nl80211: Failed to alloc cb struct");
2797                 return -1;
2798         }
2799
2800         nl_cb_set(drv->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2801                   no_seq_check, NULL);
2802         nl_cb_set(drv->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2803                   process_drv_event, drv);
2804
2805         return 0;
2806 }
2807
2808
2809 static void wpa_driver_nl80211_rfkill_blocked(void *ctx)
2810 {
2811         wpa_printf(MSG_DEBUG, "nl80211: RFKILL blocked");
2812         /*
2813          * This may be for any interface; use ifdown event to disable
2814          * interface.
2815          */
2816 }
2817
2818
2819 static void wpa_driver_nl80211_rfkill_unblocked(void *ctx)
2820 {
2821         struct wpa_driver_nl80211_data *drv = ctx;
2822         wpa_printf(MSG_DEBUG, "nl80211: RFKILL unblocked");
2823         if (linux_set_iface_flags(drv->global->ioctl_sock,
2824                                   drv->first_bss.ifname, 1)) {
2825                 wpa_printf(MSG_DEBUG, "nl80211: Could not set interface UP "
2826                            "after rfkill unblock");
2827                 return;
2828         }
2829         /* rtnetlink ifup handler will report interface as enabled */
2830 }
2831
2832
2833 static void nl80211_get_phy_name(struct wpa_driver_nl80211_data *drv)
2834 {
2835         /* Find phy (radio) to which this interface belongs */
2836         char buf[90], *pos;
2837         int f, rv;
2838
2839         drv->phyname[0] = '\0';
2840         snprintf(buf, sizeof(buf) - 1, "/sys/class/net/%s/phy80211/name",
2841                  drv->first_bss.ifname);
2842         f = open(buf, O_RDONLY);
2843         if (f < 0) {
2844                 wpa_printf(MSG_DEBUG, "Could not open file %s: %s",
2845                            buf, strerror(errno));
2846                 return;
2847         }
2848
2849         rv = read(f, drv->phyname, sizeof(drv->phyname) - 1);
2850         close(f);
2851         if (rv < 0) {
2852                 wpa_printf(MSG_DEBUG, "Could not read file %s: %s",
2853                            buf, strerror(errno));
2854                 return;
2855         }
2856
2857         drv->phyname[rv] = '\0';
2858         pos = os_strchr(drv->phyname, '\n');
2859         if (pos)
2860                 *pos = '\0';
2861         wpa_printf(MSG_DEBUG, "nl80211: interface %s in phy %s",
2862                    drv->first_bss.ifname, drv->phyname);
2863 }
2864
2865
2866 static void wpa_driver_nl80211_handle_eapol_tx_status(int sock,
2867                                                       void *eloop_ctx,
2868                                                       void *handle)
2869 {
2870         struct wpa_driver_nl80211_data *drv = eloop_ctx;
2871         u8 data[2048];
2872         struct msghdr msg;
2873         struct iovec entry;
2874         u8 control[512];
2875         struct cmsghdr *cmsg;
2876         int res, found_ee = 0, found_wifi = 0, acked = 0;
2877         union wpa_event_data event;
2878
2879         memset(&msg, 0, sizeof(msg));
2880         msg.msg_iov = &entry;
2881         msg.msg_iovlen = 1;
2882         entry.iov_base = data;
2883         entry.iov_len = sizeof(data);
2884         msg.msg_control = &control;
2885         msg.msg_controllen = sizeof(control);
2886
2887         res = recvmsg(sock, &msg, MSG_ERRQUEUE);
2888         /* if error or not fitting 802.3 header, return */
2889         if (res < 14)
2890                 return;
2891
2892         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg))
2893         {
2894                 if (cmsg->cmsg_level == SOL_SOCKET &&
2895                     cmsg->cmsg_type == SCM_WIFI_STATUS) {
2896                         int *ack;
2897
2898                         found_wifi = 1;
2899                         ack = (void *)CMSG_DATA(cmsg);
2900                         acked = *ack;
2901                 }
2902
2903                 if (cmsg->cmsg_level == SOL_PACKET &&
2904                     cmsg->cmsg_type == PACKET_TX_TIMESTAMP) {
2905                         struct sock_extended_err *err =
2906                                 (struct sock_extended_err *)CMSG_DATA(cmsg);
2907
2908                         if (err->ee_origin == SO_EE_ORIGIN_TXSTATUS)
2909                                 found_ee = 1;
2910                 }
2911         }
2912
2913         if (!found_ee || !found_wifi)
2914                 return;
2915
2916         memset(&event, 0, sizeof(event));
2917         event.eapol_tx_status.dst = data;
2918         event.eapol_tx_status.data = data + 14;
2919         event.eapol_tx_status.data_len = res - 14;
2920         event.eapol_tx_status.ack = acked;
2921         wpa_supplicant_event(drv->ctx, EVENT_EAPOL_TX_STATUS, &event);
2922 }
2923
2924
2925 static int nl80211_init_bss(struct i802_bss *bss)
2926 {
2927         bss->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
2928         if (!bss->nl_cb)
2929                 return -1;
2930
2931         nl_cb_set(bss->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
2932                   no_seq_check, NULL);
2933         nl_cb_set(bss->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
2934                   process_bss_event, bss);
2935
2936         return 0;
2937 }
2938
2939
2940 static void nl80211_destroy_bss(struct i802_bss *bss)
2941 {
2942         nl_cb_put(bss->nl_cb);
2943         bss->nl_cb = NULL;
2944 }
2945
2946
2947 /**
2948  * wpa_driver_nl80211_init - Initialize nl80211 driver interface
2949  * @ctx: context to be used when calling wpa_supplicant functions,
2950  * e.g., wpa_supplicant_event()
2951  * @ifname: interface name, e.g., wlan0
2952  * @global_priv: private driver global data from global_init()
2953  * Returns: Pointer to private data, %NULL on failure
2954  */
2955 static void * wpa_driver_nl80211_init(void *ctx, const char *ifname,
2956                                       void *global_priv)
2957 {
2958         struct wpa_driver_nl80211_data *drv;
2959         struct rfkill_config *rcfg;
2960         struct i802_bss *bss;
2961
2962         if (global_priv == NULL)
2963                 return NULL;
2964         drv = os_zalloc(sizeof(*drv));
2965         if (drv == NULL)
2966                 return NULL;
2967         drv->global = global_priv;
2968         drv->ctx = ctx;
2969         bss = &drv->first_bss;
2970         bss->drv = drv;
2971         os_strlcpy(bss->ifname, ifname, sizeof(bss->ifname));
2972         drv->monitor_ifidx = -1;
2973         drv->monitor_sock = -1;
2974         drv->eapol_tx_sock = -1;
2975         drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
2976
2977         if (wpa_driver_nl80211_init_nl(drv)) {
2978                 os_free(drv);
2979                 return NULL;
2980         }
2981
2982         if (nl80211_init_bss(bss))
2983                 goto failed;
2984
2985         nl80211_get_phy_name(drv);
2986
2987         rcfg = os_zalloc(sizeof(*rcfg));
2988         if (rcfg == NULL)
2989                 goto failed;
2990         rcfg->ctx = drv;
2991         os_strlcpy(rcfg->ifname, ifname, sizeof(rcfg->ifname));
2992         rcfg->blocked_cb = wpa_driver_nl80211_rfkill_blocked;
2993         rcfg->unblocked_cb = wpa_driver_nl80211_rfkill_unblocked;
2994         drv->rfkill = rfkill_init(rcfg);
2995         if (drv->rfkill == NULL) {
2996                 wpa_printf(MSG_DEBUG, "nl80211: RFKILL status not available");
2997                 os_free(rcfg);
2998         }
2999
3000         if (wpa_driver_nl80211_finish_drv_init(drv))
3001                 goto failed;
3002
3003         drv->eapol_tx_sock = socket(PF_PACKET, SOCK_DGRAM, 0);
3004         if (drv->eapol_tx_sock < 0)
3005                 goto failed;
3006
3007         if (drv->data_tx_status) {
3008                 int enabled = 1;
3009
3010                 if (setsockopt(drv->eapol_tx_sock, SOL_SOCKET, SO_WIFI_STATUS,
3011                                &enabled, sizeof(enabled)) < 0) {
3012                         wpa_printf(MSG_DEBUG,
3013                                 "nl80211: wifi status sockopt failed\n");
3014                         drv->data_tx_status = 0;
3015                         if (!drv->use_monitor)
3016                                 drv->capa.flags &=
3017                                         ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
3018                 } else {
3019                         eloop_register_read_sock(drv->eapol_tx_sock,
3020                                 wpa_driver_nl80211_handle_eapol_tx_status,
3021                                 drv, NULL);
3022                 }
3023         }
3024
3025         if (drv->global) {
3026                 dl_list_add(&drv->global->interfaces, &drv->list);
3027                 drv->in_interface_list = 1;
3028         }
3029
3030         return bss;
3031
3032 failed:
3033         wpa_driver_nl80211_deinit(bss);
3034         return NULL;
3035 }
3036
3037
3038 static int nl80211_register_frame(struct i802_bss *bss,
3039                                   struct nl_handle *nl_handle,
3040                                   u16 type, const u8 *match, size_t match_len)
3041 {
3042         struct wpa_driver_nl80211_data *drv = bss->drv;
3043         struct nl_msg *msg;
3044         int ret = -1;
3045
3046         msg = nlmsg_alloc();
3047         if (!msg)
3048                 return -1;
3049
3050         wpa_printf(MSG_DEBUG, "nl80211: Register frame type=0x%x nl_handle=%p",
3051                    type, nl_handle);
3052         wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
3053                     match, match_len);
3054
3055         nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_ACTION);
3056
3057         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3058         NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE, type);
3059         NLA_PUT(msg, NL80211_ATTR_FRAME_MATCH, match_len, match);
3060
3061         ret = send_and_recv(drv->global, nl_handle, msg, NULL, NULL);
3062         msg = NULL;
3063         if (ret) {
3064                 wpa_printf(MSG_DEBUG, "nl80211: Register frame command "
3065                            "failed (type=%u): ret=%d (%s)",
3066                            type, ret, strerror(-ret));
3067                 wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
3068                             match, match_len);
3069                 goto nla_put_failure;
3070         }
3071         ret = 0;
3072 nla_put_failure:
3073         nlmsg_free(msg);
3074         return ret;
3075 }
3076
3077
3078 static int nl80211_alloc_mgmt_handle(struct i802_bss *bss)
3079 {
3080         struct wpa_driver_nl80211_data *drv = bss->drv;
3081
3082         if (bss->nl_mgmt) {
3083                 wpa_printf(MSG_DEBUG, "nl80211: Mgmt reporting "
3084                            "already on! (nl_mgmt=%p)", bss->nl_mgmt);
3085                 return -1;
3086         }
3087
3088         bss->nl_mgmt = nl_create_handle(drv->nl_cb, "mgmt");
3089         if (bss->nl_mgmt == NULL)
3090                 return -1;
3091
3092         eloop_register_read_sock(nl_socket_get_fd(bss->nl_mgmt),
3093                                  wpa_driver_nl80211_event_receive, bss->nl_cb,
3094                                  bss->nl_mgmt);
3095
3096         return 0;
3097 }
3098
3099
3100 static int nl80211_register_action_frame(struct i802_bss *bss,
3101                                          const u8 *match, size_t match_len)
3102 {
3103         u16 type = (WLAN_FC_TYPE_MGMT << 2) | (WLAN_FC_STYPE_ACTION << 4);
3104         return nl80211_register_frame(bss, bss->nl_mgmt,
3105                                       type, match, match_len);
3106 }
3107
3108
3109 static int nl80211_mgmt_subscribe_non_ap(struct i802_bss *bss)
3110 {
3111         struct wpa_driver_nl80211_data *drv = bss->drv;
3112
3113         if (nl80211_alloc_mgmt_handle(bss))
3114                 return -1;
3115         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with non-AP "
3116                    "handle %p", bss->nl_mgmt);
3117
3118 #if defined(CONFIG_P2P) || defined(CONFIG_INTERWORKING)
3119         /* GAS Initial Request */
3120         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0a", 2) < 0)
3121                 return -1;
3122         /* GAS Initial Response */
3123         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0b", 2) < 0)
3124                 return -1;
3125         /* GAS Comeback Request */
3126         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0c", 2) < 0)
3127                 return -1;
3128         /* GAS Comeback Response */
3129         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0d", 2) < 0)
3130                 return -1;
3131 #endif /* CONFIG_P2P || CONFIG_INTERWORKING */
3132 #ifdef CONFIG_P2P
3133         /* P2P Public Action */
3134         if (nl80211_register_action_frame(bss,
3135                                           (u8 *) "\x04\x09\x50\x6f\x9a\x09",
3136                                           6) < 0)
3137                 return -1;
3138         /* P2P Action */
3139         if (nl80211_register_action_frame(bss,
3140                                           (u8 *) "\x7f\x50\x6f\x9a\x09",
3141                                           5) < 0)
3142                 return -1;
3143 #endif /* CONFIG_P2P */
3144 #ifdef CONFIG_IEEE80211W
3145         /* SA Query Response */
3146         if (nl80211_register_action_frame(bss, (u8 *) "\x08\x01", 2) < 0)
3147                 return -1;
3148 #endif /* CONFIG_IEEE80211W */
3149 #ifdef CONFIG_TDLS
3150         if ((drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT)) {
3151                 /* TDLS Discovery Response */
3152                 if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0e", 2) <
3153                     0)
3154                         return -1;
3155         }
3156 #endif /* CONFIG_TDLS */
3157
3158         /* FT Action frames */
3159         if (nl80211_register_action_frame(bss, (u8 *) "\x06", 1) < 0)
3160                 return -1;
3161         else
3162                 drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_FT |
3163                         WPA_DRIVER_CAPA_KEY_MGMT_FT_PSK;
3164
3165         /* WNM - BSS Transition Management Request */
3166         if (nl80211_register_action_frame(bss, (u8 *) "\x0a\x07", 2) < 0)
3167                 return -1;
3168
3169         return 0;
3170 }
3171
3172
3173 static int nl80211_register_spurious_class3(struct i802_bss *bss)
3174 {
3175         struct wpa_driver_nl80211_data *drv = bss->drv;
3176         struct nl_msg *msg;
3177         int ret = -1;
3178
3179         msg = nlmsg_alloc();
3180         if (!msg)
3181                 return -1;
3182
3183         nl80211_cmd(drv, msg, 0, NL80211_CMD_UNEXPECTED_FRAME);
3184
3185         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3186
3187         ret = send_and_recv(drv->global, bss->nl_mgmt, msg, NULL, NULL);
3188         msg = NULL;
3189         if (ret) {
3190                 wpa_printf(MSG_DEBUG, "nl80211: Register spurious class3 "
3191                            "failed: ret=%d (%s)",
3192                            ret, strerror(-ret));
3193                 goto nla_put_failure;
3194         }
3195         ret = 0;
3196 nla_put_failure:
3197         nlmsg_free(msg);
3198         return ret;
3199 }
3200
3201
3202 static int nl80211_mgmt_subscribe_ap(struct i802_bss *bss)
3203 {
3204         static const int stypes[] = {
3205                 WLAN_FC_STYPE_AUTH,
3206                 WLAN_FC_STYPE_ASSOC_REQ,
3207                 WLAN_FC_STYPE_REASSOC_REQ,
3208                 WLAN_FC_STYPE_DISASSOC,
3209                 WLAN_FC_STYPE_DEAUTH,
3210                 WLAN_FC_STYPE_ACTION,
3211                 WLAN_FC_STYPE_PROBE_REQ,
3212 /* Beacon doesn't work as mac80211 doesn't currently allow
3213  * it, but it wouldn't really be the right thing anyway as
3214  * it isn't per interface ... maybe just dump the scan
3215  * results periodically for OLBC?
3216  */
3217 //              WLAN_FC_STYPE_BEACON,
3218         };
3219         unsigned int i;
3220
3221         if (nl80211_alloc_mgmt_handle(bss))
3222                 return -1;
3223         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3224                    "handle %p", bss->nl_mgmt);
3225
3226         for (i = 0; i < sizeof(stypes) / sizeof(stypes[0]); i++) {
3227                 if (nl80211_register_frame(bss, bss->nl_mgmt,
3228                                            (WLAN_FC_TYPE_MGMT << 2) |
3229                                            (stypes[i] << 4),
3230                                            NULL, 0) < 0) {
3231                         goto out_err;
3232                 }
3233         }
3234
3235         if (nl80211_register_spurious_class3(bss))
3236                 goto out_err;
3237
3238         if (nl80211_get_wiphy_data_ap(bss) == NULL)
3239                 goto out_err;
3240
3241         return 0;
3242
3243 out_err:
3244         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3245         nl_destroy_handles(&bss->nl_mgmt);
3246         return -1;
3247 }
3248
3249
3250 static int nl80211_mgmt_subscribe_ap_dev_sme(struct i802_bss *bss)
3251 {
3252         if (nl80211_alloc_mgmt_handle(bss))
3253                 return -1;
3254         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3255                    "handle %p (device SME)", bss->nl_mgmt);
3256
3257         if (nl80211_register_frame(bss, bss->nl_mgmt,
3258                                    (WLAN_FC_TYPE_MGMT << 2) |
3259                                    (WLAN_FC_STYPE_ACTION << 4),
3260                                    NULL, 0) < 0)
3261                 goto out_err;
3262
3263         return 0;
3264
3265 out_err:
3266         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3267         nl_destroy_handles(&bss->nl_mgmt);
3268         return -1;
3269 }
3270
3271
3272 static void nl80211_mgmt_unsubscribe(struct i802_bss *bss, const char *reason)
3273 {
3274         if (bss->nl_mgmt == NULL)
3275                 return;
3276         wpa_printf(MSG_DEBUG, "nl80211: Unsubscribe mgmt frames handle %p "
3277                    "(%s)", bss->nl_mgmt, reason);
3278         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3279         nl_destroy_handles(&bss->nl_mgmt);
3280
3281         nl80211_put_wiphy_data_ap(bss);
3282 }
3283
3284
3285 static void wpa_driver_nl80211_send_rfkill(void *eloop_ctx, void *timeout_ctx)
3286 {
3287         wpa_supplicant_event(timeout_ctx, EVENT_INTERFACE_DISABLED, NULL);
3288 }
3289
3290
3291 static int
3292 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv)
3293 {
3294         struct i802_bss *bss = &drv->first_bss;
3295         int send_rfkill_event = 0;
3296
3297         drv->ifindex = if_nametoindex(bss->ifname);
3298         drv->first_bss.ifindex = drv->ifindex;
3299
3300 #ifndef HOSTAPD
3301         /*
3302          * Make sure the interface starts up in station mode unless this is a
3303          * dynamically added interface (e.g., P2P) that was already configured
3304          * with proper iftype.
3305          */
3306         if (drv->ifindex != drv->global->if_add_ifindex &&
3307             wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION) < 0) {
3308                 wpa_printf(MSG_ERROR, "nl80211: Could not configure driver to "
3309                            "use managed mode");
3310                 return -1;
3311         }
3312
3313         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
3314                 if (rfkill_is_blocked(drv->rfkill)) {
3315                         wpa_printf(MSG_DEBUG, "nl80211: Could not yet enable "
3316                                    "interface '%s' due to rfkill",
3317                                    bss->ifname);
3318                         drv->if_disabled = 1;
3319                         send_rfkill_event = 1;
3320                 } else {
3321                         wpa_printf(MSG_ERROR, "nl80211: Could not set "
3322                                    "interface '%s' UP", bss->ifname);
3323                         return -1;
3324                 }
3325         }
3326
3327         netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
3328                                1, IF_OPER_DORMANT);
3329 #endif /* HOSTAPD */
3330
3331         if (wpa_driver_nl80211_capa(drv))
3332                 return -1;
3333
3334         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
3335                                bss->addr))
3336                 return -1;
3337
3338         if (send_rfkill_event) {
3339                 eloop_register_timeout(0, 0, wpa_driver_nl80211_send_rfkill,
3340                                        drv, drv->ctx);
3341         }
3342
3343         return 0;
3344 }
3345
3346
3347 static int wpa_driver_nl80211_del_beacon(struct wpa_driver_nl80211_data *drv)
3348 {
3349         struct nl_msg *msg;
3350
3351         msg = nlmsg_alloc();
3352         if (!msg)
3353                 return -ENOMEM;
3354
3355         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_BEACON);
3356         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3357
3358         return send_and_recv_msgs(drv, msg, NULL, NULL);
3359  nla_put_failure:
3360         nlmsg_free(msg);
3361         return -ENOBUFS;
3362 }
3363
3364
3365 /**
3366  * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
3367  * @priv: Pointer to private nl80211 data from wpa_driver_nl80211_init()
3368  *
3369  * Shut down driver interface and processing of driver events. Free
3370  * private data buffer if one was allocated in wpa_driver_nl80211_init().
3371  */
3372 static void wpa_driver_nl80211_deinit(void *priv)
3373 {
3374         struct i802_bss *bss = priv;
3375         struct wpa_driver_nl80211_data *drv = bss->drv;
3376
3377         bss->in_deinit = 1;
3378         if (drv->data_tx_status)
3379                 eloop_unregister_read_sock(drv->eapol_tx_sock);
3380         if (drv->eapol_tx_sock >= 0)
3381                 close(drv->eapol_tx_sock);
3382
3383         if (bss->nl_preq)
3384                 wpa_driver_nl80211_probe_req_report(bss, 0);
3385         if (bss->added_if_into_bridge) {
3386                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
3387                                     bss->ifname) < 0)
3388                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3389                                    "interface %s from bridge %s: %s",
3390                                    bss->ifname, bss->brname, strerror(errno));
3391         }
3392         if (bss->added_bridge) {
3393                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
3394                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3395                                    "bridge %s: %s",
3396                                    bss->brname, strerror(errno));
3397         }
3398
3399         nl80211_remove_monitor_interface(drv);
3400
3401         if (is_ap_interface(drv->nlmode))
3402                 wpa_driver_nl80211_del_beacon(drv);
3403
3404 #ifdef HOSTAPD
3405         if (drv->last_freq_ht) {
3406                 /* Clear HT flags from the driver */
3407                 struct hostapd_freq_params freq;
3408                 os_memset(&freq, 0, sizeof(freq));
3409                 freq.freq = drv->last_freq;
3410                 i802_set_freq(priv, &freq);
3411         }
3412
3413         if (drv->eapol_sock >= 0) {
3414                 eloop_unregister_read_sock(drv->eapol_sock);
3415                 close(drv->eapol_sock);
3416         }
3417
3418         if (drv->if_indices != drv->default_if_indices)
3419                 os_free(drv->if_indices);
3420 #endif /* HOSTAPD */
3421
3422         if (drv->disabled_11b_rates)
3423                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
3424
3425         netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, 0,
3426                                IF_OPER_UP);
3427         rfkill_deinit(drv->rfkill);
3428
3429         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3430
3431         (void) linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0);
3432         wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION);
3433         nl80211_mgmt_unsubscribe(bss, "deinit");
3434
3435         nl_cb_put(drv->nl_cb);
3436
3437         nl80211_destroy_bss(&drv->first_bss);
3438
3439         os_free(drv->filter_ssids);
3440
3441         os_free(drv->auth_ie);
3442
3443         if (drv->in_interface_list)
3444                 dl_list_del(&drv->list);
3445
3446         os_free(drv);
3447 }
3448
3449
3450 /**
3451  * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
3452  * @eloop_ctx: Driver private data
3453  * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
3454  *
3455  * This function can be used as registered timeout when starting a scan to
3456  * generate a scan completed event if the driver does not report this.
3457  */
3458 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
3459 {
3460         struct wpa_driver_nl80211_data *drv = eloop_ctx;
3461         if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED) {
3462                 wpa_driver_nl80211_set_mode(&drv->first_bss,
3463                                             drv->ap_scan_as_station);
3464                 drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
3465         }
3466         wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
3467         wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
3468 }
3469
3470
3471 /**
3472  * wpa_driver_nl80211_scan - Request the driver to initiate scan
3473  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3474  * @params: Scan parameters
3475  * Returns: 0 on success, -1 on failure
3476  */
3477 static int wpa_driver_nl80211_scan(void *priv,
3478                                    struct wpa_driver_scan_params *params)
3479 {
3480         struct i802_bss *bss = priv;
3481         struct wpa_driver_nl80211_data *drv = bss->drv;
3482         int ret = 0, timeout;
3483         struct nl_msg *msg, *ssids, *freqs, *rates;
3484         size_t i;
3485
3486         drv->scan_for_auth = 0;
3487
3488         msg = nlmsg_alloc();
3489         ssids = nlmsg_alloc();
3490         freqs = nlmsg_alloc();
3491         rates = nlmsg_alloc();
3492         if (!msg || !ssids || !freqs || !rates) {
3493                 nlmsg_free(msg);
3494                 nlmsg_free(ssids);
3495                 nlmsg_free(freqs);
3496                 nlmsg_free(rates);
3497                 return -1;
3498         }
3499
3500         os_free(drv->filter_ssids);
3501         drv->filter_ssids = params->filter_ssids;
3502         params->filter_ssids = NULL;
3503         drv->num_filter_ssids = params->num_filter_ssids;
3504
3505         nl80211_cmd(drv, msg, 0, NL80211_CMD_TRIGGER_SCAN);
3506
3507         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3508
3509         for (i = 0; i < params->num_ssids; i++) {
3510                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan SSID",
3511                                   params->ssids[i].ssid,
3512                                   params->ssids[i].ssid_len);
3513                 NLA_PUT(ssids, i + 1, params->ssids[i].ssid_len,
3514                         params->ssids[i].ssid);
3515         }
3516         if (params->num_ssids)
3517                 nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
3518
3519         if (params->extra_ies) {
3520                 wpa_hexdump(MSG_MSGDUMP, "nl80211: Scan extra IEs",
3521                             params->extra_ies, params->extra_ies_len);
3522                 NLA_PUT(msg, NL80211_ATTR_IE, params->extra_ies_len,
3523                         params->extra_ies);
3524         }
3525
3526         if (params->freqs) {
3527                 for (i = 0; params->freqs[i]; i++) {
3528                         wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
3529                                    "MHz", params->freqs[i]);
3530                         NLA_PUT_U32(freqs, i + 1, params->freqs[i]);
3531                 }
3532                 nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs);
3533         }
3534
3535         if (params->p2p_probe) {
3536                 wpa_printf(MSG_DEBUG, "nl80211: P2P probe - mask SuppRates");
3537
3538                 /*
3539                  * Remove 2.4 GHz rates 1, 2, 5.5, 11 Mbps from supported rates
3540                  * by masking out everything else apart from the OFDM rates 6,
3541                  * 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS rates. All 5 GHz
3542                  * rates are left enabled.
3543                  */
3544                 NLA_PUT(rates, NL80211_BAND_2GHZ, 8,
3545                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
3546                 nla_put_nested(msg, NL80211_ATTR_SCAN_SUPP_RATES, rates);
3547
3548                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
3549         }
3550
3551         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3552         msg = NULL;
3553         if (ret) {
3554                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
3555                            "(%s)", ret, strerror(-ret));
3556 #ifdef HOSTAPD
3557                 if (is_ap_interface(drv->nlmode)) {
3558                         /*
3559                          * mac80211 does not allow scan requests in AP mode, so
3560                          * try to do this in station mode.
3561                          */
3562                         if (wpa_driver_nl80211_set_mode(
3563                                     bss, NL80211_IFTYPE_STATION))
3564                                 goto nla_put_failure;
3565
3566                         if (wpa_driver_nl80211_scan(drv, params)) {
3567                                 wpa_driver_nl80211_set_mode(bss, drv->nlmode);
3568                                 goto nla_put_failure;
3569                         }
3570
3571                         /* Restore AP mode when processing scan results */
3572                         drv->ap_scan_as_station = drv->nlmode;
3573                         ret = 0;
3574                 } else
3575                         goto nla_put_failure;
3576 #else /* HOSTAPD */
3577                 goto nla_put_failure;
3578 #endif /* HOSTAPD */
3579         }
3580
3581         /* Not all drivers generate "scan completed" wireless event, so try to
3582          * read results after a timeout. */
3583         timeout = 10;
3584         if (drv->scan_complete_events) {
3585                 /*
3586                  * The driver seems to deliver events to notify when scan is
3587                  * complete, so use longer timeout to avoid race conditions
3588                  * with scanning and following association request.
3589                  */
3590                 timeout = 30;
3591         }
3592         wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
3593                    "seconds", ret, timeout);
3594         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3595         eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
3596                                drv, drv->ctx);
3597
3598 nla_put_failure:
3599         nlmsg_free(ssids);
3600         nlmsg_free(msg);
3601         nlmsg_free(freqs);
3602         nlmsg_free(rates);
3603         return ret;
3604 }
3605
3606
3607 /**
3608  * wpa_driver_nl80211_sched_scan - Initiate a scheduled scan
3609  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3610  * @params: Scan parameters
3611  * @interval: Interval between scan cycles in milliseconds
3612  * Returns: 0 on success, -1 on failure or if not supported
3613  */
3614 static int wpa_driver_nl80211_sched_scan(void *priv,
3615                                          struct wpa_driver_scan_params *params,
3616                                          u32 interval)
3617 {
3618         struct i802_bss *bss = priv;
3619         struct wpa_driver_nl80211_data *drv = bss->drv;
3620         int ret = -1;
3621         struct nl_msg *msg, *ssids = NULL, *freqs = NULL;
3622         struct nl_msg *match_set_ssid = NULL, *match_sets = NULL;
3623         struct nl_msg *match_set_rssi = NULL;
3624         size_t i;
3625
3626 #ifdef ANDROID
3627         if (!drv->capa.sched_scan_supported)
3628                 return android_pno_start(bss, params);
3629 #endif /* ANDROID */
3630
3631         msg = nlmsg_alloc();
3632         if (!msg)
3633                 goto nla_put_failure;
3634
3635         os_free(drv->filter_ssids);
3636         drv->filter_ssids = params->filter_ssids;
3637         params->filter_ssids = NULL;
3638         drv->num_filter_ssids = params->num_filter_ssids;
3639
3640         nl80211_cmd(drv, msg, 0, NL80211_CMD_START_SCHED_SCAN);
3641
3642         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3643
3644         NLA_PUT_U32(msg, NL80211_ATTR_SCHED_SCAN_INTERVAL, interval);
3645
3646         if ((drv->num_filter_ssids &&
3647             (int) drv->num_filter_ssids <= drv->capa.max_match_sets) ||
3648             params->filter_rssi) {
3649                 match_sets = nlmsg_alloc();
3650                 if (match_sets == NULL)
3651                         goto nla_put_failure;
3652
3653                 for (i = 0; i < drv->num_filter_ssids; i++) {
3654                         wpa_hexdump_ascii(MSG_MSGDUMP,
3655                                           "nl80211: Sched scan filter SSID",
3656                                           drv->filter_ssids[i].ssid,
3657                                           drv->filter_ssids[i].ssid_len);
3658
3659                         match_set_ssid = nlmsg_alloc();
3660                         if (match_set_ssid == NULL)
3661                                 goto nla_put_failure;
3662                         NLA_PUT(match_set_ssid,
3663                                 NL80211_ATTR_SCHED_SCAN_MATCH_SSID,
3664                                 drv->filter_ssids[i].ssid_len,
3665                                 drv->filter_ssids[i].ssid);
3666
3667                         if (nla_put_nested(match_sets, i + 1, match_set_ssid) <
3668                             0)
3669                                 goto nla_put_failure;
3670                 }
3671
3672                 if (params->filter_rssi) {
3673                         match_set_rssi = nlmsg_alloc();
3674                         if (match_set_rssi == NULL)
3675                                 goto nla_put_failure;
3676                         NLA_PUT_U32(match_set_rssi,
3677                                     NL80211_SCHED_SCAN_MATCH_ATTR_RSSI,
3678                                     params->filter_rssi);
3679                         wpa_printf(MSG_MSGDUMP,
3680                                    "nl80211: Sched scan RSSI filter %d dBm",
3681                                    params->filter_rssi);
3682                         if (nla_put_nested(match_sets, 0, match_set_rssi) < 0)
3683                                 goto nla_put_failure;
3684                 }
3685
3686                 if (nla_put_nested(msg, NL80211_ATTR_SCHED_SCAN_MATCH,
3687                                    match_sets) < 0)
3688                         goto nla_put_failure;
3689         }
3690
3691         if (params->num_ssids) {
3692                 ssids = nlmsg_alloc();
3693                 if (ssids == NULL)
3694                         goto nla_put_failure;
3695                 for (i = 0; i < params->num_ssids; i++) {
3696                         wpa_hexdump_ascii(MSG_MSGDUMP,
3697                                           "nl80211: Sched scan SSID",
3698                                           params->ssids[i].ssid,
3699                                           params->ssids[i].ssid_len);
3700                         NLA_PUT(ssids, i + 1, params->ssids[i].ssid_len,
3701                                 params->ssids[i].ssid);
3702                 }
3703                 if (nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids) < 0)
3704                         goto nla_put_failure;
3705         }
3706
3707         if (params->extra_ies) {
3708                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Sched scan extra IEs",
3709                                   params->extra_ies, params->extra_ies_len);
3710                 NLA_PUT(msg, NL80211_ATTR_IE, params->extra_ies_len,
3711                         params->extra_ies);
3712         }
3713
3714         if (params->freqs) {
3715                 freqs = nlmsg_alloc();
3716                 if (freqs == NULL)
3717                         goto nla_put_failure;
3718                 for (i = 0; params->freqs[i]; i++) {
3719                         wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
3720                                    "MHz", params->freqs[i]);
3721                         NLA_PUT_U32(freqs, i + 1, params->freqs[i]);
3722                 }
3723                 if (nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs) <
3724                     0)
3725                         goto nla_put_failure;
3726         }
3727
3728         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3729
3730         /* TODO: if we get an error here, we should fall back to normal scan */
3731
3732         msg = NULL;
3733         if (ret) {
3734                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan start failed: "
3735                            "ret=%d (%s)", ret, strerror(-ret));
3736                 goto nla_put_failure;
3737         }
3738
3739         wpa_printf(MSG_DEBUG, "nl80211: Sched scan requested (ret=%d) - "
3740                    "scan interval %d msec", ret, interval);
3741
3742 nla_put_failure:
3743         nlmsg_free(match_set_ssid);
3744         nlmsg_free(match_sets);
3745         nlmsg_free(match_set_rssi);
3746         nlmsg_free(ssids);
3747         nlmsg_free(msg);
3748         nlmsg_free(freqs);
3749         return ret;
3750 }
3751
3752
3753 /**
3754  * wpa_driver_nl80211_stop_sched_scan - Stop a scheduled scan
3755  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3756  * Returns: 0 on success, -1 on failure or if not supported
3757  */
3758 static int wpa_driver_nl80211_stop_sched_scan(void *priv)
3759 {
3760         struct i802_bss *bss = priv;
3761         struct wpa_driver_nl80211_data *drv = bss->drv;
3762         int ret = 0;
3763         struct nl_msg *msg;
3764
3765 #ifdef ANDROID
3766         if (!drv->capa.sched_scan_supported)
3767                 return android_pno_stop(bss);
3768 #endif /* ANDROID */
3769
3770         msg = nlmsg_alloc();
3771         if (!msg)
3772                 return -1;
3773
3774         nl80211_cmd(drv, msg, 0, NL80211_CMD_STOP_SCHED_SCAN);
3775
3776         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3777
3778         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3779         msg = NULL;
3780         if (ret) {
3781                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop failed: "
3782                            "ret=%d (%s)", ret, strerror(-ret));
3783                 goto nla_put_failure;
3784         }
3785
3786         wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop sent (ret=%d)", ret);
3787
3788 nla_put_failure:
3789         nlmsg_free(msg);
3790         return ret;
3791 }
3792
3793
3794 static const u8 * nl80211_get_ie(const u8 *ies, size_t ies_len, u8 ie)
3795 {
3796         const u8 *end, *pos;
3797
3798         if (ies == NULL)
3799                 return NULL;
3800
3801         pos = ies;
3802         end = ies + ies_len;
3803
3804         while (pos + 1 < end) {
3805                 if (pos + 2 + pos[1] > end)
3806                         break;
3807                 if (pos[0] == ie)
3808                         return pos;
3809                 pos += 2 + pos[1];
3810         }
3811
3812         return NULL;
3813 }
3814
3815
3816 static int nl80211_scan_filtered(struct wpa_driver_nl80211_data *drv,
3817                                  const u8 *ie, size_t ie_len)
3818 {
3819         const u8 *ssid;
3820         size_t i;
3821
3822         if (drv->filter_ssids == NULL)
3823                 return 0;
3824
3825         ssid = nl80211_get_ie(ie, ie_len, WLAN_EID_SSID);
3826         if (ssid == NULL)
3827                 return 1;
3828
3829         for (i = 0; i < drv->num_filter_ssids; i++) {
3830                 if (ssid[1] == drv->filter_ssids[i].ssid_len &&
3831                     os_memcmp(ssid + 2, drv->filter_ssids[i].ssid, ssid[1]) ==
3832                     0)
3833                         return 0;
3834         }
3835
3836         return 1;
3837 }
3838
3839
3840 static int bss_info_handler(struct nl_msg *msg, void *arg)
3841 {
3842         struct nlattr *tb[NL80211_ATTR_MAX + 1];
3843         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3844         struct nlattr *bss[NL80211_BSS_MAX + 1];
3845         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
3846                 [NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
3847                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
3848                 [NL80211_BSS_TSF] = { .type = NLA_U64 },
3849                 [NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
3850                 [NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
3851                 [NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
3852                 [NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
3853                 [NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
3854                 [NL80211_BSS_STATUS] = { .type = NLA_U32 },
3855                 [NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
3856                 [NL80211_BSS_BEACON_IES] = { .type = NLA_UNSPEC },
3857         };
3858         struct nl80211_bss_info_arg *_arg = arg;
3859         struct wpa_scan_results *res = _arg->res;
3860         struct wpa_scan_res **tmp;
3861         struct wpa_scan_res *r;
3862         const u8 *ie, *beacon_ie;
3863         size_t ie_len, beacon_ie_len;
3864         u8 *pos;
3865         size_t i;
3866
3867         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3868                   genlmsg_attrlen(gnlh, 0), NULL);
3869         if (!tb[NL80211_ATTR_BSS])
3870                 return NL_SKIP;
3871         if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
3872                              bss_policy))
3873                 return NL_SKIP;
3874         if (bss[NL80211_BSS_STATUS]) {
3875                 enum nl80211_bss_status status;
3876                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
3877                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
3878                     bss[NL80211_BSS_FREQUENCY]) {
3879                         _arg->assoc_freq =
3880                                 nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
3881                         wpa_printf(MSG_DEBUG, "nl80211: Associated on %u MHz",
3882                                    _arg->assoc_freq);
3883                 }
3884                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
3885                     bss[NL80211_BSS_BSSID]) {
3886                         os_memcpy(_arg->assoc_bssid,
3887                                   nla_data(bss[NL80211_BSS_BSSID]), ETH_ALEN);
3888                         wpa_printf(MSG_DEBUG, "nl80211: Associated with "
3889                                    MACSTR, MAC2STR(_arg->assoc_bssid));
3890                 }
3891         }
3892         if (!res)
3893                 return NL_SKIP;
3894         if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
3895                 ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
3896                 ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
3897         } else {
3898                 ie = NULL;
3899                 ie_len = 0;
3900         }
3901         if (bss[NL80211_BSS_BEACON_IES]) {
3902                 beacon_ie = nla_data(bss[NL80211_BSS_BEACON_IES]);
3903                 beacon_ie_len = nla_len(bss[NL80211_BSS_BEACON_IES]);
3904         } else {
3905                 beacon_ie = NULL;
3906                 beacon_ie_len = 0;
3907         }
3908
3909         if (nl80211_scan_filtered(_arg->drv, ie ? ie : beacon_ie,
3910                                   ie ? ie_len : beacon_ie_len))
3911                 return NL_SKIP;
3912
3913         r = os_zalloc(sizeof(*r) + ie_len + beacon_ie_len);
3914         if (r == NULL)
3915                 return NL_SKIP;
3916         if (bss[NL80211_BSS_BSSID])
3917                 os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
3918                           ETH_ALEN);
3919         if (bss[NL80211_BSS_FREQUENCY])
3920                 r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
3921         if (bss[NL80211_BSS_BEACON_INTERVAL])
3922                 r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
3923         if (bss[NL80211_BSS_CAPABILITY])
3924                 r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
3925         r->flags |= WPA_SCAN_NOISE_INVALID;
3926         if (bss[NL80211_BSS_SIGNAL_MBM]) {
3927                 r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
3928                 r->level /= 100; /* mBm to dBm */
3929                 r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
3930         } else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
3931                 r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
3932                 r->flags |= WPA_SCAN_QUAL_INVALID;
3933         } else
3934                 r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
3935         if (bss[NL80211_BSS_TSF])
3936                 r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
3937         if (bss[NL80211_BSS_SEEN_MS_AGO])
3938                 r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
3939         r->ie_len = ie_len;
3940         pos = (u8 *) (r + 1);
3941         if (ie) {
3942                 os_memcpy(pos, ie, ie_len);
3943                 pos += ie_len;
3944         }
3945         r->beacon_ie_len = beacon_ie_len;
3946         if (beacon_ie)
3947                 os_memcpy(pos, beacon_ie, beacon_ie_len);
3948
3949         if (bss[NL80211_BSS_STATUS]) {
3950                 enum nl80211_bss_status status;
3951                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
3952                 switch (status) {
3953                 case NL80211_BSS_STATUS_AUTHENTICATED:
3954                         r->flags |= WPA_SCAN_AUTHENTICATED;
3955                         break;
3956                 case NL80211_BSS_STATUS_ASSOCIATED:
3957                         r->flags |= WPA_SCAN_ASSOCIATED;
3958                         break;
3959                 default:
3960                         break;
3961                 }
3962         }
3963
3964         /*
3965          * cfg80211 maintains separate BSS table entries for APs if the same
3966          * BSSID,SSID pair is seen on multiple channels. wpa_supplicant does
3967          * not use frequency as a separate key in the BSS table, so filter out
3968          * duplicated entries. Prefer associated BSS entry in such a case in
3969          * order to get the correct frequency into the BSS table.
3970          */
3971         for (i = 0; i < res->num; i++) {
3972                 const u8 *s1, *s2;
3973                 if (os_memcmp(res->res[i]->bssid, r->bssid, ETH_ALEN) != 0)
3974                         continue;
3975
3976                 s1 = nl80211_get_ie((u8 *) (res->res[i] + 1),
3977                                     res->res[i]->ie_len, WLAN_EID_SSID);
3978                 s2 = nl80211_get_ie((u8 *) (r + 1), r->ie_len, WLAN_EID_SSID);
3979                 if (s1 == NULL || s2 == NULL || s1[1] != s2[1] ||
3980                     os_memcmp(s1, s2, 2 + s1[1]) != 0)
3981                         continue;
3982
3983                 /* Same BSSID,SSID was already included in scan results */
3984                 wpa_printf(MSG_DEBUG, "nl80211: Remove duplicated scan result "
3985                            "for " MACSTR, MAC2STR(r->bssid));
3986
3987                 if ((r->flags & WPA_SCAN_ASSOCIATED) &&
3988                     !(res->res[i]->flags & WPA_SCAN_ASSOCIATED)) {
3989                         os_free(res->res[i]);
3990                         res->res[i] = r;
3991                 } else
3992                         os_free(r);
3993                 return NL_SKIP;
3994         }
3995
3996         tmp = os_realloc(res->res,
3997                          (res->num + 1) * sizeof(struct wpa_scan_res *));
3998         if (tmp == NULL) {
3999                 os_free(r);
4000                 return NL_SKIP;
4001         }
4002         tmp[res->num++] = r;
4003         res->res = tmp;
4004
4005         return NL_SKIP;
4006 }
4007
4008
4009 static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
4010                                  const u8 *addr)
4011 {
4012         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
4013                 wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
4014                            "mismatch (" MACSTR ")", MAC2STR(addr));
4015                 wpa_driver_nl80211_mlme(drv, addr,
4016                                         NL80211_CMD_DEAUTHENTICATE,
4017                                         WLAN_REASON_PREV_AUTH_NOT_VALID, 1);
4018         }
4019 }
4020
4021
4022 static void wpa_driver_nl80211_check_bss_status(
4023         struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
4024 {
4025         size_t i;
4026
4027         for (i = 0; i < res->num; i++) {
4028                 struct wpa_scan_res *r = res->res[i];
4029                 if (r->flags & WPA_SCAN_AUTHENTICATED) {
4030                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
4031                                    "indicates BSS status with " MACSTR
4032                                    " as authenticated",
4033                                    MAC2STR(r->bssid));
4034                         if (is_sta_interface(drv->nlmode) &&
4035                             os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
4036                             os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
4037                             0) {
4038                                 wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
4039                                            " in local state (auth=" MACSTR
4040                                            " assoc=" MACSTR ")",
4041                                            MAC2STR(drv->auth_bssid),
4042                                            MAC2STR(drv->bssid));
4043                                 clear_state_mismatch(drv, r->bssid);
4044                         }
4045                 }
4046
4047                 if (r->flags & WPA_SCAN_ASSOCIATED) {
4048                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
4049                                    "indicate BSS status with " MACSTR
4050                                    " as associated",
4051                                    MAC2STR(r->bssid));
4052                         if (is_sta_interface(drv->nlmode) &&
4053                             !drv->associated) {
4054                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
4055                                            "(not associated) does not match "
4056                                            "with BSS state");
4057                                 clear_state_mismatch(drv, r->bssid);
4058                         } else if (is_sta_interface(drv->nlmode) &&
4059                                    os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
4060                                    0) {
4061                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
4062                                            "(associated with " MACSTR ") does "
4063                                            "not match with BSS state",
4064                                            MAC2STR(drv->bssid));
4065                                 clear_state_mismatch(drv, r->bssid);
4066                                 clear_state_mismatch(drv, drv->bssid);
4067                         }
4068                 }
4069         }
4070 }
4071
4072
4073 static struct wpa_scan_results *
4074 nl80211_get_scan_results(struct wpa_driver_nl80211_data *drv)
4075 {
4076         struct nl_msg *msg;
4077         struct wpa_scan_results *res;
4078         int ret;
4079         struct nl80211_bss_info_arg arg;
4080
4081         res = os_zalloc(sizeof(*res));
4082         if (res == NULL)
4083                 return NULL;
4084         msg = nlmsg_alloc();
4085         if (!msg)
4086                 goto nla_put_failure;
4087
4088         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
4089         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4090
4091         arg.drv = drv;
4092         arg.res = res;
4093         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
4094         msg = NULL;
4095         if (ret == 0) {
4096                 wpa_printf(MSG_DEBUG, "nl80211: Received scan results (%lu "
4097                            "BSSes)", (unsigned long) res->num);
4098                 nl80211_get_noise_for_scan_results(drv, res);
4099                 return res;
4100         }
4101         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
4102                    "(%s)", ret, strerror(-ret));
4103 nla_put_failure:
4104         nlmsg_free(msg);
4105         wpa_scan_results_free(res);
4106         return NULL;
4107 }
4108
4109
4110 /**
4111  * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
4112  * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
4113  * Returns: Scan results on success, -1 on failure
4114  */
4115 static struct wpa_scan_results *
4116 wpa_driver_nl80211_get_scan_results(void *priv)
4117 {
4118         struct i802_bss *bss = priv;
4119         struct wpa_driver_nl80211_data *drv = bss->drv;
4120         struct wpa_scan_results *res;
4121
4122         res = nl80211_get_scan_results(drv);
4123         if (res)
4124                 wpa_driver_nl80211_check_bss_status(drv, res);
4125         return res;
4126 }
4127
4128
4129 static void nl80211_dump_scan(struct wpa_driver_nl80211_data *drv)
4130 {
4131         struct wpa_scan_results *res;
4132         size_t i;
4133
4134         res = nl80211_get_scan_results(drv);
4135         if (res == NULL) {
4136                 wpa_printf(MSG_DEBUG, "nl80211: Failed to get scan results");
4137                 return;
4138         }
4139
4140         wpa_printf(MSG_DEBUG, "nl80211: Scan result dump");
4141         for (i = 0; i < res->num; i++) {
4142                 struct wpa_scan_res *r = res->res[i];
4143                 wpa_printf(MSG_DEBUG, "nl80211: %d/%d " MACSTR "%s%s",
4144                            (int) i, (int) res->num, MAC2STR(r->bssid),
4145                            r->flags & WPA_SCAN_AUTHENTICATED ? " [auth]" : "",
4146                            r->flags & WPA_SCAN_ASSOCIATED ? " [assoc]" : "");
4147         }
4148
4149         wpa_scan_results_free(res);
4150 }
4151
4152
4153 static int wpa_driver_nl80211_set_key(const char *ifname, void *priv,
4154                                       enum wpa_alg alg, const u8 *addr,
4155                                       int key_idx, int set_tx,
4156                                       const u8 *seq, size_t seq_len,
4157                                       const u8 *key, size_t key_len)
4158 {
4159         struct i802_bss *bss = priv;
4160         struct wpa_driver_nl80211_data *drv = bss->drv;
4161         int ifindex = if_nametoindex(ifname);
4162         struct nl_msg *msg;
4163         int ret;
4164
4165         wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
4166                    "set_tx=%d seq_len=%lu key_len=%lu",
4167                    __func__, ifindex, alg, addr, key_idx, set_tx,
4168                    (unsigned long) seq_len, (unsigned long) key_len);
4169 #ifdef CONFIG_TDLS
4170         if (key_idx == -1)
4171                 key_idx = 0;
4172 #endif /* CONFIG_TDLS */
4173
4174         msg = nlmsg_alloc();
4175         if (!msg)
4176                 return -ENOMEM;
4177
4178         if (alg == WPA_ALG_NONE) {
4179                 nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_KEY);
4180         } else {
4181                 nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_KEY);
4182                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
4183                 switch (alg) {
4184                 case WPA_ALG_WEP:
4185                         if (key_len == 5)
4186                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4187                                             WLAN_CIPHER_SUITE_WEP40);
4188                         else
4189                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4190                                             WLAN_CIPHER_SUITE_WEP104);
4191                         break;
4192                 case WPA_ALG_TKIP:
4193                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4194                                     WLAN_CIPHER_SUITE_TKIP);
4195                         break;
4196                 case WPA_ALG_CCMP:
4197                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4198                                     WLAN_CIPHER_SUITE_CCMP);
4199                         break;
4200                 case WPA_ALG_IGTK:
4201                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4202                                     WLAN_CIPHER_SUITE_AES_CMAC);
4203                         break;
4204                 default:
4205                         wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4206                                    "algorithm %d", __func__, alg);
4207                         nlmsg_free(msg);
4208                         return -1;
4209                 }
4210         }
4211
4212         if (seq && seq_len)
4213                 NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
4214
4215         if (addr && !is_broadcast_ether_addr(addr)) {
4216                 wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
4217                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4218
4219                 if (alg != WPA_ALG_WEP && key_idx && !set_tx) {
4220                         wpa_printf(MSG_DEBUG, "   RSN IBSS RX GTK");
4221                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_TYPE,
4222                                     NL80211_KEYTYPE_GROUP);
4223                 }
4224         } else if (addr && is_broadcast_ether_addr(addr)) {
4225                 struct nl_msg *types;
4226                 int err;
4227                 wpa_printf(MSG_DEBUG, "   broadcast key");
4228                 types = nlmsg_alloc();
4229                 if (!types)
4230                         goto nla_put_failure;
4231                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4232                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4233                                      types);
4234                 nlmsg_free(types);
4235                 if (err)
4236                         goto nla_put_failure;
4237         }
4238         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4239         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4240
4241         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4242         if ((ret == -ENOENT || ret == -ENOLINK) && alg == WPA_ALG_NONE)
4243                 ret = 0;
4244         if (ret)
4245                 wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
4246                            ret, strerror(-ret));
4247
4248         /*
4249          * If we failed or don't need to set the default TX key (below),
4250          * we're done here.
4251          */
4252         if (ret || !set_tx || alg == WPA_ALG_NONE)
4253                 return ret;
4254         if (is_ap_interface(drv->nlmode) && addr &&
4255             !is_broadcast_ether_addr(addr))
4256                 return ret;
4257
4258         msg = nlmsg_alloc();
4259         if (!msg)
4260                 return -ENOMEM;
4261
4262         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_KEY);
4263         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4264         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4265         if (alg == WPA_ALG_IGTK)
4266                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
4267         else
4268                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
4269         if (addr && is_broadcast_ether_addr(addr)) {
4270                 struct nl_msg *types;
4271                 int err;
4272                 types = nlmsg_alloc();
4273                 if (!types)
4274                         goto nla_put_failure;
4275                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4276                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4277                                      types);
4278                 nlmsg_free(types);
4279                 if (err)
4280                         goto nla_put_failure;
4281         } else if (addr) {
4282                 struct nl_msg *types;
4283                 int err;
4284                 types = nlmsg_alloc();
4285                 if (!types)
4286                         goto nla_put_failure;
4287                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_UNICAST);
4288                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
4289                                      types);
4290                 nlmsg_free(types);
4291                 if (err)
4292                         goto nla_put_failure;
4293         }
4294
4295         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4296         if (ret == -ENOENT)
4297                 ret = 0;
4298         if (ret)
4299                 wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
4300                            "err=%d %s)", ret, strerror(-ret));
4301         return ret;
4302
4303 nla_put_failure:
4304         nlmsg_free(msg);
4305         return -ENOBUFS;
4306 }
4307
4308
4309 static int nl_add_key(struct nl_msg *msg, enum wpa_alg alg,
4310                       int key_idx, int defkey,
4311                       const u8 *seq, size_t seq_len,
4312                       const u8 *key, size_t key_len)
4313 {
4314         struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
4315         if (!key_attr)
4316                 return -1;
4317
4318         if (defkey && alg == WPA_ALG_IGTK)
4319                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
4320         else if (defkey)
4321                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4322
4323         NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
4324
4325         switch (alg) {
4326         case WPA_ALG_WEP:
4327                 if (key_len == 5)
4328                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4329                                     WLAN_CIPHER_SUITE_WEP40);
4330                 else
4331                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4332                                     WLAN_CIPHER_SUITE_WEP104);
4333                 break;
4334         case WPA_ALG_TKIP:
4335                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_TKIP);
4336                 break;
4337         case WPA_ALG_CCMP:
4338                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_CCMP);
4339                 break;
4340         case WPA_ALG_IGTK:
4341                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4342                             WLAN_CIPHER_SUITE_AES_CMAC);
4343                 break;
4344         default:
4345                 wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4346                            "algorithm %d", __func__, alg);
4347                 return -1;
4348         }
4349
4350         if (seq && seq_len)
4351                 NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
4352
4353         NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
4354
4355         nla_nest_end(msg, key_attr);
4356
4357         return 0;
4358  nla_put_failure:
4359         return -1;
4360 }
4361
4362
4363 static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
4364                                  struct nl_msg *msg)
4365 {
4366         int i, privacy = 0;
4367         struct nlattr *nl_keys, *nl_key;
4368
4369         for (i = 0; i < 4; i++) {
4370                 if (!params->wep_key[i])
4371                         continue;
4372                 privacy = 1;
4373                 break;
4374         }
4375         if (params->wps == WPS_MODE_PRIVACY)
4376                 privacy = 1;
4377         if (params->pairwise_suite &&
4378             params->pairwise_suite != WPA_CIPHER_NONE)
4379                 privacy = 1;
4380
4381         if (!privacy)
4382                 return 0;
4383
4384         NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
4385
4386         nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
4387         if (!nl_keys)
4388                 goto nla_put_failure;
4389
4390         for (i = 0; i < 4; i++) {
4391                 if (!params->wep_key[i])
4392                         continue;
4393
4394                 nl_key = nla_nest_start(msg, i);
4395                 if (!nl_key)
4396                         goto nla_put_failure;
4397
4398                 NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
4399                         params->wep_key[i]);
4400                 if (params->wep_key_len[i] == 5)
4401                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4402                                     WLAN_CIPHER_SUITE_WEP40);
4403                 else
4404                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4405                                     WLAN_CIPHER_SUITE_WEP104);
4406
4407                 NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
4408
4409                 if (i == params->wep_tx_keyidx)
4410                         NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4411
4412                 nla_nest_end(msg, nl_key);
4413         }
4414         nla_nest_end(msg, nl_keys);
4415
4416         return 0;
4417
4418 nla_put_failure:
4419         return -ENOBUFS;
4420 }
4421
4422
4423 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
4424                                    const u8 *addr, int cmd, u16 reason_code,
4425                                    int local_state_change)
4426 {
4427         int ret = -1;
4428         struct nl_msg *msg;
4429
4430         msg = nlmsg_alloc();
4431         if (!msg)
4432                 return -1;
4433
4434         nl80211_cmd(drv, msg, 0, cmd);
4435
4436         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4437         NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
4438         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4439         if (local_state_change)
4440                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4441
4442         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4443         msg = NULL;
4444         if (ret) {
4445                 wpa_dbg(drv->ctx, MSG_DEBUG,
4446                         "nl80211: MLME command failed: reason=%u ret=%d (%s)",
4447                         reason_code, ret, strerror(-ret));
4448                 goto nla_put_failure;
4449         }
4450         ret = 0;
4451
4452 nla_put_failure:
4453         nlmsg_free(msg);
4454         return ret;
4455 }
4456
4457
4458 static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
4459                                          const u8 *addr, int reason_code)
4460 {
4461         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
4462                    __func__, MAC2STR(addr), reason_code);
4463         drv->associated = 0;
4464         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISCONNECT,
4465                                        reason_code, 0);
4466 }
4467
4468
4469 static int wpa_driver_nl80211_deauthenticate(void *priv, const u8 *addr,
4470                                              int reason_code)
4471 {
4472         struct i802_bss *bss = priv;
4473         struct wpa_driver_nl80211_data *drv = bss->drv;
4474         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
4475                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
4476         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
4477                    __func__, MAC2STR(addr), reason_code);
4478         drv->associated = 0;
4479         if (drv->nlmode == NL80211_IFTYPE_ADHOC)
4480                 return nl80211_leave_ibss(drv);
4481         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
4482                                        reason_code, 0);
4483 }
4484
4485
4486 static int wpa_driver_nl80211_disassociate(void *priv, const u8 *addr,
4487                                            int reason_code)
4488 {
4489         struct i802_bss *bss = priv;
4490         struct wpa_driver_nl80211_data *drv = bss->drv;
4491         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
4492                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
4493         wpa_printf(MSG_DEBUG, "%s", __func__);
4494         drv->associated = 0;
4495         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISASSOCIATE,
4496                                        reason_code, 0);
4497 }
4498
4499
4500 static void nl80211_copy_auth_params(struct wpa_driver_nl80211_data *drv,
4501                                      struct wpa_driver_auth_params *params)
4502 {
4503         int i;
4504
4505         drv->auth_freq = params->freq;
4506         drv->auth_alg = params->auth_alg;
4507         drv->auth_wep_tx_keyidx = params->wep_tx_keyidx;
4508         drv->auth_local_state_change = params->local_state_change;
4509         drv->auth_p2p = params->p2p;
4510
4511         if (params->bssid)
4512                 os_memcpy(drv->auth_bssid_, params->bssid, ETH_ALEN);
4513         else
4514                 os_memset(drv->auth_bssid_, 0, ETH_ALEN);
4515
4516         if (params->ssid) {
4517                 os_memcpy(drv->auth_ssid, params->ssid, params->ssid_len);
4518                 drv->auth_ssid_len = params->ssid_len;
4519         } else
4520                 drv->auth_ssid_len = 0;
4521
4522
4523         os_free(drv->auth_ie);
4524         drv->auth_ie = NULL;
4525         drv->auth_ie_len = 0;
4526         if (params->ie) {
4527                 drv->auth_ie = os_malloc(params->ie_len);
4528                 if (drv->auth_ie) {
4529                         os_memcpy(drv->auth_ie, params->ie, params->ie_len);
4530                         drv->auth_ie_len = params->ie_len;
4531                 }
4532         }
4533
4534         for (i = 0; i < 4; i++) {
4535                 if (params->wep_key[i] && params->wep_key_len[i] &&
4536                     params->wep_key_len[i] <= 16) {
4537                         os_memcpy(drv->auth_wep_key[i], params->wep_key[i],
4538                                   params->wep_key_len[i]);
4539                         drv->auth_wep_key_len[i] = params->wep_key_len[i];
4540                 } else
4541                         drv->auth_wep_key_len[i] = 0;
4542         }
4543 }
4544
4545
4546 static int wpa_driver_nl80211_authenticate(
4547         void *priv, struct wpa_driver_auth_params *params)
4548 {
4549         struct i802_bss *bss = priv;
4550         struct wpa_driver_nl80211_data *drv = bss->drv;
4551         int ret = -1, i;
4552         struct nl_msg *msg;
4553         enum nl80211_auth_type type;
4554         enum nl80211_iftype nlmode;
4555         int count = 0;
4556         int is_retry;
4557
4558         is_retry = drv->retry_auth;
4559         drv->retry_auth = 0;
4560
4561         drv->associated = 0;
4562         os_memset(drv->auth_bssid, 0, ETH_ALEN);
4563         /* FIX: IBSS mode */
4564         nlmode = params->p2p ?
4565                 NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
4566         if (drv->nlmode != nlmode &&
4567             wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
4568                 return -1;
4569
4570 retry:
4571         msg = nlmsg_alloc();
4572         if (!msg)
4573                 return -1;
4574
4575         wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
4576                    drv->ifindex);
4577
4578         nl80211_cmd(drv, msg, 0, NL80211_CMD_AUTHENTICATE);
4579
4580         for (i = 0; i < 4; i++) {
4581                 if (!params->wep_key[i])
4582                         continue;
4583                 wpa_driver_nl80211_set_key(bss->ifname, priv, WPA_ALG_WEP,
4584                                            NULL, i,
4585                                            i == params->wep_tx_keyidx, NULL, 0,
4586                                            params->wep_key[i],
4587                                            params->wep_key_len[i]);
4588                 if (params->wep_tx_keyidx != i)
4589                         continue;
4590                 if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
4591                                params->wep_key[i], params->wep_key_len[i])) {
4592                         nlmsg_free(msg);
4593                         return -1;
4594                 }
4595         }
4596
4597         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4598         if (params->bssid) {
4599                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4600                            MAC2STR(params->bssid));
4601                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4602         }
4603         if (params->freq) {
4604                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4605                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4606         }
4607         if (params->ssid) {
4608                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4609                                   params->ssid, params->ssid_len);
4610                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4611                         params->ssid);
4612         }
4613         wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
4614         if (params->ie)
4615                 NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
4616         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
4617                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
4618         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
4619                 type = NL80211_AUTHTYPE_SHARED_KEY;
4620         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
4621                 type = NL80211_AUTHTYPE_NETWORK_EAP;
4622         else if (params->auth_alg & WPA_AUTH_ALG_FT)
4623                 type = NL80211_AUTHTYPE_FT;
4624         else
4625                 goto nla_put_failure;
4626         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
4627         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
4628         if (params->local_state_change) {
4629                 wpa_printf(MSG_DEBUG, "  * Local state change only");
4630                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4631         }
4632
4633         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4634         msg = NULL;
4635         if (ret) {
4636                 wpa_dbg(drv->ctx, MSG_DEBUG,
4637                         "nl80211: MLME command failed (auth): ret=%d (%s)",
4638                         ret, strerror(-ret));
4639                 count++;
4640                 if (ret == -EALREADY && count == 1 && params->bssid &&
4641                     !params->local_state_change) {
4642                         /*
4643                          * mac80211 does not currently accept new
4644                          * authentication if we are already authenticated. As a
4645                          * workaround, force deauthentication and try again.
4646                          */
4647                         wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
4648                                    "after forced deauthentication");
4649                         wpa_driver_nl80211_deauthenticate(
4650                                 bss, params->bssid,
4651                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
4652                         nlmsg_free(msg);
4653                         goto retry;
4654                 }
4655
4656                 if (ret == -ENOENT && params->freq && !is_retry) {
4657                         /*
4658                          * cfg80211 has likely expired the BSS entry even
4659                          * though it was previously available in our internal
4660                          * BSS table. To recover quickly, start a single
4661                          * channel scan on the specified channel.
4662                          */
4663                         struct wpa_driver_scan_params scan;
4664                         int freqs[2];
4665
4666                         os_memset(&scan, 0, sizeof(scan));
4667                         scan.num_ssids = 1;
4668                         if (params->ssid) {
4669                                 scan.ssids[0].ssid = params->ssid;
4670                                 scan.ssids[0].ssid_len = params->ssid_len;
4671                         }
4672                         freqs[0] = params->freq;
4673                         freqs[1] = 0;
4674                         scan.freqs = freqs;
4675                         wpa_printf(MSG_DEBUG, "nl80211: Trigger single "
4676                                    "channel scan to refresh cfg80211 BSS "
4677                                    "entry");
4678                         ret = wpa_driver_nl80211_scan(bss, &scan);
4679                         if (ret == 0) {
4680                                 nl80211_copy_auth_params(drv, params);
4681                                 drv->scan_for_auth = 1;
4682                         }
4683                 } else if (is_retry) {
4684                         /*
4685                          * Need to indicate this with an event since the return
4686                          * value from the retry is not delivered to core code.
4687                          */
4688                         union wpa_event_data event;
4689                         wpa_printf(MSG_DEBUG, "nl80211: Authentication retry "
4690                                    "failed");
4691                         os_memset(&event, 0, sizeof(event));
4692                         os_memcpy(event.timeout_event.addr, drv->auth_bssid_,
4693                                   ETH_ALEN);
4694                         wpa_supplicant_event(drv->ctx, EVENT_AUTH_TIMED_OUT,
4695                                              &event);
4696                 }
4697
4698                 goto nla_put_failure;
4699         }
4700         ret = 0;
4701         wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
4702                    "successfully");
4703
4704 nla_put_failure:
4705         nlmsg_free(msg);
4706         return ret;
4707 }
4708
4709
4710 static int wpa_driver_nl80211_authenticate_retry(
4711         struct wpa_driver_nl80211_data *drv)
4712 {
4713         struct wpa_driver_auth_params params;
4714         struct i802_bss *bss = &drv->first_bss;
4715         int i;
4716
4717         wpa_printf(MSG_DEBUG, "nl80211: Try to authenticate again");
4718
4719         os_memset(&params, 0, sizeof(params));
4720         params.freq = drv->auth_freq;
4721         params.auth_alg = drv->auth_alg;
4722         params.wep_tx_keyidx = drv->auth_wep_tx_keyidx;
4723         params.local_state_change = drv->auth_local_state_change;
4724         params.p2p = drv->auth_p2p;
4725
4726         if (!is_zero_ether_addr(drv->auth_bssid_))
4727                 params.bssid = drv->auth_bssid_;
4728
4729         if (drv->auth_ssid_len) {
4730                 params.ssid = drv->auth_ssid;
4731                 params.ssid_len = drv->auth_ssid_len;
4732         }
4733
4734         params.ie = drv->auth_ie;
4735         params.ie_len = drv->auth_ie_len;
4736
4737         for (i = 0; i < 4; i++) {
4738                 if (drv->auth_wep_key_len[i]) {
4739                         params.wep_key[i] = drv->auth_wep_key[i];
4740                         params.wep_key_len[i] = drv->auth_wep_key_len[i];
4741                 }
4742         }
4743
4744         drv->retry_auth = 1;
4745         return wpa_driver_nl80211_authenticate(bss, &params);
4746 }
4747
4748
4749 struct phy_info_arg {
4750         u16 *num_modes;
4751         struct hostapd_hw_modes *modes;
4752 };
4753
4754 static int phy_info_handler(struct nl_msg *msg, void *arg)
4755 {
4756         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
4757         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
4758         struct phy_info_arg *phy_info = arg;
4759
4760         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
4761
4762         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
4763         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
4764                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
4765                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
4766                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
4767                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
4768                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
4769                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
4770         };
4771
4772         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
4773         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
4774                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
4775                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
4776         };
4777
4778         struct nlattr *nl_band;
4779         struct nlattr *nl_freq;
4780         struct nlattr *nl_rate;
4781         int rem_band, rem_freq, rem_rate;
4782         struct hostapd_hw_modes *mode;
4783         int idx, mode_is_set;
4784
4785         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
4786                   genlmsg_attrlen(gnlh, 0), NULL);
4787
4788         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
4789                 return NL_SKIP;
4790
4791         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
4792                 mode = os_realloc(phy_info->modes, (*phy_info->num_modes + 1) * sizeof(*mode));
4793                 if (!mode)
4794                         return NL_SKIP;
4795                 phy_info->modes = mode;
4796
4797                 mode_is_set = 0;
4798
4799                 mode = &phy_info->modes[*(phy_info->num_modes)];
4800                 memset(mode, 0, sizeof(*mode));
4801                 mode->flags = HOSTAPD_MODE_FLAG_HT_INFO_KNOWN;
4802                 *(phy_info->num_modes) += 1;
4803
4804                 nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
4805                           nla_len(nl_band), NULL);
4806
4807                 if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
4808                         mode->ht_capab = nla_get_u16(
4809                                 tb_band[NL80211_BAND_ATTR_HT_CAPA]);
4810                 }
4811
4812                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) {
4813                         mode->a_mpdu_params |= nla_get_u8(
4814                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) &
4815                                 0x03;
4816                 }
4817
4818                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) {
4819                         mode->a_mpdu_params |= nla_get_u8(
4820                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) <<
4821                                 2;
4822                 }
4823
4824                 if (tb_band[NL80211_BAND_ATTR_HT_MCS_SET] &&
4825                     nla_len(tb_band[NL80211_BAND_ATTR_HT_MCS_SET])) {
4826                         u8 *mcs;
4827                         mcs = nla_data(tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
4828                         os_memcpy(mode->mcs_set, mcs, 16);
4829                 }
4830
4831                 if (tb_band[NL80211_BAND_ATTR_VHT_CAPA]) {
4832                         mode->vht_capab = nla_get_u32(
4833                                 tb_band[NL80211_BAND_ATTR_VHT_CAPA]);
4834                 }
4835
4836                 if (tb_band[NL80211_BAND_ATTR_VHT_MCS_SET] &&
4837                     nla_len(tb_band[NL80211_BAND_ATTR_VHT_MCS_SET])) {
4838                         u8 *mcs;
4839                         mcs = nla_data(tb_band[NL80211_BAND_ATTR_VHT_MCS_SET]);
4840                         os_memcpy(mode->vht_mcs_set, mcs, 8);
4841                 }
4842
4843                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
4844                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
4845                                   nla_len(nl_freq), freq_policy);
4846                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
4847                                 continue;
4848                         mode->num_channels++;
4849                 }
4850
4851                 mode->channels = os_zalloc(mode->num_channels * sizeof(struct hostapd_channel_data));
4852                 if (!mode->channels)
4853                         return NL_SKIP;
4854
4855                 idx = 0;
4856
4857                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
4858                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
4859                                   nla_len(nl_freq), freq_policy);
4860                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
4861                                 continue;
4862
4863                         mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
4864                         mode->channels[idx].flag = 0;
4865
4866                         if (!mode_is_set) {
4867                                 /* crude heuristic */
4868                                 if (mode->channels[idx].freq < 4000)
4869                                         mode->mode = HOSTAPD_MODE_IEEE80211B;
4870                                 else
4871                                         mode->mode = HOSTAPD_MODE_IEEE80211A;
4872                                 mode_is_set = 1;
4873                         }
4874
4875                         /* crude heuristic */
4876                         if (mode->channels[idx].freq < 4000)
4877                                 if (mode->channels[idx].freq == 2484)
4878                                         mode->channels[idx].chan = 14;
4879                                 else
4880                                         mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
4881                         else
4882                                 mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
4883
4884                         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
4885                                 mode->channels[idx].flag |=
4886                                         HOSTAPD_CHAN_DISABLED;
4887                         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
4888                                 mode->channels[idx].flag |=
4889                                         HOSTAPD_CHAN_PASSIVE_SCAN;
4890                         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
4891                                 mode->channels[idx].flag |=
4892                                         HOSTAPD_CHAN_NO_IBSS;
4893                         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
4894                                 mode->channels[idx].flag |=
4895                                         HOSTAPD_CHAN_RADAR;
4896
4897                         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
4898                             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
4899                                 mode->channels[idx].max_tx_power =
4900                                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
4901
4902                         idx++;
4903                 }
4904
4905                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
4906                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
4907                                   nla_len(nl_rate), rate_policy);
4908                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
4909                                 continue;
4910                         mode->num_rates++;
4911                 }
4912
4913                 mode->rates = os_zalloc(mode->num_rates * sizeof(int));
4914                 if (!mode->rates)
4915                         return NL_SKIP;
4916
4917                 idx = 0;
4918
4919                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
4920                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
4921                                   nla_len(nl_rate), rate_policy);
4922                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
4923                                 continue;
4924                         mode->rates[idx] = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
4925
4926                         /* crude heuristic */
4927                         if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
4928                             mode->rates[idx] > 200)
4929                                 mode->mode = HOSTAPD_MODE_IEEE80211G;
4930
4931                         idx++;
4932                 }
4933         }
4934
4935         return NL_SKIP;
4936 }
4937
4938 static struct hostapd_hw_modes *
4939 wpa_driver_nl80211_add_11b(struct hostapd_hw_modes *modes, u16 *num_modes)
4940 {
4941         u16 m;
4942         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
4943         int i, mode11g_idx = -1;
4944
4945         /* If only 802.11g mode is included, use it to construct matching
4946          * 802.11b mode data. */
4947
4948         for (m = 0; m < *num_modes; m++) {
4949                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
4950                         return modes; /* 802.11b already included */
4951                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
4952                         mode11g_idx = m;
4953         }
4954
4955         if (mode11g_idx < 0)
4956                 return modes; /* 2.4 GHz band not supported at all */
4957
4958         nmodes = os_realloc(modes, (*num_modes + 1) * sizeof(*nmodes));
4959         if (nmodes == NULL)
4960                 return modes; /* Could not add 802.11b mode */
4961
4962         mode = &nmodes[*num_modes];
4963         os_memset(mode, 0, sizeof(*mode));
4964         (*num_modes)++;
4965         modes = nmodes;
4966
4967         mode->mode = HOSTAPD_MODE_IEEE80211B;
4968
4969         mode11g = &modes[mode11g_idx];
4970         mode->num_channels = mode11g->num_channels;
4971         mode->channels = os_malloc(mode11g->num_channels *
4972                                    sizeof(struct hostapd_channel_data));
4973         if (mode->channels == NULL) {
4974                 (*num_modes)--;
4975                 return modes; /* Could not add 802.11b mode */
4976         }
4977         os_memcpy(mode->channels, mode11g->channels,
4978                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
4979
4980         mode->num_rates = 0;
4981         mode->rates = os_malloc(4 * sizeof(int));
4982         if (mode->rates == NULL) {
4983                 os_free(mode->channels);
4984                 (*num_modes)--;
4985                 return modes; /* Could not add 802.11b mode */
4986         }
4987
4988         for (i = 0; i < mode11g->num_rates; i++) {
4989                 if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 &&
4990                     mode11g->rates[i] != 55 && mode11g->rates[i] != 110)
4991                         continue;
4992                 mode->rates[mode->num_rates] = mode11g->rates[i];
4993                 mode->num_rates++;
4994                 if (mode->num_rates == 4)
4995                         break;
4996         }
4997
4998         if (mode->num_rates == 0) {
4999                 os_free(mode->channels);
5000                 os_free(mode->rates);
5001                 (*num_modes)--;
5002                 return modes; /* No 802.11b rates */
5003         }
5004
5005         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
5006                    "information");
5007
5008         return modes;
5009 }
5010
5011
5012 static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start,
5013                                   int end)
5014 {
5015         int c;
5016
5017         for (c = 0; c < mode->num_channels; c++) {
5018                 struct hostapd_channel_data *chan = &mode->channels[c];
5019                 if (chan->freq - 10 >= start && chan->freq + 10 <= end)
5020                         chan->flag |= HOSTAPD_CHAN_HT40;
5021         }
5022 }
5023
5024
5025 static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start,
5026                                       int end)
5027 {
5028         int c;
5029
5030         for (c = 0; c < mode->num_channels; c++) {
5031                 struct hostapd_channel_data *chan = &mode->channels[c];
5032                 if (!(chan->flag & HOSTAPD_CHAN_HT40))
5033                         continue;
5034                 if (chan->freq - 30 >= start && chan->freq - 10 <= end)
5035                         chan->flag |= HOSTAPD_CHAN_HT40MINUS;
5036                 if (chan->freq + 10 >= start && chan->freq + 30 <= end)
5037                         chan->flag |= HOSTAPD_CHAN_HT40PLUS;
5038         }
5039 }
5040
5041
5042 static void nl80211_reg_rule_ht40(struct nlattr *tb[],
5043                                   struct phy_info_arg *results)
5044 {
5045         u32 start, end, max_bw;
5046         u16 m;
5047
5048         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
5049             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
5050             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
5051                 return;
5052
5053         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
5054         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
5055         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
5056
5057         wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz",
5058                    start, end, max_bw);
5059         if (max_bw < 40)
5060                 return;
5061
5062         for (m = 0; m < *results->num_modes; m++) {
5063                 if (!(results->modes[m].ht_capab &
5064                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
5065                         continue;
5066                 nl80211_set_ht40_mode(&results->modes[m], start, end);
5067         }
5068 }
5069
5070
5071 static void nl80211_reg_rule_sec(struct nlattr *tb[],
5072                                  struct phy_info_arg *results)
5073 {
5074         u32 start, end, max_bw;
5075         u16 m;
5076
5077         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
5078             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
5079             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
5080                 return;
5081
5082         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
5083         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
5084         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
5085
5086         if (max_bw < 20)
5087                 return;
5088
5089         for (m = 0; m < *results->num_modes; m++) {
5090                 if (!(results->modes[m].ht_capab &
5091                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
5092                         continue;
5093                 nl80211_set_ht40_mode_sec(&results->modes[m], start, end);
5094         }
5095 }
5096
5097
5098 static int nl80211_get_reg(struct nl_msg *msg, void *arg)
5099 {
5100         struct phy_info_arg *results = arg;
5101         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
5102         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5103         struct nlattr *nl_rule;
5104         struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1];
5105         int rem_rule;
5106         static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
5107                 [NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
5108                 [NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
5109                 [NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
5110                 [NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
5111                 [NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
5112                 [NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
5113         };
5114
5115         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5116                   genlmsg_attrlen(gnlh, 0), NULL);
5117         if (!tb_msg[NL80211_ATTR_REG_ALPHA2] ||
5118             !tb_msg[NL80211_ATTR_REG_RULES]) {
5119                 wpa_printf(MSG_DEBUG, "nl80211: No regulatory information "
5120                            "available");
5121                 return NL_SKIP;
5122         }
5123
5124         wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s",
5125                    (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]));
5126
5127         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5128         {
5129                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5130                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5131                 nl80211_reg_rule_ht40(tb_rule, results);
5132         }
5133
5134         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5135         {
5136                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5137                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5138                 nl80211_reg_rule_sec(tb_rule, results);
5139         }
5140
5141         return NL_SKIP;
5142 }
5143
5144
5145 static int nl80211_set_ht40_flags(struct wpa_driver_nl80211_data *drv,
5146                                   struct phy_info_arg *results)
5147 {
5148         struct nl_msg *msg;
5149
5150         msg = nlmsg_alloc();
5151         if (!msg)
5152                 return -ENOMEM;
5153
5154         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_REG);
5155         return send_and_recv_msgs(drv, msg, nl80211_get_reg, results);
5156 }
5157
5158
5159 static struct hostapd_hw_modes *
5160 wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
5161 {
5162         struct i802_bss *bss = priv;
5163         struct wpa_driver_nl80211_data *drv = bss->drv;
5164         struct nl_msg *msg;
5165         struct phy_info_arg result = {
5166                 .num_modes = num_modes,
5167                 .modes = NULL,
5168         };
5169
5170         *num_modes = 0;
5171         *flags = 0;
5172
5173         msg = nlmsg_alloc();
5174         if (!msg)
5175                 return NULL;
5176
5177         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
5178
5179         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5180
5181         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) {
5182                 nl80211_set_ht40_flags(drv, &result);
5183                 return wpa_driver_nl80211_add_11b(result.modes, num_modes);
5184         }
5185         msg = NULL;
5186  nla_put_failure:
5187         nlmsg_free(msg);
5188         return NULL;
5189 }
5190
5191
5192 static int wpa_driver_nl80211_send_mntr(struct wpa_driver_nl80211_data *drv,
5193                                         const void *data, size_t len,
5194                                         int encrypt, int noack)
5195 {
5196         __u8 rtap_hdr[] = {
5197                 0x00, 0x00, /* radiotap version */
5198                 0x0e, 0x00, /* radiotap length */
5199                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
5200                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
5201                 0x00,       /* padding */
5202                 0x00, 0x00, /* RX and TX flags to indicate that */
5203                 0x00, 0x00, /* this is the injected frame directly */
5204         };
5205         struct iovec iov[2] = {
5206                 {
5207                         .iov_base = &rtap_hdr,
5208                         .iov_len = sizeof(rtap_hdr),
5209                 },
5210                 {
5211                         .iov_base = (void *) data,
5212                         .iov_len = len,
5213                 }
5214         };
5215         struct msghdr msg = {
5216                 .msg_name = NULL,
5217                 .msg_namelen = 0,
5218                 .msg_iov = iov,
5219                 .msg_iovlen = 2,
5220                 .msg_control = NULL,
5221                 .msg_controllen = 0,
5222                 .msg_flags = 0,
5223         };
5224         int res;
5225         u16 txflags = 0;
5226
5227         if (encrypt)
5228                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
5229
5230         if (drv->monitor_sock < 0) {
5231                 wpa_printf(MSG_DEBUG, "nl80211: No monitor socket available "
5232                            "for %s", __func__);
5233                 return -1;
5234         }
5235
5236         if (noack)
5237                 txflags |= IEEE80211_RADIOTAP_F_TX_NOACK;
5238         *(le16 *) &rtap_hdr[12] = host_to_le16(txflags);
5239
5240         res = sendmsg(drv->monitor_sock, &msg, 0);
5241         if (res < 0) {
5242                 wpa_printf(MSG_INFO, "nl80211: sendmsg: %s", strerror(errno));
5243                 return -1;
5244         }
5245         return 0;
5246 }
5247
5248
5249 static int wpa_driver_nl80211_send_frame(struct i802_bss *bss,
5250                                          const void *data, size_t len,
5251                                          int encrypt, int noack,
5252                                          unsigned int freq, int no_cck,
5253                                          int offchanok, unsigned int wait_time)
5254 {
5255         struct wpa_driver_nl80211_data *drv = bss->drv;
5256         u64 cookie;
5257
5258         if (freq == 0)
5259                 freq = bss->freq;
5260
5261         if (drv->use_monitor)
5262                 return wpa_driver_nl80211_send_mntr(drv, data, len,
5263                                                     encrypt, noack);
5264
5265         return nl80211_send_frame_cmd(bss, freq, wait_time, data, len,
5266                                       &cookie, no_cck, noack, offchanok);
5267 }
5268
5269
5270 static int wpa_driver_nl80211_send_mlme_freq(struct i802_bss *bss,
5271                                              const u8 *data,
5272                                              size_t data_len, int noack,
5273                                              unsigned int freq, int no_cck,
5274                                              int offchanok,
5275                                              unsigned int wait_time)
5276 {
5277         struct wpa_driver_nl80211_data *drv = bss->drv;
5278         struct ieee80211_mgmt *mgmt;
5279         int encrypt = 1;
5280         u16 fc;
5281
5282         mgmt = (struct ieee80211_mgmt *) data;
5283         fc = le_to_host16(mgmt->frame_control);
5284
5285         if (is_sta_interface(drv->nlmode) &&
5286             WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5287             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_PROBE_RESP) {
5288                 /*
5289                  * The use of last_mgmt_freq is a bit of a hack,
5290                  * but it works due to the single-threaded nature
5291                  * of wpa_supplicant.
5292                  */
5293                 if (freq == 0)
5294                         freq = drv->last_mgmt_freq;
5295                 return nl80211_send_frame_cmd(bss, freq, 0,
5296                                               data, data_len, NULL, 1, noack,
5297                                               1);
5298         }
5299
5300         if (drv->device_ap_sme && is_ap_interface(drv->nlmode)) {
5301                 if (freq == 0)
5302                         freq = bss->freq;
5303                 return nl80211_send_frame_cmd(bss, freq,
5304                                               (int) freq == bss->freq ? 0 :
5305                                               wait_time,
5306                                               data, data_len,
5307                                               &drv->send_action_cookie,
5308                                               no_cck, noack, offchanok);
5309         }
5310
5311         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5312             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
5313                 /*
5314                  * Only one of the authentication frame types is encrypted.
5315                  * In order for static WEP encryption to work properly (i.e.,
5316                  * to not encrypt the frame), we need to tell mac80211 about
5317                  * the frames that must not be encrypted.
5318                  */
5319                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
5320                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
5321                 if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
5322                         encrypt = 0;
5323         }
5324
5325         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt,
5326                                              noack, freq, no_cck, offchanok,
5327                                              wait_time);
5328 }
5329
5330
5331 static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
5332                                         size_t data_len, int noack)
5333 {
5334         struct i802_bss *bss = priv;
5335         return wpa_driver_nl80211_send_mlme_freq(bss, data, data_len, noack,
5336                                                  0, 0, 0, 0);
5337 }
5338
5339
5340 static int nl80211_set_bss(struct i802_bss *bss, int cts, int preamble,
5341                            int slot, int ht_opmode, int ap_isolate,
5342                            int *basic_rates)
5343 {
5344         struct wpa_driver_nl80211_data *drv = bss->drv;
5345         struct nl_msg *msg;
5346
5347         msg = nlmsg_alloc();
5348         if (!msg)
5349                 return -ENOMEM;
5350
5351         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_BSS);
5352
5353         if (cts >= 0)
5354                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
5355         if (preamble >= 0)
5356                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
5357         if (slot >= 0)
5358                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
5359         if (ht_opmode >= 0)
5360                 NLA_PUT_U16(msg, NL80211_ATTR_BSS_HT_OPMODE, ht_opmode);
5361         if (ap_isolate >= 0)
5362                 NLA_PUT_U8(msg, NL80211_ATTR_AP_ISOLATE, ap_isolate);
5363
5364         if (basic_rates) {
5365                 u8 rates[NL80211_MAX_SUPP_RATES];
5366                 u8 rates_len = 0;
5367                 int i;
5368
5369                 for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0;
5370                      i++)
5371                         rates[rates_len++] = basic_rates[i] / 5;
5372
5373                 NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
5374         }
5375
5376         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5377
5378         return send_and_recv_msgs(drv, msg, NULL, NULL);
5379  nla_put_failure:
5380         nlmsg_free(msg);
5381         return -ENOBUFS;
5382 }
5383
5384
5385 static int wpa_driver_nl80211_set_ap(void *priv,
5386                                      struct wpa_driver_ap_params *params)
5387 {
5388         struct i802_bss *bss = priv;
5389         struct wpa_driver_nl80211_data *drv = bss->drv;
5390         struct nl_msg *msg;
5391         u8 cmd = NL80211_CMD_NEW_BEACON;
5392         int ret;
5393         int beacon_set;
5394         int ifindex = if_nametoindex(bss->ifname);
5395         int num_suites;
5396         u32 suites[10];
5397         u32 ver;
5398
5399         beacon_set = bss->beacon_set;
5400
5401         msg = nlmsg_alloc();
5402         if (!msg)
5403                 return -ENOMEM;
5404
5405         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
5406                    beacon_set);
5407         if (beacon_set)
5408                 cmd = NL80211_CMD_SET_BEACON;
5409
5410         nl80211_cmd(drv, msg, 0, cmd);
5411         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, params->head_len, params->head);
5412         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, params->tail_len, params->tail);
5413         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
5414         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, params->beacon_int);
5415         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, params->dtim_period);
5416         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
5417                 params->ssid);
5418         if (params->proberesp && params->proberesp_len)
5419                 NLA_PUT(msg, NL80211_ATTR_PROBE_RESP, params->proberesp_len,
5420                         params->proberesp);
5421         switch (params->hide_ssid) {
5422         case NO_SSID_HIDING:
5423                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5424                             NL80211_HIDDEN_SSID_NOT_IN_USE);
5425                 break;
5426         case HIDDEN_SSID_ZERO_LEN:
5427                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5428                             NL80211_HIDDEN_SSID_ZERO_LEN);
5429                 break;
5430         case HIDDEN_SSID_ZERO_CONTENTS:
5431                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5432                             NL80211_HIDDEN_SSID_ZERO_CONTENTS);
5433                 break;
5434         }
5435         if (params->privacy)
5436                 NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
5437         if ((params->auth_algs & (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) ==
5438             (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) {
5439                 /* Leave out the attribute */
5440         } else if (params->auth_algs & WPA_AUTH_ALG_SHARED)
5441                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5442                             NL80211_AUTHTYPE_SHARED_KEY);
5443         else
5444                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5445                             NL80211_AUTHTYPE_OPEN_SYSTEM);
5446
5447         ver = 0;
5448         if (params->wpa_version & WPA_PROTO_WPA)
5449                 ver |= NL80211_WPA_VERSION_1;
5450         if (params->wpa_version & WPA_PROTO_RSN)
5451                 ver |= NL80211_WPA_VERSION_2;
5452         if (ver)
5453                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
5454
5455         num_suites = 0;
5456         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X)
5457                 suites[num_suites++] = WLAN_AKM_SUITE_8021X;
5458         if (params->key_mgmt_suites & WPA_KEY_MGMT_PSK)
5459                 suites[num_suites++] = WLAN_AKM_SUITE_PSK;
5460         if (num_suites) {
5461                 NLA_PUT(msg, NL80211_ATTR_AKM_SUITES,
5462                         num_suites * sizeof(u32), suites);
5463         }
5464
5465         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X &&
5466             params->pairwise_ciphers & (WPA_CIPHER_WEP104 | WPA_CIPHER_WEP40))
5467                 NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT);
5468
5469         num_suites = 0;
5470         if (params->pairwise_ciphers & WPA_CIPHER_CCMP)
5471                 suites[num_suites++] = WLAN_CIPHER_SUITE_CCMP;
5472         if (params->pairwise_ciphers & WPA_CIPHER_TKIP)
5473                 suites[num_suites++] = WLAN_CIPHER_SUITE_TKIP;
5474         if (params->pairwise_ciphers & WPA_CIPHER_WEP104)
5475                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP104;
5476         if (params->pairwise_ciphers & WPA_CIPHER_WEP40)
5477                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP40;
5478         if (num_suites) {
5479                 NLA_PUT(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE,
5480                         num_suites * sizeof(u32), suites);
5481         }
5482
5483         switch (params->group_cipher) {
5484         case WPA_CIPHER_CCMP:
5485                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5486                             WLAN_CIPHER_SUITE_CCMP);
5487                 break;
5488         case WPA_CIPHER_TKIP:
5489                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5490                             WLAN_CIPHER_SUITE_TKIP);
5491                 break;
5492         case WPA_CIPHER_WEP104:
5493                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5494                             WLAN_CIPHER_SUITE_WEP104);
5495                 break;
5496         case WPA_CIPHER_WEP40:
5497                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5498                             WLAN_CIPHER_SUITE_WEP40);
5499                 break;
5500         }
5501
5502         if (params->beacon_ies) {
5503                 NLA_PUT(msg, NL80211_ATTR_IE, wpabuf_len(params->beacon_ies),
5504                         wpabuf_head(params->beacon_ies));
5505         }
5506         if (params->proberesp_ies) {
5507                 NLA_PUT(msg, NL80211_ATTR_IE_PROBE_RESP,
5508                         wpabuf_len(params->proberesp_ies),
5509                         wpabuf_head(params->proberesp_ies));
5510         }
5511         if (params->assocresp_ies) {
5512                 NLA_PUT(msg, NL80211_ATTR_IE_ASSOC_RESP,
5513                         wpabuf_len(params->assocresp_ies),
5514                         wpabuf_head(params->assocresp_ies));
5515         }
5516
5517         if (drv->capa.flags & WPA_DRIVER_FLAGS_INACTIVITY_TIMER)  {
5518                 NLA_PUT_U16(msg, NL80211_ATTR_INACTIVITY_TIMEOUT,
5519                             params->ap_max_inactivity);
5520         }
5521
5522         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5523         if (ret) {
5524                 wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
5525                            ret, strerror(-ret));
5526         } else {
5527                 bss->beacon_set = 1;
5528                 nl80211_set_bss(bss, params->cts_protect, params->preamble,
5529                                 params->short_slot_time, params->ht_opmode,
5530                                 params->isolate, params->basic_rates);
5531         }
5532         return ret;
5533  nla_put_failure:
5534         nlmsg_free(msg);
5535         return -ENOBUFS;
5536 }
5537
5538
5539 static int wpa_driver_nl80211_set_freq(struct i802_bss *bss,
5540                                        int freq, int ht_enabled,
5541                                        int sec_channel_offset)
5542 {
5543         struct wpa_driver_nl80211_data *drv = bss->drv;
5544         struct nl_msg *msg;
5545         int ret;
5546
5547         wpa_printf(MSG_DEBUG, "nl80211: Set freq %d (ht_enabled=%d "
5548                    "sec_channel_offset=%d)",
5549                    freq, ht_enabled, sec_channel_offset);
5550         msg = nlmsg_alloc();
5551         if (!msg)
5552                 return -1;
5553
5554         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
5555
5556         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5557         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
5558         if (ht_enabled) {
5559                 switch (sec_channel_offset) {
5560                 case -1:
5561                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5562                                     NL80211_CHAN_HT40MINUS);
5563                         break;
5564                 case 1:
5565                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5566                                     NL80211_CHAN_HT40PLUS);
5567                         break;
5568                 default:
5569                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
5570                                     NL80211_CHAN_HT20);
5571                         break;
5572                 }
5573         }
5574
5575         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5576         msg = NULL;
5577         if (ret == 0) {
5578                 bss->freq = freq;
5579                 return 0;
5580         }
5581         wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
5582                    "%d (%s)", freq, ret, strerror(-ret));
5583 nla_put_failure:
5584         nlmsg_free(msg);
5585         return -1;
5586 }
5587
5588
5589 static u32 sta_flags_nl80211(int flags)
5590 {
5591         u32 f = 0;
5592
5593         if (flags & WPA_STA_AUTHORIZED)
5594                 f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
5595         if (flags & WPA_STA_WMM)
5596                 f |= BIT(NL80211_STA_FLAG_WME);
5597         if (flags & WPA_STA_SHORT_PREAMBLE)
5598                 f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
5599         if (flags & WPA_STA_MFP)
5600                 f |= BIT(NL80211_STA_FLAG_MFP);
5601         if (flags & WPA_STA_TDLS_PEER)
5602                 f |= BIT(NL80211_STA_FLAG_TDLS_PEER);
5603
5604         return f;
5605 }
5606
5607
5608 static int wpa_driver_nl80211_sta_add(void *priv,
5609                                       struct hostapd_sta_add_params *params)
5610 {
5611         struct i802_bss *bss = priv;
5612         struct wpa_driver_nl80211_data *drv = bss->drv;
5613         struct nl_msg *msg, *wme = NULL;
5614         struct nl80211_sta_flag_update upd;
5615         int ret = -ENOBUFS;
5616
5617         if ((params->flags & WPA_STA_TDLS_PEER) &&
5618             !(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
5619                 return -EOPNOTSUPP;
5620
5621         msg = nlmsg_alloc();
5622         if (!msg)
5623                 return -ENOMEM;
5624
5625         nl80211_cmd(drv, msg, 0, params->set ? NL80211_CMD_SET_STATION :
5626                     NL80211_CMD_NEW_STATION);
5627
5628         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5629         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
5630         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
5631                 params->supp_rates);
5632         if (!params->set) {
5633                 NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
5634                 NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
5635                             params->listen_interval);
5636         }
5637         if (params->ht_capabilities) {
5638                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
5639                         sizeof(*params->ht_capabilities),
5640                         params->ht_capabilities);
5641         }
5642
5643         os_memset(&upd, 0, sizeof(upd));
5644         upd.mask = sta_flags_nl80211(params->flags);
5645         upd.set = upd.mask;
5646         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
5647
5648         if (params->flags & WPA_STA_WMM) {
5649                 wme = nlmsg_alloc();
5650                 if (!wme)
5651                         goto nla_put_failure;
5652
5653                 NLA_PUT_U8(wme, NL80211_STA_WME_UAPSD_QUEUES,
5654                                 params->qosinfo & WMM_QOSINFO_STA_AC_MASK);
5655                 NLA_PUT_U8(wme, NL80211_STA_WME_MAX_SP,
5656                                 (params->qosinfo > WMM_QOSINFO_STA_SP_SHIFT) &
5657                                 WMM_QOSINFO_STA_SP_MASK);
5658                 nla_put_nested(msg, NL80211_ATTR_STA_WME, wme);
5659         }
5660
5661         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5662         msg = NULL;
5663         if (ret)
5664                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_%s_STATION "
5665                            "result: %d (%s)", params->set ? "SET" : "NEW", ret,
5666                            strerror(-ret));
5667         if (ret == -EEXIST)
5668                 ret = 0;
5669  nla_put_failure:
5670         nlmsg_free(wme);
5671         nlmsg_free(msg);
5672         return ret;
5673 }
5674
5675
5676 static int wpa_driver_nl80211_sta_remove(void *priv, const u8 *addr)
5677 {
5678         struct i802_bss *bss = priv;
5679         struct wpa_driver_nl80211_data *drv = bss->drv;
5680         struct nl_msg *msg;
5681         int ret;
5682
5683         msg = nlmsg_alloc();
5684         if (!msg)
5685                 return -ENOMEM;
5686
5687         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
5688
5689         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5690                     if_nametoindex(bss->ifname));
5691         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5692
5693         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5694         if (ret == -ENOENT)
5695                 return 0;
5696         return ret;
5697  nla_put_failure:
5698         nlmsg_free(msg);
5699         return -ENOBUFS;
5700 }
5701
5702
5703 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
5704                                  int ifidx)
5705 {
5706         struct nl_msg *msg;
5707
5708         wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
5709
5710         /* stop listening for EAPOL on this interface */
5711         del_ifidx(drv, ifidx);
5712
5713         msg = nlmsg_alloc();
5714         if (!msg)
5715                 goto nla_put_failure;
5716
5717         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_INTERFACE);
5718         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
5719
5720         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
5721                 return;
5722         msg = NULL;
5723  nla_put_failure:
5724         nlmsg_free(msg);
5725         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
5726 }
5727
5728
5729 static const char * nl80211_iftype_str(enum nl80211_iftype mode)
5730 {
5731         switch (mode) {
5732         case NL80211_IFTYPE_ADHOC:
5733                 return "ADHOC";
5734         case NL80211_IFTYPE_STATION:
5735                 return "STATION";
5736         case NL80211_IFTYPE_AP:
5737                 return "AP";
5738         case NL80211_IFTYPE_MONITOR:
5739                 return "MONITOR";
5740         case NL80211_IFTYPE_P2P_CLIENT:
5741                 return "P2P_CLIENT";
5742         case NL80211_IFTYPE_P2P_GO:
5743                 return "P2P_GO";
5744         default:
5745                 return "unknown";
5746         }
5747 }
5748
5749
5750 static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
5751                                      const char *ifname,
5752                                      enum nl80211_iftype iftype,
5753                                      const u8 *addr, int wds)
5754 {
5755         struct nl_msg *msg, *flags = NULL;
5756         int ifidx;
5757         int ret = -ENOBUFS;
5758
5759         wpa_printf(MSG_DEBUG, "nl80211: Create interface iftype %d (%s)",
5760                    iftype, nl80211_iftype_str(iftype));
5761
5762         msg = nlmsg_alloc();
5763         if (!msg)
5764                 return -1;
5765
5766         nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_INTERFACE);
5767         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5768         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
5769         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
5770
5771         if (iftype == NL80211_IFTYPE_MONITOR) {
5772                 int err;
5773
5774                 flags = nlmsg_alloc();
5775                 if (!flags)
5776                         goto nla_put_failure;
5777
5778                 NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
5779
5780                 err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
5781
5782                 nlmsg_free(flags);
5783
5784                 if (err)
5785                         goto nla_put_failure;
5786         } else if (wds) {
5787                 NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
5788         }
5789
5790         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5791         msg = NULL;
5792         if (ret) {
5793  nla_put_failure:
5794                 nlmsg_free(msg);
5795                 wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
5796                            ifname, ret, strerror(-ret));
5797                 return ret;
5798         }
5799
5800         ifidx = if_nametoindex(ifname);
5801         wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
5802                    ifname, ifidx);
5803
5804         if (ifidx <= 0)
5805                 return -1;
5806
5807         /* start listening for EAPOL on this interface */
5808         add_ifidx(drv, ifidx);
5809
5810         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
5811             linux_set_ifhwaddr(drv->global->ioctl_sock, ifname, addr)) {
5812                 nl80211_remove_iface(drv, ifidx);
5813                 return -1;
5814         }
5815
5816         return ifidx;
5817 }
5818
5819
5820 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
5821                                 const char *ifname, enum nl80211_iftype iftype,
5822                                 const u8 *addr, int wds)
5823 {
5824         int ret;
5825
5826         ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds);
5827
5828         /* if error occurred and interface exists already */
5829         if (ret == -ENFILE && if_nametoindex(ifname)) {
5830                 wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
5831
5832                 /* Try to remove the interface that was already there. */
5833                 nl80211_remove_iface(drv, if_nametoindex(ifname));
5834
5835                 /* Try to create the interface again */
5836                 ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
5837                                                 wds);
5838         }
5839
5840         if (ret >= 0 && is_p2p_interface(iftype))
5841                 nl80211_disable_11b_rates(drv, ret, 1);
5842
5843         return ret;
5844 }
5845
5846
5847 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
5848 {
5849         struct ieee80211_hdr *hdr;
5850         u16 fc;
5851         union wpa_event_data event;
5852
5853         hdr = (struct ieee80211_hdr *) buf;
5854         fc = le_to_host16(hdr->frame_control);
5855
5856         os_memset(&event, 0, sizeof(event));
5857         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
5858         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
5859         event.tx_status.dst = hdr->addr1;
5860         event.tx_status.data = buf;
5861         event.tx_status.data_len = len;
5862         event.tx_status.ack = ok;
5863         wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
5864 }
5865
5866
5867 static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
5868                              u8 *buf, size_t len)
5869 {
5870         struct ieee80211_hdr *hdr = (void *)buf;
5871         u16 fc;
5872         union wpa_event_data event;
5873
5874         if (len < sizeof(*hdr))
5875                 return;
5876
5877         fc = le_to_host16(hdr->frame_control);
5878
5879         os_memset(&event, 0, sizeof(event));
5880         event.rx_from_unknown.bssid = get_hdr_bssid(hdr, len);
5881         event.rx_from_unknown.addr = hdr->addr2;
5882         event.rx_from_unknown.wds = (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) ==
5883                 (WLAN_FC_FROMDS | WLAN_FC_TODS);
5884         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
5885 }
5886
5887
5888 static void handle_frame(struct wpa_driver_nl80211_data *drv,
5889                          u8 *buf, size_t len, int datarate, int ssi_signal)
5890 {
5891         struct ieee80211_hdr *hdr;
5892         u16 fc;
5893         union wpa_event_data event;
5894
5895         hdr = (struct ieee80211_hdr *) buf;
5896         fc = le_to_host16(hdr->frame_control);
5897
5898         switch (WLAN_FC_GET_TYPE(fc)) {
5899         case WLAN_FC_TYPE_MGMT:
5900                 os_memset(&event, 0, sizeof(event));
5901                 event.rx_mgmt.frame = buf;
5902                 event.rx_mgmt.frame_len = len;
5903                 event.rx_mgmt.datarate = datarate;
5904                 event.rx_mgmt.ssi_signal = ssi_signal;
5905                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
5906                 break;
5907         case WLAN_FC_TYPE_CTRL:
5908                 /* can only get here with PS-Poll frames */
5909                 wpa_printf(MSG_DEBUG, "CTRL");
5910                 from_unknown_sta(drv, buf, len);
5911                 break;
5912         case WLAN_FC_TYPE_DATA:
5913                 from_unknown_sta(drv, buf, len);
5914                 break;
5915         }
5916 }
5917
5918
5919 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
5920 {
5921         struct wpa_driver_nl80211_data *drv = eloop_ctx;
5922         int len;
5923         unsigned char buf[3000];
5924         struct ieee80211_radiotap_iterator iter;
5925         int ret;
5926         int datarate = 0, ssi_signal = 0;
5927         int injected = 0, failed = 0, rxflags = 0;
5928
5929         len = recv(sock, buf, sizeof(buf), 0);
5930         if (len < 0) {
5931                 perror("recv");
5932                 return;
5933         }
5934
5935         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
5936                 printf("received invalid radiotap frame\n");
5937                 return;
5938         }
5939
5940         while (1) {
5941                 ret = ieee80211_radiotap_iterator_next(&iter);
5942                 if (ret == -ENOENT)
5943                         break;
5944                 if (ret) {
5945                         printf("received invalid radiotap frame (%d)\n", ret);
5946                         return;
5947                 }
5948                 switch (iter.this_arg_index) {
5949                 case IEEE80211_RADIOTAP_FLAGS:
5950                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
5951                                 len -= 4;
5952                         break;
5953                 case IEEE80211_RADIOTAP_RX_FLAGS:
5954                         rxflags = 1;
5955                         break;
5956                 case IEEE80211_RADIOTAP_TX_FLAGS:
5957                         injected = 1;
5958                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
5959                                         IEEE80211_RADIOTAP_F_TX_FAIL;
5960                         break;
5961                 case IEEE80211_RADIOTAP_DATA_RETRIES:
5962                         break;
5963                 case IEEE80211_RADIOTAP_CHANNEL:
5964                         /* TODO: convert from freq/flags to channel number */
5965                         break;
5966                 case IEEE80211_RADIOTAP_RATE:
5967                         datarate = *iter.this_arg * 5;
5968                         break;
5969                 case IEEE80211_RADIOTAP_DBM_ANTSIGNAL:
5970                         ssi_signal = (s8) *iter.this_arg;
5971                         break;
5972                 }
5973         }
5974
5975         if (rxflags && injected)
5976                 return;
5977
5978         if (!injected)
5979                 handle_frame(drv, buf + iter.max_length,
5980                              len - iter.max_length, datarate, ssi_signal);
5981         else
5982                 handle_tx_callback(drv->ctx, buf + iter.max_length,
5983                                    len - iter.max_length, !failed);
5984 }
5985
5986
5987 /*
5988  * we post-process the filter code later and rewrite
5989  * this to the offset to the last instruction
5990  */
5991 #define PASS    0xFF
5992 #define FAIL    0xFE
5993
5994 static struct sock_filter msock_filter_insns[] = {
5995         /*
5996          * do a little-endian load of the radiotap length field
5997          */
5998         /* load lower byte into A */
5999         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
6000         /* put it into X (== index register) */
6001         BPF_STMT(BPF_MISC| BPF_TAX, 0),
6002         /* load upper byte into A */
6003         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
6004         /* left-shift it by 8 */
6005         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
6006         /* or with X */
6007         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
6008         /* put result into X */
6009         BPF_STMT(BPF_MISC| BPF_TAX, 0),
6010
6011         /*
6012          * Allow management frames through, this also gives us those
6013          * management frames that we sent ourselves with status
6014          */
6015         /* load the lower byte of the IEEE 802.11 frame control field */
6016         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
6017         /* mask off frame type and version */
6018         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
6019         /* accept frame if it's both 0, fall through otherwise */
6020         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
6021
6022         /*
6023          * TODO: add a bit to radiotap RX flags that indicates
6024          * that the sending station is not associated, then
6025          * add a filter here that filters on our DA and that flag
6026          * to allow us to deauth frames to that bad station.
6027          *
6028          * For now allow all To DS data frames through.
6029          */
6030         /* load the IEEE 802.11 frame control field */
6031         BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
6032         /* mask off frame type, version and DS status */
6033         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
6034         /* accept frame if version 0, type 2 and To DS, fall through otherwise
6035          */
6036         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
6037
6038 #if 0
6039         /*
6040          * drop non-data frames
6041          */
6042         /* load the lower byte of the frame control field */
6043         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
6044         /* mask off QoS bit */
6045         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
6046         /* drop non-data frames */
6047         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
6048 #endif
6049         /* load the upper byte of the frame control field */
6050         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
6051         /* mask off toDS/fromDS */
6052         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
6053         /* accept WDS frames */
6054         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
6055
6056         /*
6057          * add header length to index
6058          */
6059         /* load the lower byte of the frame control field */
6060         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
6061         /* mask off QoS bit */
6062         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
6063         /* right shift it by 6 to give 0 or 2 */
6064         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
6065         /* add data frame header length */
6066         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
6067         /* add index, was start of 802.11 header */
6068         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
6069         /* move to index, now start of LL header */
6070         BPF_STMT(BPF_MISC | BPF_TAX, 0),
6071
6072         /*
6073          * Accept empty data frames, we use those for
6074          * polling activity.
6075          */
6076         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
6077         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
6078
6079         /*
6080          * Accept EAPOL frames
6081          */
6082         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
6083         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
6084         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
6085         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
6086
6087         /* keep these last two statements or change the code below */
6088         /* return 0 == "DROP" */
6089         BPF_STMT(BPF_RET | BPF_K, 0),
6090         /* return ~0 == "keep all" */
6091         BPF_STMT(BPF_RET | BPF_K, ~0),
6092 };
6093
6094 static struct sock_fprog msock_filter = {
6095         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
6096         .filter = msock_filter_insns,
6097 };
6098
6099
6100 static int add_monitor_filter(int s)
6101 {
6102         int idx;
6103
6104         /* rewrite all PASS/FAIL jump offsets */
6105         for (idx = 0; idx < msock_filter.len; idx++) {
6106                 struct sock_filter *insn = &msock_filter_insns[idx];
6107
6108                 if (BPF_CLASS(insn->code) == BPF_JMP) {
6109                         if (insn->code == (BPF_JMP|BPF_JA)) {
6110                                 if (insn->k == PASS)
6111                                         insn->k = msock_filter.len - idx - 2;
6112                                 else if (insn->k == FAIL)
6113                                         insn->k = msock_filter.len - idx - 3;
6114                         }
6115
6116                         if (insn->jt == PASS)
6117                                 insn->jt = msock_filter.len - idx - 2;
6118                         else if (insn->jt == FAIL)
6119                                 insn->jt = msock_filter.len - idx - 3;
6120
6121                         if (insn->jf == PASS)
6122                                 insn->jf = msock_filter.len - idx - 2;
6123                         else if (insn->jf == FAIL)
6124                                 insn->jf = msock_filter.len - idx - 3;
6125                 }
6126         }
6127
6128         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
6129                        &msock_filter, sizeof(msock_filter))) {
6130                 perror("SO_ATTACH_FILTER");
6131                 return -1;
6132         }
6133
6134         return 0;
6135 }
6136
6137
6138 static void nl80211_remove_monitor_interface(
6139         struct wpa_driver_nl80211_data *drv)
6140 {
6141         drv->monitor_refcount--;
6142         if (drv->monitor_refcount > 0)
6143                 return;
6144
6145         if (drv->monitor_ifidx >= 0) {
6146                 nl80211_remove_iface(drv, drv->monitor_ifidx);
6147                 drv->monitor_ifidx = -1;
6148         }
6149         if (drv->monitor_sock >= 0) {
6150                 eloop_unregister_read_sock(drv->monitor_sock);
6151                 close(drv->monitor_sock);
6152                 drv->monitor_sock = -1;
6153         }
6154 }
6155
6156
6157 static int
6158 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
6159 {
6160         char buf[IFNAMSIZ];
6161         struct sockaddr_ll ll;
6162         int optval;
6163         socklen_t optlen;
6164
6165         if (drv->monitor_ifidx >= 0) {
6166                 drv->monitor_refcount++;
6167                 return 0;
6168         }
6169
6170         if (os_strncmp(drv->first_bss.ifname, "p2p-", 4) == 0) {
6171                 /*
6172                  * P2P interface name is of the format p2p-%s-%d. For monitor
6173                  * interface name corresponding to P2P GO, replace "p2p-" with
6174                  * "mon-" to retain the same interface name length and to
6175                  * indicate that it is a monitor interface.
6176                  */
6177                 snprintf(buf, IFNAMSIZ, "mon-%s", drv->first_bss.ifname + 4);
6178         } else {
6179                 /* Non-P2P interface with AP functionality. */
6180                 snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss.ifname);
6181         }
6182
6183         buf[IFNAMSIZ - 1] = '\0';
6184
6185         drv->monitor_ifidx =
6186                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
6187                                      0);
6188
6189         if (drv->monitor_ifidx == -EOPNOTSUPP) {
6190                 /*
6191                  * This is backward compatibility for a few versions of
6192                  * the kernel only that didn't advertise the right
6193                  * attributes for the only driver that then supported
6194                  * AP mode w/o monitor -- ath6kl.
6195                  */
6196                 wpa_printf(MSG_DEBUG, "nl80211: Driver does not support "
6197                            "monitor interface type - try to run without it");
6198                 drv->device_ap_sme = 1;
6199         }
6200
6201         if (drv->monitor_ifidx < 0)
6202                 return -1;
6203
6204         if (linux_set_iface_flags(drv->global->ioctl_sock, buf, 1))
6205                 goto error;
6206
6207         memset(&ll, 0, sizeof(ll));
6208         ll.sll_family = AF_PACKET;
6209         ll.sll_ifindex = drv->monitor_ifidx;
6210         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
6211         if (drv->monitor_sock < 0) {
6212                 perror("socket[PF_PACKET,SOCK_RAW]");
6213                 goto error;
6214         }
6215
6216         if (add_monitor_filter(drv->monitor_sock)) {
6217                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
6218                            "interface; do filtering in user space");
6219                 /* This works, but will cost in performance. */
6220         }
6221
6222         if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
6223                 perror("monitor socket bind");
6224                 goto error;
6225         }
6226
6227         optlen = sizeof(optval);
6228         optval = 20;
6229         if (setsockopt
6230             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
6231                 perror("Failed to set socket priority");
6232                 goto error;
6233         }
6234
6235         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
6236                                      drv, NULL)) {
6237                 printf("Could not register monitor read socket\n");
6238                 goto error;
6239         }
6240
6241         return 0;
6242  error:
6243         nl80211_remove_monitor_interface(drv);
6244         return -1;
6245 }
6246
6247
6248 static int nl80211_setup_ap(struct i802_bss *bss)
6249 {
6250         struct wpa_driver_nl80211_data *drv = bss->drv;
6251
6252         wpa_printf(MSG_DEBUG, "nl80211: Setup AP - device_ap_sme=%d "
6253                    "use_monitor=%d", drv->device_ap_sme, drv->use_monitor);
6254
6255         /*
6256          * Disable Probe Request reporting unless we need it in this way for
6257          * devices that include the AP SME, in the other case (unless using
6258          * monitor iface) we'll get it through the nl_mgmt socket instead.
6259          */
6260         if (!drv->device_ap_sme)
6261                 wpa_driver_nl80211_probe_req_report(bss, 0);
6262
6263         if (!drv->device_ap_sme && !drv->use_monitor)
6264                 if (nl80211_mgmt_subscribe_ap(bss))
6265                         return -1;
6266
6267         if (drv->device_ap_sme && !drv->use_monitor)
6268                 if (nl80211_mgmt_subscribe_ap_dev_sme(bss))
6269                         return -1;
6270
6271         if (!drv->device_ap_sme && drv->use_monitor &&
6272             nl80211_create_monitor_interface(drv) &&
6273             !drv->device_ap_sme)
6274                 return -1;
6275
6276         if (drv->device_ap_sme &&
6277             wpa_driver_nl80211_probe_req_report(bss, 1) < 0) {
6278                 wpa_printf(MSG_DEBUG, "nl80211: Failed to enable "
6279                            "Probe Request frame reporting in AP mode");
6280                 /* Try to survive without this */
6281         }
6282
6283         return 0;
6284 }
6285
6286
6287 static void nl80211_teardown_ap(struct i802_bss *bss)
6288 {
6289         struct wpa_driver_nl80211_data *drv = bss->drv;
6290
6291         if (drv->device_ap_sme) {
6292                 wpa_driver_nl80211_probe_req_report(bss, 0);
6293                 if (!drv->use_monitor)
6294                         nl80211_mgmt_unsubscribe(bss, "AP teardown (dev SME)");
6295         } else if (drv->use_monitor)
6296                 nl80211_remove_monitor_interface(drv);
6297         else
6298                 nl80211_mgmt_unsubscribe(bss, "AP teardown");
6299
6300         bss->beacon_set = 0;
6301 }
6302
6303
6304 static int nl80211_send_eapol_data(struct i802_bss *bss,
6305                                    const u8 *addr, const u8 *data,
6306                                    size_t data_len)
6307 {
6308         struct sockaddr_ll ll;
6309         int ret;
6310
6311         if (bss->drv->eapol_tx_sock < 0) {
6312                 wpa_printf(MSG_DEBUG, "nl80211: No socket to send EAPOL");
6313                 return -1;
6314         }
6315
6316         os_memset(&ll, 0, sizeof(ll));
6317         ll.sll_family = AF_PACKET;
6318         ll.sll_ifindex = bss->ifindex;
6319         ll.sll_protocol = htons(ETH_P_PAE);
6320         ll.sll_halen = ETH_ALEN;
6321         os_memcpy(ll.sll_addr, addr, ETH_ALEN);
6322         ret = sendto(bss->drv->eapol_tx_sock, data, data_len, 0,
6323                      (struct sockaddr *) &ll, sizeof(ll));
6324         if (ret < 0)
6325                 wpa_printf(MSG_ERROR, "nl80211: EAPOL TX: %s",
6326                            strerror(errno));
6327
6328         return ret;
6329 }
6330
6331
6332 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
6333
6334 static int wpa_driver_nl80211_hapd_send_eapol(
6335         void *priv, const u8 *addr, const u8 *data,
6336         size_t data_len, int encrypt, const u8 *own_addr, u32 flags)
6337 {
6338         struct i802_bss *bss = priv;
6339         struct wpa_driver_nl80211_data *drv = bss->drv;
6340         struct ieee80211_hdr *hdr;
6341         size_t len;
6342         u8 *pos;
6343         int res;
6344         int qos = flags & WPA_STA_WMM;
6345
6346         if (drv->device_ap_sme || !drv->use_monitor)
6347                 return nl80211_send_eapol_data(bss, addr, data, data_len);
6348
6349         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
6350                 data_len;
6351         hdr = os_zalloc(len);
6352         if (hdr == NULL) {
6353                 printf("malloc() failed for i802_send_data(len=%lu)\n",
6354                        (unsigned long) len);
6355                 return -1;
6356         }
6357
6358         hdr->frame_control =
6359                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
6360         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
6361         if (encrypt)
6362                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
6363         if (qos) {
6364                 hdr->frame_control |=
6365                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
6366         }
6367
6368         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
6369         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
6370         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
6371         pos = (u8 *) (hdr + 1);
6372
6373         if (qos) {
6374                 /* add an empty QoS header if needed */
6375                 pos[0] = 0;
6376                 pos[1] = 0;
6377                 pos += 2;
6378         }
6379
6380         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
6381         pos += sizeof(rfc1042_header);
6382         WPA_PUT_BE16(pos, ETH_P_PAE);
6383         pos += 2;
6384         memcpy(pos, data, data_len);
6385
6386         res = wpa_driver_nl80211_send_frame(bss, (u8 *) hdr, len, encrypt, 0,
6387                                             0, 0, 0, 0);
6388         if (res < 0) {
6389                 wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
6390                            "failed: %d (%s)",
6391                            (unsigned long) len, errno, strerror(errno));
6392         }
6393         os_free(hdr);
6394
6395         return res;
6396 }
6397
6398
6399 static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
6400                                             int total_flags,
6401                                             int flags_or, int flags_and)
6402 {
6403         struct i802_bss *bss = priv;
6404         struct wpa_driver_nl80211_data *drv = bss->drv;
6405         struct nl_msg *msg, *flags = NULL;
6406         struct nl80211_sta_flag_update upd;
6407
6408         msg = nlmsg_alloc();
6409         if (!msg)
6410                 return -ENOMEM;
6411
6412         flags = nlmsg_alloc();
6413         if (!flags) {
6414                 nlmsg_free(msg);
6415                 return -ENOMEM;
6416         }
6417
6418         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
6419
6420         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
6421                     if_nametoindex(bss->ifname));
6422         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
6423
6424         /*
6425          * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
6426          * can be removed eventually.
6427          */
6428         if (total_flags & WPA_STA_AUTHORIZED)
6429                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
6430
6431         if (total_flags & WPA_STA_WMM)
6432                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
6433
6434         if (total_flags & WPA_STA_SHORT_PREAMBLE)
6435                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
6436
6437         if (total_flags & WPA_STA_MFP)
6438                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
6439
6440         if (total_flags & WPA_STA_TDLS_PEER)
6441                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_TDLS_PEER);
6442
6443         if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
6444                 goto nla_put_failure;
6445
6446         os_memset(&upd, 0, sizeof(upd));
6447         upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
6448         upd.set = sta_flags_nl80211(flags_or);
6449         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
6450
6451         nlmsg_free(flags);
6452
6453         return send_and_recv_msgs(drv, msg, NULL, NULL);
6454  nla_put_failure:
6455         nlmsg_free(msg);
6456         nlmsg_free(flags);
6457         return -ENOBUFS;
6458 }
6459
6460
6461 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
6462                                  struct wpa_driver_associate_params *params)
6463 {
6464         enum nl80211_iftype nlmode;
6465
6466         if (params->p2p) {
6467                 wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
6468                            "group (GO)");
6469                 nlmode = NL80211_IFTYPE_P2P_GO;
6470         } else
6471                 nlmode = NL80211_IFTYPE_AP;
6472
6473         if (wpa_driver_nl80211_set_mode(&drv->first_bss, nlmode) ||
6474             wpa_driver_nl80211_set_freq(&drv->first_bss, params->freq, 0, 0)) {
6475                 nl80211_remove_monitor_interface(drv);
6476                 return -1;
6477         }
6478
6479         return 0;
6480 }
6481
6482
6483 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
6484 {
6485         struct nl_msg *msg;
6486         int ret = -1;
6487
6488         msg = nlmsg_alloc();
6489         if (!msg)
6490                 return -1;
6491
6492         nl80211_cmd(drv, msg, 0, NL80211_CMD_LEAVE_IBSS);
6493         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6494         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6495         msg = NULL;
6496         if (ret) {
6497                 wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
6498                            "(%s)", ret, strerror(-ret));
6499                 goto nla_put_failure;
6500         }
6501
6502         ret = 0;
6503         wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
6504
6505 nla_put_failure:
6506         nlmsg_free(msg);
6507         return ret;
6508 }
6509
6510
6511 static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
6512                                    struct wpa_driver_associate_params *params)
6513 {
6514         struct nl_msg *msg;
6515         int ret = -1;
6516         int count = 0;
6517
6518         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
6519
6520         if (wpa_driver_nl80211_set_mode(&drv->first_bss,
6521                                         NL80211_IFTYPE_ADHOC)) {
6522                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
6523                            "IBSS mode");
6524                 return -1;
6525         }
6526
6527 retry:
6528         msg = nlmsg_alloc();
6529         if (!msg)
6530                 return -1;
6531
6532         nl80211_cmd(drv, msg, 0, NL80211_CMD_JOIN_IBSS);
6533         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6534
6535         if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
6536                 goto nla_put_failure;
6537
6538         wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6539                           params->ssid, params->ssid_len);
6540         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6541                 params->ssid);
6542         os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6543         drv->ssid_len = params->ssid_len;
6544
6545         wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6546         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6547
6548         ret = nl80211_set_conn_keys(params, msg);
6549         if (ret)
6550                 goto nla_put_failure;
6551
6552         if (params->bssid && params->fixed_bssid) {
6553                 wpa_printf(MSG_DEBUG, "  * BSSID=" MACSTR,
6554                            MAC2STR(params->bssid));
6555                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6556         }
6557
6558         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
6559             params->key_mgmt_suite == KEY_MGMT_PSK ||
6560             params->key_mgmt_suite == KEY_MGMT_802_1X_SHA256 ||
6561             params->key_mgmt_suite == KEY_MGMT_PSK_SHA256) {
6562                 wpa_printf(MSG_DEBUG, "  * control port");
6563                 NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
6564         }
6565
6566         if (params->wpa_ie) {
6567                 wpa_hexdump(MSG_DEBUG,
6568                             "  * Extra IEs for Beacon/Probe Response frames",
6569                             params->wpa_ie, params->wpa_ie_len);
6570                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6571                         params->wpa_ie);
6572         }
6573
6574         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6575         msg = NULL;
6576         if (ret) {
6577                 wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
6578                            ret, strerror(-ret));
6579                 count++;
6580                 if (ret == -EALREADY && count == 1) {
6581                         wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
6582                                    "forced leave");
6583                         nl80211_leave_ibss(drv);
6584                         nlmsg_free(msg);
6585                         goto retry;
6586                 }
6587
6588                 goto nla_put_failure;
6589         }
6590         ret = 0;
6591         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
6592
6593 nla_put_failure:
6594         nlmsg_free(msg);
6595         return ret;
6596 }
6597
6598
6599 static unsigned int nl80211_get_assoc_bssid(struct wpa_driver_nl80211_data *drv,
6600                                             u8 *bssid)
6601 {
6602         struct nl_msg *msg;
6603         int ret;
6604         struct nl80211_bss_info_arg arg;
6605
6606         os_memset(&arg, 0, sizeof(arg));
6607         msg = nlmsg_alloc();
6608         if (!msg)
6609                 goto nla_put_failure;
6610
6611         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
6612         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6613
6614         arg.drv = drv;
6615         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
6616         msg = NULL;
6617         if (ret == 0) {
6618                 if (is_zero_ether_addr(arg.assoc_bssid))
6619                         return -ENOTCONN;
6620                 os_memcpy(bssid, arg.assoc_bssid, ETH_ALEN);
6621                 return 0;
6622         }
6623         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
6624                    "(%s)", ret, strerror(-ret));
6625 nla_put_failure:
6626         nlmsg_free(msg);
6627         return drv->assoc_freq;
6628 }
6629
6630
6631 static int nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
6632                               const u8 *bssid)
6633 {
6634         u8 addr[ETH_ALEN];
6635
6636         if (bssid == NULL) {
6637                 int res = nl80211_get_assoc_bssid(drv, addr);
6638                 if (res)
6639                         return res;
6640                 bssid = addr;
6641         }
6642
6643         return wpa_driver_nl80211_disconnect(drv, bssid,
6644                                              WLAN_REASON_PREV_AUTH_NOT_VALID);
6645 }
6646
6647
6648 static int wpa_driver_nl80211_connect(
6649         struct wpa_driver_nl80211_data *drv,
6650         struct wpa_driver_associate_params *params)
6651 {
6652         struct nl_msg *msg;
6653         enum nl80211_auth_type type;
6654         int ret = 0;
6655         int algs;
6656
6657         msg = nlmsg_alloc();
6658         if (!msg)
6659                 return -1;
6660
6661         wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
6662         nl80211_cmd(drv, msg, 0, NL80211_CMD_CONNECT);
6663
6664         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6665         if (params->bssid) {
6666                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
6667                            MAC2STR(params->bssid));
6668                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6669         }
6670         if (params->freq) {
6671                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6672                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6673         }
6674         if (params->bg_scan_period >= 0) {
6675                 wpa_printf(MSG_DEBUG, "  * bg scan period=%d",
6676                            params->bg_scan_period);
6677                 NLA_PUT_U16(msg, NL80211_ATTR_BG_SCAN_PERIOD,
6678                             params->bg_scan_period);
6679         }
6680         if (params->ssid) {
6681                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6682                                   params->ssid, params->ssid_len);
6683                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6684                         params->ssid);
6685                 if (params->ssid_len > sizeof(drv->ssid))
6686                         goto nla_put_failure;
6687                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6688                 drv->ssid_len = params->ssid_len;
6689         }
6690         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
6691         if (params->wpa_ie)
6692                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6693                         params->wpa_ie);
6694
6695         algs = 0;
6696         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
6697                 algs++;
6698         if (params->auth_alg & WPA_AUTH_ALG_SHARED)
6699                 algs++;
6700         if (params->auth_alg & WPA_AUTH_ALG_LEAP)
6701                 algs++;
6702         if (algs > 1) {
6703                 wpa_printf(MSG_DEBUG, "  * Leave out Auth Type for automatic "
6704                            "selection");
6705                 goto skip_auth_type;
6706         }
6707
6708         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
6709                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
6710         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
6711                 type = NL80211_AUTHTYPE_SHARED_KEY;
6712         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
6713                 type = NL80211_AUTHTYPE_NETWORK_EAP;
6714         else if (params->auth_alg & WPA_AUTH_ALG_FT)
6715                 type = NL80211_AUTHTYPE_FT;
6716         else
6717                 goto nla_put_failure;
6718
6719         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
6720         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
6721
6722 skip_auth_type:
6723         if (params->wpa_proto) {
6724                 enum nl80211_wpa_versions ver = 0;
6725
6726                 if (params->wpa_proto & WPA_PROTO_WPA)
6727                         ver |= NL80211_WPA_VERSION_1;
6728                 if (params->wpa_proto & WPA_PROTO_RSN)
6729                         ver |= NL80211_WPA_VERSION_2;
6730
6731                 wpa_printf(MSG_DEBUG, "  * WPA Versions 0x%x", ver);
6732                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
6733         }
6734
6735         if (params->pairwise_suite != CIPHER_NONE) {
6736                 int cipher;
6737
6738                 switch (params->pairwise_suite) {
6739                 case CIPHER_WEP40:
6740                         cipher = WLAN_CIPHER_SUITE_WEP40;
6741                         break;
6742                 case CIPHER_WEP104:
6743                         cipher = WLAN_CIPHER_SUITE_WEP104;
6744                         break;
6745                 case CIPHER_CCMP:
6746                         cipher = WLAN_CIPHER_SUITE_CCMP;
6747                         break;
6748                 case CIPHER_TKIP:
6749                 default:
6750                         cipher = WLAN_CIPHER_SUITE_TKIP;
6751                         break;
6752                 }
6753                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
6754         }
6755
6756         if (params->group_suite != CIPHER_NONE) {
6757                 int cipher;
6758
6759                 switch (params->group_suite) {
6760                 case CIPHER_WEP40:
6761                         cipher = WLAN_CIPHER_SUITE_WEP40;
6762                         break;
6763                 case CIPHER_WEP104:
6764                         cipher = WLAN_CIPHER_SUITE_WEP104;
6765                         break;
6766                 case CIPHER_CCMP:
6767                         cipher = WLAN_CIPHER_SUITE_CCMP;
6768                         break;
6769                 case CIPHER_TKIP:
6770                 default:
6771                         cipher = WLAN_CIPHER_SUITE_TKIP;
6772                         break;
6773                 }
6774                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
6775         }
6776
6777         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
6778             params->key_mgmt_suite == KEY_MGMT_PSK) {
6779                 int mgmt = WLAN_AKM_SUITE_PSK;
6780
6781                 switch (params->key_mgmt_suite) {
6782                 case KEY_MGMT_802_1X:
6783                         mgmt = WLAN_AKM_SUITE_8021X;
6784                         break;
6785                 case KEY_MGMT_PSK:
6786                 default:
6787                         mgmt = WLAN_AKM_SUITE_PSK;
6788                         break;
6789                 }
6790                 NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
6791         }
6792
6793         if (params->disable_ht)
6794                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
6795
6796         if (params->htcaps && params->htcaps_mask) {
6797                 int sz = sizeof(struct ieee80211_ht_capabilities);
6798                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
6799                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
6800                         params->htcaps_mask);
6801         }
6802
6803         ret = nl80211_set_conn_keys(params, msg);
6804         if (ret)
6805                 goto nla_put_failure;
6806
6807         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6808         msg = NULL;
6809         if (ret) {
6810                 wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
6811                            "(%s)", ret, strerror(-ret));
6812                 /*
6813                  * cfg80211 does not currently accept new connection if we are
6814                  * already connected. As a workaround, force disconnection and
6815                  * try again once the driver indicates it completed
6816                  * disconnection.
6817                  */
6818                 if (ret == -EALREADY)
6819                         nl80211_disconnect(drv, params->bssid);
6820                 goto nla_put_failure;
6821         }
6822         ret = 0;
6823         wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
6824
6825 nla_put_failure:
6826         nlmsg_free(msg);
6827         return ret;
6828
6829 }
6830
6831
6832 static int wpa_driver_nl80211_associate(
6833         void *priv, struct wpa_driver_associate_params *params)
6834 {
6835         struct i802_bss *bss = priv;
6836         struct wpa_driver_nl80211_data *drv = bss->drv;
6837         int ret = -1;
6838         struct nl_msg *msg;
6839
6840         if (params->mode == IEEE80211_MODE_AP)
6841                 return wpa_driver_nl80211_ap(drv, params);
6842
6843         if (params->mode == IEEE80211_MODE_IBSS)
6844                 return wpa_driver_nl80211_ibss(drv, params);
6845
6846         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
6847                 enum nl80211_iftype nlmode = params->p2p ?
6848                         NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
6849
6850                 if (wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
6851                         return -1;
6852                 return wpa_driver_nl80211_connect(drv, params);
6853         }
6854
6855         drv->associated = 0;
6856
6857         msg = nlmsg_alloc();
6858         if (!msg)
6859                 return -1;
6860
6861         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
6862                    drv->ifindex);
6863         nl80211_cmd(drv, msg, 0, NL80211_CMD_ASSOCIATE);
6864
6865         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6866         if (params->bssid) {
6867                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
6868                            MAC2STR(params->bssid));
6869                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
6870         }
6871         if (params->freq) {
6872                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
6873                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
6874                 drv->assoc_freq = params->freq;
6875         } else
6876                 drv->assoc_freq = 0;
6877         if (params->bg_scan_period >= 0) {
6878                 wpa_printf(MSG_DEBUG, "  * bg scan period=%d",
6879                            params->bg_scan_period);
6880                 NLA_PUT_U16(msg, NL80211_ATTR_BG_SCAN_PERIOD,
6881                             params->bg_scan_period);
6882         }
6883         if (params->ssid) {
6884                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
6885                                   params->ssid, params->ssid_len);
6886                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
6887                         params->ssid);
6888                 if (params->ssid_len > sizeof(drv->ssid))
6889                         goto nla_put_failure;
6890                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
6891                 drv->ssid_len = params->ssid_len;
6892         }
6893         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
6894         if (params->wpa_ie)
6895                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
6896                         params->wpa_ie);
6897
6898         if (params->pairwise_suite != CIPHER_NONE) {
6899                 int cipher;
6900
6901                 switch (params->pairwise_suite) {
6902                 case CIPHER_WEP40:
6903                         cipher = WLAN_CIPHER_SUITE_WEP40;
6904                         break;
6905                 case CIPHER_WEP104:
6906                         cipher = WLAN_CIPHER_SUITE_WEP104;
6907                         break;
6908                 case CIPHER_CCMP:
6909                         cipher = WLAN_CIPHER_SUITE_CCMP;
6910                         break;
6911                 case CIPHER_TKIP:
6912                 default:
6913                         cipher = WLAN_CIPHER_SUITE_TKIP;
6914                         break;
6915                 }
6916                 wpa_printf(MSG_DEBUG, "  * pairwise=0x%x", cipher);
6917                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
6918         }
6919
6920         if (params->group_suite != CIPHER_NONE) {
6921                 int cipher;
6922
6923                 switch (params->group_suite) {
6924                 case CIPHER_WEP40:
6925                         cipher = WLAN_CIPHER_SUITE_WEP40;
6926                         break;
6927                 case CIPHER_WEP104:
6928                         cipher = WLAN_CIPHER_SUITE_WEP104;
6929                         break;
6930                 case CIPHER_CCMP:
6931                         cipher = WLAN_CIPHER_SUITE_CCMP;
6932                         break;
6933                 case CIPHER_TKIP:
6934                 default:
6935                         cipher = WLAN_CIPHER_SUITE_TKIP;
6936                         break;
6937                 }
6938                 wpa_printf(MSG_DEBUG, "  * group=0x%x", cipher);
6939                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
6940         }
6941
6942 #ifdef CONFIG_IEEE80211W
6943         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
6944                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
6945 #endif /* CONFIG_IEEE80211W */
6946
6947         NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
6948
6949         if (params->prev_bssid) {
6950                 wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
6951                            MAC2STR(params->prev_bssid));
6952                 NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
6953                         params->prev_bssid);
6954         }
6955
6956         if (params->disable_ht)
6957                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
6958
6959         if (params->htcaps && params->htcaps_mask) {
6960                 int sz = sizeof(struct ieee80211_ht_capabilities);
6961                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
6962                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
6963                         params->htcaps_mask);
6964         }
6965
6966         if (params->p2p)
6967                 wpa_printf(MSG_DEBUG, "  * P2P group");
6968
6969         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6970         msg = NULL;
6971         if (ret) {
6972                 wpa_dbg(drv->ctx, MSG_DEBUG,
6973                         "nl80211: MLME command failed (assoc): ret=%d (%s)",
6974                         ret, strerror(-ret));
6975                 nl80211_dump_scan(drv);
6976                 goto nla_put_failure;
6977         }
6978         ret = 0;
6979         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
6980                    "successfully");
6981
6982 nla_put_failure:
6983         nlmsg_free(msg);
6984         return ret;
6985 }
6986
6987
6988 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
6989                             int ifindex, enum nl80211_iftype mode)
6990 {
6991         struct nl_msg *msg;
6992         int ret = -ENOBUFS;
6993
6994         wpa_printf(MSG_DEBUG, "nl80211: Set mode ifindex %d iftype %d (%s)",
6995                    ifindex, mode, nl80211_iftype_str(mode));
6996
6997         msg = nlmsg_alloc();
6998         if (!msg)
6999                 return -ENOMEM;
7000
7001         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_INTERFACE);
7002         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
7003         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
7004
7005         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7006         msg = NULL;
7007         if (!ret)
7008                 return 0;
7009 nla_put_failure:
7010         nlmsg_free(msg);
7011         wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
7012                    " %d (%s)", ifindex, mode, ret, strerror(-ret));
7013         return ret;
7014 }
7015
7016
7017 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
7018                                        enum nl80211_iftype nlmode)
7019 {
7020         struct wpa_driver_nl80211_data *drv = bss->drv;
7021         int ret = -1;
7022         int i;
7023         int was_ap = is_ap_interface(drv->nlmode);
7024         int res;
7025
7026         res = nl80211_set_mode(drv, drv->ifindex, nlmode);
7027         if (res == 0) {
7028                 drv->nlmode = nlmode;
7029                 ret = 0;
7030                 goto done;
7031         }
7032
7033         if (res == -ENODEV)
7034                 return -1;
7035
7036         if (nlmode == drv->nlmode) {
7037                 wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
7038                            "requested mode - ignore error");
7039                 ret = 0;
7040                 goto done; /* Already in the requested mode */
7041         }
7042
7043         /* mac80211 doesn't allow mode changes while the device is up, so
7044          * take the device down, try to set the mode again, and bring the
7045          * device back up.
7046          */
7047         wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
7048                    "interface down");
7049         for (i = 0; i < 10; i++) {
7050                 res = linux_set_iface_flags(drv->global->ioctl_sock,
7051                                             bss->ifname, 0);
7052                 if (res == -EACCES || res == -ENODEV)
7053                         break;
7054                 if (res == 0) {
7055                         /* Try to set the mode again while the interface is
7056                          * down */
7057                         ret = nl80211_set_mode(drv, drv->ifindex, nlmode);
7058                         if (ret == -EACCES)
7059                                 break;
7060                         res = linux_set_iface_flags(drv->global->ioctl_sock,
7061                                                     bss->ifname, 1);
7062                         if (res && !ret)
7063                                 ret = -1;
7064                         else if (ret != -EBUSY)
7065                                 break;
7066                 } else
7067                         wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
7068                                    "interface down");
7069                 os_sleep(0, 100000);
7070         }
7071
7072         if (!ret) {
7073                 wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
7074                            "interface is down");
7075                 drv->nlmode = nlmode;
7076                 drv->ignore_if_down_event = 1;
7077         }
7078
7079 done:
7080         if (ret) {
7081                 wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
7082                            "from %d failed", nlmode, drv->nlmode);
7083                 return ret;
7084         }
7085
7086         if (is_ap_interface(nlmode)) {
7087                 nl80211_mgmt_unsubscribe(bss, "start AP");
7088                 /* Setup additional AP mode functionality if needed */
7089                 if (nl80211_setup_ap(bss))
7090                         return -1;
7091         } else if (was_ap) {
7092                 /* Remove additional AP mode functionality */
7093                 nl80211_teardown_ap(bss);
7094         } else {
7095                 nl80211_mgmt_unsubscribe(bss, "mode change");
7096         }
7097
7098         if (!bss->in_deinit && !is_ap_interface(nlmode) &&
7099             nl80211_mgmt_subscribe_non_ap(bss) < 0)
7100                 wpa_printf(MSG_DEBUG, "nl80211: Failed to register Action "
7101                            "frame processing - ignore for now");
7102
7103         return 0;
7104 }
7105
7106
7107 static int wpa_driver_nl80211_get_capa(void *priv,
7108                                        struct wpa_driver_capa *capa)
7109 {
7110         struct i802_bss *bss = priv;
7111         struct wpa_driver_nl80211_data *drv = bss->drv;
7112         if (!drv->has_capability)
7113                 return -1;
7114         os_memcpy(capa, &drv->capa, sizeof(*capa));
7115         return 0;
7116 }
7117
7118
7119 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
7120 {
7121         struct i802_bss *bss = priv;
7122         struct wpa_driver_nl80211_data *drv = bss->drv;
7123
7124         wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
7125                    __func__, drv->operstate, state, state ? "UP" : "DORMANT");
7126         drv->operstate = state;
7127         return netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, -1,
7128                                       state ? IF_OPER_UP : IF_OPER_DORMANT);
7129 }
7130
7131
7132 static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
7133 {
7134         struct i802_bss *bss = priv;
7135         struct wpa_driver_nl80211_data *drv = bss->drv;
7136         struct nl_msg *msg;
7137         struct nl80211_sta_flag_update upd;
7138
7139         msg = nlmsg_alloc();
7140         if (!msg)
7141                 return -ENOMEM;
7142
7143         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
7144
7145         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7146                     if_nametoindex(bss->ifname));
7147         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
7148
7149         os_memset(&upd, 0, sizeof(upd));
7150         upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
7151         if (authorized)
7152                 upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
7153         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
7154
7155         return send_and_recv_msgs(drv, msg, NULL, NULL);
7156  nla_put_failure:
7157         nlmsg_free(msg);
7158         return -ENOBUFS;
7159 }
7160
7161
7162 /* Set kernel driver on given frequency (MHz) */
7163 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
7164 {
7165         struct i802_bss *bss = priv;
7166         return wpa_driver_nl80211_set_freq(bss, freq->freq, freq->ht_enabled,
7167                                            freq->sec_channel_offset);
7168 }
7169
7170
7171 #if defined(HOSTAPD) || defined(CONFIG_AP)
7172
7173 static inline int min_int(int a, int b)
7174 {
7175         if (a < b)
7176                 return a;
7177         return b;
7178 }
7179
7180
7181 static int get_key_handler(struct nl_msg *msg, void *arg)
7182 {
7183         struct nlattr *tb[NL80211_ATTR_MAX + 1];
7184         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7185
7186         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7187                   genlmsg_attrlen(gnlh, 0), NULL);
7188
7189         /*
7190          * TODO: validate the key index and mac address!
7191          * Otherwise, there's a race condition as soon as
7192          * the kernel starts sending key notifications.
7193          */
7194
7195         if (tb[NL80211_ATTR_KEY_SEQ])
7196                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
7197                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
7198         return NL_SKIP;
7199 }
7200
7201
7202 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
7203                            int idx, u8 *seq)
7204 {
7205         struct i802_bss *bss = priv;
7206         struct wpa_driver_nl80211_data *drv = bss->drv;
7207         struct nl_msg *msg;
7208
7209         msg = nlmsg_alloc();
7210         if (!msg)
7211                 return -ENOMEM;
7212
7213         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_KEY);
7214
7215         if (addr)
7216                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7217         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
7218         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
7219
7220         memset(seq, 0, 6);
7221
7222         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
7223  nla_put_failure:
7224         nlmsg_free(msg);
7225         return -ENOBUFS;
7226 }
7227
7228
7229 static int i802_set_rts(void *priv, int rts)
7230 {
7231         struct i802_bss *bss = priv;
7232         struct wpa_driver_nl80211_data *drv = bss->drv;
7233         struct nl_msg *msg;
7234         int ret = -ENOBUFS;
7235         u32 val;
7236
7237         msg = nlmsg_alloc();
7238         if (!msg)
7239                 return -ENOMEM;
7240
7241         if (rts >= 2347)
7242                 val = (u32) -1;
7243         else
7244                 val = rts;
7245
7246         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7247         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7248         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
7249
7250         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7251         msg = NULL;
7252         if (!ret)
7253                 return 0;
7254 nla_put_failure:
7255         nlmsg_free(msg);
7256         wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
7257                    "%d (%s)", rts, ret, strerror(-ret));
7258         return ret;
7259 }
7260
7261
7262 static int i802_set_frag(void *priv, int frag)
7263 {
7264         struct i802_bss *bss = priv;
7265         struct wpa_driver_nl80211_data *drv = bss->drv;
7266         struct nl_msg *msg;
7267         int ret = -ENOBUFS;
7268         u32 val;
7269
7270         msg = nlmsg_alloc();
7271         if (!msg)
7272                 return -ENOMEM;
7273
7274         if (frag >= 2346)
7275                 val = (u32) -1;
7276         else
7277                 val = frag;
7278
7279         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7280         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7281         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
7282
7283         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7284         msg = NULL;
7285         if (!ret)
7286                 return 0;
7287 nla_put_failure:
7288         nlmsg_free(msg);
7289         wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
7290                    "%d: %d (%s)", frag, ret, strerror(-ret));
7291         return ret;
7292 }
7293
7294
7295 static int i802_flush(void *priv)
7296 {
7297         struct i802_bss *bss = priv;
7298         struct wpa_driver_nl80211_data *drv = bss->drv;
7299         struct nl_msg *msg;
7300         int res;
7301
7302         msg = nlmsg_alloc();
7303         if (!msg)
7304                 return -1;
7305
7306         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
7307
7308         /*
7309          * XXX: FIX! this needs to flush all VLANs too
7310          */
7311         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7312                     if_nametoindex(bss->ifname));
7313
7314         res = send_and_recv_msgs(drv, msg, NULL, NULL);
7315         if (res) {
7316                 wpa_printf(MSG_DEBUG, "nl80211: Station flush failed: ret=%d "
7317                            "(%s)", res, strerror(-res));
7318         }
7319         return res;
7320  nla_put_failure:
7321         nlmsg_free(msg);
7322         return -ENOBUFS;
7323 }
7324
7325
7326 static int get_sta_handler(struct nl_msg *msg, void *arg)
7327 {
7328         struct nlattr *tb[NL80211_ATTR_MAX + 1];
7329         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7330         struct hostap_sta_driver_data *data = arg;
7331         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
7332         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
7333                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
7334                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
7335                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
7336                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
7337                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
7338         };
7339
7340         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7341                   genlmsg_attrlen(gnlh, 0), NULL);
7342
7343         /*
7344          * TODO: validate the interface and mac address!
7345          * Otherwise, there's a race condition as soon as
7346          * the kernel starts sending station notifications.
7347          */
7348
7349         if (!tb[NL80211_ATTR_STA_INFO]) {
7350                 wpa_printf(MSG_DEBUG, "sta stats missing!");
7351                 return NL_SKIP;
7352         }
7353         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
7354                              tb[NL80211_ATTR_STA_INFO],
7355                              stats_policy)) {
7356                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
7357                 return NL_SKIP;
7358         }
7359
7360         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
7361                 data->inactive_msec =
7362                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
7363         if (stats[NL80211_STA_INFO_RX_BYTES])
7364                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
7365         if (stats[NL80211_STA_INFO_TX_BYTES])
7366                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
7367         if (stats[NL80211_STA_INFO_RX_PACKETS])
7368                 data->rx_packets =
7369                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
7370         if (stats[NL80211_STA_INFO_TX_PACKETS])
7371                 data->tx_packets =
7372                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
7373
7374         return NL_SKIP;
7375 }
7376
7377 static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
7378                               const u8 *addr)
7379 {
7380         struct i802_bss *bss = priv;
7381         struct wpa_driver_nl80211_data *drv = bss->drv;
7382         struct nl_msg *msg;
7383
7384         os_memset(data, 0, sizeof(*data));
7385         msg = nlmsg_alloc();
7386         if (!msg)
7387                 return -ENOMEM;
7388
7389         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
7390
7391         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7392         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7393
7394         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
7395  nla_put_failure:
7396         nlmsg_free(msg);
7397         return -ENOBUFS;
7398 }
7399
7400
7401 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
7402                                     int cw_min, int cw_max, int burst_time)
7403 {
7404         struct i802_bss *bss = priv;
7405         struct wpa_driver_nl80211_data *drv = bss->drv;
7406         struct nl_msg *msg;
7407         struct nlattr *txq, *params;
7408
7409         msg = nlmsg_alloc();
7410         if (!msg)
7411                 return -1;
7412
7413         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7414
7415         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7416
7417         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
7418         if (!txq)
7419                 goto nla_put_failure;
7420
7421         /* We are only sending parameters for a single TXQ at a time */
7422         params = nla_nest_start(msg, 1);
7423         if (!params)
7424                 goto nla_put_failure;
7425
7426         switch (queue) {
7427         case 0:
7428                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
7429                 break;
7430         case 1:
7431                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
7432                 break;
7433         case 2:
7434                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
7435                 break;
7436         case 3:
7437                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
7438                 break;
7439         }
7440         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
7441          * 32 usec, so need to convert the value here. */
7442         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
7443         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
7444         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
7445         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
7446
7447         nla_nest_end(msg, params);
7448
7449         nla_nest_end(msg, txq);
7450
7451         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
7452                 return 0;
7453         msg = NULL;
7454  nla_put_failure:
7455         nlmsg_free(msg);
7456         return -1;
7457 }
7458
7459
7460 static int i802_set_sta_vlan(void *priv, const u8 *addr,
7461                              const char *ifname, int vlan_id)
7462 {
7463         struct i802_bss *bss = priv;
7464         struct wpa_driver_nl80211_data *drv = bss->drv;
7465         struct nl_msg *msg;
7466         int ret = -ENOBUFS;
7467
7468         msg = nlmsg_alloc();
7469         if (!msg)
7470                 return -ENOMEM;
7471
7472         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
7473
7474         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7475                     if_nametoindex(bss->ifname));
7476         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7477         NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
7478                     if_nametoindex(ifname));
7479
7480         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7481         msg = NULL;
7482         if (ret < 0) {
7483                 wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
7484                            MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
7485                            MAC2STR(addr), ifname, vlan_id, ret,
7486                            strerror(-ret));
7487         }
7488  nla_put_failure:
7489         nlmsg_free(msg);
7490         return ret;
7491 }
7492
7493
7494 static int i802_get_inact_sec(void *priv, const u8 *addr)
7495 {
7496         struct hostap_sta_driver_data data;
7497         int ret;
7498
7499         data.inactive_msec = (unsigned long) -1;
7500         ret = i802_read_sta_data(priv, &data, addr);
7501         if (ret || data.inactive_msec == (unsigned long) -1)
7502                 return -1;
7503         return data.inactive_msec / 1000;
7504 }
7505
7506
7507 static int i802_sta_clear_stats(void *priv, const u8 *addr)
7508 {
7509 #if 0
7510         /* TODO */
7511 #endif
7512         return 0;
7513 }
7514
7515
7516 static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
7517                            int reason)
7518 {
7519         struct i802_bss *bss = priv;
7520         struct wpa_driver_nl80211_data *drv = bss->drv;
7521         struct ieee80211_mgmt mgmt;
7522
7523         if (drv->device_ap_sme)
7524                 return wpa_driver_nl80211_sta_remove(bss, addr);
7525
7526         memset(&mgmt, 0, sizeof(mgmt));
7527         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
7528                                           WLAN_FC_STYPE_DEAUTH);
7529         memcpy(mgmt.da, addr, ETH_ALEN);
7530         memcpy(mgmt.sa, own_addr, ETH_ALEN);
7531         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
7532         mgmt.u.deauth.reason_code = host_to_le16(reason);
7533         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
7534                                             IEEE80211_HDRLEN +
7535                                             sizeof(mgmt.u.deauth), 0);
7536 }
7537
7538
7539 static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
7540                              int reason)
7541 {
7542         struct i802_bss *bss = priv;
7543         struct wpa_driver_nl80211_data *drv = bss->drv;
7544         struct ieee80211_mgmt mgmt;
7545
7546         if (drv->device_ap_sme)
7547                 return wpa_driver_nl80211_sta_remove(bss, addr);
7548
7549         memset(&mgmt, 0, sizeof(mgmt));
7550         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
7551                                           WLAN_FC_STYPE_DISASSOC);
7552         memcpy(mgmt.da, addr, ETH_ALEN);
7553         memcpy(mgmt.sa, own_addr, ETH_ALEN);
7554         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
7555         mgmt.u.disassoc.reason_code = host_to_le16(reason);
7556         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
7557                                             IEEE80211_HDRLEN +
7558                                             sizeof(mgmt.u.disassoc), 0);
7559 }
7560
7561 #endif /* HOSTAPD || CONFIG_AP */
7562
7563 #ifdef HOSTAPD
7564
7565 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7566 {
7567         int i;
7568         int *old;
7569
7570         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
7571                    ifidx);
7572         for (i = 0; i < drv->num_if_indices; i++) {
7573                 if (drv->if_indices[i] == 0) {
7574                         drv->if_indices[i] = ifidx;
7575                         return;
7576                 }
7577         }
7578
7579         if (drv->if_indices != drv->default_if_indices)
7580                 old = drv->if_indices;
7581         else
7582                 old = NULL;
7583
7584         drv->if_indices = os_realloc(old,
7585                                      sizeof(int) * (drv->num_if_indices + 1));
7586         if (!drv->if_indices) {
7587                 if (!old)
7588                         drv->if_indices = drv->default_if_indices;
7589                 else
7590                         drv->if_indices = old;
7591                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
7592                            "interfaces");
7593                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
7594                 return;
7595         } else if (!old)
7596                 os_memcpy(drv->if_indices, drv->default_if_indices,
7597                           sizeof(drv->default_if_indices));
7598         drv->if_indices[drv->num_if_indices] = ifidx;
7599         drv->num_if_indices++;
7600 }
7601
7602
7603 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7604 {
7605         int i;
7606
7607         for (i = 0; i < drv->num_if_indices; i++) {
7608                 if (drv->if_indices[i] == ifidx) {
7609                         drv->if_indices[i] = 0;
7610                         break;
7611                 }
7612         }
7613 }
7614
7615
7616 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
7617 {
7618         int i;
7619
7620         for (i = 0; i < drv->num_if_indices; i++)
7621                 if (drv->if_indices[i] == ifidx)
7622                         return 1;
7623
7624         return 0;
7625 }
7626
7627
7628 static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
7629                             const char *bridge_ifname)
7630 {
7631         struct i802_bss *bss = priv;
7632         struct wpa_driver_nl80211_data *drv = bss->drv;
7633         char name[IFNAMSIZ + 1];
7634
7635         os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
7636         wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
7637                    " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
7638         if (val) {
7639                 if (!if_nametoindex(name)) {
7640                         if (nl80211_create_iface(drv, name,
7641                                                  NL80211_IFTYPE_AP_VLAN,
7642                                                  NULL, 1) < 0)
7643                                 return -1;
7644                         if (bridge_ifname &&
7645                             linux_br_add_if(drv->global->ioctl_sock,
7646                                             bridge_ifname, name) < 0)
7647                                 return -1;
7648                 }
7649                 linux_set_iface_flags(drv->global->ioctl_sock, name, 1);
7650                 return i802_set_sta_vlan(priv, addr, name, 0);
7651         } else {
7652                 i802_set_sta_vlan(priv, addr, bss->ifname, 0);
7653                 return wpa_driver_nl80211_if_remove(priv, WPA_IF_AP_VLAN,
7654                                                     name);
7655         }
7656 }
7657
7658
7659 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
7660 {
7661         struct wpa_driver_nl80211_data *drv = eloop_ctx;
7662         struct sockaddr_ll lladdr;
7663         unsigned char buf[3000];
7664         int len;
7665         socklen_t fromlen = sizeof(lladdr);
7666
7667         len = recvfrom(sock, buf, sizeof(buf), 0,
7668                        (struct sockaddr *)&lladdr, &fromlen);
7669         if (len < 0) {
7670                 perror("recv");
7671                 return;
7672         }
7673
7674         if (have_ifidx(drv, lladdr.sll_ifindex))
7675                 drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
7676 }
7677
7678
7679 static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
7680                              struct i802_bss *bss,
7681                              const char *brname, const char *ifname)
7682 {
7683         int ifindex;
7684         char in_br[IFNAMSIZ];
7685
7686         os_strlcpy(bss->brname, brname, IFNAMSIZ);
7687         ifindex = if_nametoindex(brname);
7688         if (ifindex == 0) {
7689                 /*
7690                  * Bridge was configured, but the bridge device does
7691                  * not exist. Try to add it now.
7692                  */
7693                 if (linux_br_add(drv->global->ioctl_sock, brname) < 0) {
7694                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
7695                                    "bridge interface %s: %s",
7696                                    brname, strerror(errno));
7697                         return -1;
7698                 }
7699                 bss->added_bridge = 1;
7700                 add_ifidx(drv, if_nametoindex(brname));
7701         }
7702
7703         if (linux_br_get(in_br, ifname) == 0) {
7704                 if (os_strcmp(in_br, brname) == 0)
7705                         return 0; /* already in the bridge */
7706
7707                 wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
7708                            "bridge %s", ifname, in_br);
7709                 if (linux_br_del_if(drv->global->ioctl_sock, in_br, ifname) <
7710                     0) {
7711                         wpa_printf(MSG_ERROR, "nl80211: Failed to "
7712                                    "remove interface %s from bridge "
7713                                    "%s: %s",
7714                                    ifname, brname, strerror(errno));
7715                         return -1;
7716                 }
7717         }
7718
7719         wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
7720                    ifname, brname);
7721         if (linux_br_add_if(drv->global->ioctl_sock, brname, ifname) < 0) {
7722                 wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
7723                            "into bridge %s: %s",
7724                            ifname, brname, strerror(errno));
7725                 return -1;
7726         }
7727         bss->added_if_into_bridge = 1;
7728
7729         return 0;
7730 }
7731
7732
7733 static void *i802_init(struct hostapd_data *hapd,
7734                        struct wpa_init_params *params)
7735 {
7736         struct wpa_driver_nl80211_data *drv;
7737         struct i802_bss *bss;
7738         size_t i;
7739         char brname[IFNAMSIZ];
7740         int ifindex, br_ifindex;
7741         int br_added = 0;
7742
7743         bss = wpa_driver_nl80211_init(hapd, params->ifname,
7744                                       params->global_priv);
7745         if (bss == NULL)
7746                 return NULL;
7747
7748         drv = bss->drv;
7749         drv->nlmode = NL80211_IFTYPE_AP;
7750         drv->eapol_sock = -1;
7751
7752         if (linux_br_get(brname, params->ifname) == 0) {
7753                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
7754                            params->ifname, brname);
7755                 br_ifindex = if_nametoindex(brname);
7756         } else {
7757                 brname[0] = '\0';
7758                 br_ifindex = 0;
7759         }
7760
7761         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
7762         drv->if_indices = drv->default_if_indices;
7763         for (i = 0; i < params->num_bridge; i++) {
7764                 if (params->bridge[i]) {
7765                         ifindex = if_nametoindex(params->bridge[i]);
7766                         if (ifindex)
7767                                 add_ifidx(drv, ifindex);
7768                         if (ifindex == br_ifindex)
7769                                 br_added = 1;
7770                 }
7771         }
7772         if (!br_added && br_ifindex &&
7773             (params->num_bridge == 0 || !params->bridge[0]))
7774                 add_ifidx(drv, br_ifindex);
7775
7776         /* start listening for EAPOL on the default AP interface */
7777         add_ifidx(drv, drv->ifindex);
7778
7779         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0))
7780                 goto failed;
7781
7782         if (params->bssid) {
7783                 if (linux_set_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7784                                        params->bssid))
7785                         goto failed;
7786         }
7787
7788         if (wpa_driver_nl80211_set_mode(bss, drv->nlmode)) {
7789                 wpa_printf(MSG_ERROR, "nl80211: Failed to set interface %s "
7790                            "into AP mode", bss->ifname);
7791                 goto failed;
7792         }
7793
7794         if (params->num_bridge && params->bridge[0] &&
7795             i802_check_bridge(drv, bss, params->bridge[0], params->ifname) < 0)
7796                 goto failed;
7797
7798         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1))
7799                 goto failed;
7800
7801         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
7802         if (drv->eapol_sock < 0) {
7803                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
7804                 goto failed;
7805         }
7806
7807         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
7808         {
7809                 printf("Could not register read socket for eapol\n");
7810                 goto failed;
7811         }
7812
7813         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7814                                params->own_addr))
7815                 goto failed;
7816
7817         memcpy(bss->addr, params->own_addr, ETH_ALEN);
7818
7819         return bss;
7820
7821 failed:
7822         wpa_driver_nl80211_deinit(bss);
7823         return NULL;
7824 }
7825
7826
7827 static void i802_deinit(void *priv)
7828 {
7829         wpa_driver_nl80211_deinit(priv);
7830 }
7831
7832 #endif /* HOSTAPD */
7833
7834
7835 static enum nl80211_iftype wpa_driver_nl80211_if_type(
7836         enum wpa_driver_if_type type)
7837 {
7838         switch (type) {
7839         case WPA_IF_STATION:
7840                 return NL80211_IFTYPE_STATION;
7841         case WPA_IF_P2P_CLIENT:
7842         case WPA_IF_P2P_GROUP:
7843                 return NL80211_IFTYPE_P2P_CLIENT;
7844         case WPA_IF_AP_VLAN:
7845                 return NL80211_IFTYPE_AP_VLAN;
7846         case WPA_IF_AP_BSS:
7847                 return NL80211_IFTYPE_AP;
7848         case WPA_IF_P2P_GO:
7849                 return NL80211_IFTYPE_P2P_GO;
7850         }
7851         return -1;
7852 }
7853
7854
7855 #ifdef CONFIG_P2P
7856
7857 static int nl80211_addr_in_use(struct nl80211_global *global, const u8 *addr)
7858 {
7859         struct wpa_driver_nl80211_data *drv;
7860         dl_list_for_each(drv, &global->interfaces,
7861                          struct wpa_driver_nl80211_data, list) {
7862                 if (os_memcmp(addr, drv->first_bss.addr, ETH_ALEN) == 0)
7863                         return 1;
7864         }
7865         return 0;
7866 }
7867
7868
7869 static int nl80211_p2p_interface_addr(struct wpa_driver_nl80211_data *drv,
7870                                       u8 *new_addr)
7871 {
7872         unsigned int idx;
7873
7874         if (!drv->global)
7875                 return -1;
7876
7877         os_memcpy(new_addr, drv->first_bss.addr, ETH_ALEN);
7878         for (idx = 0; idx < 64; idx++) {
7879                 new_addr[0] = drv->first_bss.addr[0] | 0x02;
7880                 new_addr[0] ^= idx << 2;
7881                 if (!nl80211_addr_in_use(drv->global, new_addr))
7882                         break;
7883         }
7884         if (idx == 64)
7885                 return -1;
7886
7887         wpa_printf(MSG_DEBUG, "nl80211: Assigned new P2P Interface Address "
7888                    MACSTR, MAC2STR(new_addr));
7889
7890         return 0;
7891 }
7892
7893 #endif /* CONFIG_P2P */
7894
7895
7896 static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
7897                                      const char *ifname, const u8 *addr,
7898                                      void *bss_ctx, void **drv_priv,
7899                                      char *force_ifname, u8 *if_addr,
7900                                      const char *bridge)
7901 {
7902         struct i802_bss *bss = priv;
7903         struct wpa_driver_nl80211_data *drv = bss->drv;
7904         int ifidx;
7905 #ifdef HOSTAPD
7906         struct i802_bss *new_bss = NULL;
7907
7908         if (type == WPA_IF_AP_BSS) {
7909                 new_bss = os_zalloc(sizeof(*new_bss));
7910                 if (new_bss == NULL)
7911                         return -1;
7912         }
7913 #endif /* HOSTAPD */
7914
7915         if (addr)
7916                 os_memcpy(if_addr, addr, ETH_ALEN);
7917         ifidx = nl80211_create_iface(drv, ifname,
7918                                      wpa_driver_nl80211_if_type(type), addr,
7919                                      0);
7920         if (ifidx < 0) {
7921 #ifdef HOSTAPD
7922                 os_free(new_bss);
7923 #endif /* HOSTAPD */
7924                 return -1;
7925         }
7926
7927         if (!addr &&
7928             linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7929                                if_addr) < 0) {
7930                 nl80211_remove_iface(drv, ifidx);
7931                 return -1;
7932         }
7933
7934 #ifdef CONFIG_P2P
7935         if (!addr &&
7936             (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
7937              type == WPA_IF_P2P_GO)) {
7938                 /* Enforce unique P2P Interface Address */
7939                 u8 new_addr[ETH_ALEN], own_addr[ETH_ALEN];
7940
7941                 if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
7942                                        own_addr) < 0 ||
7943                     linux_get_ifhwaddr(drv->global->ioctl_sock, ifname,
7944                                        new_addr) < 0) {
7945                         nl80211_remove_iface(drv, ifidx);
7946                         return -1;
7947                 }
7948                 if (os_memcmp(own_addr, new_addr, ETH_ALEN) == 0) {
7949                         wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
7950                                    "for P2P group interface");
7951                         if (nl80211_p2p_interface_addr(drv, new_addr) < 0) {
7952                                 nl80211_remove_iface(drv, ifidx);
7953                                 return -1;
7954                         }
7955                         if (linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
7956                                                new_addr) < 0) {
7957                                 nl80211_remove_iface(drv, ifidx);
7958                                 return -1;
7959                         }
7960                 }
7961                 os_memcpy(if_addr, new_addr, ETH_ALEN);
7962         }
7963 #endif /* CONFIG_P2P */
7964
7965 #ifdef HOSTAPD
7966         if (bridge &&
7967             i802_check_bridge(drv, new_bss, bridge, ifname) < 0) {
7968                 wpa_printf(MSG_ERROR, "nl80211: Failed to add the new "
7969                            "interface %s to a bridge %s", ifname, bridge);
7970                 nl80211_remove_iface(drv, ifidx);
7971                 os_free(new_bss);
7972                 return -1;
7973         }
7974
7975         if (type == WPA_IF_AP_BSS) {
7976                 if (linux_set_iface_flags(drv->global->ioctl_sock, ifname, 1))
7977                 {
7978                         nl80211_remove_iface(drv, ifidx);
7979                         os_free(new_bss);
7980                         return -1;
7981                 }
7982                 os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
7983                 os_memcpy(new_bss->addr, if_addr, ETH_ALEN);
7984                 new_bss->ifindex = ifidx;
7985                 new_bss->drv = drv;
7986                 new_bss->next = drv->first_bss.next;
7987                 new_bss->freq = drv->first_bss.freq;
7988                 drv->first_bss.next = new_bss;
7989                 if (drv_priv)
7990                         *drv_priv = new_bss;
7991                 nl80211_init_bss(new_bss);
7992
7993                 /* Subscribe management frames for this WPA_IF_AP_BSS */
7994                 if (nl80211_setup_ap(new_bss))
7995                         return -1;
7996         }
7997 #endif /* HOSTAPD */
7998
7999         if (drv->global)
8000                 drv->global->if_add_ifindex = ifidx;
8001
8002         return 0;
8003 }
8004
8005
8006 static int wpa_driver_nl80211_if_remove(void *priv,
8007                                         enum wpa_driver_if_type type,
8008                                         const char *ifname)
8009 {
8010         struct i802_bss *bss = priv;
8011         struct wpa_driver_nl80211_data *drv = bss->drv;
8012         int ifindex = if_nametoindex(ifname);
8013
8014         wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d",
8015                    __func__, type, ifname, ifindex);
8016         if (ifindex <= 0)
8017                 return -1;
8018
8019 #ifdef HOSTAPD
8020         if (bss->added_if_into_bridge) {
8021                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
8022                                     bss->ifname) < 0)
8023                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
8024                                    "interface %s from bridge %s: %s",
8025                                    bss->ifname, bss->brname, strerror(errno));
8026         }
8027         if (bss->added_bridge) {
8028                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
8029                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
8030                                    "bridge %s: %s",
8031                                    bss->brname, strerror(errno));
8032         }
8033 #endif /* HOSTAPD */
8034
8035         nl80211_remove_iface(drv, ifindex);
8036
8037 #ifdef HOSTAPD
8038         if (type != WPA_IF_AP_BSS)
8039                 return 0;
8040
8041         if (bss != &drv->first_bss) {
8042                 struct i802_bss *tbss;
8043
8044                 for (tbss = &drv->first_bss; tbss; tbss = tbss->next) {
8045                         if (tbss->next == bss) {
8046                                 tbss->next = bss->next;
8047                                 /* Unsubscribe management frames */
8048                                 nl80211_teardown_ap(bss);
8049                                 nl80211_destroy_bss(bss);
8050                                 os_free(bss);
8051                                 bss = NULL;
8052                                 break;
8053                         }
8054                 }
8055                 if (bss)
8056                         wpa_printf(MSG_INFO, "nl80211: %s - could not find "
8057                                    "BSS %p in the list", __func__, bss);
8058         }
8059 #endif /* HOSTAPD */
8060
8061         return 0;
8062 }
8063
8064
8065 static int cookie_handler(struct nl_msg *msg, void *arg)
8066 {
8067         struct nlattr *tb[NL80211_ATTR_MAX + 1];
8068         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
8069         u64 *cookie = arg;
8070         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
8071                   genlmsg_attrlen(gnlh, 0), NULL);
8072         if (tb[NL80211_ATTR_COOKIE])
8073                 *cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
8074         return NL_SKIP;
8075 }
8076
8077
8078 static int nl80211_send_frame_cmd(struct i802_bss *bss,
8079                                   unsigned int freq, unsigned int wait,
8080                                   const u8 *buf, size_t buf_len,
8081                                   u64 *cookie_out, int no_cck, int no_ack,
8082                                   int offchanok)
8083 {
8084         struct wpa_driver_nl80211_data *drv = bss->drv;
8085         struct nl_msg *msg;
8086         u64 cookie;
8087         int ret = -1;
8088
8089         msg = nlmsg_alloc();
8090         if (!msg)
8091                 return -1;
8092
8093         wpa_printf(MSG_DEBUG, "nl80211: CMD_FRAME freq=%u wait=%u no_cck=%d "
8094                    "no_ack=%d offchanok=%d",
8095                    freq, wait, no_cck, no_ack, offchanok);
8096         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME);
8097
8098         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8099         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
8100         if (wait)
8101                 NLA_PUT_U32(msg, NL80211_ATTR_DURATION, wait);
8102         if (offchanok && (drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX))
8103                 NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
8104         if (no_cck)
8105                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
8106         if (no_ack)
8107                 NLA_PUT_FLAG(msg, NL80211_ATTR_DONT_WAIT_FOR_ACK);
8108
8109         NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
8110
8111         cookie = 0;
8112         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
8113         msg = NULL;
8114         if (ret) {
8115                 wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
8116                            "(%s) (freq=%u wait=%u)", ret, strerror(-ret),
8117                            freq, wait);
8118                 goto nla_put_failure;
8119         }
8120         wpa_printf(MSG_DEBUG, "nl80211: Frame TX command accepted%s; "
8121                    "cookie 0x%llx", no_ack ? " (no ACK)" : "",
8122                    (long long unsigned int) cookie);
8123
8124         if (cookie_out)
8125                 *cookie_out = no_ack ? (u64) -1 : cookie;
8126
8127 nla_put_failure:
8128         nlmsg_free(msg);
8129         return ret;
8130 }
8131
8132
8133 static int wpa_driver_nl80211_send_action(void *priv, unsigned int freq,
8134                                           unsigned int wait_time,
8135                                           const u8 *dst, const u8 *src,
8136                                           const u8 *bssid,
8137                                           const u8 *data, size_t data_len,
8138                                           int no_cck)
8139 {
8140         struct i802_bss *bss = priv;
8141         struct wpa_driver_nl80211_data *drv = bss->drv;
8142         int ret = -1;
8143         u8 *buf;
8144         struct ieee80211_hdr *hdr;
8145
8146         wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d, "
8147                    "freq=%u MHz wait=%d ms no_cck=%d)",
8148                    drv->ifindex, freq, wait_time, no_cck);
8149
8150         buf = os_zalloc(24 + data_len);
8151         if (buf == NULL)
8152                 return ret;
8153         os_memcpy(buf + 24, data, data_len);
8154         hdr = (struct ieee80211_hdr *) buf;
8155         hdr->frame_control =
8156                 IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
8157         os_memcpy(hdr->addr1, dst, ETH_ALEN);
8158         os_memcpy(hdr->addr2, src, ETH_ALEN);
8159         os_memcpy(hdr->addr3, bssid, ETH_ALEN);
8160
8161         if (is_ap_interface(drv->nlmode))
8162                 ret = wpa_driver_nl80211_send_mlme_freq(priv, buf,
8163                                                         24 + data_len,
8164                                                         0, freq, no_cck, 1,
8165                                                         wait_time);
8166         else
8167                 ret = nl80211_send_frame_cmd(bss, freq, wait_time, buf,
8168                                              24 + data_len,
8169                                              &drv->send_action_cookie,
8170                                              no_cck, 0, 1);
8171
8172         os_free(buf);
8173         return ret;
8174 }
8175
8176
8177 static void wpa_driver_nl80211_send_action_cancel_wait(void *priv)
8178 {
8179         struct i802_bss *bss = priv;
8180         struct wpa_driver_nl80211_data *drv = bss->drv;
8181         struct nl_msg *msg;
8182         int ret;
8183
8184         msg = nlmsg_alloc();
8185         if (!msg)
8186                 return;
8187
8188         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME_WAIT_CANCEL);
8189
8190         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8191         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->send_action_cookie);
8192
8193         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8194         msg = NULL;
8195         if (ret)
8196                 wpa_printf(MSG_DEBUG, "nl80211: wait cancel failed: ret=%d "
8197                            "(%s)", ret, strerror(-ret));
8198
8199  nla_put_failure:
8200         nlmsg_free(msg);
8201 }
8202
8203
8204 static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
8205                                                 unsigned int duration)
8206 {
8207         struct i802_bss *bss = priv;
8208         struct wpa_driver_nl80211_data *drv = bss->drv;
8209         struct nl_msg *msg;
8210         int ret;
8211         u64 cookie;
8212
8213         msg = nlmsg_alloc();
8214         if (!msg)
8215                 return -1;
8216
8217         nl80211_cmd(drv, msg, 0, NL80211_CMD_REMAIN_ON_CHANNEL);
8218
8219         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8220         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
8221         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
8222
8223         cookie = 0;
8224         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
8225         msg = NULL;
8226         if (ret == 0) {
8227                 wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
8228                            "0x%llx for freq=%u MHz duration=%u",
8229                            (long long unsigned int) cookie, freq, duration);
8230                 drv->remain_on_chan_cookie = cookie;
8231                 drv->pending_remain_on_chan = 1;
8232                 return 0;
8233         }
8234         wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
8235                    "(freq=%d duration=%u): %d (%s)",
8236                    freq, duration, ret, strerror(-ret));
8237 nla_put_failure:
8238         nlmsg_free(msg);
8239         return -1;
8240 }
8241
8242
8243 static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
8244 {
8245         struct i802_bss *bss = priv;
8246         struct wpa_driver_nl80211_data *drv = bss->drv;
8247         struct nl_msg *msg;
8248         int ret;
8249
8250         if (!drv->pending_remain_on_chan) {
8251                 wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
8252                            "to cancel");
8253                 return -1;
8254         }
8255
8256         wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
8257                    "0x%llx",
8258                    (long long unsigned int) drv->remain_on_chan_cookie);
8259
8260         msg = nlmsg_alloc();
8261         if (!msg)
8262                 return -1;
8263
8264         nl80211_cmd(drv, msg, 0, NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL);
8265
8266         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8267         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
8268
8269         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8270         msg = NULL;
8271         if (ret == 0)
8272                 return 0;
8273         wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
8274                    "%d (%s)", ret, strerror(-ret));
8275 nla_put_failure:
8276         nlmsg_free(msg);
8277         return -1;
8278 }
8279
8280
8281 static int wpa_driver_nl80211_probe_req_report(void *priv, int report)
8282 {
8283         struct i802_bss *bss = priv;
8284         struct wpa_driver_nl80211_data *drv = bss->drv;
8285
8286         if (!report) {
8287                 if (bss->nl_preq && drv->device_ap_sme &&
8288                     is_ap_interface(drv->nlmode)) {
8289                         /*
8290                          * Do not disable Probe Request reporting that was
8291                          * enabled in nl80211_setup_ap().
8292                          */
8293                         wpa_printf(MSG_DEBUG, "nl80211: Skip disabling of "
8294                                    "Probe Request reporting nl_preq=%p while "
8295                                    "in AP mode", bss->nl_preq);
8296                 } else if (bss->nl_preq) {
8297                         wpa_printf(MSG_DEBUG, "nl80211: Disable Probe Request "
8298                                    "reporting nl_preq=%p", bss->nl_preq);
8299                         eloop_unregister_read_sock(
8300                                 nl_socket_get_fd(bss->nl_preq));
8301                         nl_destroy_handles(&bss->nl_preq);
8302                 }
8303                 return 0;
8304         }
8305
8306         if (bss->nl_preq) {
8307                 wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
8308                            "already on! nl_preq=%p", bss->nl_preq);
8309                 return 0;
8310         }
8311
8312         bss->nl_preq = nl_create_handle(drv->global->nl_cb, "preq");
8313         if (bss->nl_preq == NULL)
8314                 return -1;
8315         wpa_printf(MSG_DEBUG, "nl80211: Enable Probe Request "
8316                    "reporting nl_preq=%p", bss->nl_preq);
8317
8318         if (nl80211_register_frame(bss, bss->nl_preq,
8319                                    (WLAN_FC_TYPE_MGMT << 2) |
8320                                    (WLAN_FC_STYPE_PROBE_REQ << 4),
8321                                    NULL, 0) < 0)
8322                 goto out_err;
8323
8324         eloop_register_read_sock(nl_socket_get_fd(bss->nl_preq),
8325                                  wpa_driver_nl80211_event_receive, bss->nl_cb,
8326                                  bss->nl_preq);
8327
8328         return 0;
8329
8330  out_err:
8331         nl_destroy_handles(&bss->nl_preq);
8332         return -1;
8333 }
8334
8335
8336 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
8337                                      int ifindex, int disabled)
8338 {
8339         struct nl_msg *msg;
8340         struct nlattr *bands, *band;
8341         int ret;
8342
8343         msg = nlmsg_alloc();
8344         if (!msg)
8345                 return -1;
8346
8347         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_TX_BITRATE_MASK);
8348         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
8349
8350         bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
8351         if (!bands)
8352                 goto nla_put_failure;
8353
8354         /*
8355          * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
8356          * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
8357          * rates. All 5 GHz rates are left enabled.
8358          */
8359         band = nla_nest_start(msg, NL80211_BAND_2GHZ);
8360         if (!band)
8361                 goto nla_put_failure;
8362         if (disabled) {
8363                 NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
8364                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
8365         }
8366         nla_nest_end(msg, band);
8367
8368         nla_nest_end(msg, bands);
8369
8370         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8371         msg = NULL;
8372         if (ret) {
8373                 wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
8374                            "(%s)", ret, strerror(-ret));
8375         }
8376
8377         return ret;
8378
8379 nla_put_failure:
8380         nlmsg_free(msg);
8381         return -1;
8382 }
8383
8384
8385 static int wpa_driver_nl80211_deinit_ap(void *priv)
8386 {
8387         struct i802_bss *bss = priv;
8388         struct wpa_driver_nl80211_data *drv = bss->drv;
8389         if (!is_ap_interface(drv->nlmode))
8390                 return -1;
8391         wpa_driver_nl80211_del_beacon(drv);
8392         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
8393 }
8394
8395
8396 static int wpa_driver_nl80211_deinit_p2p_cli(void *priv)
8397 {
8398         struct i802_bss *bss = priv;
8399         struct wpa_driver_nl80211_data *drv = bss->drv;
8400         if (drv->nlmode != NL80211_IFTYPE_P2P_CLIENT)
8401                 return -1;
8402         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
8403 }
8404
8405
8406 static void wpa_driver_nl80211_resume(void *priv)
8407 {
8408         struct i802_bss *bss = priv;
8409         struct wpa_driver_nl80211_data *drv = bss->drv;
8410         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
8411                 wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on "
8412                            "resume event");
8413         }
8414 }
8415
8416
8417 static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
8418                                   const u8 *ies, size_t ies_len)
8419 {
8420         struct i802_bss *bss = priv;
8421         struct wpa_driver_nl80211_data *drv = bss->drv;
8422         int ret;
8423         u8 *data, *pos;
8424         size_t data_len;
8425         const u8 *own_addr = bss->addr;
8426
8427         if (action != 1) {
8428                 wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
8429                            "action %d", action);
8430                 return -1;
8431         }
8432
8433         /*
8434          * Action frame payload:
8435          * Category[1] = 6 (Fast BSS Transition)
8436          * Action[1] = 1 (Fast BSS Transition Request)
8437          * STA Address
8438          * Target AP Address
8439          * FT IEs
8440          */
8441
8442         data_len = 2 + 2 * ETH_ALEN + ies_len;
8443         data = os_malloc(data_len);
8444         if (data == NULL)
8445                 return -1;
8446         pos = data;
8447         *pos++ = 0x06; /* FT Action category */
8448         *pos++ = action;
8449         os_memcpy(pos, own_addr, ETH_ALEN);
8450         pos += ETH_ALEN;
8451         os_memcpy(pos, target_ap, ETH_ALEN);
8452         pos += ETH_ALEN;
8453         os_memcpy(pos, ies, ies_len);
8454
8455         ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, 0,
8456                                              drv->bssid, own_addr, drv->bssid,
8457                                              data, data_len, 0);
8458         os_free(data);
8459
8460         return ret;
8461 }
8462
8463
8464 static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
8465 {
8466         struct i802_bss *bss = priv;
8467         struct wpa_driver_nl80211_data *drv = bss->drv;
8468         struct nl_msg *msg, *cqm = NULL;
8469
8470         wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
8471                    "hysteresis=%d", threshold, hysteresis);
8472
8473         msg = nlmsg_alloc();
8474         if (!msg)
8475                 return -1;
8476
8477         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_CQM);
8478
8479         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8480
8481         cqm = nlmsg_alloc();
8482         if (cqm == NULL)
8483                 goto nla_put_failure;
8484
8485         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
8486         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
8487         nla_put_nested(msg, NL80211_ATTR_CQM, cqm);
8488
8489         nlmsg_free(cqm);
8490         cqm = NULL;
8491
8492         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
8493                 return 0;
8494         msg = NULL;
8495
8496 nla_put_failure:
8497         nlmsg_free(cqm);
8498         nlmsg_free(msg);
8499         return -1;
8500 }
8501
8502
8503 static int nl80211_signal_poll(void *priv, struct wpa_signal_info *si)
8504 {
8505         struct i802_bss *bss = priv;
8506         struct wpa_driver_nl80211_data *drv = bss->drv;
8507         int res;
8508
8509         os_memset(si, 0, sizeof(*si));
8510         res = nl80211_get_link_signal(drv, si);
8511         if (res != 0)
8512                 return res;
8513
8514         return nl80211_get_link_noise(drv, si);
8515 }
8516
8517
8518 static int wpa_driver_nl80211_shared_freq(void *priv)
8519 {
8520         struct i802_bss *bss = priv;
8521         struct wpa_driver_nl80211_data *drv = bss->drv;
8522         struct wpa_driver_nl80211_data *driver;
8523         int freq = 0;
8524
8525         /*
8526          * If the same PHY is in connected state with some other interface,
8527          * then retrieve the assoc freq.
8528          */
8529         wpa_printf(MSG_DEBUG, "nl80211: Get shared freq for PHY %s",
8530                    drv->phyname);
8531
8532         dl_list_for_each(driver, &drv->global->interfaces,
8533                          struct wpa_driver_nl80211_data, list) {
8534                 if (drv == driver ||
8535                     os_strcmp(drv->phyname, driver->phyname) != 0 ||
8536                     !driver->associated)
8537                         continue;
8538
8539                 wpa_printf(MSG_DEBUG, "nl80211: Found a match for PHY %s - %s "
8540                            MACSTR,
8541                            driver->phyname, driver->first_bss.ifname,
8542                            MAC2STR(driver->first_bss.addr));
8543                 if (is_ap_interface(driver->nlmode))
8544                         freq = driver->first_bss.freq;
8545                 else
8546                         freq = nl80211_get_assoc_freq(driver);
8547                 wpa_printf(MSG_DEBUG, "nl80211: Shared freq for PHY %s: %d",
8548                            drv->phyname, freq);
8549         }
8550
8551         if (!freq)
8552                 wpa_printf(MSG_DEBUG, "nl80211: No shared interface for "
8553                            "PHY (%s) in associated state", drv->phyname);
8554
8555         return freq;
8556 }
8557
8558
8559 static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
8560                               int encrypt)
8561 {
8562         struct i802_bss *bss = priv;
8563         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt, 0,
8564                                              0, 0, 0, 0);
8565 }
8566
8567
8568 static int nl80211_set_param(void *priv, const char *param)
8569 {
8570         wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
8571         if (param == NULL)
8572                 return 0;
8573
8574 #ifdef CONFIG_P2P
8575         if (os_strstr(param, "use_p2p_group_interface=1")) {
8576                 struct i802_bss *bss = priv;
8577                 struct wpa_driver_nl80211_data *drv = bss->drv;
8578
8579                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
8580                            "interface");
8581                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
8582                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
8583         }
8584 #endif /* CONFIG_P2P */
8585
8586         return 0;
8587 }
8588
8589
8590 static void * nl80211_global_init(void)
8591 {
8592         struct nl80211_global *global;
8593         struct netlink_config *cfg;
8594
8595         global = os_zalloc(sizeof(*global));
8596         if (global == NULL)
8597                 return NULL;
8598         global->ioctl_sock = -1;
8599         dl_list_init(&global->interfaces);
8600         global->if_add_ifindex = -1;
8601
8602         cfg = os_zalloc(sizeof(*cfg));
8603         if (cfg == NULL)
8604                 goto err;
8605
8606         cfg->ctx = global;
8607         cfg->newlink_cb = wpa_driver_nl80211_event_rtm_newlink;
8608         cfg->dellink_cb = wpa_driver_nl80211_event_rtm_dellink;
8609         global->netlink = netlink_init(cfg);
8610         if (global->netlink == NULL) {
8611                 os_free(cfg);
8612                 goto err;
8613         }
8614
8615         if (wpa_driver_nl80211_init_nl_global(global) < 0)
8616                 goto err;
8617
8618         global->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
8619         if (global->ioctl_sock < 0) {
8620                 perror("socket(PF_INET,SOCK_DGRAM)");
8621                 goto err;
8622         }
8623
8624         return global;
8625
8626 err:
8627         nl80211_global_deinit(global);
8628         return NULL;
8629 }
8630
8631
8632 static void nl80211_global_deinit(void *priv)
8633 {
8634         struct nl80211_global *global = priv;
8635         if (global == NULL)
8636                 return;
8637         if (!dl_list_empty(&global->interfaces)) {
8638                 wpa_printf(MSG_ERROR, "nl80211: %u interface(s) remain at "
8639                            "nl80211_global_deinit",
8640                            dl_list_len(&global->interfaces));
8641         }
8642
8643         if (global->netlink)
8644                 netlink_deinit(global->netlink);
8645
8646         nl_destroy_handles(&global->nl);
8647
8648         if (global->nl_event) {
8649                 eloop_unregister_read_sock(
8650                         nl_socket_get_fd(global->nl_event));
8651                 nl_destroy_handles(&global->nl_event);
8652         }
8653
8654         nl_cb_put(global->nl_cb);
8655
8656         if (global->ioctl_sock >= 0)
8657                 close(global->ioctl_sock);
8658
8659         os_free(global);
8660 }
8661
8662
8663 static const char * nl80211_get_radio_name(void *priv)
8664 {
8665         struct i802_bss *bss = priv;
8666         struct wpa_driver_nl80211_data *drv = bss->drv;
8667         return drv->phyname;
8668 }
8669
8670
8671 static int nl80211_pmkid(struct i802_bss *bss, int cmd, const u8 *bssid,
8672                          const u8 *pmkid)
8673 {
8674         struct nl_msg *msg;
8675
8676         msg = nlmsg_alloc();
8677         if (!msg)
8678                 return -ENOMEM;
8679
8680         nl80211_cmd(bss->drv, msg, 0, cmd);
8681
8682         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
8683         if (pmkid)
8684                 NLA_PUT(msg, NL80211_ATTR_PMKID, 16, pmkid);
8685         if (bssid)
8686                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
8687
8688         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
8689  nla_put_failure:
8690         nlmsg_free(msg);
8691         return -ENOBUFS;
8692 }
8693
8694
8695 static int nl80211_add_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
8696 {
8697         struct i802_bss *bss = priv;
8698         wpa_printf(MSG_DEBUG, "nl80211: Add PMKID for " MACSTR, MAC2STR(bssid));
8699         return nl80211_pmkid(bss, NL80211_CMD_SET_PMKSA, bssid, pmkid);
8700 }
8701
8702
8703 static int nl80211_remove_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
8704 {
8705         struct i802_bss *bss = priv;
8706         wpa_printf(MSG_DEBUG, "nl80211: Delete PMKID for " MACSTR,
8707                    MAC2STR(bssid));
8708         return nl80211_pmkid(bss, NL80211_CMD_DEL_PMKSA, bssid, pmkid);
8709 }
8710
8711
8712 static int nl80211_flush_pmkid(void *priv)
8713 {
8714         struct i802_bss *bss = priv;
8715         wpa_printf(MSG_DEBUG, "nl80211: Flush PMKIDs");
8716         return nl80211_pmkid(bss, NL80211_CMD_FLUSH_PMKSA, NULL, NULL);
8717 }
8718
8719
8720 static void nl80211_set_rekey_info(void *priv, const u8 *kek, const u8 *kck,
8721                                    const u8 *replay_ctr)
8722 {
8723         struct i802_bss *bss = priv;
8724         struct wpa_driver_nl80211_data *drv = bss->drv;
8725         struct nlattr *replay_nested;
8726         struct nl_msg *msg;
8727
8728         msg = nlmsg_alloc();
8729         if (!msg)
8730                 return;
8731
8732         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_REKEY_OFFLOAD);
8733
8734         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8735
8736         replay_nested = nla_nest_start(msg, NL80211_ATTR_REKEY_DATA);
8737         if (!replay_nested)
8738                 goto nla_put_failure;
8739
8740         NLA_PUT(msg, NL80211_REKEY_DATA_KEK, NL80211_KEK_LEN, kek);
8741         NLA_PUT(msg, NL80211_REKEY_DATA_KCK, NL80211_KCK_LEN, kck);
8742         NLA_PUT(msg, NL80211_REKEY_DATA_REPLAY_CTR, NL80211_REPLAY_CTR_LEN,
8743                 replay_ctr);
8744
8745         nla_nest_end(msg, replay_nested);
8746
8747         send_and_recv_msgs(drv, msg, NULL, NULL);
8748         return;
8749  nla_put_failure:
8750         nlmsg_free(msg);
8751 }
8752
8753
8754 static void nl80211_send_null_frame(struct i802_bss *bss, const u8 *own_addr,
8755                                     const u8 *addr, int qos)
8756 {
8757         /* send data frame to poll STA and check whether
8758          * this frame is ACKed */
8759         struct {
8760                 struct ieee80211_hdr hdr;
8761                 u16 qos_ctl;
8762         } STRUCT_PACKED nulldata;
8763         size_t size;
8764
8765         /* Send data frame to poll STA and check whether this frame is ACKed */
8766
8767         os_memset(&nulldata, 0, sizeof(nulldata));
8768
8769         if (qos) {
8770                 nulldata.hdr.frame_control =
8771                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
8772                                      WLAN_FC_STYPE_QOS_NULL);
8773                 size = sizeof(nulldata);
8774         } else {
8775                 nulldata.hdr.frame_control =
8776                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
8777                                      WLAN_FC_STYPE_NULLFUNC);
8778                 size = sizeof(struct ieee80211_hdr);
8779         }
8780
8781         nulldata.hdr.frame_control |= host_to_le16(WLAN_FC_FROMDS);
8782         os_memcpy(nulldata.hdr.IEEE80211_DA_FROMDS, addr, ETH_ALEN);
8783         os_memcpy(nulldata.hdr.IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
8784         os_memcpy(nulldata.hdr.IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
8785
8786         if (wpa_driver_nl80211_send_mlme(bss, (u8 *) &nulldata, size, 0) < 0)
8787                 wpa_printf(MSG_DEBUG, "nl80211_send_null_frame: Failed to "
8788                            "send poll frame");
8789 }
8790
8791 static void nl80211_poll_client(void *priv, const u8 *own_addr, const u8 *addr,
8792                                 int qos)
8793 {
8794         struct i802_bss *bss = priv;
8795         struct wpa_driver_nl80211_data *drv = bss->drv;
8796         struct nl_msg *msg;
8797
8798         if (!drv->poll_command_supported) {
8799                 nl80211_send_null_frame(bss, own_addr, addr, qos);
8800                 return;
8801         }
8802
8803         msg = nlmsg_alloc();
8804         if (!msg)
8805                 return;
8806
8807         nl80211_cmd(drv, msg, 0, NL80211_CMD_PROBE_CLIENT);
8808
8809         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8810         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
8811
8812         send_and_recv_msgs(drv, msg, NULL, NULL);
8813         return;
8814  nla_put_failure:
8815         nlmsg_free(msg);
8816 }
8817
8818
8819 static int nl80211_set_power_save(struct i802_bss *bss, int enabled)
8820 {
8821         struct nl_msg *msg;
8822
8823         msg = nlmsg_alloc();
8824         if (!msg)
8825                 return -ENOMEM;
8826
8827         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_SET_POWER_SAVE);
8828         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8829         NLA_PUT_U32(msg, NL80211_ATTR_PS_STATE,
8830                     enabled ? NL80211_PS_ENABLED : NL80211_PS_DISABLED);
8831         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
8832 nla_put_failure:
8833         nlmsg_free(msg);
8834         return -ENOBUFS;
8835 }
8836
8837
8838 static int nl80211_set_p2p_powersave(void *priv, int legacy_ps, int opp_ps,
8839                                      int ctwindow)
8840 {
8841         struct i802_bss *bss = priv;
8842
8843         wpa_printf(MSG_DEBUG, "nl80211: set_p2p_powersave (legacy_ps=%d "
8844                    "opp_ps=%d ctwindow=%d)", legacy_ps, opp_ps, ctwindow);
8845
8846         if (opp_ps != -1 || ctwindow != -1)
8847                 return -1; /* Not yet supported */
8848
8849         if (legacy_ps == -1)
8850                 return 0;
8851         if (legacy_ps != 0 && legacy_ps != 1)
8852                 return -1; /* Not yet supported */
8853
8854         return nl80211_set_power_save(bss, legacy_ps);
8855 }
8856
8857
8858 #ifdef CONFIG_TDLS
8859
8860 static int nl80211_send_tdls_mgmt(void *priv, const u8 *dst, u8 action_code,
8861                                   u8 dialog_token, u16 status_code,
8862                                   const u8 *buf, size_t len)
8863 {
8864         struct i802_bss *bss = priv;
8865         struct wpa_driver_nl80211_data *drv = bss->drv;
8866         struct nl_msg *msg;
8867
8868         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
8869                 return -EOPNOTSUPP;
8870
8871         if (!dst)
8872                 return -EINVAL;
8873
8874         msg = nlmsg_alloc();
8875         if (!msg)
8876                 return -ENOMEM;
8877
8878         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_MGMT);
8879         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8880         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, dst);
8881         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_ACTION, action_code);
8882         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_DIALOG_TOKEN, dialog_token);
8883         NLA_PUT_U16(msg, NL80211_ATTR_STATUS_CODE, status_code);
8884         NLA_PUT(msg, NL80211_ATTR_IE, len, buf);
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
8894 static int nl80211_tdls_oper(void *priv, enum tdls_oper oper, const u8 *peer)
8895 {
8896         struct i802_bss *bss = priv;
8897         struct wpa_driver_nl80211_data *drv = bss->drv;
8898         struct nl_msg *msg;
8899         enum nl80211_tdls_operation nl80211_oper;
8900
8901         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
8902                 return -EOPNOTSUPP;
8903
8904         switch (oper) {
8905         case TDLS_DISCOVERY_REQ:
8906                 nl80211_oper = NL80211_TDLS_DISCOVERY_REQ;
8907                 break;
8908         case TDLS_SETUP:
8909                 nl80211_oper = NL80211_TDLS_SETUP;
8910                 break;
8911         case TDLS_TEARDOWN:
8912                 nl80211_oper = NL80211_TDLS_TEARDOWN;
8913                 break;
8914         case TDLS_ENABLE_LINK:
8915                 nl80211_oper = NL80211_TDLS_ENABLE_LINK;
8916                 break;
8917         case TDLS_DISABLE_LINK:
8918                 nl80211_oper = NL80211_TDLS_DISABLE_LINK;
8919                 break;
8920         case TDLS_ENABLE:
8921                 return 0;
8922         case TDLS_DISABLE:
8923                 return 0;
8924         default:
8925                 return -EINVAL;
8926         }
8927
8928         msg = nlmsg_alloc();
8929         if (!msg)
8930                 return -ENOMEM;
8931
8932         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_OPER);
8933         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_OPERATION, nl80211_oper);
8934         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8935         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, peer);
8936
8937         return send_and_recv_msgs(drv, msg, NULL, NULL);
8938
8939 nla_put_failure:
8940         nlmsg_free(msg);
8941         return -ENOBUFS;
8942 }
8943
8944 #endif /* CONFIG TDLS */
8945
8946
8947 #ifdef ANDROID
8948
8949 typedef struct android_wifi_priv_cmd {
8950         char *buf;
8951         int used_len;
8952         int total_len;
8953 } android_wifi_priv_cmd;
8954
8955 static int drv_errors = 0;
8956
8957 static void wpa_driver_send_hang_msg(struct wpa_driver_nl80211_data *drv)
8958 {
8959         drv_errors++;
8960         if (drv_errors > DRV_NUMBER_SEQUENTIAL_ERRORS) {
8961                 drv_errors = 0;
8962                 wpa_msg(drv->ctx, MSG_INFO, WPA_EVENT_DRIVER_STATE "HANGED");
8963         }
8964 }
8965
8966
8967 static int android_priv_cmd(struct i802_bss *bss, const char *cmd)
8968 {
8969         struct wpa_driver_nl80211_data *drv = bss->drv;
8970         struct ifreq ifr;
8971         android_wifi_priv_cmd priv_cmd;
8972         char buf[MAX_DRV_CMD_SIZE];
8973         int ret;
8974
8975         os_memset(&ifr, 0, sizeof(ifr));
8976         os_memset(&priv_cmd, 0, sizeof(priv_cmd));
8977         os_strlcpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
8978
8979         os_memset(buf, 0, sizeof(buf));
8980         os_strlcpy(buf, cmd, sizeof(buf));
8981
8982         priv_cmd.buf = buf;
8983         priv_cmd.used_len = sizeof(buf);
8984         priv_cmd.total_len = sizeof(buf);
8985         ifr.ifr_data = &priv_cmd;
8986
8987         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
8988         if (ret < 0) {
8989                 wpa_printf(MSG_ERROR, "%s: failed to issue private commands",
8990                            __func__);
8991                 wpa_driver_send_hang_msg(drv);
8992                 return ret;
8993         }
8994
8995         drv_errors = 0;
8996         return 0;
8997 }
8998
8999
9000 static int android_pno_start(struct i802_bss *bss,
9001                              struct wpa_driver_scan_params *params)
9002 {
9003         struct wpa_driver_nl80211_data *drv = bss->drv;
9004         struct ifreq ifr;
9005         android_wifi_priv_cmd priv_cmd;
9006         int ret = 0, i = 0, bp;
9007         char buf[WEXT_PNO_MAX_COMMAND_SIZE];
9008
9009         bp = WEXT_PNOSETUP_HEADER_SIZE;
9010         os_memcpy(buf, WEXT_PNOSETUP_HEADER, bp);
9011         buf[bp++] = WEXT_PNO_TLV_PREFIX;
9012         buf[bp++] = WEXT_PNO_TLV_VERSION;
9013         buf[bp++] = WEXT_PNO_TLV_SUBVERSION;
9014         buf[bp++] = WEXT_PNO_TLV_RESERVED;
9015
9016         while (i < WEXT_PNO_AMOUNT && (size_t) i < params->num_ssids) {
9017                 /* Check that there is enough space needed for 1 more SSID, the
9018                  * other sections and null termination */
9019                 if ((bp + WEXT_PNO_SSID_HEADER_SIZE + MAX_SSID_LEN +
9020                      WEXT_PNO_NONSSID_SECTIONS_SIZE + 1) >= (int) sizeof(buf))
9021                         break;
9022                 wpa_hexdump_ascii(MSG_DEBUG, "For PNO Scan",
9023                                   params->ssids[i].ssid,
9024                                   params->ssids[i].ssid_len);
9025                 buf[bp++] = WEXT_PNO_SSID_SECTION;
9026                 buf[bp++] = params->ssids[i].ssid_len;
9027                 os_memcpy(&buf[bp], params->ssids[i].ssid,
9028                           params->ssids[i].ssid_len);
9029                 bp += params->ssids[i].ssid_len;
9030                 i++;
9031         }
9032
9033         buf[bp++] = WEXT_PNO_SCAN_INTERVAL_SECTION;
9034         os_snprintf(&buf[bp], WEXT_PNO_SCAN_INTERVAL_LENGTH + 1, "%x",
9035                     WEXT_PNO_SCAN_INTERVAL);
9036         bp += WEXT_PNO_SCAN_INTERVAL_LENGTH;
9037
9038         buf[bp++] = WEXT_PNO_REPEAT_SECTION;
9039         os_snprintf(&buf[bp], WEXT_PNO_REPEAT_LENGTH + 1, "%x",
9040                     WEXT_PNO_REPEAT);
9041         bp += WEXT_PNO_REPEAT_LENGTH;
9042
9043         buf[bp++] = WEXT_PNO_MAX_REPEAT_SECTION;
9044         os_snprintf(&buf[bp], WEXT_PNO_MAX_REPEAT_LENGTH + 1, "%x",
9045                     WEXT_PNO_MAX_REPEAT);
9046         bp += WEXT_PNO_MAX_REPEAT_LENGTH + 1;
9047
9048         memset(&ifr, 0, sizeof(ifr));
9049         memset(&priv_cmd, 0, sizeof(priv_cmd));
9050         os_strncpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
9051
9052         priv_cmd.buf = buf;
9053         priv_cmd.used_len = bp;
9054         priv_cmd.total_len = bp;
9055         ifr.ifr_data = &priv_cmd;
9056
9057         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
9058
9059         if (ret < 0) {
9060                 wpa_printf(MSG_ERROR, "ioctl[SIOCSIWPRIV] (pnosetup): %d",
9061                            ret);
9062                 wpa_driver_send_hang_msg(drv);
9063                 return ret;
9064         }
9065
9066         drv_errors = 0;
9067
9068         return android_priv_cmd(bss, "PNOFORCE 1");
9069 }
9070
9071
9072 static int android_pno_stop(struct i802_bss *bss)
9073 {
9074         return android_priv_cmd(bss, "PNOFORCE 0");
9075 }
9076
9077 #endif /* ANDROID */
9078
9079
9080 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
9081         .name = "nl80211",
9082         .desc = "Linux nl80211/cfg80211",
9083         .get_bssid = wpa_driver_nl80211_get_bssid,
9084         .get_ssid = wpa_driver_nl80211_get_ssid,
9085         .set_key = wpa_driver_nl80211_set_key,
9086         .scan2 = wpa_driver_nl80211_scan,
9087         .sched_scan = wpa_driver_nl80211_sched_scan,
9088         .stop_sched_scan = wpa_driver_nl80211_stop_sched_scan,
9089         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
9090         .deauthenticate = wpa_driver_nl80211_deauthenticate,
9091         .disassociate = wpa_driver_nl80211_disassociate,
9092         .authenticate = wpa_driver_nl80211_authenticate,
9093         .associate = wpa_driver_nl80211_associate,
9094         .global_init = nl80211_global_init,
9095         .global_deinit = nl80211_global_deinit,
9096         .init2 = wpa_driver_nl80211_init,
9097         .deinit = wpa_driver_nl80211_deinit,
9098         .get_capa = wpa_driver_nl80211_get_capa,
9099         .set_operstate = wpa_driver_nl80211_set_operstate,
9100         .set_supp_port = wpa_driver_nl80211_set_supp_port,
9101         .set_country = wpa_driver_nl80211_set_country,
9102         .set_ap = wpa_driver_nl80211_set_ap,
9103         .if_add = wpa_driver_nl80211_if_add,
9104         .if_remove = wpa_driver_nl80211_if_remove,
9105         .send_mlme = wpa_driver_nl80211_send_mlme,
9106         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
9107         .sta_add = wpa_driver_nl80211_sta_add,
9108         .sta_remove = wpa_driver_nl80211_sta_remove,
9109         .hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
9110         .sta_set_flags = wpa_driver_nl80211_sta_set_flags,
9111 #ifdef HOSTAPD
9112         .hapd_init = i802_init,
9113         .hapd_deinit = i802_deinit,
9114         .set_wds_sta = i802_set_wds_sta,
9115 #endif /* HOSTAPD */
9116 #if defined(HOSTAPD) || defined(CONFIG_AP)
9117         .get_seqnum = i802_get_seqnum,
9118         .flush = i802_flush,
9119         .read_sta_data = i802_read_sta_data,
9120         .get_inact_sec = i802_get_inact_sec,
9121         .sta_clear_stats = i802_sta_clear_stats,
9122         .set_rts = i802_set_rts,
9123         .set_frag = i802_set_frag,
9124         .set_tx_queue_params = i802_set_tx_queue_params,
9125         .set_sta_vlan = i802_set_sta_vlan,
9126         .sta_deauth = i802_sta_deauth,
9127         .sta_disassoc = i802_sta_disassoc,
9128 #endif /* HOSTAPD || CONFIG_AP */
9129         .set_freq = i802_set_freq,
9130         .send_action = wpa_driver_nl80211_send_action,
9131         .send_action_cancel_wait = wpa_driver_nl80211_send_action_cancel_wait,
9132         .remain_on_channel = wpa_driver_nl80211_remain_on_channel,
9133         .cancel_remain_on_channel =
9134         wpa_driver_nl80211_cancel_remain_on_channel,
9135         .probe_req_report = wpa_driver_nl80211_probe_req_report,
9136         .deinit_ap = wpa_driver_nl80211_deinit_ap,
9137         .deinit_p2p_cli = wpa_driver_nl80211_deinit_p2p_cli,
9138         .resume = wpa_driver_nl80211_resume,
9139         .send_ft_action = nl80211_send_ft_action,
9140         .signal_monitor = nl80211_signal_monitor,
9141         .signal_poll = nl80211_signal_poll,
9142         .send_frame = nl80211_send_frame,
9143         .shared_freq = wpa_driver_nl80211_shared_freq,
9144         .set_param = nl80211_set_param,
9145         .get_radio_name = nl80211_get_radio_name,
9146         .add_pmkid = nl80211_add_pmkid,
9147         .remove_pmkid = nl80211_remove_pmkid,
9148         .flush_pmkid = nl80211_flush_pmkid,
9149         .set_rekey_info = nl80211_set_rekey_info,
9150         .poll_client = nl80211_poll_client,
9151         .set_p2p_powersave = nl80211_set_p2p_powersave,
9152 #ifdef CONFIG_TDLS
9153         .send_tdls_mgmt = nl80211_send_tdls_mgmt,
9154         .tdls_oper = nl80211_tdls_oper,
9155 #endif /* CONFIG_TDLS */
9156 };