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