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