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