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