nl80211: Add preliminary code for testing separate P2P group interface
[mech_eap.git] / src / drivers / driver_nl80211.c
1 /*
2  * Driver interaction with Linux nl80211/cfg80211
3  * Copyright (c) 2002-2010, 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 program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * Alternatively, this software may be distributed under the terms of BSD
14  * license.
15  *
16  * See README and COPYING for more details.
17  */
18
19 #include "includes.h"
20 #include <sys/ioctl.h>
21 #include <net/if.h>
22 #include <netlink/genl/genl.h>
23 #include <netlink/genl/family.h>
24 #include <netlink/genl/ctrl.h>
25 #include <linux/rtnetlink.h>
26 #include <netpacket/packet.h>
27 #include <linux/filter.h>
28 #include "nl80211_copy.h"
29
30 #include "common.h"
31 #include "eloop.h"
32 #include "common/ieee802_11_defs.h"
33 #include "netlink.h"
34 #include "linux_ioctl.h"
35 #include "radiotap.h"
36 #include "radiotap_iter.h"
37 #include "rfkill.h"
38 #include "driver.h"
39
40 #ifdef CONFIG_LIBNL20
41 /* libnl 2.0 compatibility code */
42 #define nl_handle nl_sock
43 #define nl80211_handle_alloc nl_socket_alloc_cb
44 #define nl80211_handle_destroy nl_socket_free
45 #else
46 /*
47  * libnl 1.1 has a bug, it tries to allocate socket numbers densely
48  * but when you free a socket again it will mess up its bitmap and
49  * and use the wrong number the next time it needs a socket ID.
50  * Therefore, we wrap the handle alloc/destroy and add our own pid
51  * accounting.
52  */
53 static uint32_t port_bitmap[32] = { 0 };
54
55 static struct nl_handle *nl80211_handle_alloc(void *cb)
56 {
57         struct nl_handle *handle;
58         uint32_t pid = getpid() & 0x3FFFFF;
59         int i;
60
61         handle = nl_handle_alloc_cb(cb);
62
63         for (i = 0; i < 1024; i++) {
64                 if (port_bitmap[i / 32] & (1 << (i % 32)))
65                         continue;
66                 port_bitmap[i / 32] |= 1 << (i % 32);
67                 pid += i << 22;
68                 break;
69         }
70
71         nl_socket_set_local_port(handle, pid);
72
73         return handle;
74 }
75
76 static void nl80211_handle_destroy(struct nl_handle *handle)
77 {
78         uint32_t port = nl_socket_get_local_port(handle);
79
80         port >>= 22;
81         port_bitmap[port / 32] &= ~(1 << (port % 32));
82
83         nl_handle_destroy(handle);
84 }
85 #endif /* CONFIG_LIBNL20 */
86
87
88 #ifndef IFF_LOWER_UP
89 #define IFF_LOWER_UP   0x10000         /* driver signals L1 up         */
90 #endif
91 #ifndef IFF_DORMANT
92 #define IFF_DORMANT    0x20000         /* driver signals dormant       */
93 #endif
94
95 #ifndef IF_OPER_DORMANT
96 #define IF_OPER_DORMANT 5
97 #endif
98 #ifndef IF_OPER_UP
99 #define IF_OPER_UP 6
100 #endif
101
102 struct i802_bss {
103         struct wpa_driver_nl80211_data *drv;
104         struct i802_bss *next;
105         int ifindex;
106         char ifname[IFNAMSIZ + 1];
107         unsigned int beacon_set:1;
108 };
109
110 struct wpa_driver_nl80211_data {
111         void *ctx;
112         struct netlink_data *netlink;
113         int ioctl_sock; /* socket for ioctl() use */
114         char brname[IFNAMSIZ];
115         int ifindex;
116         int if_removed;
117         int if_disabled;
118         struct rfkill_data *rfkill;
119         struct wpa_driver_capa capa;
120         int has_capability;
121
122         int operstate;
123
124         int scan_complete_events;
125
126         struct nl_handle *nl_handle;
127         struct nl_handle *nl_handle_event;
128         struct nl_handle *nl_handle_preq;
129         struct nl_cache *nl_cache;
130         struct nl_cache *nl_cache_event;
131         struct nl_cache *nl_cache_preq;
132         struct nl_cb *nl_cb;
133         struct genl_family *nl80211;
134
135         u8 auth_bssid[ETH_ALEN];
136         u8 bssid[ETH_ALEN];
137         int associated;
138         u8 ssid[32];
139         size_t ssid_len;
140         int nlmode;
141         int ap_scan_as_station;
142         unsigned int assoc_freq;
143
144         int monitor_sock;
145         int monitor_ifidx;
146         int disable_11b_rates;
147
148         unsigned int pending_remain_on_chan:1;
149         unsigned int added_bridge:1;
150         unsigned int added_if_into_bridge:1;
151
152         u64 remain_on_chan_cookie;
153         u64 send_action_cookie;
154
155         unsigned int last_mgmt_freq;
156
157         struct wpa_driver_scan_filter *filter_ssids;
158         size_t num_filter_ssids;
159
160         struct i802_bss first_bss;
161
162 #ifdef HOSTAPD
163         int eapol_sock; /* socket for EAPOL frames */
164
165         int default_if_indices[16];
166         int *if_indices;
167         int num_if_indices;
168
169         int last_freq;
170         int last_freq_ht;
171 #endif /* HOSTAPD */
172 };
173
174
175 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx,
176                                             void *timeout_ctx);
177 static int wpa_driver_nl80211_set_mode(void *priv, int mode);
178 static int
179 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv);
180 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
181                                    const u8 *addr, int cmd, u16 reason_code,
182                                    int local_state_change);
183 static void nl80211_remove_monitor_interface(
184         struct wpa_driver_nl80211_data *drv);
185 static int nl80211_send_frame_cmd(struct wpa_driver_nl80211_data *drv,
186                                   unsigned int freq, const u8 *buf,
187                                   size_t buf_len, u64 *cookie);
188 static int wpa_driver_nl80211_probe_req_report(void *priv, int report);
189
190 #ifdef HOSTAPD
191 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
192 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
193 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
194 static int wpa_driver_nl80211_if_remove(void *priv,
195                                         enum wpa_driver_if_type type,
196                                         const char *ifname);
197 #else /* HOSTAPD */
198 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
199 {
200         return 0;
201 }
202 #endif /* HOSTAPD */
203
204 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq);
205 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
206                                      int ifindex, int disabled);
207
208
209 /* nl80211 code */
210 static int ack_handler(struct nl_msg *msg, void *arg)
211 {
212         int *err = arg;
213         *err = 0;
214         return NL_STOP;
215 }
216
217 static int finish_handler(struct nl_msg *msg, void *arg)
218 {
219         int *ret = arg;
220         *ret = 0;
221         return NL_SKIP;
222 }
223
224 static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err,
225                          void *arg)
226 {
227         int *ret = arg;
228         *ret = err->error;
229         return NL_SKIP;
230 }
231
232
233 static int no_seq_check(struct nl_msg *msg, void *arg)
234 {
235         return NL_OK;
236 }
237
238
239 static int send_and_recv(struct wpa_driver_nl80211_data *drv,
240                          struct nl_handle *nl_handle, struct nl_msg *msg,
241                          int (*valid_handler)(struct nl_msg *, void *),
242                          void *valid_data)
243 {
244         struct nl_cb *cb;
245         int err = -ENOMEM;
246
247         cb = nl_cb_clone(drv->nl_cb);
248         if (!cb)
249                 goto out;
250
251         err = nl_send_auto_complete(nl_handle, msg);
252         if (err < 0)
253                 goto out;
254
255         err = 1;
256
257         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
258         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
259         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
260
261         if (valid_handler)
262                 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM,
263                           valid_handler, valid_data);
264
265         while (err > 0)
266                 nl_recvmsgs(nl_handle, cb);
267  out:
268         nl_cb_put(cb);
269         nlmsg_free(msg);
270         return err;
271 }
272
273
274 static int send_and_recv_msgs(struct wpa_driver_nl80211_data *drv,
275                               struct nl_msg *msg,
276                               int (*valid_handler)(struct nl_msg *, void *),
277                               void *valid_data)
278 {
279         return send_and_recv(drv, drv->nl_handle, msg, valid_handler,
280                              valid_data);
281 }
282
283
284 struct family_data {
285         const char *group;
286         int id;
287 };
288
289
290 static int family_handler(struct nl_msg *msg, void *arg)
291 {
292         struct family_data *res = arg;
293         struct nlattr *tb[CTRL_ATTR_MAX + 1];
294         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
295         struct nlattr *mcgrp;
296         int i;
297
298         nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
299                   genlmsg_attrlen(gnlh, 0), NULL);
300         if (!tb[CTRL_ATTR_MCAST_GROUPS])
301                 return NL_SKIP;
302
303         nla_for_each_nested(mcgrp, tb[CTRL_ATTR_MCAST_GROUPS], i) {
304                 struct nlattr *tb2[CTRL_ATTR_MCAST_GRP_MAX + 1];
305                 nla_parse(tb2, CTRL_ATTR_MCAST_GRP_MAX, nla_data(mcgrp),
306                           nla_len(mcgrp), NULL);
307                 if (!tb2[CTRL_ATTR_MCAST_GRP_NAME] ||
308                     !tb2[CTRL_ATTR_MCAST_GRP_ID] ||
309                     os_strncmp(nla_data(tb2[CTRL_ATTR_MCAST_GRP_NAME]),
310                                res->group,
311                                nla_len(tb2[CTRL_ATTR_MCAST_GRP_NAME])) != 0)
312                         continue;
313                 res->id = nla_get_u32(tb2[CTRL_ATTR_MCAST_GRP_ID]);
314                 break;
315         };
316
317         return NL_SKIP;
318 }
319
320
321 static int nl_get_multicast_id(struct wpa_driver_nl80211_data *drv,
322                                const char *family, const char *group)
323 {
324         struct nl_msg *msg;
325         int ret = -1;
326         struct family_data res = { group, -ENOENT };
327
328         msg = nlmsg_alloc();
329         if (!msg)
330                 return -ENOMEM;
331         genlmsg_put(msg, 0, 0, genl_ctrl_resolve(drv->nl_handle, "nlctrl"),
332                     0, 0, CTRL_CMD_GETFAMILY, 0);
333         NLA_PUT_STRING(msg, CTRL_ATTR_FAMILY_NAME, family);
334
335         ret = send_and_recv_msgs(drv, msg, family_handler, &res);
336         msg = NULL;
337         if (ret == 0)
338                 ret = res.id;
339
340 nla_put_failure:
341         nlmsg_free(msg);
342         return ret;
343 }
344
345
346 static int wpa_driver_nl80211_get_bssid(void *priv, u8 *bssid)
347 {
348         struct i802_bss *bss = priv;
349         struct wpa_driver_nl80211_data *drv = bss->drv;
350         if (!drv->associated)
351                 return -1;
352         os_memcpy(bssid, drv->bssid, ETH_ALEN);
353         return 0;
354 }
355
356
357 static int wpa_driver_nl80211_get_ssid(void *priv, u8 *ssid)
358 {
359         struct i802_bss *bss = priv;
360         struct wpa_driver_nl80211_data *drv = bss->drv;
361         if (!drv->associated)
362                 return -1;
363         os_memcpy(ssid, drv->ssid, drv->ssid_len);
364         return drv->ssid_len;
365 }
366
367
368 static void wpa_driver_nl80211_event_link(struct wpa_driver_nl80211_data *drv,
369                                           char *buf, size_t len, int del)
370 {
371         union wpa_event_data event;
372
373         os_memset(&event, 0, sizeof(event));
374         if (len > sizeof(event.interface_status.ifname))
375                 len = sizeof(event.interface_status.ifname) - 1;
376         os_memcpy(event.interface_status.ifname, buf, len);
377         event.interface_status.ievent = del ? EVENT_INTERFACE_REMOVED :
378                 EVENT_INTERFACE_ADDED;
379
380         wpa_printf(MSG_DEBUG, "RTM_%sLINK, IFLA_IFNAME: Interface '%s' %s",
381                    del ? "DEL" : "NEW",
382                    event.interface_status.ifname,
383                    del ? "removed" : "added");
384
385         if (os_strcmp(drv->first_bss.ifname, event.interface_status.ifname) == 0) {
386                 if (del)
387                         drv->if_removed = 1;
388                 else
389                         drv->if_removed = 0;
390         }
391
392         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_STATUS, &event);
393 }
394
395
396 static int wpa_driver_nl80211_own_ifname(struct wpa_driver_nl80211_data *drv,
397                                          u8 *buf, size_t len)
398 {
399         int attrlen, rta_len;
400         struct rtattr *attr;
401
402         attrlen = len;
403         attr = (struct rtattr *) buf;
404
405         rta_len = RTA_ALIGN(sizeof(struct rtattr));
406         while (RTA_OK(attr, attrlen)) {
407                 if (attr->rta_type == IFLA_IFNAME) {
408                         if (os_strcmp(((char *) attr) + rta_len, drv->first_bss.ifname)
409                             == 0)
410                                 return 1;
411                         else
412                                 break;
413                 }
414                 attr = RTA_NEXT(attr, attrlen);
415         }
416
417         return 0;
418 }
419
420
421 static int wpa_driver_nl80211_own_ifindex(struct wpa_driver_nl80211_data *drv,
422                                           int ifindex, u8 *buf, size_t len)
423 {
424         if (drv->ifindex == ifindex)
425                 return 1;
426
427         if (drv->if_removed && wpa_driver_nl80211_own_ifname(drv, buf, len)) {
428                 drv->first_bss.ifindex = if_nametoindex(drv->first_bss.ifname);
429                 wpa_printf(MSG_DEBUG, "nl80211: Update ifindex for a removed "
430                            "interface");
431                 wpa_driver_nl80211_finish_drv_init(drv);
432                 return 1;
433         }
434
435         return 0;
436 }
437
438
439 static void wpa_driver_nl80211_event_rtm_newlink(void *ctx,
440                                                  struct ifinfomsg *ifi,
441                                                  u8 *buf, size_t len)
442 {
443         struct wpa_driver_nl80211_data *drv = ctx;
444         int attrlen, rta_len;
445         struct rtattr *attr;
446         u32 brid = 0;
447
448         if (!wpa_driver_nl80211_own_ifindex(drv, ifi->ifi_index, buf, len) &&
449             !have_ifidx(drv, ifi->ifi_index)) {
450                 wpa_printf(MSG_DEBUG, "nl80211: Ignore event for foreign "
451                            "ifindex %d", ifi->ifi_index);
452                 return;
453         }
454
455         wpa_printf(MSG_DEBUG, "RTM_NEWLINK: operstate=%d ifi_flags=0x%x "
456                    "(%s%s%s%s)",
457                    drv->operstate, ifi->ifi_flags,
458                    (ifi->ifi_flags & IFF_UP) ? "[UP]" : "",
459                    (ifi->ifi_flags & IFF_RUNNING) ? "[RUNNING]" : "",
460                    (ifi->ifi_flags & IFF_LOWER_UP) ? "[LOWER_UP]" : "",
461                    (ifi->ifi_flags & IFF_DORMANT) ? "[DORMANT]" : "");
462
463         if (!drv->if_disabled && !(ifi->ifi_flags & IFF_UP)) {
464                 wpa_printf(MSG_DEBUG, "nl80211: Interface down");
465                 drv->if_disabled = 1;
466                 wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_DISABLED, NULL);
467         }
468
469         if (drv->if_disabled && (ifi->ifi_flags & IFF_UP)) {
470                 wpa_printf(MSG_DEBUG, "nl80211: Interface up");
471                 drv->if_disabled = 0;
472                 wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_ENABLED, NULL);
473         }
474
475         /*
476          * Some drivers send the association event before the operup event--in
477          * this case, lifting operstate in wpa_driver_nl80211_set_operstate()
478          * fails. This will hit us when wpa_supplicant does not need to do
479          * IEEE 802.1X authentication
480          */
481         if (drv->operstate == 1 &&
482             (ifi->ifi_flags & (IFF_LOWER_UP | IFF_DORMANT)) == IFF_LOWER_UP &&
483             !(ifi->ifi_flags & IFF_RUNNING))
484                 netlink_send_oper_ifla(drv->netlink, drv->ifindex,
485                                        -1, IF_OPER_UP);
486
487         attrlen = len;
488         attr = (struct rtattr *) buf;
489         rta_len = RTA_ALIGN(sizeof(struct rtattr));
490         while (RTA_OK(attr, attrlen)) {
491                 if (attr->rta_type == IFLA_IFNAME) {
492                         wpa_driver_nl80211_event_link(
493                                 drv,
494                                 ((char *) attr) + rta_len,
495                                 attr->rta_len - rta_len, 0);
496                 } else if (attr->rta_type == IFLA_MASTER)
497                         brid = nla_get_u32((struct nlattr *) attr);
498                 attr = RTA_NEXT(attr, attrlen);
499         }
500
501 #ifdef HOSTAPD
502         if (ifi->ifi_family == AF_BRIDGE && brid) {
503                 /* device has been added to bridge */
504                 char namebuf[IFNAMSIZ];
505                 if_indextoname(brid, namebuf);
506                 wpa_printf(MSG_DEBUG, "nl80211: Add ifindex %u for bridge %s",
507                            brid, namebuf);
508                 add_ifidx(drv, brid);
509         }
510 #endif /* HOSTAPD */
511 }
512
513
514 static void wpa_driver_nl80211_event_rtm_dellink(void *ctx,
515                                                  struct ifinfomsg *ifi,
516                                                  u8 *buf, size_t len)
517 {
518         struct wpa_driver_nl80211_data *drv = ctx;
519         int attrlen, rta_len;
520         struct rtattr *attr;
521         u32 brid = 0;
522
523         attrlen = len;
524         attr = (struct rtattr *) buf;
525
526         rta_len = RTA_ALIGN(sizeof(struct rtattr));
527         while (RTA_OK(attr, attrlen)) {
528                 if (attr->rta_type == IFLA_IFNAME) {
529                         wpa_driver_nl80211_event_link(
530                                 drv,
531                                 ((char *) attr) + rta_len,
532                                 attr->rta_len - rta_len, 1);
533                 } else if (attr->rta_type == IFLA_MASTER)
534                         brid = nla_get_u32((struct nlattr *) attr);
535                 attr = RTA_NEXT(attr, attrlen);
536         }
537
538 #ifdef HOSTAPD
539         if (ifi->ifi_family == AF_BRIDGE && brid) {
540                 /* device has been removed from bridge */
541                 char namebuf[IFNAMSIZ];
542                 if_indextoname(brid, namebuf);
543                 wpa_printf(MSG_DEBUG, "nl80211: Remove ifindex %u for bridge "
544                            "%s", brid, namebuf);
545                 del_ifidx(drv, brid);
546         }
547 #endif /* HOSTAPD */
548 }
549
550
551 static void mlme_event_auth(struct wpa_driver_nl80211_data *drv,
552                             const u8 *frame, size_t len)
553 {
554         const struct ieee80211_mgmt *mgmt;
555         union wpa_event_data event;
556
557         mgmt = (const struct ieee80211_mgmt *) frame;
558         if (len < 24 + sizeof(mgmt->u.auth)) {
559                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
560                            "frame");
561                 return;
562         }
563
564         os_memcpy(drv->auth_bssid, mgmt->sa, ETH_ALEN);
565         os_memset(&event, 0, sizeof(event));
566         os_memcpy(event.auth.peer, mgmt->sa, ETH_ALEN);
567         event.auth.auth_type = le_to_host16(mgmt->u.auth.auth_alg);
568         event.auth.status_code = le_to_host16(mgmt->u.auth.status_code);
569         if (len > 24 + sizeof(mgmt->u.auth)) {
570                 event.auth.ies = mgmt->u.auth.variable;
571                 event.auth.ies_len = len - 24 - sizeof(mgmt->u.auth);
572         }
573
574         wpa_supplicant_event(drv->ctx, EVENT_AUTH, &event);
575 }
576
577
578 static void mlme_event_assoc(struct wpa_driver_nl80211_data *drv,
579                             const u8 *frame, size_t len)
580 {
581         const struct ieee80211_mgmt *mgmt;
582         union wpa_event_data event;
583         u16 status;
584
585         mgmt = (const struct ieee80211_mgmt *) frame;
586         if (len < 24 + sizeof(mgmt->u.assoc_resp)) {
587                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
588                            "frame");
589                 return;
590         }
591
592         status = le_to_host16(mgmt->u.assoc_resp.status_code);
593         if (status != WLAN_STATUS_SUCCESS) {
594                 os_memset(&event, 0, sizeof(event));
595                 event.assoc_reject.bssid = mgmt->bssid;
596                 if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
597                         event.assoc_reject.resp_ies =
598                                 (u8 *) mgmt->u.assoc_resp.variable;
599                         event.assoc_reject.resp_ies_len =
600                                 len - 24 - sizeof(mgmt->u.assoc_resp);
601                 }
602                 event.assoc_reject.status_code = status;
603
604                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
605                 return;
606         }
607
608         drv->associated = 1;
609         os_memcpy(drv->bssid, mgmt->sa, ETH_ALEN);
610
611         os_memset(&event, 0, sizeof(event));
612         if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
613                 event.assoc_info.resp_ies = (u8 *) mgmt->u.assoc_resp.variable;
614                 event.assoc_info.resp_ies_len =
615                         len - 24 - sizeof(mgmt->u.assoc_resp);
616         }
617
618         event.assoc_info.freq = drv->assoc_freq;
619
620         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
621 }
622
623
624 static void mlme_event_connect(struct wpa_driver_nl80211_data *drv,
625                                enum nl80211_commands cmd, struct nlattr *status,
626                                struct nlattr *addr, struct nlattr *req_ie,
627                                struct nlattr *resp_ie)
628 {
629         union wpa_event_data event;
630
631         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
632                 /*
633                  * Avoid reporting two association events that would confuse
634                  * the core code.
635                  */
636                 wpa_printf(MSG_DEBUG, "nl80211: Ignore connect event (cmd=%d) "
637                            "when using userspace SME", cmd);
638                 return;
639         }
640
641         os_memset(&event, 0, sizeof(event));
642         if (cmd == NL80211_CMD_CONNECT &&
643             nla_get_u16(status) != WLAN_STATUS_SUCCESS) {
644                 if (resp_ie) {
645                         event.assoc_reject.resp_ies = nla_data(resp_ie);
646                         event.assoc_reject.resp_ies_len = nla_len(resp_ie);
647                 }
648                 event.assoc_reject.status_code = nla_get_u16(status);
649                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
650                 return;
651         }
652
653         drv->associated = 1;
654         if (addr)
655                 os_memcpy(drv->bssid, nla_data(addr), ETH_ALEN);
656
657         if (req_ie) {
658                 event.assoc_info.req_ies = nla_data(req_ie);
659                 event.assoc_info.req_ies_len = nla_len(req_ie);
660         }
661         if (resp_ie) {
662                 event.assoc_info.resp_ies = nla_data(resp_ie);
663                 event.assoc_info.resp_ies_len = nla_len(resp_ie);
664         }
665
666         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
667 }
668
669
670 static void mlme_timeout_event(struct wpa_driver_nl80211_data *drv,
671                                enum nl80211_commands cmd, struct nlattr *addr)
672 {
673         union wpa_event_data event;
674         enum wpa_event_type ev;
675
676         if (nla_len(addr) != ETH_ALEN)
677                 return;
678
679         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d; timeout with " MACSTR,
680                    cmd, MAC2STR((u8 *) nla_data(addr)));
681
682         if (cmd == NL80211_CMD_AUTHENTICATE)
683                 ev = EVENT_AUTH_TIMED_OUT;
684         else if (cmd == NL80211_CMD_ASSOCIATE)
685                 ev = EVENT_ASSOC_TIMED_OUT;
686         else
687                 return;
688
689         os_memset(&event, 0, sizeof(event));
690         os_memcpy(event.timeout_event.addr, nla_data(addr), ETH_ALEN);
691         wpa_supplicant_event(drv->ctx, ev, &event);
692 }
693
694
695 static void mlme_event_mgmt(struct wpa_driver_nl80211_data *drv,
696                             struct nlattr *freq, const u8 *frame, size_t len)
697 {
698         const struct ieee80211_mgmt *mgmt;
699         union wpa_event_data event;
700         u16 fc, stype;
701
702         mgmt = (const struct ieee80211_mgmt *) frame;
703         if (len < 24) {
704                 wpa_printf(MSG_DEBUG, "nl80211: Too short action frame");
705                 return;
706         }
707
708         fc = le_to_host16(mgmt->frame_control);
709         stype = WLAN_FC_GET_STYPE(fc);
710
711         os_memset(&event, 0, sizeof(event));
712         if (freq) {
713                 event.rx_action.freq = nla_get_u32(freq);
714                 drv->last_mgmt_freq = event.rx_action.freq;
715         }
716         if (stype == WLAN_FC_STYPE_ACTION) {
717                 event.rx_action.da = mgmt->da;
718                 event.rx_action.sa = mgmt->sa;
719                 event.rx_action.bssid = mgmt->bssid;
720                 event.rx_action.category = mgmt->u.action.category;
721                 event.rx_action.data = &mgmt->u.action.category + 1;
722                 event.rx_action.len = frame + len - event.rx_action.data;
723                 wpa_supplicant_event(drv->ctx, EVENT_RX_ACTION, &event);
724         } else {
725                 event.rx_mgmt.frame = frame;
726                 event.rx_mgmt.frame_len = len;
727                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
728         }
729 }
730
731
732 static void mlme_event_action_tx_status(struct wpa_driver_nl80211_data *drv,
733                                         struct nlattr *cookie, const u8 *frame,
734                                         size_t len, struct nlattr *ack)
735 {
736         union wpa_event_data event;
737         const struct ieee80211_hdr *hdr;
738         u16 fc;
739         u64 cookie_val;
740
741         if (!cookie)
742                 return;
743
744         cookie_val = nla_get_u64(cookie);
745         wpa_printf(MSG_DEBUG, "nl80211: Action TX status: cookie=0%llx%s "
746                    "(ack=%d)",
747                    (long long unsigned int) cookie_val,
748                    cookie_val == drv->send_action_cookie ?
749                    " (match)" : " (unknown)", ack != NULL);
750         if (cookie_val != drv->send_action_cookie)
751                 return;
752
753         hdr = (const struct ieee80211_hdr *) frame;
754         fc = le_to_host16(hdr->frame_control);
755
756         os_memset(&event, 0, sizeof(event));
757         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
758         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
759         event.tx_status.dst = hdr->addr1;
760         event.tx_status.data = frame;
761         event.tx_status.data_len = len;
762         event.tx_status.ack = ack != NULL;
763         wpa_supplicant_event(drv->ctx, EVENT_TX_STATUS, &event);
764 }
765
766
767 static void mlme_event_deauth_disassoc(struct wpa_driver_nl80211_data *drv,
768                                        enum wpa_event_type type,
769                                        const u8 *frame, size_t len)
770 {
771         const struct ieee80211_mgmt *mgmt;
772         union wpa_event_data event;
773         const u8 *bssid = NULL;
774         u16 reason_code = 0;
775
776         mgmt = (const struct ieee80211_mgmt *) frame;
777         if (len >= 24) {
778                 bssid = mgmt->bssid;
779
780                 if (drv->associated != 0 &&
781                     os_memcmp(bssid, drv->bssid, ETH_ALEN) != 0 &&
782                     os_memcmp(bssid, drv->auth_bssid, ETH_ALEN) != 0) {
783                         /*
784                          * We have presumably received this deauth as a
785                          * response to a clear_state_mismatch() outgoing
786                          * deauth.  Don't let it take us offline!
787                          */
788                         wpa_printf(MSG_DEBUG, "nl80211: Deauth received "
789                                    "from Unknown BSSID " MACSTR " -- ignoring",
790                                    MAC2STR(bssid));
791                         return;
792                 }
793         }
794
795         drv->associated = 0;
796         os_memset(&event, 0, sizeof(event));
797
798         /* Note: Same offset for Reason Code in both frame subtypes */
799         if (len >= 24 + sizeof(mgmt->u.deauth))
800                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
801
802         if (type == EVENT_DISASSOC) {
803                 event.disassoc_info.addr = bssid;
804                 event.disassoc_info.reason_code = reason_code;
805                 if (frame + len > mgmt->u.disassoc.variable) {
806                         event.disassoc_info.ie = mgmt->u.disassoc.variable;
807                         event.disassoc_info.ie_len = frame + len -
808                                 mgmt->u.disassoc.variable;
809                 }
810         } else {
811                 event.deauth_info.addr = bssid;
812                 event.deauth_info.reason_code = reason_code;
813                 if (frame + len > mgmt->u.deauth.variable) {
814                         event.deauth_info.ie = mgmt->u.deauth.variable;
815                         event.deauth_info.ie_len = frame + len -
816                                 mgmt->u.deauth.variable;
817                 }
818         }
819
820         wpa_supplicant_event(drv->ctx, type, &event);
821 }
822
823
824 static void mlme_event(struct wpa_driver_nl80211_data *drv,
825                        enum nl80211_commands cmd, struct nlattr *frame,
826                        struct nlattr *addr, struct nlattr *timed_out,
827                        struct nlattr *freq, struct nlattr *ack,
828                        struct nlattr *cookie)
829 {
830         if (timed_out && addr) {
831                 mlme_timeout_event(drv, cmd, addr);
832                 return;
833         }
834
835         if (frame == NULL) {
836                 wpa_printf(MSG_DEBUG, "nl80211: MLME event %d without frame "
837                            "data", cmd);
838                 return;
839         }
840
841         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d", cmd);
842         wpa_hexdump(MSG_MSGDUMP, "nl80211: MLME event frame",
843                     nla_data(frame), nla_len(frame));
844
845         switch (cmd) {
846         case NL80211_CMD_AUTHENTICATE:
847                 mlme_event_auth(drv, nla_data(frame), nla_len(frame));
848                 break;
849         case NL80211_CMD_ASSOCIATE:
850                 mlme_event_assoc(drv, nla_data(frame), nla_len(frame));
851                 break;
852         case NL80211_CMD_DEAUTHENTICATE:
853                 mlme_event_deauth_disassoc(drv, EVENT_DEAUTH,
854                                            nla_data(frame), nla_len(frame));
855                 break;
856         case NL80211_CMD_DISASSOCIATE:
857                 mlme_event_deauth_disassoc(drv, EVENT_DISASSOC,
858                                            nla_data(frame), nla_len(frame));
859                 break;
860         case NL80211_CMD_FRAME:
861                 mlme_event_mgmt(drv, freq, nla_data(frame), nla_len(frame));
862                 break;
863         case NL80211_CMD_FRAME_TX_STATUS:
864                 mlme_event_action_tx_status(drv, cookie, nla_data(frame),
865                                             nla_len(frame), ack);
866                 break;
867         default:
868                 break;
869         }
870 }
871
872
873 static void mlme_event_michael_mic_failure(struct wpa_driver_nl80211_data *drv,
874                                            struct nlattr *tb[])
875 {
876         union wpa_event_data data;
877
878         wpa_printf(MSG_DEBUG, "nl80211: MLME event Michael MIC failure");
879         os_memset(&data, 0, sizeof(data));
880         if (tb[NL80211_ATTR_MAC]) {
881                 wpa_hexdump(MSG_DEBUG, "nl80211: Source MAC address",
882                             nla_data(tb[NL80211_ATTR_MAC]),
883                             nla_len(tb[NL80211_ATTR_MAC]));
884                 data.michael_mic_failure.src = nla_data(tb[NL80211_ATTR_MAC]);
885         }
886         if (tb[NL80211_ATTR_KEY_SEQ]) {
887                 wpa_hexdump(MSG_DEBUG, "nl80211: TSC",
888                             nla_data(tb[NL80211_ATTR_KEY_SEQ]),
889                             nla_len(tb[NL80211_ATTR_KEY_SEQ]));
890         }
891         if (tb[NL80211_ATTR_KEY_TYPE]) {
892                 enum nl80211_key_type key_type =
893                         nla_get_u32(tb[NL80211_ATTR_KEY_TYPE]);
894                 wpa_printf(MSG_DEBUG, "nl80211: Key Type %d", key_type);
895                 if (key_type == NL80211_KEYTYPE_PAIRWISE)
896                         data.michael_mic_failure.unicast = 1;
897         } else
898                 data.michael_mic_failure.unicast = 1;
899
900         if (tb[NL80211_ATTR_KEY_IDX]) {
901                 u8 key_id = nla_get_u8(tb[NL80211_ATTR_KEY_IDX]);
902                 wpa_printf(MSG_DEBUG, "nl80211: Key Id %d", key_id);
903         }
904
905         wpa_supplicant_event(drv->ctx, EVENT_MICHAEL_MIC_FAILURE, &data);
906 }
907
908
909 static void mlme_event_join_ibss(struct wpa_driver_nl80211_data *drv,
910                                  struct nlattr *tb[])
911 {
912         if (tb[NL80211_ATTR_MAC] == NULL) {
913                 wpa_printf(MSG_DEBUG, "nl80211: No address in IBSS joined "
914                            "event");
915                 return;
916         }
917         os_memcpy(drv->bssid, nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
918         drv->associated = 1;
919         wpa_printf(MSG_DEBUG, "nl80211: IBSS " MACSTR " joined",
920                    MAC2STR(drv->bssid));
921
922         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, NULL);
923 }
924
925
926 static void mlme_event_remain_on_channel(struct wpa_driver_nl80211_data *drv,
927                                          int cancel_event, struct nlattr *tb[])
928 {
929         unsigned int freq, chan_type, duration;
930         union wpa_event_data data;
931         u64 cookie;
932
933         if (tb[NL80211_ATTR_WIPHY_FREQ])
934                 freq = nla_get_u32(tb[NL80211_ATTR_WIPHY_FREQ]);
935         else
936                 freq = 0;
937
938         if (tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE])
939                 chan_type = nla_get_u32(tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
940         else
941                 chan_type = 0;
942
943         if (tb[NL80211_ATTR_DURATION])
944                 duration = nla_get_u32(tb[NL80211_ATTR_DURATION]);
945         else
946                 duration = 0;
947
948         if (tb[NL80211_ATTR_COOKIE])
949                 cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
950         else
951                 cookie = 0;
952
953         wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel event (cancel=%d "
954                    "freq=%u channel_type=%u duration=%u cookie=0x%llx (%s))",
955                    cancel_event, freq, chan_type, duration,
956                    (long long unsigned int) cookie,
957                    cookie == drv->remain_on_chan_cookie ? "match" : "unknown");
958
959         if (cookie != drv->remain_on_chan_cookie)
960                 return; /* not for us */
961
962         drv->pending_remain_on_chan = !cancel_event;
963
964         os_memset(&data, 0, sizeof(data));
965         data.remain_on_channel.freq = freq;
966         data.remain_on_channel.duration = duration;
967         wpa_supplicant_event(drv->ctx, cancel_event ?
968                              EVENT_CANCEL_REMAIN_ON_CHANNEL :
969                              EVENT_REMAIN_ON_CHANNEL, &data);
970 }
971
972
973 static void send_scan_event(struct wpa_driver_nl80211_data *drv, int aborted,
974                             struct nlattr *tb[])
975 {
976         union wpa_event_data event;
977         struct nlattr *nl;
978         int rem;
979         struct scan_info *info;
980 #define MAX_REPORT_FREQS 50
981         int freqs[MAX_REPORT_FREQS];
982         int num_freqs = 0;
983
984         os_memset(&event, 0, sizeof(event));
985         info = &event.scan_info;
986         info->aborted = aborted;
987
988         if (tb[NL80211_ATTR_SCAN_SSIDS]) {
989                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_SSIDS], rem) {
990                         struct wpa_driver_scan_ssid *s =
991                                 &info->ssids[info->num_ssids];
992                         s->ssid = nla_data(nl);
993                         s->ssid_len = nla_len(nl);
994                         info->num_ssids++;
995                         if (info->num_ssids == WPAS_MAX_SCAN_SSIDS)
996                                 break;
997                 }
998         }
999         if (tb[NL80211_ATTR_SCAN_FREQUENCIES]) {
1000                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_FREQUENCIES], rem)
1001                 {
1002                         freqs[num_freqs] = nla_get_u32(nl);
1003                         num_freqs++;
1004                         if (num_freqs == MAX_REPORT_FREQS - 1)
1005                                 break;
1006                 }
1007                 info->freqs = freqs;
1008                 info->num_freqs = num_freqs;
1009         }
1010         wpa_supplicant_event(drv->ctx, EVENT_SCAN_RESULTS, &event);
1011 }
1012
1013
1014 static int get_link_signal(struct nl_msg *msg, void *arg)
1015 {
1016         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1017         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1018         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
1019         static struct nla_policy policy[NL80211_STA_INFO_MAX + 1] = {
1020                 [NL80211_STA_INFO_SIGNAL] = { .type = NLA_U8 },
1021         };
1022         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
1023         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
1024                 [NL80211_RATE_INFO_BITRATE] = { .type = NLA_U16 },
1025                 [NL80211_RATE_INFO_MCS] = { .type = NLA_U8 },
1026                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG },
1027                 [NL80211_RATE_INFO_SHORT_GI] = { .type = NLA_FLAG },
1028         };
1029         struct signal_change *sig_change = arg;
1030
1031         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1032                   genlmsg_attrlen(gnlh, 0), NULL);
1033         if (!tb[NL80211_ATTR_STA_INFO] ||
1034             nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
1035                              tb[NL80211_ATTR_STA_INFO], policy))
1036                 return NL_SKIP;
1037         if (!sinfo[NL80211_STA_INFO_SIGNAL])
1038                 return NL_SKIP;
1039
1040         sig_change->current_signal =
1041                 (s8) nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
1042
1043         if (sinfo[NL80211_STA_INFO_TX_BITRATE]) {
1044                 if (nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1045                                      sinfo[NL80211_STA_INFO_TX_BITRATE],
1046                                      rate_policy)) {
1047                         sig_change->current_txrate = 0;
1048                 } else {
1049                         if (rinfo[NL80211_RATE_INFO_BITRATE]) {
1050                                 sig_change->current_txrate =
1051                                         nla_get_u16(rinfo[
1052                                              NL80211_RATE_INFO_BITRATE]) * 100;
1053                         }
1054                 }
1055         }
1056
1057         return NL_SKIP;
1058 }
1059
1060
1061 static int nl80211_get_link_signal(struct wpa_driver_nl80211_data *drv,
1062                                    struct signal_change *sig)
1063 {
1064         struct nl_msg *msg;
1065
1066         sig->current_signal = -9999;
1067         sig->current_txrate = 0;
1068
1069         msg = nlmsg_alloc();
1070         if (!msg)
1071                 return -ENOMEM;
1072
1073         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1074                     0, NL80211_CMD_GET_STATION, 0);
1075
1076         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1077         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
1078
1079         return send_and_recv_msgs(drv, msg, get_link_signal, sig);
1080  nla_put_failure:
1081         return -ENOBUFS;
1082 }
1083
1084
1085 static int get_link_noise(struct nl_msg *msg, void *arg)
1086 {
1087         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1088         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1089         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1090         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1091                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1092                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
1093         };
1094         struct signal_change *sig_change = arg;
1095
1096         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1097                   genlmsg_attrlen(gnlh, 0), NULL);
1098
1099         if (!tb[NL80211_ATTR_SURVEY_INFO]) {
1100                 wpa_printf(MSG_DEBUG, "nl80211: survey data missing!");
1101                 return NL_SKIP;
1102         }
1103
1104         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1105                              tb[NL80211_ATTR_SURVEY_INFO],
1106                              survey_policy)) {
1107                 wpa_printf(MSG_DEBUG, "nl80211: failed to parse nested "
1108                            "attributes!");
1109                 return NL_SKIP;
1110         }
1111
1112         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1113                 return NL_SKIP;
1114
1115         if (nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
1116             sig_change->frequency)
1117                 return NL_SKIP;
1118
1119         if (!sinfo[NL80211_SURVEY_INFO_NOISE])
1120                 return NL_SKIP;
1121
1122         sig_change->current_noise =
1123                 (s8) nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1124
1125         return NL_SKIP;
1126 }
1127
1128
1129 static int nl80211_get_link_noise(struct wpa_driver_nl80211_data *drv,
1130                                   struct signal_change *sig_change)
1131 {
1132         struct nl_msg *msg;
1133
1134         sig_change->current_noise = 9999;
1135         sig_change->frequency = drv->assoc_freq;
1136
1137         msg = nlmsg_alloc();
1138         if (!msg)
1139                 return -ENOMEM;
1140
1141         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1142                     NLM_F_DUMP, NL80211_CMD_GET_SURVEY, 0);
1143
1144         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1145
1146         return send_and_recv_msgs(drv, msg, get_link_noise, sig_change);
1147  nla_put_failure:
1148         return -ENOBUFS;
1149 }
1150
1151
1152 static void nl80211_cqm_event(struct wpa_driver_nl80211_data *drv,
1153                               struct nlattr *tb[])
1154 {
1155         static struct nla_policy cqm_policy[NL80211_ATTR_CQM_MAX + 1] = {
1156                 [NL80211_ATTR_CQM_RSSI_THOLD] = { .type = NLA_U32 },
1157                 [NL80211_ATTR_CQM_RSSI_HYST] = { .type = NLA_U8 },
1158                 [NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] = { .type = NLA_U32 },
1159         };
1160         struct nlattr *cqm[NL80211_ATTR_CQM_MAX + 1];
1161         enum nl80211_cqm_rssi_threshold_event event;
1162         union wpa_event_data ed;
1163         struct signal_change sig;
1164         int res;
1165
1166         if (tb[NL80211_ATTR_CQM] == NULL ||
1167             nla_parse_nested(cqm, NL80211_ATTR_CQM_MAX, tb[NL80211_ATTR_CQM],
1168                              cqm_policy)) {
1169                 wpa_printf(MSG_DEBUG, "nl80211: Ignore invalid CQM event");
1170                 return;
1171         }
1172
1173         if (cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] == NULL)
1174                 return;
1175         event = nla_get_u32(cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]);
1176
1177         os_memset(&ed, 0, sizeof(ed));
1178
1179         if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH) {
1180                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1181                            "event: RSSI high");
1182                 ed.signal_change.above_threshold = 1;
1183         } else if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW) {
1184                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1185                            "event: RSSI low");
1186                 ed.signal_change.above_threshold = 0;
1187         } else
1188                 return;
1189
1190         res = nl80211_get_link_signal(drv, &sig);
1191         if (res == 0) {
1192                 ed.signal_change.current_signal = sig.current_signal;
1193                 ed.signal_change.current_txrate = sig.current_txrate;
1194                 wpa_printf(MSG_DEBUG, "nl80211: Signal: %d dBm  txrate: %d",
1195                            sig.current_signal, sig.current_txrate);
1196         }
1197
1198         res = nl80211_get_link_noise(drv, &sig);
1199         if (res == 0) {
1200                 ed.signal_change.current_noise = sig.current_noise;
1201                 wpa_printf(MSG_DEBUG, "nl80211: Noise: %d dBm",
1202                            sig.current_noise);
1203         }
1204
1205         wpa_supplicant_event(drv->ctx, EVENT_SIGNAL_CHANGE, &ed);
1206 }
1207
1208
1209 static int process_event(struct nl_msg *msg, void *arg)
1210 {
1211         struct wpa_driver_nl80211_data *drv = arg;
1212         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1213         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1214         union wpa_event_data data;
1215
1216         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1217                   genlmsg_attrlen(gnlh, 0), NULL);
1218
1219         if (tb[NL80211_ATTR_IFINDEX]) {
1220                 int ifindex = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
1221                 if (ifindex != drv->ifindex && !have_ifidx(drv, ifindex)) {
1222                         wpa_printf(MSG_DEBUG, "nl80211: Ignored event (cmd=%d)"
1223                                    " for foreign interface (ifindex %d)",
1224                                    gnlh->cmd, ifindex);
1225                         return NL_SKIP;
1226                 }
1227         }
1228
1229         if (drv->ap_scan_as_station &&
1230             (gnlh->cmd == NL80211_CMD_NEW_SCAN_RESULTS ||
1231              gnlh->cmd == NL80211_CMD_SCAN_ABORTED)) {
1232                 wpa_driver_nl80211_set_mode(&drv->first_bss,
1233                                             IEEE80211_MODE_AP);
1234                 drv->ap_scan_as_station = 0;
1235         }
1236
1237         switch (gnlh->cmd) {
1238         case NL80211_CMD_TRIGGER_SCAN:
1239                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger");
1240                 break;
1241         case NL80211_CMD_NEW_SCAN_RESULTS:
1242                 wpa_printf(MSG_DEBUG, "nl80211: New scan results available");
1243                 drv->scan_complete_events = 1;
1244                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
1245                                      drv->ctx);
1246                 send_scan_event(drv, 0, tb);
1247                 break;
1248         case NL80211_CMD_SCAN_ABORTED:
1249                 wpa_printf(MSG_DEBUG, "nl80211: Scan aborted");
1250                 /*
1251                  * Need to indicate that scan results are available in order
1252                  * not to make wpa_supplicant stop its scanning.
1253                  */
1254                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
1255                                      drv->ctx);
1256                 send_scan_event(drv, 1, tb);
1257                 break;
1258         case NL80211_CMD_AUTHENTICATE:
1259         case NL80211_CMD_ASSOCIATE:
1260         case NL80211_CMD_DEAUTHENTICATE:
1261         case NL80211_CMD_DISASSOCIATE:
1262         case NL80211_CMD_FRAME:
1263         case NL80211_CMD_FRAME_TX_STATUS:
1264                 mlme_event(drv, gnlh->cmd, tb[NL80211_ATTR_FRAME],
1265                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
1266                            tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
1267                            tb[NL80211_ATTR_COOKIE]);
1268                 break;
1269         case NL80211_CMD_CONNECT:
1270         case NL80211_CMD_ROAM:
1271                 mlme_event_connect(drv, gnlh->cmd,
1272                                    tb[NL80211_ATTR_STATUS_CODE],
1273                                    tb[NL80211_ATTR_MAC],
1274                                    tb[NL80211_ATTR_REQ_IE],
1275                                    tb[NL80211_ATTR_RESP_IE]);
1276                 break;
1277         case NL80211_CMD_DISCONNECT:
1278                 if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1279                         /*
1280                          * Avoid reporting two disassociation events that could
1281                          * confuse the core code.
1282                          */
1283                         wpa_printf(MSG_DEBUG, "nl80211: Ignore disconnect "
1284                                    "event when using userspace SME");
1285                         break;
1286                 }
1287                 drv->associated = 0;
1288                 os_memset(&data, 0, sizeof(data));
1289                 if (tb[NL80211_ATTR_REASON_CODE])
1290                         data.disassoc_info.reason_code =
1291                                 nla_get_u16(tb[NL80211_ATTR_REASON_CODE]);
1292                 wpa_supplicant_event(drv->ctx, EVENT_DISASSOC, &data);
1293                 break;
1294         case NL80211_CMD_MICHAEL_MIC_FAILURE:
1295                 mlme_event_michael_mic_failure(drv, tb);
1296                 break;
1297         case NL80211_CMD_JOIN_IBSS:
1298                 mlme_event_join_ibss(drv, tb);
1299                 break;
1300         case NL80211_CMD_REMAIN_ON_CHANNEL:
1301                 mlme_event_remain_on_channel(drv, 0, tb);
1302                 break;
1303         case NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL:
1304                 mlme_event_remain_on_channel(drv, 1, tb);
1305                 break;
1306         case NL80211_CMD_NOTIFY_CQM:
1307                 nl80211_cqm_event(drv, tb);
1308                 break;
1309         case NL80211_CMD_REG_CHANGE:
1310                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory domain change");
1311                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
1312                                      NULL);
1313                 break;
1314         case NL80211_CMD_REG_BEACON_HINT:
1315                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory beacon hint");
1316                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
1317                                      NULL);
1318                 break;
1319         default:
1320                 wpa_printf(MSG_DEBUG, "nl80211: Ignored unknown event "
1321                            "(cmd=%d)", gnlh->cmd);
1322                 break;
1323         }
1324
1325         return NL_SKIP;
1326 }
1327
1328
1329 static void wpa_driver_nl80211_event_receive(int sock, void *eloop_ctx,
1330                                              void *handle)
1331 {
1332         struct nl_cb *cb;
1333         struct wpa_driver_nl80211_data *drv = eloop_ctx;
1334
1335         wpa_printf(MSG_DEBUG, "nl80211: Event message available");
1336
1337         cb = nl_cb_clone(drv->nl_cb);
1338         if (!cb)
1339                 return;
1340         nl_cb_set(cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, no_seq_check, NULL);
1341         nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM, process_event, drv);
1342         nl_recvmsgs(handle, cb);
1343         nl_cb_put(cb);
1344 }
1345
1346
1347 /**
1348  * wpa_driver_nl80211_set_country - ask nl80211 to set the regulatory domain
1349  * @priv: driver_nl80211 private data
1350  * @alpha2_arg: country to which to switch to
1351  * Returns: 0 on success, -1 on failure
1352  *
1353  * This asks nl80211 to set the regulatory domain for given
1354  * country ISO / IEC alpha2.
1355  */
1356 static int wpa_driver_nl80211_set_country(void *priv, const char *alpha2_arg)
1357 {
1358         struct i802_bss *bss = priv;
1359         struct wpa_driver_nl80211_data *drv = bss->drv;
1360         char alpha2[3];
1361         struct nl_msg *msg;
1362
1363         msg = nlmsg_alloc();
1364         if (!msg)
1365                 return -ENOMEM;
1366
1367         alpha2[0] = alpha2_arg[0];
1368         alpha2[1] = alpha2_arg[1];
1369         alpha2[2] = '\0';
1370
1371         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1372                     0, NL80211_CMD_REQ_SET_REG, 0);
1373
1374         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
1375         if (send_and_recv_msgs(drv, msg, NULL, NULL))
1376                 return -EINVAL;
1377         return 0;
1378 nla_put_failure:
1379         return -EINVAL;
1380 }
1381
1382
1383 #ifndef HOSTAPD
1384 struct wiphy_info_data {
1385         int max_scan_ssids;
1386         int ap_supported;
1387         int auth_supported;
1388         int connect_supported;
1389 };
1390
1391
1392 static int wiphy_info_handler(struct nl_msg *msg, void *arg)
1393 {
1394         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1395         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1396         struct wiphy_info_data *info = arg;
1397
1398         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1399                   genlmsg_attrlen(gnlh, 0), NULL);
1400
1401         if (tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS])
1402                 info->max_scan_ssids =
1403                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS]);
1404
1405         if (tb[NL80211_ATTR_SUPPORTED_IFTYPES]) {
1406                 struct nlattr *nl_mode;
1407                 int i;
1408                 nla_for_each_nested(nl_mode,
1409                                     tb[NL80211_ATTR_SUPPORTED_IFTYPES], i) {
1410                         if (nl_mode->nla_type == NL80211_IFTYPE_AP) {
1411                                 info->ap_supported = 1;
1412                                 break;
1413                         }
1414                 }
1415         }
1416
1417         if (tb[NL80211_ATTR_SUPPORTED_COMMANDS]) {
1418                 struct nlattr *nl_cmd;
1419                 int i;
1420
1421                 nla_for_each_nested(nl_cmd,
1422                                     tb[NL80211_ATTR_SUPPORTED_COMMANDS], i) {
1423                         u32 cmd = nla_get_u32(nl_cmd);
1424                         if (cmd == NL80211_CMD_AUTHENTICATE)
1425                                 info->auth_supported = 1;
1426                         else if (cmd == NL80211_CMD_CONNECT)
1427                                 info->connect_supported = 1;
1428                 }
1429         }
1430
1431         return NL_SKIP;
1432 }
1433
1434
1435 static int wpa_driver_nl80211_get_info(struct wpa_driver_nl80211_data *drv,
1436                                        struct wiphy_info_data *info)
1437 {
1438         struct nl_msg *msg;
1439
1440         os_memset(info, 0, sizeof(*info));
1441         msg = nlmsg_alloc();
1442         if (!msg)
1443                 return -1;
1444
1445         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1446                     0, NL80211_CMD_GET_WIPHY, 0);
1447
1448         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->first_bss.ifindex);
1449
1450         if (send_and_recv_msgs(drv, msg, wiphy_info_handler, info) == 0)
1451                 return 0;
1452         msg = NULL;
1453 nla_put_failure:
1454         nlmsg_free(msg);
1455         return -1;
1456 }
1457
1458
1459 static int wpa_driver_nl80211_capa(struct wpa_driver_nl80211_data *drv)
1460 {
1461         struct wiphy_info_data info;
1462         if (wpa_driver_nl80211_get_info(drv, &info))
1463                 return -1;
1464         drv->has_capability = 1;
1465         /* For now, assume TKIP, CCMP, WPA, WPA2 are supported */
1466         drv->capa.key_mgmt = WPA_DRIVER_CAPA_KEY_MGMT_WPA |
1467                 WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK |
1468                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2 |
1469                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK;
1470         drv->capa.enc = WPA_DRIVER_CAPA_ENC_WEP40 |
1471                 WPA_DRIVER_CAPA_ENC_WEP104 |
1472                 WPA_DRIVER_CAPA_ENC_TKIP |
1473                 WPA_DRIVER_CAPA_ENC_CCMP;
1474         drv->capa.auth = WPA_DRIVER_AUTH_OPEN |
1475                 WPA_DRIVER_AUTH_SHARED |
1476                 WPA_DRIVER_AUTH_LEAP;
1477
1478         drv->capa.max_scan_ssids = info.max_scan_ssids;
1479         if (info.ap_supported)
1480                 drv->capa.flags |= WPA_DRIVER_FLAGS_AP;
1481
1482         if (info.auth_supported)
1483                 drv->capa.flags |= WPA_DRIVER_FLAGS_SME;
1484         else if (!info.connect_supported) {
1485                 wpa_printf(MSG_INFO, "nl80211: Driver does not support "
1486                            "authentication/association or connect commands");
1487                 return -1;
1488         }
1489
1490         drv->capa.flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE;
1491         drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CAPABLE;
1492         drv->capa.max_remain_on_chan = 5000;
1493
1494         return 0;
1495 }
1496 #endif /* HOSTAPD */
1497
1498
1499 static int wpa_driver_nl80211_init_nl(struct wpa_driver_nl80211_data *drv)
1500 {
1501         int ret;
1502
1503         /* Initialize generic netlink and nl80211 */
1504
1505         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
1506         if (drv->nl_cb == NULL) {
1507                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1508                            "callbacks");
1509                 goto err1;
1510         }
1511
1512         drv->nl_handle = nl80211_handle_alloc(drv->nl_cb);
1513         if (drv->nl_handle == NULL) {
1514                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1515                            "callbacks");
1516                 goto err2;
1517         }
1518
1519         drv->nl_handle_event = nl80211_handle_alloc(drv->nl_cb);
1520         if (drv->nl_handle_event == NULL) {
1521                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
1522                            "callbacks (event)");
1523                 goto err2b;
1524         }
1525
1526         if (genl_connect(drv->nl_handle)) {
1527                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
1528                            "netlink");
1529                 goto err3;
1530         }
1531
1532         if (genl_connect(drv->nl_handle_event)) {
1533                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
1534                            "netlink (event)");
1535                 goto err3;
1536         }
1537
1538 #ifdef CONFIG_LIBNL20
1539         if (genl_ctrl_alloc_cache(drv->nl_handle, &drv->nl_cache) < 0) {
1540                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1541                            "netlink cache");
1542                 goto err3;
1543         }
1544         if (genl_ctrl_alloc_cache(drv->nl_handle_event, &drv->nl_cache_event) <
1545             0) {
1546                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1547                            "netlink cache (event)");
1548                 goto err3b;
1549         }
1550 #else /* CONFIG_LIBNL20 */
1551         drv->nl_cache = genl_ctrl_alloc_cache(drv->nl_handle);
1552         if (drv->nl_cache == NULL) {
1553                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1554                            "netlink cache");
1555                 goto err3;
1556         }
1557         drv->nl_cache_event = genl_ctrl_alloc_cache(drv->nl_handle_event);
1558         if (drv->nl_cache_event == NULL) {
1559                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
1560                            "netlink cache (event)");
1561                 goto err3b;
1562         }
1563 #endif /* CONFIG_LIBNL20 */
1564
1565         drv->nl80211 = genl_ctrl_search_by_name(drv->nl_cache, "nl80211");
1566         if (drv->nl80211 == NULL) {
1567                 wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
1568                            "found");
1569                 goto err4;
1570         }
1571
1572         ret = nl_get_multicast_id(drv, "nl80211", "scan");
1573         if (ret >= 0)
1574                 ret = nl_socket_add_membership(drv->nl_handle_event, ret);
1575         if (ret < 0) {
1576                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
1577                            "membership for scan events: %d (%s)",
1578                            ret, strerror(-ret));
1579                 goto err4;
1580         }
1581
1582         ret = nl_get_multicast_id(drv, "nl80211", "mlme");
1583         if (ret >= 0)
1584                 ret = nl_socket_add_membership(drv->nl_handle_event, ret);
1585         if (ret < 0) {
1586                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
1587                            "membership for mlme events: %d (%s)",
1588                            ret, strerror(-ret));
1589                 goto err4;
1590         }
1591
1592         ret = nl_get_multicast_id(drv, "nl80211", "regulatory");
1593         if (ret >= 0)
1594                 ret = nl_socket_add_membership(drv->nl_handle_event, ret);
1595         if (ret < 0) {
1596                 wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
1597                            "membership for regulatory events: %d (%s)",
1598                            ret, strerror(-ret));
1599                 /* Continue without regulatory events */
1600         }
1601
1602         eloop_register_read_sock(nl_socket_get_fd(drv->nl_handle_event),
1603                                  wpa_driver_nl80211_event_receive, drv,
1604                                  drv->nl_handle_event);
1605
1606         return 0;
1607
1608 err4:
1609         nl_cache_free(drv->nl_cache_event);
1610 err3b:
1611         nl_cache_free(drv->nl_cache);
1612 err3:
1613         nl80211_handle_destroy(drv->nl_handle_event);
1614 err2b:
1615         nl80211_handle_destroy(drv->nl_handle);
1616 err2:
1617         nl_cb_put(drv->nl_cb);
1618 err1:
1619         return -1;
1620 }
1621
1622
1623 static void wpa_driver_nl80211_rfkill_blocked(void *ctx)
1624 {
1625         wpa_printf(MSG_DEBUG, "nl80211: RFKILL blocked");
1626         /*
1627          * This may be for any interface; use ifdown event to disable
1628          * interface.
1629          */
1630 }
1631
1632
1633 static void wpa_driver_nl80211_rfkill_unblocked(void *ctx)
1634 {
1635         struct wpa_driver_nl80211_data *drv = ctx;
1636         wpa_printf(MSG_DEBUG, "nl80211: RFKILL unblocked");
1637         if (linux_set_iface_flags(drv->ioctl_sock, drv->first_bss.ifname, 1)) {
1638                 wpa_printf(MSG_DEBUG, "nl80211: Could not set interface UP "
1639                            "after rfkill unblock");
1640                 return;
1641         }
1642         /* rtnetlink ifup handler will report interface as enabled */
1643 }
1644
1645
1646 /**
1647  * wpa_driver_nl80211_init - Initialize nl80211 driver interface
1648  * @ctx: context to be used when calling wpa_supplicant functions,
1649  * e.g., wpa_supplicant_event()
1650  * @ifname: interface name, e.g., wlan0
1651  * Returns: Pointer to private data, %NULL on failure
1652  */
1653 static void * wpa_driver_nl80211_init(void *ctx, const char *ifname)
1654 {
1655         struct wpa_driver_nl80211_data *drv;
1656         struct netlink_config *cfg;
1657         struct rfkill_config *rcfg;
1658         struct i802_bss *bss;
1659
1660         drv = os_zalloc(sizeof(*drv));
1661         if (drv == NULL)
1662                 return NULL;
1663         drv->ctx = ctx;
1664         bss = &drv->first_bss;
1665         bss->drv = drv;
1666         os_strlcpy(bss->ifname, ifname, sizeof(bss->ifname));
1667         drv->monitor_ifidx = -1;
1668         drv->monitor_sock = -1;
1669         drv->ioctl_sock = -1;
1670
1671         if (wpa_driver_nl80211_init_nl(drv)) {
1672                 os_free(drv);
1673                 return NULL;
1674         }
1675
1676         drv->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
1677         if (drv->ioctl_sock < 0) {
1678                 perror("socket(PF_INET,SOCK_DGRAM)");
1679                 goto failed;
1680         }
1681
1682         cfg = os_zalloc(sizeof(*cfg));
1683         if (cfg == NULL)
1684                 goto failed;
1685         cfg->ctx = drv;
1686         cfg->newlink_cb = wpa_driver_nl80211_event_rtm_newlink;
1687         cfg->dellink_cb = wpa_driver_nl80211_event_rtm_dellink;
1688         drv->netlink = netlink_init(cfg);
1689         if (drv->netlink == NULL) {
1690                 os_free(cfg);
1691                 goto failed;
1692         }
1693
1694         rcfg = os_zalloc(sizeof(*rcfg));
1695         if (rcfg == NULL)
1696                 goto failed;
1697         rcfg->ctx = drv;
1698         os_strlcpy(rcfg->ifname, ifname, sizeof(rcfg->ifname));
1699         rcfg->blocked_cb = wpa_driver_nl80211_rfkill_blocked;
1700         rcfg->unblocked_cb = wpa_driver_nl80211_rfkill_unblocked;
1701         drv->rfkill = rfkill_init(rcfg);
1702         if (drv->rfkill == NULL) {
1703                 wpa_printf(MSG_DEBUG, "nl80211: RFKILL status not available");
1704                 os_free(rcfg);
1705         }
1706
1707         if (wpa_driver_nl80211_finish_drv_init(drv))
1708                 goto failed;
1709
1710         return bss;
1711
1712 failed:
1713         rfkill_deinit(drv->rfkill);
1714         netlink_deinit(drv->netlink);
1715         if (drv->ioctl_sock >= 0)
1716                 close(drv->ioctl_sock);
1717
1718         genl_family_put(drv->nl80211);
1719         nl_cache_free(drv->nl_cache);
1720         nl80211_handle_destroy(drv->nl_handle);
1721         nl_cb_put(drv->nl_cb);
1722         eloop_unregister_read_sock(nl_socket_get_fd(drv->nl_handle_event));
1723
1724         os_free(drv);
1725         return NULL;
1726 }
1727
1728
1729 static int nl80211_register_frame(struct wpa_driver_nl80211_data *drv,
1730                                   struct nl_handle *nl_handle,
1731                                   u16 type, const u8 *match, size_t match_len)
1732 {
1733         struct nl_msg *msg;
1734         int ret = -1;
1735
1736         msg = nlmsg_alloc();
1737         if (!msg)
1738                 return -1;
1739
1740         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
1741                     NL80211_CMD_REGISTER_ACTION, 0);
1742
1743         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1744         NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE, type);
1745         NLA_PUT(msg, NL80211_ATTR_FRAME_MATCH, match_len, match);
1746
1747         ret = send_and_recv(drv, nl_handle, msg, NULL, NULL);
1748         msg = NULL;
1749         if (ret) {
1750                 wpa_printf(MSG_DEBUG, "nl80211: Register frame command "
1751                            "failed (type=%u): ret=%d (%s)",
1752                            type, ret, strerror(-ret));
1753                 wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
1754                             match, match_len);
1755                 goto nla_put_failure;
1756         }
1757         ret = 0;
1758 nla_put_failure:
1759         nlmsg_free(msg);
1760         return ret;
1761 }
1762
1763
1764 static int nl80211_register_action_frame(struct wpa_driver_nl80211_data *drv,
1765                                          const u8 *match, size_t match_len)
1766 {
1767         u16 type = (WLAN_FC_TYPE_MGMT << 2) | (WLAN_FC_STYPE_ACTION << 4);
1768         return nl80211_register_frame(drv, drv->nl_handle_event,
1769                                       type, match, match_len);
1770 }
1771
1772
1773 static int nl80211_register_action_frames(struct wpa_driver_nl80211_data *drv)
1774 {
1775 #ifdef CONFIG_P2P
1776         /* GAS Initial Request */
1777         if (nl80211_register_action_frame(drv, (u8 *) "\x04\x0a", 2) < 0)
1778                 return -1;
1779         /* GAS Initial Response */
1780         if (nl80211_register_action_frame(drv, (u8 *) "\x04\x0b", 2) < 0)
1781                 return -1;
1782         /* GAS Comeback Request */
1783         if (nl80211_register_action_frame(drv, (u8 *) "\x04\x0c", 2) < 0)
1784                 return -1;
1785         /* GAS Comeback Response */
1786         if (nl80211_register_action_frame(drv, (u8 *) "\x04\x0d", 2) < 0)
1787                 return -1;
1788         /* P2P Public Action */
1789         if (nl80211_register_action_frame(drv,
1790                                           (u8 *) "\x04\x09\x50\x6f\x9a\x09",
1791                                           6) < 0)
1792                 return -1;
1793         /* P2P Action */
1794         if (nl80211_register_action_frame(drv,
1795                                           (u8 *) "\x7f\x50\x6f\x9a\x09",
1796                                           5) < 0)
1797                 return -1;
1798 #endif /* CONFIG_P2P */
1799
1800         /* FT Action frames */
1801         if (nl80211_register_action_frame(drv, (u8 *) "\x06", 1) < 0)
1802                 return -1;
1803         else
1804                 drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_FT |
1805                         WPA_DRIVER_CAPA_KEY_MGMT_FT_PSK;
1806
1807         return 0;
1808 }
1809
1810
1811 static void wpa_driver_nl80211_send_rfkill(void *eloop_ctx, void *timeout_ctx)
1812 {
1813         wpa_supplicant_event(timeout_ctx, EVENT_INTERFACE_DISABLED, NULL);
1814 }
1815
1816
1817 static int
1818 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv)
1819 {
1820         struct i802_bss *bss = &drv->first_bss;
1821         int send_rfkill_event = 0;
1822
1823         drv->ifindex = if_nametoindex(bss->ifname);
1824         drv->first_bss.ifindex = drv->ifindex;
1825
1826 #ifndef HOSTAPD
1827         if (wpa_driver_nl80211_set_mode(bss, IEEE80211_MODE_INFRA) < 0) {
1828                 wpa_printf(MSG_DEBUG, "nl80211: Could not configure driver to "
1829                            "use managed mode");
1830         }
1831
1832         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 1)) {
1833                 if (rfkill_is_blocked(drv->rfkill)) {
1834                         wpa_printf(MSG_DEBUG, "nl80211: Could not yet enable "
1835                                    "interface '%s' due to rfkill",
1836                                    bss->ifname);
1837                         drv->if_disabled = 1;
1838                         send_rfkill_event = 1;
1839                 } else {
1840                         wpa_printf(MSG_ERROR, "nl80211: Could not set "
1841                                    "interface '%s' UP", bss->ifname);
1842                         return -1;
1843                 }
1844         }
1845
1846         if (wpa_driver_nl80211_capa(drv))
1847                 return -1;
1848
1849         netlink_send_oper_ifla(drv->netlink, drv->ifindex,
1850                                1, IF_OPER_DORMANT);
1851 #endif /* HOSTAPD */
1852
1853         if (nl80211_register_action_frames(drv) < 0) {
1854                 wpa_printf(MSG_DEBUG, "nl80211: Failed to register Action "
1855                            "frame processing - ignore for now");
1856                 /*
1857                  * Older kernel versions did not support this, so ignore the
1858                  * error for now. Some functionality may not be available
1859                  * because of this.
1860                  */
1861         }
1862
1863         if (send_rfkill_event) {
1864                 eloop_register_timeout(0, 0, wpa_driver_nl80211_send_rfkill,
1865                                        drv, drv->ctx);
1866         }
1867
1868         return 0;
1869 }
1870
1871
1872 static int wpa_driver_nl80211_del_beacon(struct wpa_driver_nl80211_data *drv)
1873 {
1874         struct nl_msg *msg;
1875
1876         msg = nlmsg_alloc();
1877         if (!msg)
1878                 return -ENOMEM;
1879
1880         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
1881                     0, NL80211_CMD_DEL_BEACON, 0);
1882         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1883
1884         return send_and_recv_msgs(drv, msg, NULL, NULL);
1885  nla_put_failure:
1886         return -ENOBUFS;
1887 }
1888
1889
1890 /**
1891  * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
1892  * @priv: Pointer to private nl80211 data from wpa_driver_nl80211_init()
1893  *
1894  * Shut down driver interface and processing of driver events. Free
1895  * private data buffer if one was allocated in wpa_driver_nl80211_init().
1896  */
1897 static void wpa_driver_nl80211_deinit(void *priv)
1898 {
1899         struct i802_bss *bss = priv;
1900         struct wpa_driver_nl80211_data *drv = bss->drv;
1901
1902         if (drv->nl_handle_preq)
1903                 wpa_driver_nl80211_probe_req_report(bss, 0);
1904         if (drv->added_if_into_bridge) {
1905                 if (linux_br_del_if(drv->ioctl_sock, drv->brname, bss->ifname)
1906                     < 0)
1907                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
1908                                    "interface %s from bridge %s: %s",
1909                                    bss->ifname, drv->brname, strerror(errno));
1910         }
1911         if (drv->added_bridge) {
1912                 if (linux_br_del(drv->ioctl_sock, drv->brname) < 0)
1913                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
1914                                    "bridge %s: %s",
1915                                    drv->brname, strerror(errno));
1916         }
1917
1918         nl80211_remove_monitor_interface(drv);
1919
1920         if (drv->nlmode == NL80211_IFTYPE_AP)
1921                 wpa_driver_nl80211_del_beacon(drv);
1922
1923 #ifdef HOSTAPD
1924         if (drv->last_freq_ht) {
1925                 /* Clear HT flags from the driver */
1926                 struct hostapd_freq_params freq;
1927                 os_memset(&freq, 0, sizeof(freq));
1928                 freq.freq = drv->last_freq;
1929                 i802_set_freq(priv, &freq);
1930         }
1931
1932         if (drv->eapol_sock >= 0) {
1933                 eloop_unregister_read_sock(drv->eapol_sock);
1934                 close(drv->eapol_sock);
1935         }
1936
1937         if (drv->if_indices != drv->default_if_indices)
1938                 os_free(drv->if_indices);
1939 #endif /* HOSTAPD */
1940
1941         if (drv->disable_11b_rates)
1942                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
1943
1944         netlink_send_oper_ifla(drv->netlink, drv->ifindex, 0, IF_OPER_UP);
1945         netlink_deinit(drv->netlink);
1946         rfkill_deinit(drv->rfkill);
1947
1948         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
1949
1950         (void) linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 0);
1951         wpa_driver_nl80211_set_mode(bss, IEEE80211_MODE_INFRA);
1952
1953         if (drv->ioctl_sock >= 0)
1954                 close(drv->ioctl_sock);
1955
1956         eloop_unregister_read_sock(nl_socket_get_fd(drv->nl_handle_event));
1957         genl_family_put(drv->nl80211);
1958         nl_cache_free(drv->nl_cache);
1959         nl_cache_free(drv->nl_cache_event);
1960         nl80211_handle_destroy(drv->nl_handle);
1961         nl80211_handle_destroy(drv->nl_handle_event);
1962         nl_cb_put(drv->nl_cb);
1963
1964         os_free(drv->filter_ssids);
1965
1966         os_free(drv);
1967 }
1968
1969
1970 /**
1971  * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
1972  * @eloop_ctx: Driver private data
1973  * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
1974  *
1975  * This function can be used as registered timeout when starting a scan to
1976  * generate a scan completed event if the driver does not report this.
1977  */
1978 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
1979 {
1980         struct wpa_driver_nl80211_data *drv = eloop_ctx;
1981         if (drv->ap_scan_as_station) {
1982                 wpa_driver_nl80211_set_mode(&drv->first_bss,
1983                                             IEEE80211_MODE_AP);
1984                 drv->ap_scan_as_station = 0;
1985         }
1986         wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
1987         wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
1988 }
1989
1990
1991 /**
1992  * wpa_driver_nl80211_scan - Request the driver to initiate scan
1993  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
1994  * @params: Scan parameters
1995  * Returns: 0 on success, -1 on failure
1996  */
1997 static int wpa_driver_nl80211_scan(void *priv,
1998                                    struct wpa_driver_scan_params *params)
1999 {
2000         struct i802_bss *bss = priv;
2001         struct wpa_driver_nl80211_data *drv = bss->drv;
2002         int ret = 0, timeout;
2003         struct nl_msg *msg, *ssids, *freqs;
2004         size_t i;
2005
2006         msg = nlmsg_alloc();
2007         ssids = nlmsg_alloc();
2008         freqs = nlmsg_alloc();
2009         if (!msg || !ssids || !freqs) {
2010                 nlmsg_free(msg);
2011                 nlmsg_free(ssids);
2012                 nlmsg_free(freqs);
2013                 return -1;
2014         }
2015
2016         os_free(drv->filter_ssids);
2017         drv->filter_ssids = params->filter_ssids;
2018         params->filter_ssids = NULL;
2019         drv->num_filter_ssids = params->num_filter_ssids;
2020
2021         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
2022                     NL80211_CMD_TRIGGER_SCAN, 0);
2023
2024         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2025
2026         for (i = 0; i < params->num_ssids; i++) {
2027                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan SSID",
2028                                   params->ssids[i].ssid,
2029                                   params->ssids[i].ssid_len);
2030                 NLA_PUT(ssids, i + 1, params->ssids[i].ssid_len,
2031                         params->ssids[i].ssid);
2032         }
2033         if (params->num_ssids)
2034                 nla_put_nested(msg, NL80211_ATTR_SCAN_SSIDS, ssids);
2035
2036         if (params->extra_ies) {
2037                 wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan extra IEs",
2038                                   params->extra_ies, params->extra_ies_len);
2039                 NLA_PUT(msg, NL80211_ATTR_IE, params->extra_ies_len,
2040                         params->extra_ies);
2041         }
2042
2043         if (params->freqs) {
2044                 for (i = 0; params->freqs[i]; i++) {
2045                         wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
2046                                    "MHz", params->freqs[i]);
2047                         NLA_PUT_U32(freqs, i + 1, params->freqs[i]);
2048                 }
2049                 nla_put_nested(msg, NL80211_ATTR_SCAN_FREQUENCIES, freqs);
2050         }
2051
2052         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2053         msg = NULL;
2054         if (ret) {
2055                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
2056                            "(%s)", ret, strerror(-ret));
2057 #ifdef HOSTAPD
2058                 if (drv->nlmode == NL80211_IFTYPE_AP) {
2059                         /*
2060                          * mac80211 does not allow scan requests in AP mode, so
2061                          * try to do this in station mode.
2062                          */
2063                         if (wpa_driver_nl80211_set_mode(bss,
2064                                                         IEEE80211_MODE_INFRA))
2065                                 goto nla_put_failure;
2066
2067                         if (wpa_driver_nl80211_scan(drv, params)) {
2068                                 wpa_driver_nl80211_set_mode(bss,
2069                                                             IEEE80211_MODE_AP);
2070                                 goto nla_put_failure;
2071                         }
2072
2073                         /* Restore AP mode when processing scan results */
2074                         drv->ap_scan_as_station = 1;
2075                         ret = 0;
2076                 } else
2077                         goto nla_put_failure;
2078 #else /* HOSTAPD */
2079                 goto nla_put_failure;
2080 #endif /* HOSTAPD */
2081         }
2082
2083         /* Not all drivers generate "scan completed" wireless event, so try to
2084          * read results after a timeout. */
2085         timeout = 10;
2086         if (drv->scan_complete_events) {
2087                 /*
2088                  * The driver seems to deliver events to notify when scan is
2089                  * complete, so use longer timeout to avoid race conditions
2090                  * with scanning and following association request.
2091                  */
2092                 timeout = 30;
2093         }
2094         wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
2095                    "seconds", ret, timeout);
2096         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
2097         eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
2098                                drv, drv->ctx);
2099
2100 nla_put_failure:
2101         nlmsg_free(ssids);
2102         nlmsg_free(msg);
2103         nlmsg_free(freqs);
2104         return ret;
2105 }
2106
2107
2108 static const u8 * nl80211_get_ie(const u8 *ies, size_t ies_len, u8 ie)
2109 {
2110         const u8 *end, *pos;
2111
2112         if (ies == NULL)
2113                 return NULL;
2114
2115         pos = ies;
2116         end = ies + ies_len;
2117
2118         while (pos + 1 < end) {
2119                 if (pos + 2 + pos[1] > end)
2120                         break;
2121                 if (pos[0] == ie)
2122                         return pos;
2123                 pos += 2 + pos[1];
2124         }
2125
2126         return NULL;
2127 }
2128
2129
2130 static int nl80211_scan_filtered(struct wpa_driver_nl80211_data *drv,
2131                                  const u8 *ie, size_t ie_len)
2132 {
2133         const u8 *ssid;
2134         size_t i;
2135
2136         if (drv->filter_ssids == NULL)
2137                 return 0;
2138
2139         ssid = nl80211_get_ie(ie, ie_len, WLAN_EID_SSID);
2140         if (ssid == NULL)
2141                 return 1;
2142
2143         for (i = 0; i < drv->num_filter_ssids; i++) {
2144                 if (ssid[1] == drv->filter_ssids[i].ssid_len &&
2145                     os_memcmp(ssid + 2, drv->filter_ssids[i].ssid, ssid[1]) ==
2146                     0)
2147                         return 0;
2148         }
2149
2150         return 1;
2151 }
2152
2153
2154 struct nl80211_bss_info_arg {
2155         struct wpa_driver_nl80211_data *drv;
2156         struct wpa_scan_results *res;
2157 };
2158
2159 static int bss_info_handler(struct nl_msg *msg, void *arg)
2160 {
2161         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2162         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2163         struct nlattr *bss[NL80211_BSS_MAX + 1];
2164         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
2165                 [NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
2166                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
2167                 [NL80211_BSS_TSF] = { .type = NLA_U64 },
2168                 [NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
2169                 [NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
2170                 [NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
2171                 [NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
2172                 [NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
2173                 [NL80211_BSS_STATUS] = { .type = NLA_U32 },
2174                 [NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
2175                 [NL80211_BSS_BEACON_IES] = { .type = NLA_UNSPEC },
2176         };
2177         struct nl80211_bss_info_arg *_arg = arg;
2178         struct wpa_scan_results *res = _arg->res;
2179         struct wpa_scan_res **tmp;
2180         struct wpa_scan_res *r;
2181         const u8 *ie, *beacon_ie;
2182         size_t ie_len, beacon_ie_len;
2183         u8 *pos;
2184
2185         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2186                   genlmsg_attrlen(gnlh, 0), NULL);
2187         if (!tb[NL80211_ATTR_BSS])
2188                 return NL_SKIP;
2189         if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
2190                              bss_policy))
2191                 return NL_SKIP;
2192         if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
2193                 ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2194                 ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2195         } else {
2196                 ie = NULL;
2197                 ie_len = 0;
2198         }
2199         if (bss[NL80211_BSS_BEACON_IES]) {
2200                 beacon_ie = nla_data(bss[NL80211_BSS_BEACON_IES]);
2201                 beacon_ie_len = nla_len(bss[NL80211_BSS_BEACON_IES]);
2202         } else {
2203                 beacon_ie = NULL;
2204                 beacon_ie_len = 0;
2205         }
2206
2207         if (nl80211_scan_filtered(_arg->drv, ie ? ie : beacon_ie,
2208                                   ie ? ie_len : beacon_ie_len))
2209                 return NL_SKIP;
2210
2211         r = os_zalloc(sizeof(*r) + ie_len + beacon_ie_len);
2212         if (r == NULL)
2213                 return NL_SKIP;
2214         if (bss[NL80211_BSS_BSSID])
2215                 os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
2216                           ETH_ALEN);
2217         if (bss[NL80211_BSS_FREQUENCY])
2218                 r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
2219         if (bss[NL80211_BSS_BEACON_INTERVAL])
2220                 r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
2221         if (bss[NL80211_BSS_CAPABILITY])
2222                 r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
2223         r->flags |= WPA_SCAN_NOISE_INVALID;
2224         if (bss[NL80211_BSS_SIGNAL_MBM]) {
2225                 r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
2226                 r->level /= 100; /* mBm to dBm */
2227                 r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
2228         } else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
2229                 r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
2230                 r->flags |= WPA_SCAN_LEVEL_INVALID;
2231         } else
2232                 r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
2233         if (bss[NL80211_BSS_TSF])
2234                 r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
2235         if (bss[NL80211_BSS_SEEN_MS_AGO])
2236                 r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
2237         r->ie_len = ie_len;
2238         pos = (u8 *) (r + 1);
2239         if (ie) {
2240                 os_memcpy(pos, ie, ie_len);
2241                 pos += ie_len;
2242         }
2243         r->beacon_ie_len = beacon_ie_len;
2244         if (beacon_ie)
2245                 os_memcpy(pos, beacon_ie, beacon_ie_len);
2246
2247         if (bss[NL80211_BSS_STATUS]) {
2248                 enum nl80211_bss_status status;
2249                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
2250                 switch (status) {
2251                 case NL80211_BSS_STATUS_AUTHENTICATED:
2252                         r->flags |= WPA_SCAN_AUTHENTICATED;
2253                         break;
2254                 case NL80211_BSS_STATUS_ASSOCIATED:
2255                         r->flags |= WPA_SCAN_ASSOCIATED;
2256                         break;
2257                 default:
2258                         break;
2259                 }
2260         }
2261
2262         tmp = os_realloc(res->res,
2263                          (res->num + 1) * sizeof(struct wpa_scan_res *));
2264         if (tmp == NULL) {
2265                 os_free(r);
2266                 return NL_SKIP;
2267         }
2268         tmp[res->num++] = r;
2269         res->res = tmp;
2270
2271         return NL_SKIP;
2272 }
2273
2274
2275 static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
2276                                  const u8 *addr)
2277 {
2278         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
2279                 wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
2280                            "mismatch (" MACSTR ")", MAC2STR(addr));
2281                 wpa_driver_nl80211_mlme(drv, addr,
2282                                         NL80211_CMD_DEAUTHENTICATE,
2283                                         WLAN_REASON_PREV_AUTH_NOT_VALID, 1);
2284         }
2285 }
2286
2287
2288 static void wpa_driver_nl80211_check_bss_status(
2289         struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
2290 {
2291         size_t i;
2292
2293         for (i = 0; i < res->num; i++) {
2294                 struct wpa_scan_res *r = res->res[i];
2295                 if (r->flags & WPA_SCAN_AUTHENTICATED) {
2296                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
2297                                    "indicates BSS status with " MACSTR
2298                                    " as authenticated",
2299                                    MAC2STR(r->bssid));
2300                         if (drv->nlmode == NL80211_IFTYPE_STATION &&
2301                             os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
2302                             os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
2303                             0) {
2304                                 wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
2305                                            " in local state (auth=" MACSTR
2306                                            " assoc=" MACSTR ")",
2307                                            MAC2STR(drv->auth_bssid),
2308                                            MAC2STR(drv->bssid));
2309                                 clear_state_mismatch(drv, r->bssid);
2310                         }
2311                 }
2312
2313                 if (r->flags & WPA_SCAN_ASSOCIATED) {
2314                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
2315                                    "indicate BSS status with " MACSTR
2316                                    " as associated",
2317                                    MAC2STR(r->bssid));
2318                         if (drv->nlmode == NL80211_IFTYPE_STATION &&
2319                             !drv->associated) {
2320                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
2321                                            "(not associated) does not match "
2322                                            "with BSS state");
2323                                 clear_state_mismatch(drv, r->bssid);
2324                         } else if (drv->nlmode == NL80211_IFTYPE_STATION &&
2325                                    os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
2326                                    0) {
2327                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
2328                                            "(associated with " MACSTR ") does "
2329                                            "not match with BSS state",
2330                                            MAC2STR(drv->bssid));
2331                                 clear_state_mismatch(drv, r->bssid);
2332                                 clear_state_mismatch(drv, drv->bssid);
2333                         }
2334                 }
2335         }
2336 }
2337
2338
2339 static void wpa_scan_results_free(struct wpa_scan_results *res)
2340 {
2341         size_t i;
2342
2343         if (res == NULL)
2344                 return;
2345
2346         for (i = 0; i < res->num; i++)
2347                 os_free(res->res[i]);
2348         os_free(res->res);
2349         os_free(res);
2350 }
2351
2352
2353 static struct wpa_scan_results *
2354 nl80211_get_scan_results(struct wpa_driver_nl80211_data *drv)
2355 {
2356         struct nl_msg *msg;
2357         struct wpa_scan_results *res;
2358         int ret;
2359         struct nl80211_bss_info_arg arg;
2360
2361         res = os_zalloc(sizeof(*res));
2362         if (res == NULL)
2363                 return NULL;
2364         msg = nlmsg_alloc();
2365         if (!msg)
2366                 goto nla_put_failure;
2367
2368         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, NLM_F_DUMP,
2369                     NL80211_CMD_GET_SCAN, 0);
2370         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2371
2372         arg.drv = drv;
2373         arg.res = res;
2374         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
2375         msg = NULL;
2376         if (ret == 0) {
2377                 wpa_printf(MSG_DEBUG, "Received scan results (%lu BSSes)",
2378                            (unsigned long) res->num);
2379                 return res;
2380         }
2381         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
2382                    "(%s)", ret, strerror(-ret));
2383 nla_put_failure:
2384         nlmsg_free(msg);
2385         wpa_scan_results_free(res);
2386         return NULL;
2387 }
2388
2389
2390 /**
2391  * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
2392  * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
2393  * Returns: Scan results on success, -1 on failure
2394  */
2395 static struct wpa_scan_results *
2396 wpa_driver_nl80211_get_scan_results(void *priv)
2397 {
2398         struct i802_bss *bss = priv;
2399         struct wpa_driver_nl80211_data *drv = bss->drv;
2400         struct wpa_scan_results *res;
2401
2402         res = nl80211_get_scan_results(drv);
2403         if (res)
2404                 wpa_driver_nl80211_check_bss_status(drv, res);
2405         return res;
2406 }
2407
2408
2409 static void nl80211_dump_scan(struct wpa_driver_nl80211_data *drv)
2410 {
2411         struct wpa_scan_results *res;
2412         size_t i;
2413
2414         res = nl80211_get_scan_results(drv);
2415         if (res == NULL) {
2416                 wpa_printf(MSG_DEBUG, "nl80211: Failed to get scan results");
2417                 return;
2418         }
2419
2420         wpa_printf(MSG_DEBUG, "nl80211: Scan result dump");
2421         for (i = 0; i < res->num; i++) {
2422                 struct wpa_scan_res *r = res->res[i];
2423                 wpa_printf(MSG_DEBUG, "nl80211: %d/%d " MACSTR "%s%s",
2424                            (int) i, (int) res->num, MAC2STR(r->bssid),
2425                            r->flags & WPA_SCAN_AUTHENTICATED ? " [auth]" : "",
2426                            r->flags & WPA_SCAN_ASSOCIATED ? " [assoc]" : "");
2427         }
2428
2429         wpa_scan_results_free(res);
2430 }
2431
2432
2433 static int wpa_driver_nl80211_set_key(const char *ifname, void *priv,
2434                                       enum wpa_alg alg, const u8 *addr,
2435                                       int key_idx, int set_tx,
2436                                       const u8 *seq, size_t seq_len,
2437                                       const u8 *key, size_t key_len)
2438 {
2439         struct i802_bss *bss = priv;
2440         struct wpa_driver_nl80211_data *drv = bss->drv;
2441         int ifindex = if_nametoindex(ifname);
2442         struct nl_msg *msg;
2443         int ret;
2444
2445         wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
2446                    "set_tx=%d seq_len=%lu key_len=%lu",
2447                    __func__, ifindex, alg, addr, key_idx, set_tx,
2448                    (unsigned long) seq_len, (unsigned long) key_len);
2449
2450         msg = nlmsg_alloc();
2451         if (!msg)
2452                 return -ENOMEM;
2453
2454         if (alg == WPA_ALG_NONE) {
2455                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2456                             0, NL80211_CMD_DEL_KEY, 0);
2457         } else {
2458                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2459                             0, NL80211_CMD_NEW_KEY, 0);
2460                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
2461                 switch (alg) {
2462                 case WPA_ALG_WEP:
2463                         if (key_len == 5)
2464                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2465                                             WLAN_CIPHER_SUITE_WEP40);
2466                         else
2467                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2468                                             WLAN_CIPHER_SUITE_WEP104);
2469                         break;
2470                 case WPA_ALG_TKIP:
2471                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2472                                     WLAN_CIPHER_SUITE_TKIP);
2473                         break;
2474                 case WPA_ALG_CCMP:
2475                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2476                                     WLAN_CIPHER_SUITE_CCMP);
2477                         break;
2478                 case WPA_ALG_IGTK:
2479                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2480                                     WLAN_CIPHER_SUITE_AES_CMAC);
2481                         break;
2482                 default:
2483                         wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
2484                                    "algorithm %d", __func__, alg);
2485                         nlmsg_free(msg);
2486                         return -1;
2487                 }
2488         }
2489
2490         if (seq && seq_len)
2491                 NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
2492
2493         if (addr && os_memcmp(addr, "\xff\xff\xff\xff\xff\xff", ETH_ALEN) != 0)
2494         {
2495                 wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
2496                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
2497         }
2498         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
2499         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
2500
2501         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2502         if ((ret == -ENOENT || ret == -ENOLINK) && alg == WPA_ALG_NONE)
2503                 ret = 0;
2504         if (ret)
2505                 wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
2506                            ret, strerror(-ret));
2507
2508         /*
2509          * If we failed or don't need to set the default TX key (below),
2510          * we're done here.
2511          */
2512         if (ret || !set_tx || alg == WPA_ALG_NONE)
2513                 return ret;
2514 #ifdef HOSTAPD
2515         if (addr)
2516                 return ret;
2517 #else /* HOSTAPD */
2518         if (drv->nlmode == NL80211_IFTYPE_AP && addr)
2519                 return ret;
2520 #endif /* HOSTAPD */
2521
2522         msg = nlmsg_alloc();
2523         if (!msg)
2524                 return -ENOMEM;
2525
2526         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2527                     0, NL80211_CMD_SET_KEY, 0);
2528         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
2529         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
2530         if (alg == WPA_ALG_IGTK)
2531                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
2532         else
2533                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
2534
2535         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2536         if (ret == -ENOENT)
2537                 ret = 0;
2538         if (ret)
2539                 wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
2540                            "err=%d %s)", ret, strerror(-ret));
2541         return ret;
2542
2543 nla_put_failure:
2544         return -ENOBUFS;
2545 }
2546
2547
2548 static int nl_add_key(struct nl_msg *msg, enum wpa_alg alg,
2549                       int key_idx, int defkey,
2550                       const u8 *seq, size_t seq_len,
2551                       const u8 *key, size_t key_len)
2552 {
2553         struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
2554         if (!key_attr)
2555                 return -1;
2556
2557         if (defkey && alg == WPA_ALG_IGTK)
2558                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
2559         else if (defkey)
2560                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
2561
2562         NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
2563
2564         switch (alg) {
2565         case WPA_ALG_WEP:
2566                 if (key_len == 5)
2567                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2568                                     WLAN_CIPHER_SUITE_WEP40);
2569                 else
2570                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2571                                     WLAN_CIPHER_SUITE_WEP104);
2572                 break;
2573         case WPA_ALG_TKIP:
2574                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_TKIP);
2575                 break;
2576         case WPA_ALG_CCMP:
2577                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_CCMP);
2578                 break;
2579         case WPA_ALG_IGTK:
2580                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2581                             WLAN_CIPHER_SUITE_AES_CMAC);
2582                 break;
2583         default:
2584                 wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
2585                            "algorithm %d", __func__, alg);
2586                 return -1;
2587         }
2588
2589         if (seq && seq_len)
2590                 NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
2591
2592         NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
2593
2594         nla_nest_end(msg, key_attr);
2595
2596         return 0;
2597  nla_put_failure:
2598         return -1;
2599 }
2600
2601
2602 static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
2603                                  struct nl_msg *msg)
2604 {
2605         int i, privacy = 0;
2606         struct nlattr *nl_keys, *nl_key;
2607
2608         for (i = 0; i < 4; i++) {
2609                 if (!params->wep_key[i])
2610                         continue;
2611                 privacy = 1;
2612                 break;
2613         }
2614         if (!privacy)
2615                 return 0;
2616
2617         NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
2618
2619         nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
2620         if (!nl_keys)
2621                 goto nla_put_failure;
2622
2623         for (i = 0; i < 4; i++) {
2624                 if (!params->wep_key[i])
2625                         continue;
2626
2627                 nl_key = nla_nest_start(msg, i);
2628                 if (!nl_key)
2629                         goto nla_put_failure;
2630
2631                 NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
2632                         params->wep_key[i]);
2633                 if (params->wep_key_len[i] == 5)
2634                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2635                                     WLAN_CIPHER_SUITE_WEP40);
2636                 else
2637                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2638                                     WLAN_CIPHER_SUITE_WEP104);
2639
2640                 NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
2641
2642                 if (i == params->wep_tx_keyidx)
2643                         NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
2644
2645                 nla_nest_end(msg, nl_key);
2646         }
2647         nla_nest_end(msg, nl_keys);
2648
2649         return 0;
2650
2651 nla_put_failure:
2652         return -ENOBUFS;
2653 }
2654
2655
2656 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
2657                                    const u8 *addr, int cmd, u16 reason_code,
2658                                    int local_state_change)
2659 {
2660         int ret = -1;
2661         struct nl_msg *msg;
2662
2663         msg = nlmsg_alloc();
2664         if (!msg)
2665                 return -1;
2666
2667         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0, cmd, 0);
2668
2669         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2670         NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
2671         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
2672         if (local_state_change)
2673                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
2674
2675         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2676         msg = NULL;
2677         if (ret) {
2678                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
2679                            "(%s)", ret, strerror(-ret));
2680                 goto nla_put_failure;
2681         }
2682         ret = 0;
2683
2684 nla_put_failure:
2685         nlmsg_free(msg);
2686         return ret;
2687 }
2688
2689
2690 static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
2691                                          const u8 *addr, int reason_code)
2692 {
2693         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
2694                    __func__, MAC2STR(addr), reason_code);
2695         drv->associated = 0;
2696         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISCONNECT,
2697                                        reason_code, 0);
2698 }
2699
2700
2701 static int wpa_driver_nl80211_deauthenticate(void *priv, const u8 *addr,
2702                                              int reason_code)
2703 {
2704         struct i802_bss *bss = priv;
2705         struct wpa_driver_nl80211_data *drv = bss->drv;
2706         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
2707                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
2708         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
2709                    __func__, MAC2STR(addr), reason_code);
2710         drv->associated = 0;
2711         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
2712                                        reason_code, 0);
2713 }
2714
2715
2716 static int wpa_driver_nl80211_disassociate(void *priv, const u8 *addr,
2717                                            int reason_code)
2718 {
2719         struct i802_bss *bss = priv;
2720         struct wpa_driver_nl80211_data *drv = bss->drv;
2721         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
2722                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
2723         wpa_printf(MSG_DEBUG, "%s", __func__);
2724         drv->associated = 0;
2725         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISASSOCIATE,
2726                                        reason_code, 0);
2727 }
2728
2729
2730 static int wpa_driver_nl80211_authenticate(
2731         void *priv, struct wpa_driver_auth_params *params)
2732 {
2733         struct i802_bss *bss = priv;
2734         struct wpa_driver_nl80211_data *drv = bss->drv;
2735         int ret = -1, i;
2736         struct nl_msg *msg;
2737         enum nl80211_auth_type type;
2738         int count = 0;
2739
2740         drv->associated = 0;
2741         os_memset(drv->auth_bssid, 0, ETH_ALEN);
2742         /* FIX: IBSS mode */
2743         if (drv->nlmode != NL80211_IFTYPE_STATION)
2744                 wpa_driver_nl80211_set_mode(priv, IEEE80211_MODE_INFRA);
2745
2746         if (wpa_driver_nl80211_set_mode(priv, IEEE80211_MODE_INFRA) < 0)
2747                 return -1;
2748
2749 retry:
2750         msg = nlmsg_alloc();
2751         if (!msg)
2752                 return -1;
2753
2754         wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
2755                    drv->ifindex);
2756
2757         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
2758                     NL80211_CMD_AUTHENTICATE, 0);
2759
2760         for (i = 0; i < 4; i++) {
2761                 if (!params->wep_key[i])
2762                         continue;
2763                 wpa_driver_nl80211_set_key(bss->ifname, priv, WPA_ALG_WEP,
2764                                            NULL, i,
2765                                            i == params->wep_tx_keyidx, NULL, 0,
2766                                            params->wep_key[i],
2767                                            params->wep_key_len[i]);
2768                 if (params->wep_tx_keyidx != i)
2769                         continue;
2770                 if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
2771                                params->wep_key[i], params->wep_key_len[i])) {
2772                         nlmsg_free(msg);
2773                         return -1;
2774                 }
2775         }
2776
2777         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2778         if (params->bssid) {
2779                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
2780                            MAC2STR(params->bssid));
2781                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
2782         }
2783         if (params->freq) {
2784                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
2785                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
2786         }
2787         if (params->ssid) {
2788                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
2789                                   params->ssid, params->ssid_len);
2790                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
2791                         params->ssid);
2792         }
2793         wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
2794         if (params->ie)
2795                 NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
2796         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
2797                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
2798         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
2799                 type = NL80211_AUTHTYPE_SHARED_KEY;
2800         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
2801                 type = NL80211_AUTHTYPE_NETWORK_EAP;
2802         else if (params->auth_alg & WPA_AUTH_ALG_FT)
2803                 type = NL80211_AUTHTYPE_FT;
2804         else
2805                 goto nla_put_failure;
2806         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
2807         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
2808         if (params->local_state_change) {
2809                 wpa_printf(MSG_DEBUG, "  * Local state change only");
2810                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
2811         }
2812
2813         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2814         msg = NULL;
2815         if (ret) {
2816                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
2817                            "(%s)", ret, strerror(-ret));
2818                 count++;
2819                 if (ret == -EALREADY && count == 1 && params->bssid &&
2820                     !params->local_state_change) {
2821                         /*
2822                          * mac80211 does not currently accept new
2823                          * authentication if we are already authenticated. As a
2824                          * workaround, force deauthentication and try again.
2825                          */
2826                         wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
2827                                    "after forced deauthentication");
2828                         wpa_driver_nl80211_deauthenticate(
2829                                 bss, params->bssid,
2830                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
2831                         nlmsg_free(msg);
2832                         goto retry;
2833                 }
2834                 goto nla_put_failure;
2835         }
2836         ret = 0;
2837         wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
2838                    "successfully");
2839
2840 nla_put_failure:
2841         nlmsg_free(msg);
2842         return ret;
2843 }
2844
2845
2846 struct phy_info_arg {
2847         u16 *num_modes;
2848         struct hostapd_hw_modes *modes;
2849 };
2850
2851 static int phy_info_handler(struct nl_msg *msg, void *arg)
2852 {
2853         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
2854         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2855         struct phy_info_arg *phy_info = arg;
2856
2857         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
2858
2859         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
2860         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
2861                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
2862                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
2863                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
2864                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
2865                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
2866                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
2867         };
2868
2869         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
2870         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
2871                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
2872                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
2873         };
2874
2875         struct nlattr *nl_band;
2876         struct nlattr *nl_freq;
2877         struct nlattr *nl_rate;
2878         int rem_band, rem_freq, rem_rate;
2879         struct hostapd_hw_modes *mode;
2880         int idx, mode_is_set;
2881
2882         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2883                   genlmsg_attrlen(gnlh, 0), NULL);
2884
2885         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
2886                 return NL_SKIP;
2887
2888         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
2889                 mode = os_realloc(phy_info->modes, (*phy_info->num_modes + 1) * sizeof(*mode));
2890                 if (!mode)
2891                         return NL_SKIP;
2892                 phy_info->modes = mode;
2893
2894                 mode_is_set = 0;
2895
2896                 mode = &phy_info->modes[*(phy_info->num_modes)];
2897                 memset(mode, 0, sizeof(*mode));
2898                 *(phy_info->num_modes) += 1;
2899
2900                 nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
2901                           nla_len(nl_band), NULL);
2902
2903                 if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
2904                         mode->ht_capab = nla_get_u16(
2905                                 tb_band[NL80211_BAND_ATTR_HT_CAPA]);
2906                 }
2907
2908                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) {
2909                         mode->a_mpdu_params |= nla_get_u8(
2910                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) &
2911                                 0x03;
2912                 }
2913
2914                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) {
2915                         mode->a_mpdu_params |= nla_get_u8(
2916                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) <<
2917                                 2;
2918                 }
2919
2920                 if (tb_band[NL80211_BAND_ATTR_HT_MCS_SET] &&
2921                     nla_len(tb_band[NL80211_BAND_ATTR_HT_MCS_SET])) {
2922                         u8 *mcs;
2923                         mcs = nla_data(tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
2924                         os_memcpy(mode->mcs_set, mcs, 16);
2925                 }
2926
2927                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
2928                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
2929                                   nla_len(nl_freq), freq_policy);
2930                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
2931                                 continue;
2932                         mode->num_channels++;
2933                 }
2934
2935                 mode->channels = os_zalloc(mode->num_channels * sizeof(struct hostapd_channel_data));
2936                 if (!mode->channels)
2937                         return NL_SKIP;
2938
2939                 idx = 0;
2940
2941                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
2942                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
2943                                   nla_len(nl_freq), freq_policy);
2944                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
2945                                 continue;
2946
2947                         mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
2948                         mode->channels[idx].flag = 0;
2949
2950                         if (!mode_is_set) {
2951                                 /* crude heuristic */
2952                                 if (mode->channels[idx].freq < 4000)
2953                                         mode->mode = HOSTAPD_MODE_IEEE80211B;
2954                                 else
2955                                         mode->mode = HOSTAPD_MODE_IEEE80211A;
2956                                 mode_is_set = 1;
2957                         }
2958
2959                         /* crude heuristic */
2960                         if (mode->channels[idx].freq < 4000)
2961                                 if (mode->channels[idx].freq == 2484)
2962                                         mode->channels[idx].chan = 14;
2963                                 else
2964                                         mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
2965                         else
2966                                 mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
2967
2968                         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
2969                                 mode->channels[idx].flag |=
2970                                         HOSTAPD_CHAN_DISABLED;
2971                         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
2972                                 mode->channels[idx].flag |=
2973                                         HOSTAPD_CHAN_PASSIVE_SCAN;
2974                         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
2975                                 mode->channels[idx].flag |=
2976                                         HOSTAPD_CHAN_NO_IBSS;
2977                         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
2978                                 mode->channels[idx].flag |=
2979                                         HOSTAPD_CHAN_RADAR;
2980
2981                         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
2982                             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
2983                                 mode->channels[idx].max_tx_power =
2984                                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
2985
2986                         idx++;
2987                 }
2988
2989                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
2990                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
2991                                   nla_len(nl_rate), rate_policy);
2992                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
2993                                 continue;
2994                         mode->num_rates++;
2995                 }
2996
2997                 mode->rates = os_zalloc(mode->num_rates * sizeof(int));
2998                 if (!mode->rates)
2999                         return NL_SKIP;
3000
3001                 idx = 0;
3002
3003                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
3004                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
3005                                   nla_len(nl_rate), rate_policy);
3006                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
3007                                 continue;
3008                         mode->rates[idx] = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
3009
3010                         /* crude heuristic */
3011                         if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
3012                             mode->rates[idx] > 200)
3013                                 mode->mode = HOSTAPD_MODE_IEEE80211G;
3014
3015                         idx++;
3016                 }
3017         }
3018
3019         return NL_SKIP;
3020 }
3021
3022 static struct hostapd_hw_modes *
3023 wpa_driver_nl80211_add_11b(struct hostapd_hw_modes *modes, u16 *num_modes)
3024 {
3025         u16 m;
3026         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
3027         int i, mode11g_idx = -1;
3028
3029         /* If only 802.11g mode is included, use it to construct matching
3030          * 802.11b mode data. */
3031
3032         for (m = 0; m < *num_modes; m++) {
3033                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
3034                         return modes; /* 802.11b already included */
3035                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
3036                         mode11g_idx = m;
3037         }
3038
3039         if (mode11g_idx < 0)
3040                 return modes; /* 2.4 GHz band not supported at all */
3041
3042         nmodes = os_realloc(modes, (*num_modes + 1) * sizeof(*nmodes));
3043         if (nmodes == NULL)
3044                 return modes; /* Could not add 802.11b mode */
3045
3046         mode = &nmodes[*num_modes];
3047         os_memset(mode, 0, sizeof(*mode));
3048         (*num_modes)++;
3049         modes = nmodes;
3050
3051         mode->mode = HOSTAPD_MODE_IEEE80211B;
3052
3053         mode11g = &modes[mode11g_idx];
3054         mode->num_channels = mode11g->num_channels;
3055         mode->channels = os_malloc(mode11g->num_channels *
3056                                    sizeof(struct hostapd_channel_data));
3057         if (mode->channels == NULL) {
3058                 (*num_modes)--;
3059                 return modes; /* Could not add 802.11b mode */
3060         }
3061         os_memcpy(mode->channels, mode11g->channels,
3062                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
3063
3064         mode->num_rates = 0;
3065         mode->rates = os_malloc(4 * sizeof(int));
3066         if (mode->rates == NULL) {
3067                 os_free(mode->channels);
3068                 (*num_modes)--;
3069                 return modes; /* Could not add 802.11b mode */
3070         }
3071
3072         for (i = 0; i < mode11g->num_rates; i++) {
3073                 if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 &&
3074                     mode11g->rates[i] != 55 && mode11g->rates[i] != 110)
3075                         continue;
3076                 mode->rates[mode->num_rates] = mode11g->rates[i];
3077                 mode->num_rates++;
3078                 if (mode->num_rates == 4)
3079                         break;
3080         }
3081
3082         if (mode->num_rates == 0) {
3083                 os_free(mode->channels);
3084                 os_free(mode->rates);
3085                 (*num_modes)--;
3086                 return modes; /* No 802.11b rates */
3087         }
3088
3089         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
3090                    "information");
3091
3092         return modes;
3093 }
3094
3095
3096 static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start,
3097                                   int end)
3098 {
3099         int c;
3100
3101         for (c = 0; c < mode->num_channels; c++) {
3102                 struct hostapd_channel_data *chan = &mode->channels[c];
3103                 if (chan->freq - 10 >= start && chan->freq + 10 <= end)
3104                         chan->flag |= HOSTAPD_CHAN_HT40;
3105         }
3106 }
3107
3108
3109 static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start,
3110                                       int end)
3111 {
3112         int c;
3113
3114         for (c = 0; c < mode->num_channels; c++) {
3115                 struct hostapd_channel_data *chan = &mode->channels[c];
3116                 if (!(chan->flag & HOSTAPD_CHAN_HT40))
3117                         continue;
3118                 if (chan->freq - 30 >= start && chan->freq - 10 <= end)
3119                         chan->flag |= HOSTAPD_CHAN_HT40MINUS;
3120                 if (chan->freq + 10 >= start && chan->freq + 30 <= end)
3121                         chan->flag |= HOSTAPD_CHAN_HT40PLUS;
3122         }
3123 }
3124
3125
3126 static void nl80211_reg_rule_ht40(struct nlattr *tb[],
3127                                   struct phy_info_arg *results)
3128 {
3129         u32 start, end, max_bw;
3130         u16 m;
3131
3132         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
3133             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
3134             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
3135                 return;
3136
3137         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
3138         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
3139         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
3140
3141         wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz",
3142                    start, end, max_bw);
3143         if (max_bw < 40)
3144                 return;
3145
3146         for (m = 0; m < *results->num_modes; m++) {
3147                 if (!(results->modes[m].ht_capab &
3148                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
3149                         continue;
3150                 nl80211_set_ht40_mode(&results->modes[m], start, end);
3151         }
3152 }
3153
3154
3155 static void nl80211_reg_rule_sec(struct nlattr *tb[],
3156                                  struct phy_info_arg *results)
3157 {
3158         u32 start, end, max_bw;
3159         u16 m;
3160
3161         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
3162             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
3163             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
3164                 return;
3165
3166         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
3167         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
3168         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
3169
3170         if (max_bw < 20)
3171                 return;
3172
3173         for (m = 0; m < *results->num_modes; m++) {
3174                 if (!(results->modes[m].ht_capab &
3175                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
3176                         continue;
3177                 nl80211_set_ht40_mode_sec(&results->modes[m], start, end);
3178         }
3179 }
3180
3181
3182 static int nl80211_get_reg(struct nl_msg *msg, void *arg)
3183 {
3184         struct phy_info_arg *results = arg;
3185         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
3186         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3187         struct nlattr *nl_rule;
3188         struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1];
3189         int rem_rule;
3190         static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
3191                 [NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
3192                 [NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
3193                 [NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
3194                 [NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
3195                 [NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
3196                 [NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
3197         };
3198
3199         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3200                   genlmsg_attrlen(gnlh, 0), NULL);
3201         if (!tb_msg[NL80211_ATTR_REG_ALPHA2] ||
3202             !tb_msg[NL80211_ATTR_REG_RULES]) {
3203                 wpa_printf(MSG_DEBUG, "nl80211: No regulatory information "
3204                            "available");
3205                 return NL_SKIP;
3206         }
3207
3208         wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s",
3209                    (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]));
3210
3211         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
3212         {
3213                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
3214                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
3215                 nl80211_reg_rule_ht40(tb_rule, results);
3216         }
3217
3218         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
3219         {
3220                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
3221                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
3222                 nl80211_reg_rule_sec(tb_rule, results);
3223         }
3224
3225         return NL_SKIP;
3226 }
3227
3228
3229 static int nl80211_set_ht40_flags(struct wpa_driver_nl80211_data *drv,
3230                                   struct phy_info_arg *results)
3231 {
3232         struct nl_msg *msg;
3233
3234         msg = nlmsg_alloc();
3235         if (!msg)
3236                 return -ENOMEM;
3237
3238         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3239                     0, NL80211_CMD_GET_REG, 0);
3240         return send_and_recv_msgs(drv, msg, nl80211_get_reg, results);
3241 }
3242
3243
3244 static struct hostapd_hw_modes *
3245 wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
3246 {
3247         struct i802_bss *bss = priv;
3248         struct wpa_driver_nl80211_data *drv = bss->drv;
3249         struct nl_msg *msg;
3250         struct phy_info_arg result = {
3251                 .num_modes = num_modes,
3252                 .modes = NULL,
3253         };
3254
3255         *num_modes = 0;
3256         *flags = 0;
3257
3258         msg = nlmsg_alloc();
3259         if (!msg)
3260                 return NULL;
3261
3262         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3263                     0, NL80211_CMD_GET_WIPHY, 0);
3264
3265         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3266
3267         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) {
3268                 nl80211_set_ht40_flags(drv, &result);
3269                 return wpa_driver_nl80211_add_11b(result.modes, num_modes);
3270         }
3271  nla_put_failure:
3272         return NULL;
3273 }
3274
3275
3276 static int wpa_driver_nl80211_send_frame(struct wpa_driver_nl80211_data *drv,
3277                                          const void *data, size_t len,
3278                                          int encrypt)
3279 {
3280         __u8 rtap_hdr[] = {
3281                 0x00, 0x00, /* radiotap version */
3282                 0x0e, 0x00, /* radiotap length */
3283                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
3284                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
3285                 0x00,       /* padding */
3286                 0x00, 0x00, /* RX and TX flags to indicate that */
3287                 0x00, 0x00, /* this is the injected frame directly */
3288         };
3289         struct iovec iov[2] = {
3290                 {
3291                         .iov_base = &rtap_hdr,
3292                         .iov_len = sizeof(rtap_hdr),
3293                 },
3294                 {
3295                         .iov_base = (void *) data,
3296                         .iov_len = len,
3297                 }
3298         };
3299         struct msghdr msg = {
3300                 .msg_name = NULL,
3301                 .msg_namelen = 0,
3302                 .msg_iov = iov,
3303                 .msg_iovlen = 2,
3304                 .msg_control = NULL,
3305                 .msg_controllen = 0,
3306                 .msg_flags = 0,
3307         };
3308         int res;
3309
3310         if (encrypt)
3311                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
3312
3313         res = sendmsg(drv->monitor_sock, &msg, 0);
3314         if (res < 0) {
3315                 wpa_printf(MSG_INFO, "nl80211: sendmsg: %s", strerror(errno));
3316                 return -1;
3317         }
3318         return 0;
3319 }
3320
3321
3322 static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
3323                                         size_t data_len)
3324 {
3325         struct i802_bss *bss = priv;
3326         struct wpa_driver_nl80211_data *drv = bss->drv;
3327         struct ieee80211_mgmt *mgmt;
3328         int encrypt = 1;
3329         u16 fc;
3330
3331         mgmt = (struct ieee80211_mgmt *) data;
3332         fc = le_to_host16(mgmt->frame_control);
3333
3334         if (drv->nlmode == NL80211_IFTYPE_STATION &&
3335             WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
3336             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_PROBE_RESP) {
3337                 /*
3338                  * The use of last_mgmt_freq is a bit of a hack,
3339                  * but it works due to the single-threaded nature
3340                  * of wpa_supplicant.
3341                  */
3342                 return nl80211_send_frame_cmd(drv, drv->last_mgmt_freq,
3343                                               data, data_len, NULL);
3344         }
3345
3346         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
3347             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
3348                 /*
3349                  * Only one of the authentication frame types is encrypted.
3350                  * In order for static WEP encryption to work properly (i.e.,
3351                  * to not encrypt the frame), we need to tell mac80211 about
3352                  * the frames that must not be encrypted.
3353                  */
3354                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
3355                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
3356                 if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
3357                         encrypt = 0;
3358         }
3359
3360         return wpa_driver_nl80211_send_frame(drv, data, data_len, encrypt);
3361 }
3362
3363
3364 static int wpa_driver_nl80211_set_beacon(void *priv,
3365                                          const u8 *head, size_t head_len,
3366                                          const u8 *tail, size_t tail_len,
3367                                          int dtim_period, int beacon_int)
3368 {
3369         struct i802_bss *bss = priv;
3370         struct wpa_driver_nl80211_data *drv = bss->drv;
3371         struct nl_msg *msg;
3372         u8 cmd = NL80211_CMD_NEW_BEACON;
3373         int ret;
3374         int beacon_set;
3375         int ifindex = if_nametoindex(bss->ifname);
3376
3377         beacon_set = bss->beacon_set;
3378
3379         msg = nlmsg_alloc();
3380         if (!msg)
3381                 return -ENOMEM;
3382
3383         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
3384                    beacon_set);
3385         if (beacon_set)
3386                 cmd = NL80211_CMD_SET_BEACON;
3387
3388         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3389                     0, cmd, 0);
3390         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, head_len, head);
3391         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, tail_len, tail);
3392         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
3393         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, beacon_int);
3394         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, dtim_period);
3395
3396         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3397         if (ret) {
3398                 wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
3399                            ret, strerror(-ret));
3400         } else {
3401                 bss->beacon_set = 1;
3402         }
3403         return ret;
3404  nla_put_failure:
3405         return -ENOBUFS;
3406 }
3407
3408
3409 static int wpa_driver_nl80211_set_freq(struct wpa_driver_nl80211_data *drv,
3410                                        int freq, int ht_enabled,
3411                                        int sec_channel_offset)
3412 {
3413         struct nl_msg *msg;
3414         int ret;
3415
3416         msg = nlmsg_alloc();
3417         if (!msg)
3418                 return -1;
3419
3420         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
3421                     NL80211_CMD_SET_WIPHY, 0);
3422
3423         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3424         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
3425         if (ht_enabled) {
3426                 switch (sec_channel_offset) {
3427                 case -1:
3428                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3429                                     NL80211_CHAN_HT40MINUS);
3430                         break;
3431                 case 1:
3432                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3433                                     NL80211_CHAN_HT40PLUS);
3434                         break;
3435                 default:
3436                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3437                                     NL80211_CHAN_HT20);
3438                         break;
3439                 }
3440         }
3441
3442         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3443         if (ret == 0)
3444                 return 0;
3445         wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
3446                    "%d (%s)", freq, ret, strerror(-ret));
3447 nla_put_failure:
3448         return -1;
3449 }
3450
3451
3452 static int wpa_driver_nl80211_sta_add(void *priv,
3453                                       struct hostapd_sta_add_params *params)
3454 {
3455         struct i802_bss *bss = priv;
3456         struct wpa_driver_nl80211_data *drv = bss->drv;
3457         struct nl_msg *msg;
3458         int ret = -ENOBUFS;
3459
3460         msg = nlmsg_alloc();
3461         if (!msg)
3462                 return -ENOMEM;
3463
3464         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3465                     0, NL80211_CMD_NEW_STATION, 0);
3466
3467         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
3468         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
3469         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
3470         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
3471                 params->supp_rates);
3472         NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
3473                     params->listen_interval);
3474         if (params->ht_capabilities) {
3475                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
3476                         sizeof(*params->ht_capabilities),
3477                         params->ht_capabilities);
3478         }
3479
3480         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3481         if (ret)
3482                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_NEW_STATION "
3483                            "result: %d (%s)", ret, strerror(-ret));
3484         if (ret == -EEXIST)
3485                 ret = 0;
3486  nla_put_failure:
3487         return ret;
3488 }
3489
3490
3491 static int wpa_driver_nl80211_sta_remove(void *priv, const u8 *addr)
3492 {
3493         struct i802_bss *bss = priv;
3494         struct wpa_driver_nl80211_data *drv = bss->drv;
3495         struct nl_msg *msg;
3496         int ret;
3497
3498         msg = nlmsg_alloc();
3499         if (!msg)
3500                 return -ENOMEM;
3501
3502         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3503                     0, NL80211_CMD_DEL_STATION, 0);
3504
3505         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3506                     if_nametoindex(bss->ifname));
3507         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3508
3509         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3510         if (ret == -ENOENT)
3511                 return 0;
3512         return ret;
3513  nla_put_failure:
3514         return -ENOBUFS;
3515 }
3516
3517
3518 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
3519                                  int ifidx)
3520 {
3521         struct nl_msg *msg;
3522
3523         wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
3524
3525 #ifdef HOSTAPD
3526         /* stop listening for EAPOL on this interface */
3527         del_ifidx(drv, ifidx);
3528 #endif /* HOSTAPD */
3529
3530         msg = nlmsg_alloc();
3531         if (!msg)
3532                 goto nla_put_failure;
3533
3534         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3535                     0, NL80211_CMD_DEL_INTERFACE, 0);
3536         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
3537
3538         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
3539                 return;
3540  nla_put_failure:
3541         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
3542 }
3543
3544
3545 static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
3546                                      const char *ifname,
3547                                      enum nl80211_iftype iftype,
3548                                      const u8 *addr, int wds)
3549 {
3550         struct nl_msg *msg, *flags = NULL;
3551         int ifidx;
3552         int ret = -ENOBUFS;
3553
3554         msg = nlmsg_alloc();
3555         if (!msg)
3556                 return -1;
3557
3558         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3559                     0, NL80211_CMD_NEW_INTERFACE, 0);
3560         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3561         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
3562         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
3563
3564         if (iftype == NL80211_IFTYPE_MONITOR) {
3565                 int err;
3566
3567                 flags = nlmsg_alloc();
3568                 if (!flags)
3569                         goto nla_put_failure;
3570
3571                 NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
3572
3573                 err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
3574
3575                 nlmsg_free(flags);
3576
3577                 if (err)
3578                         goto nla_put_failure;
3579         } else if (wds) {
3580                 NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
3581         }
3582
3583         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3584         if (ret) {
3585  nla_put_failure:
3586                 wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
3587                            ifname, ret, strerror(-ret));
3588                 return ret;
3589         }
3590
3591         ifidx = if_nametoindex(ifname);
3592         wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
3593                    ifname, ifidx);
3594
3595         if (ifidx <= 0)
3596                 return -1;
3597
3598 #ifdef HOSTAPD
3599         /* start listening for EAPOL on this interface */
3600         add_ifidx(drv, ifidx);
3601 #endif /* HOSTAPD */
3602
3603         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
3604             linux_set_ifhwaddr(drv->ioctl_sock, ifname, addr)) {
3605                 nl80211_remove_iface(drv, ifidx);
3606                 return -1;
3607         }
3608
3609         return ifidx;
3610 }
3611
3612
3613 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
3614                                 const char *ifname, enum nl80211_iftype iftype,
3615                                 const u8 *addr, int wds)
3616 {
3617         int ret;
3618
3619         ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds);
3620
3621         /* if error occured and interface exists already */
3622         if (ret == -ENFILE && if_nametoindex(ifname)) {
3623                 wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
3624
3625                 /* Try to remove the interface that was already there. */
3626                 nl80211_remove_iface(drv, if_nametoindex(ifname));
3627
3628                 /* Try to create the interface again */
3629                 ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
3630                                                 wds);
3631         }
3632
3633         if (ret >= 0 && drv->disable_11b_rates)
3634                 nl80211_disable_11b_rates(drv, ret, 1);
3635
3636         return ret;
3637 }
3638
3639
3640 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
3641 {
3642         struct ieee80211_hdr *hdr;
3643         u16 fc;
3644         union wpa_event_data event;
3645
3646         hdr = (struct ieee80211_hdr *) buf;
3647         fc = le_to_host16(hdr->frame_control);
3648
3649         os_memset(&event, 0, sizeof(event));
3650         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
3651         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
3652         event.tx_status.dst = hdr->addr1;
3653         event.tx_status.data = buf;
3654         event.tx_status.data_len = len;
3655         event.tx_status.ack = ok;
3656         wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
3657 }
3658
3659
3660 static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
3661                              u8 *buf, size_t len)
3662 {
3663         union wpa_event_data event;
3664         os_memset(&event, 0, sizeof(event));
3665         event.rx_from_unknown.frame = buf;
3666         event.rx_from_unknown.len = len;
3667         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
3668 }
3669
3670
3671 static void handle_frame(struct wpa_driver_nl80211_data *drv,
3672                          u8 *buf, size_t len, int datarate, int ssi_signal)
3673 {
3674         struct ieee80211_hdr *hdr;
3675         u16 fc;
3676         union wpa_event_data event;
3677
3678         hdr = (struct ieee80211_hdr *) buf;
3679         fc = le_to_host16(hdr->frame_control);
3680
3681         switch (WLAN_FC_GET_TYPE(fc)) {
3682         case WLAN_FC_TYPE_MGMT:
3683                 os_memset(&event, 0, sizeof(event));
3684                 event.rx_mgmt.frame = buf;
3685                 event.rx_mgmt.frame_len = len;
3686                 event.rx_mgmt.datarate = datarate;
3687                 event.rx_mgmt.ssi_signal = ssi_signal;
3688                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
3689                 break;
3690         case WLAN_FC_TYPE_CTRL:
3691                 /* can only get here with PS-Poll frames */
3692                 wpa_printf(MSG_DEBUG, "CTRL");
3693                 from_unknown_sta(drv, buf, len);
3694                 break;
3695         case WLAN_FC_TYPE_DATA:
3696                 from_unknown_sta(drv, buf, len);
3697                 break;
3698         }
3699 }
3700
3701
3702 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
3703 {
3704         struct wpa_driver_nl80211_data *drv = eloop_ctx;
3705         int len;
3706         unsigned char buf[3000];
3707         struct ieee80211_radiotap_iterator iter;
3708         int ret;
3709         int datarate = 0, ssi_signal = 0;
3710         int injected = 0, failed = 0, rxflags = 0;
3711
3712         len = recv(sock, buf, sizeof(buf), 0);
3713         if (len < 0) {
3714                 perror("recv");
3715                 return;
3716         }
3717
3718         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
3719                 printf("received invalid radiotap frame\n");
3720                 return;
3721         }
3722
3723         while (1) {
3724                 ret = ieee80211_radiotap_iterator_next(&iter);
3725                 if (ret == -ENOENT)
3726                         break;
3727                 if (ret) {
3728                         printf("received invalid radiotap frame (%d)\n", ret);
3729                         return;
3730                 }
3731                 switch (iter.this_arg_index) {
3732                 case IEEE80211_RADIOTAP_FLAGS:
3733                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
3734                                 len -= 4;
3735                         break;
3736                 case IEEE80211_RADIOTAP_RX_FLAGS:
3737                         rxflags = 1;
3738                         break;
3739                 case IEEE80211_RADIOTAP_TX_FLAGS:
3740                         injected = 1;
3741                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
3742                                         IEEE80211_RADIOTAP_F_TX_FAIL;
3743                         break;
3744                 case IEEE80211_RADIOTAP_DATA_RETRIES:
3745                         break;
3746                 case IEEE80211_RADIOTAP_CHANNEL:
3747                         /* TODO: convert from freq/flags to channel number */
3748                         break;
3749                 case IEEE80211_RADIOTAP_RATE:
3750                         datarate = *iter.this_arg * 5;
3751                         break;
3752                 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
3753                         ssi_signal = *iter.this_arg;
3754                         break;
3755                 }
3756         }
3757
3758         if (rxflags && injected)
3759                 return;
3760
3761         if (!injected)
3762                 handle_frame(drv, buf + iter.max_length,
3763                              len - iter.max_length, datarate, ssi_signal);
3764         else
3765                 handle_tx_callback(drv->ctx, buf + iter.max_length,
3766                                    len - iter.max_length, !failed);
3767 }
3768
3769
3770 /*
3771  * we post-process the filter code later and rewrite
3772  * this to the offset to the last instruction
3773  */
3774 #define PASS    0xFF
3775 #define FAIL    0xFE
3776
3777 static struct sock_filter msock_filter_insns[] = {
3778         /*
3779          * do a little-endian load of the radiotap length field
3780          */
3781         /* load lower byte into A */
3782         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
3783         /* put it into X (== index register) */
3784         BPF_STMT(BPF_MISC| BPF_TAX, 0),
3785         /* load upper byte into A */
3786         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
3787         /* left-shift it by 8 */
3788         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
3789         /* or with X */
3790         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
3791         /* put result into X */
3792         BPF_STMT(BPF_MISC| BPF_TAX, 0),
3793
3794         /*
3795          * Allow management frames through, this also gives us those
3796          * management frames that we sent ourselves with status
3797          */
3798         /* load the lower byte of the IEEE 802.11 frame control field */
3799         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
3800         /* mask off frame type and version */
3801         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
3802         /* accept frame if it's both 0, fall through otherwise */
3803         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
3804
3805         /*
3806          * TODO: add a bit to radiotap RX flags that indicates
3807          * that the sending station is not associated, then
3808          * add a filter here that filters on our DA and that flag
3809          * to allow us to deauth frames to that bad station.
3810          *
3811          * For now allow all To DS data frames through.
3812          */
3813         /* load the IEEE 802.11 frame control field */
3814         BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
3815         /* mask off frame type, version and DS status */
3816         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
3817         /* accept frame if version 0, type 2 and To DS, fall through otherwise
3818          */
3819         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
3820
3821 #if 0
3822         /*
3823          * drop non-data frames
3824          */
3825         /* load the lower byte of the frame control field */
3826         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
3827         /* mask off QoS bit */
3828         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
3829         /* drop non-data frames */
3830         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
3831 #endif
3832         /* load the upper byte of the frame control field */
3833         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
3834         /* mask off toDS/fromDS */
3835         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
3836         /* accept WDS frames */
3837         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
3838
3839         /*
3840          * add header length to index
3841          */
3842         /* load the lower byte of the frame control field */
3843         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
3844         /* mask off QoS bit */
3845         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
3846         /* right shift it by 6 to give 0 or 2 */
3847         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
3848         /* add data frame header length */
3849         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
3850         /* add index, was start of 802.11 header */
3851         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
3852         /* move to index, now start of LL header */
3853         BPF_STMT(BPF_MISC | BPF_TAX, 0),
3854
3855         /*
3856          * Accept empty data frames, we use those for
3857          * polling activity.
3858          */
3859         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
3860         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
3861
3862         /*
3863          * Accept EAPOL frames
3864          */
3865         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
3866         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
3867         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
3868         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
3869
3870         /* keep these last two statements or change the code below */
3871         /* return 0 == "DROP" */
3872         BPF_STMT(BPF_RET | BPF_K, 0),
3873         /* return ~0 == "keep all" */
3874         BPF_STMT(BPF_RET | BPF_K, ~0),
3875 };
3876
3877 static struct sock_fprog msock_filter = {
3878         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
3879         .filter = msock_filter_insns,
3880 };
3881
3882
3883 static int add_monitor_filter(int s)
3884 {
3885         int idx;
3886
3887         /* rewrite all PASS/FAIL jump offsets */
3888         for (idx = 0; idx < msock_filter.len; idx++) {
3889                 struct sock_filter *insn = &msock_filter_insns[idx];
3890
3891                 if (BPF_CLASS(insn->code) == BPF_JMP) {
3892                         if (insn->code == (BPF_JMP|BPF_JA)) {
3893                                 if (insn->k == PASS)
3894                                         insn->k = msock_filter.len - idx - 2;
3895                                 else if (insn->k == FAIL)
3896                                         insn->k = msock_filter.len - idx - 3;
3897                         }
3898
3899                         if (insn->jt == PASS)
3900                                 insn->jt = msock_filter.len - idx - 2;
3901                         else if (insn->jt == FAIL)
3902                                 insn->jt = msock_filter.len - idx - 3;
3903
3904                         if (insn->jf == PASS)
3905                                 insn->jf = msock_filter.len - idx - 2;
3906                         else if (insn->jf == FAIL)
3907                                 insn->jf = msock_filter.len - idx - 3;
3908                 }
3909         }
3910
3911         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
3912                        &msock_filter, sizeof(msock_filter))) {
3913                 perror("SO_ATTACH_FILTER");
3914                 return -1;
3915         }
3916
3917         return 0;
3918 }
3919
3920
3921 static void nl80211_remove_monitor_interface(
3922         struct wpa_driver_nl80211_data *drv)
3923 {
3924         if (drv->monitor_ifidx >= 0) {
3925                 nl80211_remove_iface(drv, drv->monitor_ifidx);
3926                 drv->monitor_ifidx = -1;
3927         }
3928         if (drv->monitor_sock >= 0) {
3929                 eloop_unregister_read_sock(drv->monitor_sock);
3930                 close(drv->monitor_sock);
3931                 drv->monitor_sock = -1;
3932         }
3933 }
3934
3935
3936 static int
3937 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
3938 {
3939         char buf[IFNAMSIZ];
3940         struct sockaddr_ll ll;
3941         int optval;
3942         socklen_t optlen;
3943
3944         snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss.ifname);
3945         buf[IFNAMSIZ - 1] = '\0';
3946
3947         drv->monitor_ifidx =
3948                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
3949                                      0);
3950
3951         if (drv->monitor_ifidx < 0)
3952                 return -1;
3953
3954         if (linux_set_iface_flags(drv->ioctl_sock, buf, 1))
3955                 goto error;
3956
3957         memset(&ll, 0, sizeof(ll));
3958         ll.sll_family = AF_PACKET;
3959         ll.sll_ifindex = drv->monitor_ifidx;
3960         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
3961         if (drv->monitor_sock < 0) {
3962                 perror("socket[PF_PACKET,SOCK_RAW]");
3963                 goto error;
3964         }
3965
3966         if (add_monitor_filter(drv->monitor_sock)) {
3967                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
3968                            "interface; do filtering in user space");
3969                 /* This works, but will cost in performance. */
3970         }
3971
3972         if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
3973                 perror("monitor socket bind");
3974                 goto error;
3975         }
3976
3977         optlen = sizeof(optval);
3978         optval = 20;
3979         if (setsockopt
3980             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
3981                 perror("Failed to set socket priority");
3982                 goto error;
3983         }
3984
3985         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
3986                                      drv, NULL)) {
3987                 printf("Could not register monitor read socket\n");
3988                 goto error;
3989         }
3990
3991         return 0;
3992  error:
3993         nl80211_remove_monitor_interface(drv);
3994         return -1;
3995 }
3996
3997
3998 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
3999
4000 static int wpa_driver_nl80211_hapd_send_eapol(
4001         void *priv, const u8 *addr, const u8 *data,
4002         size_t data_len, int encrypt, const u8 *own_addr)
4003 {
4004         struct i802_bss *bss = priv;
4005         struct wpa_driver_nl80211_data *drv = bss->drv;
4006         struct ieee80211_hdr *hdr;
4007         size_t len;
4008         u8 *pos;
4009         int res;
4010 #if 0 /* FIX */
4011         int qos = sta->flags & WPA_STA_WMM;
4012 #else
4013         int qos = 0;
4014 #endif
4015
4016         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
4017                 data_len;
4018         hdr = os_zalloc(len);
4019         if (hdr == NULL) {
4020                 printf("malloc() failed for i802_send_data(len=%lu)\n",
4021                        (unsigned long) len);
4022                 return -1;
4023         }
4024
4025         hdr->frame_control =
4026                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
4027         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
4028         if (encrypt)
4029                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
4030 #if 0 /* To be enabled if qos determination is added above */
4031         if (qos) {
4032                 hdr->frame_control |=
4033                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
4034         }
4035 #endif
4036
4037         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
4038         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
4039         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
4040         pos = (u8 *) (hdr + 1);
4041
4042 #if 0 /* To be enabled if qos determination is added above */
4043         if (qos) {
4044                 /* add an empty QoS header if needed */
4045                 pos[0] = 0;
4046                 pos[1] = 0;
4047                 pos += 2;
4048         }
4049 #endif
4050
4051         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
4052         pos += sizeof(rfc1042_header);
4053         WPA_PUT_BE16(pos, ETH_P_PAE);
4054         pos += 2;
4055         memcpy(pos, data, data_len);
4056
4057         res = wpa_driver_nl80211_send_frame(drv, (u8 *) hdr, len, encrypt);
4058         if (res < 0) {
4059                 wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
4060                            "failed: %d (%s)",
4061                            (unsigned long) len, errno, strerror(errno));
4062         }
4063         os_free(hdr);
4064
4065         return res;
4066 }
4067
4068
4069 static u32 sta_flags_nl80211(int flags)
4070 {
4071         u32 f = 0;
4072
4073         if (flags & WPA_STA_AUTHORIZED)
4074                 f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
4075         if (flags & WPA_STA_WMM)
4076                 f |= BIT(NL80211_STA_FLAG_WME);
4077         if (flags & WPA_STA_SHORT_PREAMBLE)
4078                 f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
4079         if (flags & WPA_STA_MFP)
4080                 f |= BIT(NL80211_STA_FLAG_MFP);
4081
4082         return f;
4083 }
4084
4085
4086 static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
4087                                             int total_flags,
4088                                             int flags_or, int flags_and)
4089 {
4090         struct i802_bss *bss = priv;
4091         struct wpa_driver_nl80211_data *drv = bss->drv;
4092         struct nl_msg *msg, *flags = NULL;
4093         struct nl80211_sta_flag_update upd;
4094
4095         msg = nlmsg_alloc();
4096         if (!msg)
4097                 return -ENOMEM;
4098
4099         flags = nlmsg_alloc();
4100         if (!flags) {
4101                 nlmsg_free(msg);
4102                 return -ENOMEM;
4103         }
4104
4105         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4106                     0, NL80211_CMD_SET_STATION, 0);
4107
4108         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
4109                     if_nametoindex(bss->ifname));
4110         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4111
4112         /*
4113          * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
4114          * can be removed eventually.
4115          */
4116         if (total_flags & WPA_STA_AUTHORIZED)
4117                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
4118
4119         if (total_flags & WPA_STA_WMM)
4120                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
4121
4122         if (total_flags & WPA_STA_SHORT_PREAMBLE)
4123                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
4124
4125         if (total_flags & WPA_STA_MFP)
4126                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
4127
4128         if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
4129                 goto nla_put_failure;
4130
4131         os_memset(&upd, 0, sizeof(upd));
4132         upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
4133         upd.set = sta_flags_nl80211(flags_or);
4134         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
4135
4136         nlmsg_free(flags);
4137
4138         return send_and_recv_msgs(drv, msg, NULL, NULL);
4139  nla_put_failure:
4140         nlmsg_free(flags);
4141         return -ENOBUFS;
4142 }
4143
4144
4145 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
4146                                  struct wpa_driver_associate_params *params)
4147 {
4148         if (params->p2p)
4149                 wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
4150                            "group (GO)");
4151         if (wpa_driver_nl80211_set_mode(&drv->first_bss, params->mode) ||
4152             wpa_driver_nl80211_set_freq(drv, params->freq, 0, 0)) {
4153                 nl80211_remove_monitor_interface(drv);
4154                 return -1;
4155         }
4156
4157         /* TODO: setup monitor interface (and add code somewhere to remove this
4158          * when AP mode is stopped; associate with mode != 2 or drv_deinit) */
4159
4160         return 0;
4161 }
4162
4163
4164 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
4165 {
4166         struct nl_msg *msg;
4167         int ret = -1;
4168
4169         msg = nlmsg_alloc();
4170         if (!msg)
4171                 return -1;
4172
4173         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4174                     NL80211_CMD_LEAVE_IBSS, 0);
4175         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4176         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4177         msg = NULL;
4178         if (ret) {
4179                 wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
4180                            "(%s)", ret, strerror(-ret));
4181                 goto nla_put_failure;
4182         }
4183
4184         ret = 0;
4185         wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
4186
4187 nla_put_failure:
4188         nlmsg_free(msg);
4189         return ret;
4190 }
4191
4192
4193 static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
4194                                    struct wpa_driver_associate_params *params)
4195 {
4196         struct nl_msg *msg;
4197         int ret = -1;
4198         int count = 0;
4199
4200         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
4201
4202         if (wpa_driver_nl80211_set_mode(&drv->first_bss, params->mode)) {
4203                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
4204                            "IBSS mode");
4205                 return -1;
4206         }
4207
4208 retry:
4209         msg = nlmsg_alloc();
4210         if (!msg)
4211                 return -1;
4212
4213         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4214                     NL80211_CMD_JOIN_IBSS, 0);
4215         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4216
4217         if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
4218                 goto nla_put_failure;
4219
4220         wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4221                           params->ssid, params->ssid_len);
4222         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4223                 params->ssid);
4224         os_memcpy(drv->ssid, params->ssid, params->ssid_len);
4225         drv->ssid_len = params->ssid_len;
4226
4227         wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4228         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4229
4230         ret = nl80211_set_conn_keys(params, msg);
4231         if (ret)
4232                 goto nla_put_failure;
4233
4234         if (params->wpa_ie) {
4235                 wpa_hexdump(MSG_DEBUG,
4236                             "  * Extra IEs for Beacon/Probe Response frames",
4237                             params->wpa_ie, params->wpa_ie_len);
4238                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
4239                         params->wpa_ie);
4240         }
4241
4242         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4243         msg = NULL;
4244         if (ret) {
4245                 wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
4246                            ret, strerror(-ret));
4247                 count++;
4248                 if (ret == -EALREADY && count == 1) {
4249                         wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
4250                                    "forced leave");
4251                         nl80211_leave_ibss(drv);
4252                         nlmsg_free(msg);
4253                         goto retry;
4254                 }
4255
4256                 goto nla_put_failure;
4257         }
4258         ret = 0;
4259         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
4260
4261 nla_put_failure:
4262         nlmsg_free(msg);
4263         return ret;
4264 }
4265
4266
4267 static int wpa_driver_nl80211_connect(
4268         struct wpa_driver_nl80211_data *drv,
4269         struct wpa_driver_associate_params *params)
4270 {
4271         struct nl_msg *msg;
4272         enum nl80211_auth_type type;
4273         int ret = 0;
4274
4275         msg = nlmsg_alloc();
4276         if (!msg)
4277                 return -1;
4278
4279         wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
4280         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4281                     NL80211_CMD_CONNECT, 0);
4282
4283         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4284         if (params->bssid) {
4285                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4286                            MAC2STR(params->bssid));
4287                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4288         }
4289         if (params->freq) {
4290                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4291                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4292         }
4293         if (params->ssid) {
4294                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4295                                   params->ssid, params->ssid_len);
4296                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4297                         params->ssid);
4298                 if (params->ssid_len > sizeof(drv->ssid))
4299                         goto nla_put_failure;
4300                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
4301                 drv->ssid_len = params->ssid_len;
4302         }
4303         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
4304         if (params->wpa_ie)
4305                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
4306                         params->wpa_ie);
4307
4308         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
4309                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
4310         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
4311                 type = NL80211_AUTHTYPE_SHARED_KEY;
4312         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
4313                 type = NL80211_AUTHTYPE_NETWORK_EAP;
4314         else if (params->auth_alg & WPA_AUTH_ALG_FT)
4315                 type = NL80211_AUTHTYPE_FT;
4316         else
4317                 goto nla_put_failure;
4318
4319         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
4320         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
4321
4322         if (params->wpa_ie && params->wpa_ie_len) {
4323                 enum nl80211_wpa_versions ver;
4324
4325                 if (params->wpa_ie[0] == WLAN_EID_RSN)
4326                         ver = NL80211_WPA_VERSION_2;
4327                 else
4328                         ver = NL80211_WPA_VERSION_1;
4329
4330                 wpa_printf(MSG_DEBUG, "  * WPA Version %d", ver);
4331                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
4332         }
4333
4334         if (params->pairwise_suite != CIPHER_NONE) {
4335                 int cipher;
4336
4337                 switch (params->pairwise_suite) {
4338                 case CIPHER_WEP40:
4339                         cipher = WLAN_CIPHER_SUITE_WEP40;
4340                         break;
4341                 case CIPHER_WEP104:
4342                         cipher = WLAN_CIPHER_SUITE_WEP104;
4343                         break;
4344                 case CIPHER_CCMP:
4345                         cipher = WLAN_CIPHER_SUITE_CCMP;
4346                         break;
4347                 case CIPHER_TKIP:
4348                 default:
4349                         cipher = WLAN_CIPHER_SUITE_TKIP;
4350                         break;
4351                 }
4352                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
4353         }
4354
4355         if (params->group_suite != CIPHER_NONE) {
4356                 int cipher;
4357
4358                 switch (params->group_suite) {
4359                 case CIPHER_WEP40:
4360                         cipher = WLAN_CIPHER_SUITE_WEP40;
4361                         break;
4362                 case CIPHER_WEP104:
4363                         cipher = WLAN_CIPHER_SUITE_WEP104;
4364                         break;
4365                 case CIPHER_CCMP:
4366                         cipher = WLAN_CIPHER_SUITE_CCMP;
4367                         break;
4368                 case CIPHER_TKIP:
4369                 default:
4370                         cipher = WLAN_CIPHER_SUITE_TKIP;
4371                         break;
4372                 }
4373                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
4374         }
4375
4376         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
4377             params->key_mgmt_suite == KEY_MGMT_PSK) {
4378                 int mgmt = WLAN_AKM_SUITE_PSK;
4379
4380                 switch (params->key_mgmt_suite) {
4381                 case KEY_MGMT_802_1X:
4382                         mgmt = WLAN_AKM_SUITE_8021X;
4383                         break;
4384                 case KEY_MGMT_PSK:
4385                 default:
4386                         mgmt = WLAN_AKM_SUITE_PSK;
4387                         break;
4388                 }
4389                 NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
4390         }
4391
4392         ret = nl80211_set_conn_keys(params, msg);
4393         if (ret)
4394                 goto nla_put_failure;
4395
4396         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4397         msg = NULL;
4398         if (ret) {
4399                 wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
4400                            "(%s)", ret, strerror(-ret));
4401                 goto nla_put_failure;
4402         }
4403         ret = 0;
4404         wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
4405
4406 nla_put_failure:
4407         nlmsg_free(msg);
4408         return ret;
4409
4410 }
4411
4412
4413 static int wpa_driver_nl80211_associate(
4414         void *priv, struct wpa_driver_associate_params *params)
4415 {
4416         struct i802_bss *bss = priv;
4417         struct wpa_driver_nl80211_data *drv = bss->drv;
4418         int ret = -1;
4419         struct nl_msg *msg;
4420
4421         if (params->mode == IEEE80211_MODE_AP)
4422                 return wpa_driver_nl80211_ap(drv, params);
4423
4424         if (params->mode == IEEE80211_MODE_IBSS)
4425                 return wpa_driver_nl80211_ibss(drv, params);
4426
4427         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
4428                 if (wpa_driver_nl80211_set_mode(priv, params->mode) < 0)
4429                         return -1;
4430                 return wpa_driver_nl80211_connect(drv, params);
4431         }
4432
4433         drv->associated = 0;
4434
4435         msg = nlmsg_alloc();
4436         if (!msg)
4437                 return -1;
4438
4439         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
4440                    drv->ifindex);
4441         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4442                     NL80211_CMD_ASSOCIATE, 0);
4443
4444         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4445         if (params->bssid) {
4446                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4447                            MAC2STR(params->bssid));
4448                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4449         }
4450         if (params->freq) {
4451                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4452                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4453                 drv->assoc_freq = params->freq;
4454         } else
4455                 drv->assoc_freq = 0;
4456         if (params->ssid) {
4457                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4458                                   params->ssid, params->ssid_len);
4459                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4460                         params->ssid);
4461                 if (params->ssid_len > sizeof(drv->ssid))
4462                         goto nla_put_failure;
4463                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
4464                 drv->ssid_len = params->ssid_len;
4465         }
4466         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
4467         if (params->wpa_ie)
4468                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
4469                         params->wpa_ie);
4470
4471 #ifdef CONFIG_IEEE80211W
4472         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
4473                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
4474 #endif /* CONFIG_IEEE80211W */
4475
4476         NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
4477
4478         if (params->prev_bssid) {
4479                 wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
4480                            MAC2STR(params->prev_bssid));
4481                 NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
4482                         params->prev_bssid);
4483         }
4484
4485         if (params->p2p)
4486                 wpa_printf(MSG_DEBUG, "  * P2P group");
4487
4488         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4489         msg = NULL;
4490         if (ret) {
4491                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
4492                            "(%s)", ret, strerror(-ret));
4493                 nl80211_dump_scan(drv);
4494                 goto nla_put_failure;
4495         }
4496         ret = 0;
4497         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
4498                    "successfully");
4499
4500 nla_put_failure:
4501         nlmsg_free(msg);
4502         return ret;
4503 }
4504
4505
4506 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
4507                             int ifindex, int mode)
4508 {
4509         struct nl_msg *msg;
4510         int ret = -ENOBUFS;
4511
4512         msg = nlmsg_alloc();
4513         if (!msg)
4514                 return -ENOMEM;
4515
4516         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4517                     0, NL80211_CMD_SET_INTERFACE, 0);
4518         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4519         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
4520
4521         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4522         if (!ret)
4523                 return 0;
4524 nla_put_failure:
4525         wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
4526                    " %d (%s)", ifindex, mode, ret, strerror(-ret));
4527         return ret;
4528 }
4529
4530
4531 static int wpa_driver_nl80211_set_mode(void *priv, int mode)
4532 {
4533         struct i802_bss *bss = priv;
4534         struct wpa_driver_nl80211_data *drv = bss->drv;
4535         int ret = -1;
4536         int nlmode;
4537         int i;
4538
4539         switch (mode) {
4540         case 0:
4541                 nlmode = NL80211_IFTYPE_STATION;
4542                 break;
4543         case 1:
4544                 nlmode = NL80211_IFTYPE_ADHOC;
4545                 break;
4546         case 2:
4547                 nlmode = NL80211_IFTYPE_AP;
4548                 break;
4549         default:
4550                 return -1;
4551         }
4552
4553         if (nl80211_set_mode(drv, drv->ifindex, nlmode) == 0) {
4554                 drv->nlmode = nlmode;
4555                 ret = 0;
4556                 goto done;
4557         }
4558
4559         if (nlmode == drv->nlmode) {
4560                 wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
4561                            "requested mode - ignore error");
4562                 ret = 0;
4563                 goto done; /* Already in the requested mode */
4564         }
4565
4566         /* mac80211 doesn't allow mode changes while the device is up, so
4567          * take the device down, try to set the mode again, and bring the
4568          * device back up.
4569          */
4570         wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
4571                    "interface down");
4572         for (i = 0; i < 10; i++) {
4573                 if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 0) ==
4574                     0) {
4575                         /* Try to set the mode again while the interface is
4576                          * down */
4577                         ret = nl80211_set_mode(drv, drv->ifindex, nlmode);
4578                         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname,
4579                                                   1))
4580                                 ret = -1;
4581                         if (!ret)
4582                                 break;
4583                 } else
4584                         wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
4585                                    "interface down");
4586                 os_sleep(0, 100000);
4587         }
4588
4589         if (!ret) {
4590                 wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
4591                            "interface is down");
4592                 drv->nlmode = nlmode;
4593         }
4594
4595 done:
4596         if (!ret && nlmode == NL80211_IFTYPE_AP) {
4597                 /* Setup additional AP mode functionality if needed */
4598                 if (drv->monitor_ifidx < 0 &&
4599                     nl80211_create_monitor_interface(drv))
4600                         return -1;
4601         } else if (!ret && nlmode != NL80211_IFTYPE_AP) {
4602                 /* Remove additional AP mode functionality */
4603                 nl80211_remove_monitor_interface(drv);
4604                 bss->beacon_set = 0;
4605         }
4606
4607         if (ret)
4608                 wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
4609                            "from %d failed", nlmode, drv->nlmode);
4610
4611         return ret;
4612 }
4613
4614
4615 static int wpa_driver_nl80211_get_capa(void *priv,
4616                                        struct wpa_driver_capa *capa)
4617 {
4618         struct i802_bss *bss = priv;
4619         struct wpa_driver_nl80211_data *drv = bss->drv;
4620         if (!drv->has_capability)
4621                 return -1;
4622         os_memcpy(capa, &drv->capa, sizeof(*capa));
4623         return 0;
4624 }
4625
4626
4627 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
4628 {
4629         struct i802_bss *bss = priv;
4630         struct wpa_driver_nl80211_data *drv = bss->drv;
4631
4632         wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
4633                    __func__, drv->operstate, state, state ? "UP" : "DORMANT");
4634         drv->operstate = state;
4635         return netlink_send_oper_ifla(drv->netlink, drv->ifindex, -1,
4636                                       state ? IF_OPER_UP : IF_OPER_DORMANT);
4637 }
4638
4639
4640 static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
4641 {
4642         struct i802_bss *bss = priv;
4643         struct wpa_driver_nl80211_data *drv = bss->drv;
4644         struct nl_msg *msg;
4645         struct nl80211_sta_flag_update upd;
4646
4647         msg = nlmsg_alloc();
4648         if (!msg)
4649                 return -ENOMEM;
4650
4651         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4652                     0, NL80211_CMD_SET_STATION, 0);
4653
4654         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
4655                     if_nametoindex(bss->ifname));
4656         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
4657
4658         os_memset(&upd, 0, sizeof(upd));
4659         upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
4660         if (authorized)
4661                 upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
4662         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
4663
4664         return send_and_recv_msgs(drv, msg, NULL, NULL);
4665  nla_put_failure:
4666         return -ENOBUFS;
4667 }
4668
4669
4670 #ifdef HOSTAPD
4671
4672 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
4673 {
4674         int i;
4675         int *old;
4676
4677         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
4678                    ifidx);
4679         for (i = 0; i < drv->num_if_indices; i++) {
4680                 if (drv->if_indices[i] == 0) {
4681                         drv->if_indices[i] = ifidx;
4682                         return;
4683                 }
4684         }
4685
4686         if (drv->if_indices != drv->default_if_indices)
4687                 old = drv->if_indices;
4688         else
4689                 old = NULL;
4690
4691         drv->if_indices = os_realloc(old,
4692                                      sizeof(int) * (drv->num_if_indices + 1));
4693         if (!drv->if_indices) {
4694                 if (!old)
4695                         drv->if_indices = drv->default_if_indices;
4696                 else
4697                         drv->if_indices = old;
4698                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
4699                            "interfaces");
4700                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
4701                 return;
4702         } else if (!old)
4703                 os_memcpy(drv->if_indices, drv->default_if_indices,
4704                           sizeof(drv->default_if_indices));
4705         drv->if_indices[drv->num_if_indices] = ifidx;
4706         drv->num_if_indices++;
4707 }
4708
4709
4710 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
4711 {
4712         int i;
4713
4714         for (i = 0; i < drv->num_if_indices; i++) {
4715                 if (drv->if_indices[i] == ifidx) {
4716                         drv->if_indices[i] = 0;
4717                         break;
4718                 }
4719         }
4720 }
4721
4722
4723 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
4724 {
4725         int i;
4726
4727         for (i = 0; i < drv->num_if_indices; i++)
4728                 if (drv->if_indices[i] == ifidx)
4729                         return 1;
4730
4731         return 0;
4732 }
4733
4734
4735 static inline int min_int(int a, int b)
4736 {
4737         if (a < b)
4738                 return a;
4739         return b;
4740 }
4741
4742
4743 static int get_key_handler(struct nl_msg *msg, void *arg)
4744 {
4745         struct nlattr *tb[NL80211_ATTR_MAX + 1];
4746         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
4747
4748         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
4749                   genlmsg_attrlen(gnlh, 0), NULL);
4750
4751         /*
4752          * TODO: validate the key index and mac address!
4753          * Otherwise, there's a race condition as soon as
4754          * the kernel starts sending key notifications.
4755          */
4756
4757         if (tb[NL80211_ATTR_KEY_SEQ])
4758                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
4759                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
4760         return NL_SKIP;
4761 }
4762
4763
4764 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
4765                            int idx, u8 *seq)
4766 {
4767         struct i802_bss *bss = priv;
4768         struct wpa_driver_nl80211_data *drv = bss->drv;
4769         struct nl_msg *msg;
4770
4771         msg = nlmsg_alloc();
4772         if (!msg)
4773                 return -ENOMEM;
4774
4775         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4776                     0, NL80211_CMD_GET_KEY, 0);
4777
4778         if (addr)
4779                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4780         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
4781         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
4782
4783         memset(seq, 0, 6);
4784
4785         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
4786  nla_put_failure:
4787         return -ENOBUFS;
4788 }
4789
4790
4791 static int i802_set_rate_sets(void *priv, int *supp_rates, int *basic_rates,
4792                               int mode)
4793 {
4794         struct i802_bss *bss = priv;
4795         struct wpa_driver_nl80211_data *drv = bss->drv;
4796         struct nl_msg *msg;
4797         u8 rates[NL80211_MAX_SUPP_RATES];
4798         u8 rates_len = 0;
4799         int i;
4800
4801         msg = nlmsg_alloc();
4802         if (!msg)
4803                 return -ENOMEM;
4804
4805         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4806                     NL80211_CMD_SET_BSS, 0);
4807
4808         for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0; i++)
4809                 rates[rates_len++] = basic_rates[i] / 5;
4810
4811         NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
4812
4813         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
4814
4815         return send_and_recv_msgs(drv, msg, NULL, NULL);
4816  nla_put_failure:
4817         return -ENOBUFS;
4818 }
4819
4820 #endif /* HOSTAPD */
4821
4822
4823 /* Set kernel driver on given frequency (MHz) */
4824 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
4825 {
4826         struct i802_bss *bss = priv;
4827         struct wpa_driver_nl80211_data *drv = bss->drv;
4828         return wpa_driver_nl80211_set_freq(drv, freq->freq, freq->ht_enabled,
4829                                            freq->sec_channel_offset);
4830 }
4831
4832
4833 #ifdef HOSTAPD
4834
4835 static int i802_set_rts(void *priv, int rts)
4836 {
4837         struct i802_bss *bss = priv;
4838         struct wpa_driver_nl80211_data *drv = bss->drv;
4839         struct nl_msg *msg;
4840         int ret = -ENOBUFS;
4841         u32 val;
4842
4843         msg = nlmsg_alloc();
4844         if (!msg)
4845                 return -ENOMEM;
4846
4847         if (rts >= 2347)
4848                 val = (u32) -1;
4849         else
4850                 val = rts;
4851
4852         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4853                     0, NL80211_CMD_SET_WIPHY, 0);
4854         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4855         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
4856
4857         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4858         if (!ret)
4859                 return 0;
4860 nla_put_failure:
4861         wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
4862                    "%d (%s)", rts, ret, strerror(-ret));
4863         return ret;
4864 }
4865
4866
4867 static int i802_set_frag(void *priv, int frag)
4868 {
4869         struct i802_bss *bss = priv;
4870         struct wpa_driver_nl80211_data *drv = bss->drv;
4871         struct nl_msg *msg;
4872         int ret = -ENOBUFS;
4873         u32 val;
4874
4875         msg = nlmsg_alloc();
4876         if (!msg)
4877                 return -ENOMEM;
4878
4879         if (frag >= 2346)
4880                 val = (u32) -1;
4881         else
4882                 val = frag;
4883
4884         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4885                     0, NL80211_CMD_SET_WIPHY, 0);
4886         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4887         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
4888
4889         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4890         if (!ret)
4891                 return 0;
4892 nla_put_failure:
4893         wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
4894                    "%d: %d (%s)", frag, ret, strerror(-ret));
4895         return ret;
4896 }
4897
4898
4899 static int i802_flush(void *priv)
4900 {
4901         struct i802_bss *bss = priv;
4902         struct wpa_driver_nl80211_data *drv = bss->drv;
4903         struct nl_msg *msg;
4904
4905         msg = nlmsg_alloc();
4906         if (!msg)
4907                 return -1;
4908
4909         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4910                     0, NL80211_CMD_DEL_STATION, 0);
4911
4912         /*
4913          * XXX: FIX! this needs to flush all VLANs too
4914          */
4915         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
4916                     if_nametoindex(bss->ifname));
4917
4918         return send_and_recv_msgs(drv, msg, NULL, NULL);
4919  nla_put_failure:
4920         return -ENOBUFS;
4921 }
4922
4923
4924 static int get_sta_handler(struct nl_msg *msg, void *arg)
4925 {
4926         struct nlattr *tb[NL80211_ATTR_MAX + 1];
4927         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
4928         struct hostap_sta_driver_data *data = arg;
4929         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
4930         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
4931                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
4932                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
4933                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
4934                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
4935                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
4936         };
4937
4938         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
4939                   genlmsg_attrlen(gnlh, 0), NULL);
4940
4941         /*
4942          * TODO: validate the interface and mac address!
4943          * Otherwise, there's a race condition as soon as
4944          * the kernel starts sending station notifications.
4945          */
4946
4947         if (!tb[NL80211_ATTR_STA_INFO]) {
4948                 wpa_printf(MSG_DEBUG, "sta stats missing!");
4949                 return NL_SKIP;
4950         }
4951         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
4952                              tb[NL80211_ATTR_STA_INFO],
4953                              stats_policy)) {
4954                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
4955                 return NL_SKIP;
4956         }
4957
4958         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
4959                 data->inactive_msec =
4960                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
4961         if (stats[NL80211_STA_INFO_RX_BYTES])
4962                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
4963         if (stats[NL80211_STA_INFO_TX_BYTES])
4964                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
4965         if (stats[NL80211_STA_INFO_RX_PACKETS])
4966                 data->rx_packets =
4967                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
4968         if (stats[NL80211_STA_INFO_TX_PACKETS])
4969                 data->tx_packets =
4970                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
4971
4972         return NL_SKIP;
4973 }
4974
4975 static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
4976                               const u8 *addr)
4977 {
4978         struct i802_bss *bss = priv;
4979         struct wpa_driver_nl80211_data *drv = bss->drv;
4980         struct nl_msg *msg;
4981
4982         os_memset(data, 0, sizeof(*data));
4983         msg = nlmsg_alloc();
4984         if (!msg)
4985                 return -ENOMEM;
4986
4987         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4988                     0, NL80211_CMD_GET_STATION, 0);
4989
4990         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4991         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
4992
4993         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
4994  nla_put_failure:
4995         return -ENOBUFS;
4996 }
4997
4998
4999 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
5000                                     int cw_min, int cw_max, int burst_time)
5001 {
5002         struct i802_bss *bss = priv;
5003         struct wpa_driver_nl80211_data *drv = bss->drv;
5004         struct nl_msg *msg;
5005         struct nlattr *txq, *params;
5006
5007         msg = nlmsg_alloc();
5008         if (!msg)
5009                 return -1;
5010
5011         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5012                     0, NL80211_CMD_SET_WIPHY, 0);
5013
5014         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5015
5016         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
5017         if (!txq)
5018                 goto nla_put_failure;
5019
5020         /* We are only sending parameters for a single TXQ at a time */
5021         params = nla_nest_start(msg, 1);
5022         if (!params)
5023                 goto nla_put_failure;
5024
5025         switch (queue) {
5026         case 0:
5027                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
5028                 break;
5029         case 1:
5030                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
5031                 break;
5032         case 2:
5033                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
5034                 break;
5035         case 3:
5036                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
5037                 break;
5038         }
5039         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
5040          * 32 usec, so need to convert the value here. */
5041         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
5042         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
5043         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
5044         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
5045
5046         nla_nest_end(msg, params);
5047
5048         nla_nest_end(msg, txq);
5049
5050         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
5051                 return 0;
5052  nla_put_failure:
5053         return -1;
5054 }
5055
5056
5057 static int i802_set_bss(void *priv, int cts, int preamble, int slot)
5058 {
5059         struct i802_bss *bss = priv;
5060         struct wpa_driver_nl80211_data *drv = bss->drv;
5061         struct nl_msg *msg;
5062
5063         msg = nlmsg_alloc();
5064         if (!msg)
5065                 return -ENOMEM;
5066
5067         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5068                     NL80211_CMD_SET_BSS, 0);
5069
5070         if (cts >= 0)
5071                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
5072         if (preamble >= 0)
5073                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
5074         if (slot >= 0)
5075                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
5076
5077         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5078
5079         return send_and_recv_msgs(drv, msg, NULL, NULL);
5080  nla_put_failure:
5081         return -ENOBUFS;
5082 }
5083
5084
5085 static int i802_set_cts_protect(void *priv, int value)
5086 {
5087         return i802_set_bss(priv, value, -1, -1);
5088 }
5089
5090
5091 static int i802_set_preamble(void *priv, int value)
5092 {
5093         return i802_set_bss(priv, -1, value, -1);
5094 }
5095
5096
5097 static int i802_set_short_slot_time(void *priv, int value)
5098 {
5099         return i802_set_bss(priv, -1, -1, value);
5100 }
5101
5102
5103 static int i802_set_sta_vlan(void *priv, const u8 *addr,
5104                              const char *ifname, int vlan_id)
5105 {
5106         struct i802_bss *bss = priv;
5107         struct wpa_driver_nl80211_data *drv = bss->drv;
5108         struct nl_msg *msg;
5109         int ret = -ENOBUFS;
5110
5111         msg = nlmsg_alloc();
5112         if (!msg)
5113                 return -ENOMEM;
5114
5115         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5116                     0, NL80211_CMD_SET_STATION, 0);
5117
5118         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5119                     if_nametoindex(bss->ifname));
5120         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5121         NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
5122                     if_nametoindex(ifname));
5123
5124         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5125         if (ret < 0) {
5126                 wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
5127                            MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
5128                            MAC2STR(addr), ifname, vlan_id, ret,
5129                            strerror(-ret));
5130         }
5131  nla_put_failure:
5132         return ret;
5133 }
5134
5135
5136 static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
5137                             const char *bridge_ifname)
5138 {
5139         struct i802_bss *bss = priv;
5140         struct wpa_driver_nl80211_data *drv = bss->drv;
5141         char name[IFNAMSIZ + 1];
5142
5143         os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
5144         wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
5145                    " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
5146         if (val) {
5147                 if (!if_nametoindex(name)) {
5148                         if (nl80211_create_iface(drv, name,
5149                                                  NL80211_IFTYPE_AP_VLAN,
5150                                                  NULL, 1) < 0)
5151                                 return -1;
5152                         if (bridge_ifname &&
5153                             linux_br_add_if(drv->ioctl_sock, bridge_ifname,
5154                                             name) < 0)
5155                                 return -1;
5156                 }
5157                 linux_set_iface_flags(drv->ioctl_sock, name, 1);
5158                 return i802_set_sta_vlan(priv, addr, name, 0);
5159         } else {
5160                 i802_set_sta_vlan(priv, addr, bss->ifname, 0);
5161                 return wpa_driver_nl80211_if_remove(priv, WPA_IF_AP_VLAN,
5162                                                     name);
5163         }
5164 }
5165
5166
5167 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
5168 {
5169         struct wpa_driver_nl80211_data *drv = eloop_ctx;
5170         struct sockaddr_ll lladdr;
5171         unsigned char buf[3000];
5172         int len;
5173         socklen_t fromlen = sizeof(lladdr);
5174
5175         len = recvfrom(sock, buf, sizeof(buf), 0,
5176                        (struct sockaddr *)&lladdr, &fromlen);
5177         if (len < 0) {
5178                 perror("recv");
5179                 return;
5180         }
5181
5182         if (have_ifidx(drv, lladdr.sll_ifindex))
5183                 drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
5184 }
5185
5186
5187 static int i802_get_inact_sec(void *priv, const u8 *addr)
5188 {
5189         struct hostap_sta_driver_data data;
5190         int ret;
5191
5192         data.inactive_msec = (unsigned long) -1;
5193         ret = i802_read_sta_data(priv, &data, addr);
5194         if (ret || data.inactive_msec == (unsigned long) -1)
5195                 return -1;
5196         return data.inactive_msec / 1000;
5197 }
5198
5199
5200 static int i802_sta_clear_stats(void *priv, const u8 *addr)
5201 {
5202 #if 0
5203         /* TODO */
5204 #endif
5205         return 0;
5206 }
5207
5208
5209 static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
5210                            int reason)
5211 {
5212         struct i802_bss *bss = priv;
5213         struct ieee80211_mgmt mgmt;
5214
5215         memset(&mgmt, 0, sizeof(mgmt));
5216         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
5217                                           WLAN_FC_STYPE_DEAUTH);
5218         memcpy(mgmt.da, addr, ETH_ALEN);
5219         memcpy(mgmt.sa, own_addr, ETH_ALEN);
5220         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
5221         mgmt.u.deauth.reason_code = host_to_le16(reason);
5222         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
5223                                             IEEE80211_HDRLEN +
5224                                             sizeof(mgmt.u.deauth));
5225 }
5226
5227
5228 static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
5229                              int reason)
5230 {
5231         struct i802_bss *bss = priv;
5232         struct ieee80211_mgmt mgmt;
5233
5234         memset(&mgmt, 0, sizeof(mgmt));
5235         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
5236                                           WLAN_FC_STYPE_DISASSOC);
5237         memcpy(mgmt.da, addr, ETH_ALEN);
5238         memcpy(mgmt.sa, own_addr, ETH_ALEN);
5239         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
5240         mgmt.u.disassoc.reason_code = host_to_le16(reason);
5241         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
5242                                             IEEE80211_HDRLEN +
5243                                             sizeof(mgmt.u.disassoc));
5244 }
5245
5246
5247 static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
5248                              const char *brname, const char *ifname)
5249 {
5250         int ifindex;
5251         char in_br[IFNAMSIZ];
5252
5253         os_strlcpy(drv->brname, brname, IFNAMSIZ);
5254         ifindex = if_nametoindex(brname);
5255         if (ifindex == 0) {
5256                 /*
5257                  * Bridge was configured, but the bridge device does
5258                  * not exist. Try to add it now.
5259                  */
5260                 if (linux_br_add(drv->ioctl_sock, brname) < 0) {
5261                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
5262                                    "bridge interface %s: %s",
5263                                    brname, strerror(errno));
5264                         return -1;
5265                 }
5266                 drv->added_bridge = 1;
5267                 add_ifidx(drv, if_nametoindex(brname));
5268         }
5269
5270         if (linux_br_get(in_br, ifname) == 0) {
5271                 if (os_strcmp(in_br, brname) == 0)
5272                         return 0; /* already in the bridge */
5273
5274                 wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
5275                            "bridge %s", ifname, in_br);
5276                 if (linux_br_del_if(drv->ioctl_sock, in_br, ifname) < 0) {
5277                         wpa_printf(MSG_ERROR, "nl80211: Failed to "
5278                                    "remove interface %s from bridge "
5279                                    "%s: %s",
5280                                    ifname, brname, strerror(errno));
5281                         return -1;
5282                 }
5283         }
5284
5285         wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
5286                    ifname, brname);
5287         if (linux_br_add_if(drv->ioctl_sock, brname, ifname) < 0) {
5288                 wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
5289                            "into bridge %s: %s",
5290                            ifname, brname, strerror(errno));
5291                 return -1;
5292         }
5293         drv->added_if_into_bridge = 1;
5294
5295         return 0;
5296 }
5297
5298
5299 static void *i802_init(struct hostapd_data *hapd,
5300                        struct wpa_init_params *params)
5301 {
5302         struct wpa_driver_nl80211_data *drv;
5303         struct i802_bss *bss;
5304         size_t i;
5305         char brname[IFNAMSIZ];
5306         int ifindex, br_ifindex;
5307         int br_added = 0;
5308
5309         bss = wpa_driver_nl80211_init(hapd, params->ifname);
5310         if (bss == NULL)
5311                 return NULL;
5312
5313         drv = bss->drv;
5314         if (linux_br_get(brname, params->ifname) == 0) {
5315                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
5316                            params->ifname, brname);
5317                 br_ifindex = if_nametoindex(brname);
5318         } else {
5319                 brname[0] = '\0';
5320                 br_ifindex = 0;
5321         }
5322
5323         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
5324         drv->if_indices = drv->default_if_indices;
5325         for (i = 0; i < params->num_bridge; i++) {
5326                 if (params->bridge[i]) {
5327                         ifindex = if_nametoindex(params->bridge[i]);
5328                         if (ifindex)
5329                                 add_ifidx(drv, ifindex);
5330                         if (ifindex == br_ifindex)
5331                                 br_added = 1;
5332                 }
5333         }
5334         if (!br_added && br_ifindex &&
5335             (params->num_bridge == 0 || !params->bridge[0]))
5336                 add_ifidx(drv, br_ifindex);
5337
5338         /* start listening for EAPOL on the default AP interface */
5339         add_ifidx(drv, drv->ifindex);
5340
5341         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 0))
5342                 goto failed;
5343
5344         if (params->bssid) {
5345                 if (linux_set_ifhwaddr(drv->ioctl_sock, bss->ifname,
5346                                        params->bssid))
5347                         goto failed;
5348         }
5349
5350         if (wpa_driver_nl80211_set_mode(bss, IEEE80211_MODE_AP)) {
5351                 wpa_printf(MSG_ERROR, "nl80211: Failed to set interface %s "
5352                            "into AP mode", bss->ifname);
5353                 goto failed;
5354         }
5355
5356         if (params->num_bridge && params->bridge[0] &&
5357             i802_check_bridge(drv, params->bridge[0], params->ifname) < 0)
5358                 goto failed;
5359
5360         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 1))
5361                 goto failed;
5362
5363         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
5364         if (drv->eapol_sock < 0) {
5365                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
5366                 goto failed;
5367         }
5368
5369         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
5370         {
5371                 printf("Could not register read socket for eapol\n");
5372                 goto failed;
5373         }
5374
5375         if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, params->own_addr))
5376                 goto failed;
5377
5378         return bss;
5379
5380 failed:
5381         nl80211_remove_monitor_interface(drv);
5382         if (drv->ioctl_sock >= 0)
5383                 close(drv->ioctl_sock);
5384
5385         genl_family_put(drv->nl80211);
5386         nl_cache_free(drv->nl_cache);
5387         nl80211_handle_destroy(drv->nl_handle);
5388         nl_cb_put(drv->nl_cb);
5389
5390         os_free(drv);
5391         return NULL;
5392 }
5393
5394
5395 static void i802_deinit(void *priv)
5396 {
5397         wpa_driver_nl80211_deinit(priv);
5398 }
5399
5400 #endif /* HOSTAPD */
5401
5402
5403 static enum nl80211_iftype wpa_driver_nl80211_if_type(
5404         enum wpa_driver_if_type type)
5405 {
5406         switch (type) {
5407         case WPA_IF_STATION:
5408         case WPA_IF_P2P_CLIENT:
5409         case WPA_IF_P2P_GROUP:
5410                 return NL80211_IFTYPE_STATION;
5411         case WPA_IF_AP_VLAN:
5412                 return NL80211_IFTYPE_AP_VLAN;
5413         case WPA_IF_AP_BSS:
5414         case WPA_IF_P2P_GO:
5415                 return NL80211_IFTYPE_AP;
5416         }
5417         return -1;
5418 }
5419
5420
5421 static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
5422                                      const char *ifname, const u8 *addr,
5423                                      void *bss_ctx, void **drv_priv,
5424                                      char *force_ifname, u8 *if_addr)
5425 {
5426         struct i802_bss *bss = priv;
5427         struct wpa_driver_nl80211_data *drv = bss->drv;
5428         int ifidx;
5429 #ifdef HOSTAPD
5430         struct i802_bss *new_bss = NULL;
5431
5432         if (type == WPA_IF_AP_BSS) {
5433                 new_bss = os_zalloc(sizeof(*new_bss));
5434                 if (new_bss == NULL)
5435                         return -1;
5436         }
5437 #endif /* HOSTAPD */
5438
5439         if (addr)
5440                 os_memcpy(if_addr, addr, ETH_ALEN);
5441         ifidx = nl80211_create_iface(drv, ifname,
5442                                      wpa_driver_nl80211_if_type(type), addr,
5443                                      0);
5444         if (ifidx < 0) {
5445 #ifdef HOSTAPD
5446                 os_free(new_bss);
5447 #endif /* HOSTAPD */
5448                 return -1;
5449         }
5450
5451         if (!addr &&
5452             linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, if_addr) < 0) {
5453                 nl80211_remove_iface(drv, ifidx);
5454                 return -1;
5455         }
5456
5457 #ifdef CONFIG_P2P
5458         if (!addr &&
5459             (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
5460              type == WPA_IF_P2P_GO)) {
5461                 /* Enforce unique P2P Interface Address */
5462                 u8 new_addr[ETH_ALEN], own_addr[ETH_ALEN];
5463
5464                 if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, own_addr)
5465                     < 0 ||
5466                     linux_get_ifhwaddr(drv->ioctl_sock, ifname, new_addr) < 0)
5467                 {
5468                         nl80211_remove_iface(drv, ifidx);
5469                         return -1;
5470                 }
5471                 if (os_memcmp(own_addr, new_addr, ETH_ALEN) == 0) {
5472                         wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
5473                                    "for P2P group interface");
5474                         /* TODO: more complete implementation to handle
5475                          * multiple groups etc.. */
5476                         if (own_addr[0] & 0x02) {
5477                                 nl80211_remove_iface(drv, ifidx);
5478                                 return -1;
5479                         }
5480                         new_addr[0] |= 0x02;
5481                         if (linux_set_ifhwaddr(drv->ioctl_sock, ifname,
5482                                                new_addr) < 0) {
5483                                 nl80211_remove_iface(drv, ifidx);
5484                                 return -1;
5485                         }
5486                         os_memcpy(if_addr, new_addr, ETH_ALEN);
5487                 }
5488         }
5489 #endif /* CONFIG_P2P */
5490
5491 #ifdef HOSTAPD
5492         if (type == WPA_IF_AP_BSS) {
5493                 if (linux_set_iface_flags(drv->ioctl_sock, ifname, 1)) {
5494                         nl80211_remove_iface(drv, ifidx);
5495                         os_free(new_bss);
5496                         return -1;
5497                 }
5498                 os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
5499                 new_bss->ifindex = ifidx;
5500                 new_bss->drv = drv;
5501                 new_bss->next = drv->first_bss.next;
5502                 drv->first_bss.next = new_bss;
5503                 if (drv_priv)
5504                         *drv_priv = new_bss;
5505         }
5506 #endif /* HOSTAPD */
5507
5508         return 0;
5509 }
5510
5511
5512 static int wpa_driver_nl80211_if_remove(void *priv,
5513                                         enum wpa_driver_if_type type,
5514                                         const char *ifname)
5515 {
5516         struct i802_bss *bss = priv;
5517         struct wpa_driver_nl80211_data *drv = bss->drv;
5518         int ifindex = if_nametoindex(ifname);
5519
5520         wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d",
5521                    __func__, type, ifname, ifindex);
5522         if (ifindex <= 0)
5523                 return -1;
5524         nl80211_remove_iface(drv, ifindex);
5525
5526 #ifdef HOSTAPD
5527         if (type != WPA_IF_AP_BSS)
5528                 return 0;
5529
5530         if (bss != &drv->first_bss) {
5531                 struct i802_bss *tbss = &drv->first_bss;
5532
5533                 while (tbss) {
5534                         if (tbss->next != bss)
5535                                 continue;
5536
5537                         tbss->next = bss->next;
5538                         os_free(bss);
5539                         break;
5540                 }
5541         }
5542 #endif /* HOSTAPD */
5543
5544         return 0;
5545 }
5546
5547
5548 static int cookie_handler(struct nl_msg *msg, void *arg)
5549 {
5550         struct nlattr *tb[NL80211_ATTR_MAX + 1];
5551         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5552         u64 *cookie = arg;
5553         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5554                   genlmsg_attrlen(gnlh, 0), NULL);
5555         if (tb[NL80211_ATTR_COOKIE])
5556                 *cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
5557         return NL_SKIP;
5558 }
5559
5560
5561 static int nl80211_send_frame_cmd(struct wpa_driver_nl80211_data *drv,
5562                                   unsigned int freq, const u8 *buf,
5563                                   size_t buf_len, u64 *cookie_out)
5564 {
5565         struct nl_msg *msg;
5566         u64 cookie;
5567         int ret = -1;
5568
5569         msg = nlmsg_alloc();
5570         if (!msg)
5571                 return -1;
5572
5573         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5574                     NL80211_CMD_FRAME, 0);
5575
5576         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5577         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
5578         NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
5579
5580         cookie = 0;
5581         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
5582         msg = NULL;
5583         if (ret) {
5584                 wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
5585                            "(%s)", ret, strerror(-ret));
5586                 goto nla_put_failure;
5587         }
5588         wpa_printf(MSG_DEBUG, "nl80211: Frame TX command accepted; "
5589                    "cookie 0x%llx", (long long unsigned int) cookie);
5590
5591         if (cookie_out)
5592                 *cookie_out = cookie;
5593
5594 nla_put_failure:
5595         nlmsg_free(msg);
5596         return ret;
5597 }
5598
5599
5600 static int wpa_driver_nl80211_send_action(void *priv, unsigned int freq,
5601                                           const u8 *dst, const u8 *src,
5602                                           const u8 *bssid,
5603                                           const u8 *data, size_t data_len)
5604 {
5605         struct i802_bss *bss = priv;
5606         struct wpa_driver_nl80211_data *drv = bss->drv;
5607         int ret = -1;
5608         u8 *buf;
5609         struct ieee80211_hdr *hdr;
5610
5611         wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d)",
5612                    drv->ifindex);
5613
5614         buf = os_zalloc(24 + data_len);
5615         if (buf == NULL)
5616                 return ret;
5617         os_memcpy(buf + 24, data, data_len);
5618         hdr = (struct ieee80211_hdr *) buf;
5619         hdr->frame_control =
5620                 IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
5621         os_memcpy(hdr->addr1, dst, ETH_ALEN);
5622         os_memcpy(hdr->addr2, src, ETH_ALEN);
5623         os_memcpy(hdr->addr3, bssid, ETH_ALEN);
5624
5625         if (drv->nlmode == NL80211_IFTYPE_AP)
5626                 ret = wpa_driver_nl80211_send_mlme(priv, buf, 24 + data_len);
5627         else
5628                 ret = nl80211_send_frame_cmd(drv, freq, buf, 24 + data_len,
5629                                              &drv->send_action_cookie);
5630
5631         os_free(buf);
5632         return ret;
5633 }
5634
5635
5636 static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
5637                                                 unsigned int duration)
5638 {
5639         struct i802_bss *bss = priv;
5640         struct wpa_driver_nl80211_data *drv = bss->drv;
5641         struct nl_msg *msg;
5642         int ret;
5643         u64 cookie;
5644
5645         msg = nlmsg_alloc();
5646         if (!msg)
5647                 return -1;
5648
5649         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5650                     NL80211_CMD_REMAIN_ON_CHANNEL, 0);
5651
5652         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5653         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
5654         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
5655
5656         cookie = 0;
5657         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
5658         if (ret == 0) {
5659                 wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
5660                            "0x%llx for freq=%u MHz duration=%u",
5661                            (long long unsigned int) cookie, freq, duration);
5662                 drv->remain_on_chan_cookie = cookie;
5663                 return 0;
5664         }
5665         wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
5666                    "(freq=%d duration=%u): %d (%s)",
5667                    freq, duration, ret, strerror(-ret));
5668 nla_put_failure:
5669         return -1;
5670 }
5671
5672
5673 static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
5674 {
5675         struct i802_bss *bss = priv;
5676         struct wpa_driver_nl80211_data *drv = bss->drv;
5677         struct nl_msg *msg;
5678         int ret;
5679
5680         if (!drv->pending_remain_on_chan) {
5681                 wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
5682                            "to cancel");
5683                 return -1;
5684         }
5685
5686         wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
5687                    "0x%llx",
5688                    (long long unsigned int) drv->remain_on_chan_cookie);
5689
5690         msg = nlmsg_alloc();
5691         if (!msg)
5692                 return -1;
5693
5694         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5695                     NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL, 0);
5696
5697         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5698         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
5699
5700         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5701         if (ret == 0)
5702                 return 0;
5703         wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
5704                    "%d (%s)", ret, strerror(-ret));
5705 nla_put_failure:
5706         return -1;
5707 }
5708
5709
5710 static int wpa_driver_nl80211_probe_req_report(void *priv, int report)
5711 {
5712         struct i802_bss *bss = priv;
5713         struct wpa_driver_nl80211_data *drv = bss->drv;
5714
5715         if (drv->nlmode != NL80211_IFTYPE_STATION) {
5716                 wpa_printf(MSG_DEBUG, "nl80211: probe_req_report control only "
5717                            "allowed in station mode (iftype=%d)",
5718                            drv->nlmode);
5719                 return -1;
5720         }
5721
5722         if (!report) {
5723                 if (drv->nl_handle_preq) {
5724                         eloop_unregister_read_sock(
5725                                 nl_socket_get_fd(drv->nl_handle_preq));
5726                         nl_cache_free(drv->nl_cache_preq);
5727                         nl80211_handle_destroy(drv->nl_handle_preq);
5728                         drv->nl_handle_preq = NULL;
5729                 }
5730                 return 0;
5731         }
5732
5733         if (drv->nl_handle_preq) {
5734                 wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
5735                            "already on!");
5736                 return 0;
5737         }
5738
5739         drv->nl_handle_preq = nl80211_handle_alloc(drv->nl_cb);
5740         if (drv->nl_handle_preq == NULL) {
5741                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate "
5742                            "netlink callbacks (preq)");
5743                 goto out_err1;
5744         }
5745
5746         if (genl_connect(drv->nl_handle_preq)) {
5747                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to "
5748                            "generic netlink (preq)");
5749                 goto out_err2;
5750                 return -1;
5751         }
5752
5753 #ifdef CONFIG_LIBNL20
5754         if (genl_ctrl_alloc_cache(drv->nl_handle_preq,
5755                                   &drv->nl_cache_preq) < 0) {
5756                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
5757                            "netlink cache (preq)");
5758                 goto out_err2;
5759         }
5760 #else /* CONFIG_LIBNL20 */
5761         drv->nl_cache_preq = genl_ctrl_alloc_cache(drv->nl_handle_preq);
5762         if (drv->nl_cache_preq == NULL) {
5763                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
5764                            "netlink cache (preq)");
5765                 goto out_err2;
5766         }
5767 #endif /* CONFIG_LIBNL20 */
5768
5769         if (nl80211_register_frame(drv, drv->nl_handle_preq,
5770                                    (WLAN_FC_TYPE_MGMT << 2) |
5771                                    (WLAN_FC_STYPE_PROBE_REQ << 4),
5772                                    NULL, 0) < 0) {
5773                 goto out_err3;
5774         }
5775
5776         eloop_register_read_sock(nl_socket_get_fd(drv->nl_handle_preq),
5777                                  wpa_driver_nl80211_event_receive, drv,
5778                                  drv->nl_handle_preq);
5779
5780         return 0;
5781
5782  out_err3:
5783         nl_cache_free(drv->nl_cache_preq);
5784  out_err2:
5785         nl80211_handle_destroy(drv->nl_handle_preq);
5786         drv->nl_handle_preq = NULL;
5787  out_err1:
5788         return -1;
5789 }
5790
5791
5792 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
5793                                      int ifindex, int disabled)
5794 {
5795         struct nl_msg *msg;
5796         struct nlattr *bands, *band;
5797         int ret;
5798
5799         msg = nlmsg_alloc();
5800         if (!msg)
5801                 return -1;
5802
5803         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5804                     NL80211_CMD_SET_TX_BITRATE_MASK, 0);
5805         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
5806
5807         bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
5808         if (!bands)
5809                 goto nla_put_failure;
5810
5811         /*
5812          * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
5813          * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
5814          * rates. All 5 GHz rates are left enabled.
5815          */
5816         band = nla_nest_start(msg, NL80211_BAND_2GHZ);
5817         if (!band)
5818                 goto nla_put_failure;
5819         NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
5820                 "\x0c\x12\x18\x24\x30\x48\x60\x6c");
5821         nla_nest_end(msg, band);
5822
5823         nla_nest_end(msg, bands);
5824
5825         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5826         msg = NULL;
5827         if (ret) {
5828                 wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
5829                            "(%s)", ret, strerror(-ret));
5830         }
5831
5832         return ret;
5833
5834 nla_put_failure:
5835         nlmsg_free(msg);
5836         return -1;
5837 }
5838
5839
5840 static int wpa_driver_nl80211_disable_11b_rates(void *priv, int disabled)
5841 {
5842         struct i802_bss *bss = priv;
5843         struct wpa_driver_nl80211_data *drv = bss->drv;
5844         drv->disable_11b_rates = disabled;
5845         return nl80211_disable_11b_rates(drv, drv->ifindex, disabled);
5846 }
5847
5848
5849 static int wpa_driver_nl80211_deinit_ap(void *priv)
5850 {
5851         struct i802_bss *bss = priv;
5852         struct wpa_driver_nl80211_data *drv = bss->drv;
5853         if (drv->nlmode != NL80211_IFTYPE_AP)
5854                 return -1;
5855         wpa_driver_nl80211_del_beacon(drv);
5856         return wpa_driver_nl80211_set_mode(priv, IEEE80211_MODE_INFRA);
5857 }
5858
5859
5860 static void wpa_driver_nl80211_resume(void *priv)
5861 {
5862         struct i802_bss *bss = priv;
5863         struct wpa_driver_nl80211_data *drv = bss->drv;
5864         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 1)) {
5865                 wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on "
5866                            "resume event");
5867         }
5868 }
5869
5870
5871 static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
5872                                   const u8 *ies, size_t ies_len)
5873 {
5874         struct i802_bss *bss = priv;
5875         struct wpa_driver_nl80211_data *drv = bss->drv;
5876         int ret;
5877         u8 *data, *pos;
5878         size_t data_len;
5879         u8 own_addr[ETH_ALEN];
5880
5881         if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, own_addr) < 0)
5882                 return -1;
5883
5884         if (action != 1) {
5885                 wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
5886                            "action %d", action);
5887                 return -1;
5888         }
5889
5890         /*
5891          * Action frame payload:
5892          * Category[1] = 6 (Fast BSS Transition)
5893          * Action[1] = 1 (Fast BSS Transition Request)
5894          * STA Address
5895          * Target AP Address
5896          * FT IEs
5897          */
5898
5899         data_len = 2 + 2 * ETH_ALEN + ies_len;
5900         data = os_malloc(data_len);
5901         if (data == NULL)
5902                 return -1;
5903         pos = data;
5904         *pos++ = 0x06; /* FT Action category */
5905         *pos++ = action;
5906         os_memcpy(pos, own_addr, ETH_ALEN);
5907         pos += ETH_ALEN;
5908         os_memcpy(pos, target_ap, ETH_ALEN);
5909         pos += ETH_ALEN;
5910         os_memcpy(pos, ies, ies_len);
5911
5912         ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, drv->bssid,
5913                                              own_addr, drv->bssid,
5914                                              data, data_len);
5915         os_free(data);
5916
5917         return ret;
5918 }
5919
5920
5921 static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
5922 {
5923         struct i802_bss *bss = priv;
5924         struct wpa_driver_nl80211_data *drv = bss->drv;
5925         struct nl_msg *msg, *cqm = NULL;
5926
5927         wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
5928                    "hysteresis=%d", threshold, hysteresis);
5929
5930         msg = nlmsg_alloc();
5931         if (!msg)
5932                 return -1;
5933
5934         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5935                     0, NL80211_CMD_SET_CQM, 0);
5936
5937         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
5938
5939         cqm = nlmsg_alloc();
5940         if (cqm == NULL)
5941                 return -1;
5942
5943         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
5944         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
5945         nla_put_nested(msg, NL80211_ATTR_CQM, cqm);
5946
5947         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
5948                 return 0;
5949         msg = NULL;
5950
5951 nla_put_failure:
5952         if (cqm)
5953                 nlmsg_free(cqm);
5954         nlmsg_free(msg);
5955         return -1;
5956 }
5957
5958
5959 static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
5960                               int encrypt)
5961 {
5962         struct i802_bss *bss = priv;
5963         struct wpa_driver_nl80211_data *drv = bss->drv;
5964         return wpa_driver_nl80211_send_frame(drv, data, data_len, encrypt);
5965 }
5966
5967
5968 static int nl80211_set_intra_bss(void *priv, int enabled)
5969 {
5970         struct i802_bss *bss = priv;
5971         struct wpa_driver_nl80211_data *drv = bss->drv;
5972         struct nl_msg *msg;
5973
5974         msg = nlmsg_alloc();
5975         if (!msg)
5976                 return -ENOMEM;
5977
5978         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5979                     NL80211_CMD_SET_BSS, 0);
5980
5981         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5982         NLA_PUT_U8(msg, NL80211_ATTR_AP_ISOLATE, !enabled);
5983
5984         return send_and_recv_msgs(drv, msg, NULL, NULL);
5985  nla_put_failure:
5986         return -ENOBUFS;
5987 }
5988
5989
5990 static int nl80211_set_param(void *priv, const char *param)
5991 {
5992         struct i802_bss *bss = priv;
5993         struct wpa_driver_nl80211_data *drv = bss->drv;
5994
5995         wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
5996         if (param == NULL)
5997                 return 0;
5998
5999 #ifdef CONFIG_P2P
6000         if (os_strstr(param, "use_p2p_group_interface=1")) {
6001                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
6002                            "interface");
6003                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
6004                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
6005         }
6006 #endif /* CONFIG_P2P */
6007
6008         return 0;
6009 }
6010
6011
6012 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
6013         .name = "nl80211",
6014         .desc = "Linux nl80211/cfg80211",
6015         .get_bssid = wpa_driver_nl80211_get_bssid,
6016         .get_ssid = wpa_driver_nl80211_get_ssid,
6017         .set_key = wpa_driver_nl80211_set_key,
6018         .scan2 = wpa_driver_nl80211_scan,
6019         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
6020         .deauthenticate = wpa_driver_nl80211_deauthenticate,
6021         .disassociate = wpa_driver_nl80211_disassociate,
6022         .authenticate = wpa_driver_nl80211_authenticate,
6023         .associate = wpa_driver_nl80211_associate,
6024         .init = wpa_driver_nl80211_init,
6025         .deinit = wpa_driver_nl80211_deinit,
6026         .get_capa = wpa_driver_nl80211_get_capa,
6027         .set_operstate = wpa_driver_nl80211_set_operstate,
6028         .set_supp_port = wpa_driver_nl80211_set_supp_port,
6029         .set_country = wpa_driver_nl80211_set_country,
6030         .set_beacon = wpa_driver_nl80211_set_beacon,
6031         .if_add = wpa_driver_nl80211_if_add,
6032         .if_remove = wpa_driver_nl80211_if_remove,
6033         .send_mlme = wpa_driver_nl80211_send_mlme,
6034         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
6035         .sta_add = wpa_driver_nl80211_sta_add,
6036         .sta_remove = wpa_driver_nl80211_sta_remove,
6037         .hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
6038         .sta_set_flags = wpa_driver_nl80211_sta_set_flags,
6039 #ifdef HOSTAPD
6040         .hapd_init = i802_init,
6041         .hapd_deinit = i802_deinit,
6042         .get_seqnum = i802_get_seqnum,
6043         .flush = i802_flush,
6044         .read_sta_data = i802_read_sta_data,
6045         .sta_deauth = i802_sta_deauth,
6046         .sta_disassoc = i802_sta_disassoc,
6047         .get_inact_sec = i802_get_inact_sec,
6048         .sta_clear_stats = i802_sta_clear_stats,
6049         .set_rts = i802_set_rts,
6050         .set_frag = i802_set_frag,
6051         .set_rate_sets = i802_set_rate_sets,
6052         .set_cts_protect = i802_set_cts_protect,
6053         .set_preamble = i802_set_preamble,
6054         .set_short_slot_time = i802_set_short_slot_time,
6055         .set_tx_queue_params = i802_set_tx_queue_params,
6056         .set_sta_vlan = i802_set_sta_vlan,
6057         .set_wds_sta = i802_set_wds_sta,
6058 #endif /* HOSTAPD */
6059         .set_freq = i802_set_freq,
6060         .send_action = wpa_driver_nl80211_send_action,
6061         .remain_on_channel = wpa_driver_nl80211_remain_on_channel,
6062         .cancel_remain_on_channel =
6063         wpa_driver_nl80211_cancel_remain_on_channel,
6064         .probe_req_report = wpa_driver_nl80211_probe_req_report,
6065         .disable_11b_rates = wpa_driver_nl80211_disable_11b_rates,
6066         .deinit_ap = wpa_driver_nl80211_deinit_ap,
6067         .resume = wpa_driver_nl80211_resume,
6068         .send_ft_action = nl80211_send_ft_action,
6069         .signal_monitor = nl80211_signal_monitor,
6070         .send_frame = nl80211_send_frame,
6071         .set_intra_bss = nl80211_set_intra_bss,
6072         .set_param = nl80211_set_param,
6073 };