nl80211: Implement set_rate_sets for non-hostapd AP case
[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         size_t i;
2419
2420         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2421                   genlmsg_attrlen(gnlh, 0), NULL);
2422         if (!tb[NL80211_ATTR_BSS])
2423                 return NL_SKIP;
2424         if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
2425                              bss_policy))
2426                 return NL_SKIP;
2427         if (bss[NL80211_BSS_STATUS]) {
2428                 enum nl80211_bss_status status;
2429                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
2430                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
2431                     bss[NL80211_BSS_FREQUENCY]) {
2432                         _arg->assoc_freq =
2433                                 nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
2434                         wpa_printf(MSG_DEBUG, "nl80211: Associated on %u MHz",
2435                                    _arg->assoc_freq);
2436                 }
2437         }
2438         if (!res)
2439                 return NL_SKIP;
2440         if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
2441                 ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2442                 ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
2443         } else {
2444                 ie = NULL;
2445                 ie_len = 0;
2446         }
2447         if (bss[NL80211_BSS_BEACON_IES]) {
2448                 beacon_ie = nla_data(bss[NL80211_BSS_BEACON_IES]);
2449                 beacon_ie_len = nla_len(bss[NL80211_BSS_BEACON_IES]);
2450         } else {
2451                 beacon_ie = NULL;
2452                 beacon_ie_len = 0;
2453         }
2454
2455         if (nl80211_scan_filtered(_arg->drv, ie ? ie : beacon_ie,
2456                                   ie ? ie_len : beacon_ie_len))
2457                 return NL_SKIP;
2458
2459         r = os_zalloc(sizeof(*r) + ie_len + beacon_ie_len);
2460         if (r == NULL)
2461                 return NL_SKIP;
2462         if (bss[NL80211_BSS_BSSID])
2463                 os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
2464                           ETH_ALEN);
2465         if (bss[NL80211_BSS_FREQUENCY])
2466                 r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
2467         if (bss[NL80211_BSS_BEACON_INTERVAL])
2468                 r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
2469         if (bss[NL80211_BSS_CAPABILITY])
2470                 r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
2471         r->flags |= WPA_SCAN_NOISE_INVALID;
2472         if (bss[NL80211_BSS_SIGNAL_MBM]) {
2473                 r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
2474                 r->level /= 100; /* mBm to dBm */
2475                 r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
2476         } else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
2477                 r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
2478                 r->flags |= WPA_SCAN_LEVEL_INVALID;
2479         } else
2480                 r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
2481         if (bss[NL80211_BSS_TSF])
2482                 r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
2483         if (bss[NL80211_BSS_SEEN_MS_AGO])
2484                 r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
2485         r->ie_len = ie_len;
2486         pos = (u8 *) (r + 1);
2487         if (ie) {
2488                 os_memcpy(pos, ie, ie_len);
2489                 pos += ie_len;
2490         }
2491         r->beacon_ie_len = beacon_ie_len;
2492         if (beacon_ie)
2493                 os_memcpy(pos, beacon_ie, beacon_ie_len);
2494
2495         if (bss[NL80211_BSS_STATUS]) {
2496                 enum nl80211_bss_status status;
2497                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
2498                 switch (status) {
2499                 case NL80211_BSS_STATUS_AUTHENTICATED:
2500                         r->flags |= WPA_SCAN_AUTHENTICATED;
2501                         break;
2502                 case NL80211_BSS_STATUS_ASSOCIATED:
2503                         r->flags |= WPA_SCAN_ASSOCIATED;
2504                         break;
2505                 default:
2506                         break;
2507                 }
2508         }
2509
2510         /*
2511          * cfg80211 maintains separate BSS table entries for APs if the same
2512          * BSSID,SSID pair is seen on multiple channels. wpa_supplicant does
2513          * not use frequency as a separate key in the BSS table, so filter out
2514          * duplicated entries. Prefer associated BSS entry in such a case in
2515          * order to get the correct frequency into the BSS table.
2516          */
2517         for (i = 0; i < res->num; i++) {
2518                 const u8 *s1, *s2;
2519                 if (os_memcmp(res->res[i]->bssid, r->bssid, ETH_ALEN) != 0)
2520                         continue;
2521
2522                 s1 = nl80211_get_ie((u8 *) (res->res[i] + 1),
2523                                     res->res[i]->ie_len, WLAN_EID_SSID);
2524                 s2 = nl80211_get_ie((u8 *) (r + 1), r->ie_len, WLAN_EID_SSID);
2525                 if (s1 == NULL || s2 == NULL || s1[1] != s2[1] ||
2526                     os_memcmp(s1, s2, 2 + s1[1]) != 0)
2527                         continue;
2528
2529                 /* Same BSSID,SSID was already included in scan results */
2530                 wpa_printf(MSG_DEBUG, "nl80211: Remove duplicated scan result "
2531                            "for " MACSTR, MAC2STR(r->bssid));
2532
2533                 if ((r->flags & WPA_SCAN_ASSOCIATED) &&
2534                     !(res->res[i]->flags & WPA_SCAN_ASSOCIATED)) {
2535                         os_free(res->res[i]);
2536                         res->res[i] = r;
2537                 } else
2538                         os_free(r);
2539                 return NL_SKIP;
2540         }
2541
2542         tmp = os_realloc(res->res,
2543                          (res->num + 1) * sizeof(struct wpa_scan_res *));
2544         if (tmp == NULL) {
2545                 os_free(r);
2546                 return NL_SKIP;
2547         }
2548         tmp[res->num++] = r;
2549         res->res = tmp;
2550
2551         return NL_SKIP;
2552 }
2553
2554
2555 static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
2556                                  const u8 *addr)
2557 {
2558         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
2559                 wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
2560                            "mismatch (" MACSTR ")", MAC2STR(addr));
2561                 wpa_driver_nl80211_mlme(drv, addr,
2562                                         NL80211_CMD_DEAUTHENTICATE,
2563                                         WLAN_REASON_PREV_AUTH_NOT_VALID, 1);
2564         }
2565 }
2566
2567
2568 static void wpa_driver_nl80211_check_bss_status(
2569         struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
2570 {
2571         size_t i;
2572
2573         for (i = 0; i < res->num; i++) {
2574                 struct wpa_scan_res *r = res->res[i];
2575                 if (r->flags & WPA_SCAN_AUTHENTICATED) {
2576                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
2577                                    "indicates BSS status with " MACSTR
2578                                    " as authenticated",
2579                                    MAC2STR(r->bssid));
2580                         if (drv->nlmode == NL80211_IFTYPE_STATION &&
2581                             os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
2582                             os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
2583                             0) {
2584                                 wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
2585                                            " in local state (auth=" MACSTR
2586                                            " assoc=" MACSTR ")",
2587                                            MAC2STR(drv->auth_bssid),
2588                                            MAC2STR(drv->bssid));
2589                                 clear_state_mismatch(drv, r->bssid);
2590                         }
2591                 }
2592
2593                 if (r->flags & WPA_SCAN_ASSOCIATED) {
2594                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
2595                                    "indicate BSS status with " MACSTR
2596                                    " as associated",
2597                                    MAC2STR(r->bssid));
2598                         if (drv->nlmode == NL80211_IFTYPE_STATION &&
2599                             !drv->associated) {
2600                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
2601                                            "(not associated) does not match "
2602                                            "with BSS state");
2603                                 clear_state_mismatch(drv, r->bssid);
2604                         } else if (drv->nlmode == NL80211_IFTYPE_STATION &&
2605                                    os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
2606                                    0) {
2607                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
2608                                            "(associated with " MACSTR ") does "
2609                                            "not match with BSS state",
2610                                            MAC2STR(drv->bssid));
2611                                 clear_state_mismatch(drv, r->bssid);
2612                                 clear_state_mismatch(drv, drv->bssid);
2613                         }
2614                 }
2615         }
2616 }
2617
2618
2619 static void wpa_scan_results_free(struct wpa_scan_results *res)
2620 {
2621         size_t i;
2622
2623         if (res == NULL)
2624                 return;
2625
2626         for (i = 0; i < res->num; i++)
2627                 os_free(res->res[i]);
2628         os_free(res->res);
2629         os_free(res);
2630 }
2631
2632
2633 static struct wpa_scan_results *
2634 nl80211_get_scan_results(struct wpa_driver_nl80211_data *drv)
2635 {
2636         struct nl_msg *msg;
2637         struct wpa_scan_results *res;
2638         int ret;
2639         struct nl80211_bss_info_arg arg;
2640
2641         res = os_zalloc(sizeof(*res));
2642         if (res == NULL)
2643                 return NULL;
2644         msg = nlmsg_alloc();
2645         if (!msg)
2646                 goto nla_put_failure;
2647
2648         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, NLM_F_DUMP,
2649                     NL80211_CMD_GET_SCAN, 0);
2650         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2651
2652         arg.drv = drv;
2653         arg.res = res;
2654         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
2655         msg = NULL;
2656         if (ret == 0) {
2657                 wpa_printf(MSG_DEBUG, "Received scan results (%lu BSSes)",
2658                            (unsigned long) res->num);
2659                 return res;
2660         }
2661         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
2662                    "(%s)", ret, strerror(-ret));
2663 nla_put_failure:
2664         nlmsg_free(msg);
2665         wpa_scan_results_free(res);
2666         return NULL;
2667 }
2668
2669
2670 /**
2671  * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
2672  * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
2673  * Returns: Scan results on success, -1 on failure
2674  */
2675 static struct wpa_scan_results *
2676 wpa_driver_nl80211_get_scan_results(void *priv)
2677 {
2678         struct i802_bss *bss = priv;
2679         struct wpa_driver_nl80211_data *drv = bss->drv;
2680         struct wpa_scan_results *res;
2681
2682         res = nl80211_get_scan_results(drv);
2683         if (res)
2684                 wpa_driver_nl80211_check_bss_status(drv, res);
2685         return res;
2686 }
2687
2688
2689 static void nl80211_dump_scan(struct wpa_driver_nl80211_data *drv)
2690 {
2691         struct wpa_scan_results *res;
2692         size_t i;
2693
2694         res = nl80211_get_scan_results(drv);
2695         if (res == NULL) {
2696                 wpa_printf(MSG_DEBUG, "nl80211: Failed to get scan results");
2697                 return;
2698         }
2699
2700         wpa_printf(MSG_DEBUG, "nl80211: Scan result dump");
2701         for (i = 0; i < res->num; i++) {
2702                 struct wpa_scan_res *r = res->res[i];
2703                 wpa_printf(MSG_DEBUG, "nl80211: %d/%d " MACSTR "%s%s",
2704                            (int) i, (int) res->num, MAC2STR(r->bssid),
2705                            r->flags & WPA_SCAN_AUTHENTICATED ? " [auth]" : "",
2706                            r->flags & WPA_SCAN_ASSOCIATED ? " [assoc]" : "");
2707         }
2708
2709         wpa_scan_results_free(res);
2710 }
2711
2712
2713 static int wpa_driver_nl80211_set_key(const char *ifname, void *priv,
2714                                       enum wpa_alg alg, const u8 *addr,
2715                                       int key_idx, int set_tx,
2716                                       const u8 *seq, size_t seq_len,
2717                                       const u8 *key, size_t key_len)
2718 {
2719         struct i802_bss *bss = priv;
2720         struct wpa_driver_nl80211_data *drv = bss->drv;
2721         int ifindex = if_nametoindex(ifname);
2722         struct nl_msg *msg;
2723         int ret;
2724
2725         wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
2726                    "set_tx=%d seq_len=%lu key_len=%lu",
2727                    __func__, ifindex, alg, addr, key_idx, set_tx,
2728                    (unsigned long) seq_len, (unsigned long) key_len);
2729
2730         msg = nlmsg_alloc();
2731         if (!msg)
2732                 return -ENOMEM;
2733
2734         if (alg == WPA_ALG_NONE) {
2735                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2736                             0, NL80211_CMD_DEL_KEY, 0);
2737         } else {
2738                 genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2739                             0, NL80211_CMD_NEW_KEY, 0);
2740                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
2741                 switch (alg) {
2742                 case WPA_ALG_WEP:
2743                         if (key_len == 5)
2744                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2745                                             WLAN_CIPHER_SUITE_WEP40);
2746                         else
2747                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2748                                             WLAN_CIPHER_SUITE_WEP104);
2749                         break;
2750                 case WPA_ALG_TKIP:
2751                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2752                                     WLAN_CIPHER_SUITE_TKIP);
2753                         break;
2754                 case WPA_ALG_CCMP:
2755                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2756                                     WLAN_CIPHER_SUITE_CCMP);
2757                         break;
2758                 case WPA_ALG_IGTK:
2759                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
2760                                     WLAN_CIPHER_SUITE_AES_CMAC);
2761                         break;
2762                 default:
2763                         wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
2764                                    "algorithm %d", __func__, alg);
2765                         nlmsg_free(msg);
2766                         return -1;
2767                 }
2768         }
2769
2770         if (seq && seq_len)
2771                 NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
2772
2773         if (addr && !is_broadcast_ether_addr(addr)) {
2774                 wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
2775                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
2776
2777                 if (alg != WPA_ALG_WEP && key_idx && !set_tx) {
2778                         wpa_printf(MSG_DEBUG, "   RSN IBSS RX GTK");
2779                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_TYPE,
2780                                     NL80211_KEYTYPE_GROUP);
2781                 }
2782         } else if (addr && is_broadcast_ether_addr(addr)) {
2783                 struct nl_msg *types;
2784                 int err;
2785                 wpa_printf(MSG_DEBUG, "   broadcast key");
2786                 types = nlmsg_alloc();
2787                 if (!types)
2788                         goto nla_put_failure;
2789                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
2790                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
2791                                      types);
2792                 nlmsg_free(types);
2793                 if (err)
2794                         goto nla_put_failure;
2795         }
2796         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
2797         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
2798
2799         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2800         if ((ret == -ENOENT || ret == -ENOLINK) && alg == WPA_ALG_NONE)
2801                 ret = 0;
2802         if (ret)
2803                 wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
2804                            ret, strerror(-ret));
2805
2806         /*
2807          * If we failed or don't need to set the default TX key (below),
2808          * we're done here.
2809          */
2810         if (ret || !set_tx || alg == WPA_ALG_NONE)
2811                 return ret;
2812         if (drv->nlmode == NL80211_IFTYPE_AP && addr &&
2813             !is_broadcast_ether_addr(addr))
2814                 return ret;
2815
2816         msg = nlmsg_alloc();
2817         if (!msg)
2818                 return -ENOMEM;
2819
2820         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
2821                     0, NL80211_CMD_SET_KEY, 0);
2822         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
2823         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
2824         if (alg == WPA_ALG_IGTK)
2825                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
2826         else
2827                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
2828         if (addr && is_broadcast_ether_addr(addr)) {
2829                 struct nl_msg *types;
2830                 int err;
2831                 types = nlmsg_alloc();
2832                 if (!types)
2833                         goto nla_put_failure;
2834                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
2835                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
2836                                      types);
2837                 nlmsg_free(types);
2838                 if (err)
2839                         goto nla_put_failure;
2840         } else if (addr) {
2841                 struct nl_msg *types;
2842                 int err;
2843                 types = nlmsg_alloc();
2844                 if (!types)
2845                         goto nla_put_failure;
2846                 NLA_PUT_FLAG(types, NL80211_KEY_DEFAULT_TYPE_UNICAST);
2847                 err = nla_put_nested(msg, NL80211_ATTR_KEY_DEFAULT_TYPES,
2848                                      types);
2849                 nlmsg_free(types);
2850                 if (err)
2851                         goto nla_put_failure;
2852         }
2853
2854         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
2855         if (ret == -ENOENT)
2856                 ret = 0;
2857         if (ret)
2858                 wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
2859                            "err=%d %s)", ret, strerror(-ret));
2860         return ret;
2861
2862 nla_put_failure:
2863         return -ENOBUFS;
2864 }
2865
2866
2867 static int nl_add_key(struct nl_msg *msg, enum wpa_alg alg,
2868                       int key_idx, int defkey,
2869                       const u8 *seq, size_t seq_len,
2870                       const u8 *key, size_t key_len)
2871 {
2872         struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
2873         if (!key_attr)
2874                 return -1;
2875
2876         if (defkey && alg == WPA_ALG_IGTK)
2877                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
2878         else if (defkey)
2879                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
2880
2881         NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
2882
2883         switch (alg) {
2884         case WPA_ALG_WEP:
2885                 if (key_len == 5)
2886                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2887                                     WLAN_CIPHER_SUITE_WEP40);
2888                 else
2889                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2890                                     WLAN_CIPHER_SUITE_WEP104);
2891                 break;
2892         case WPA_ALG_TKIP:
2893                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_TKIP);
2894                 break;
2895         case WPA_ALG_CCMP:
2896                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_CCMP);
2897                 break;
2898         case WPA_ALG_IGTK:
2899                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2900                             WLAN_CIPHER_SUITE_AES_CMAC);
2901                 break;
2902         default:
2903                 wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
2904                            "algorithm %d", __func__, alg);
2905                 return -1;
2906         }
2907
2908         if (seq && seq_len)
2909                 NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
2910
2911         NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
2912
2913         nla_nest_end(msg, key_attr);
2914
2915         return 0;
2916  nla_put_failure:
2917         return -1;
2918 }
2919
2920
2921 static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
2922                                  struct nl_msg *msg)
2923 {
2924         int i, privacy = 0;
2925         struct nlattr *nl_keys, *nl_key;
2926
2927         for (i = 0; i < 4; i++) {
2928                 if (!params->wep_key[i])
2929                         continue;
2930                 privacy = 1;
2931                 break;
2932         }
2933         if (params->wps == WPS_MODE_PRIVACY)
2934                 privacy = 1;
2935         if (params->pairwise_suite &&
2936             params->pairwise_suite != WPA_CIPHER_NONE)
2937                 privacy = 1;
2938
2939         if (!privacy)
2940                 return 0;
2941
2942         NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
2943
2944         nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
2945         if (!nl_keys)
2946                 goto nla_put_failure;
2947
2948         for (i = 0; i < 4; i++) {
2949                 if (!params->wep_key[i])
2950                         continue;
2951
2952                 nl_key = nla_nest_start(msg, i);
2953                 if (!nl_key)
2954                         goto nla_put_failure;
2955
2956                 NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
2957                         params->wep_key[i]);
2958                 if (params->wep_key_len[i] == 5)
2959                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2960                                     WLAN_CIPHER_SUITE_WEP40);
2961                 else
2962                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
2963                                     WLAN_CIPHER_SUITE_WEP104);
2964
2965                 NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
2966
2967                 if (i == params->wep_tx_keyidx)
2968                         NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
2969
2970                 nla_nest_end(msg, nl_key);
2971         }
2972         nla_nest_end(msg, nl_keys);
2973
2974         return 0;
2975
2976 nla_put_failure:
2977         return -ENOBUFS;
2978 }
2979
2980
2981 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
2982                                    const u8 *addr, int cmd, u16 reason_code,
2983                                    int local_state_change)
2984 {
2985         int ret = -1;
2986         struct nl_msg *msg;
2987
2988         msg = nlmsg_alloc();
2989         if (!msg)
2990                 return -1;
2991
2992         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0, cmd, 0);
2993
2994         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
2995         NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
2996         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
2997         if (local_state_change)
2998                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
2999
3000         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3001         msg = NULL;
3002         if (ret) {
3003                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
3004                            "(%s)", ret, strerror(-ret));
3005                 goto nla_put_failure;
3006         }
3007         ret = 0;
3008
3009 nla_put_failure:
3010         nlmsg_free(msg);
3011         return ret;
3012 }
3013
3014
3015 static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
3016                                          const u8 *addr, int reason_code)
3017 {
3018         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
3019                    __func__, MAC2STR(addr), reason_code);
3020         drv->associated = 0;
3021         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISCONNECT,
3022                                        reason_code, 0);
3023 }
3024
3025
3026 static int wpa_driver_nl80211_deauthenticate(void *priv, const u8 *addr,
3027                                              int reason_code)
3028 {
3029         struct i802_bss *bss = priv;
3030         struct wpa_driver_nl80211_data *drv = bss->drv;
3031         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
3032                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
3033         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
3034                    __func__, MAC2STR(addr), reason_code);
3035         drv->associated = 0;
3036         if (drv->nlmode == NL80211_IFTYPE_ADHOC)
3037                 return nl80211_leave_ibss(drv);
3038         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
3039                                        reason_code, 0);
3040 }
3041
3042
3043 static int wpa_driver_nl80211_disassociate(void *priv, const u8 *addr,
3044                                            int reason_code)
3045 {
3046         struct i802_bss *bss = priv;
3047         struct wpa_driver_nl80211_data *drv = bss->drv;
3048         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
3049                 return wpa_driver_nl80211_disconnect(drv, addr, reason_code);
3050         wpa_printf(MSG_DEBUG, "%s", __func__);
3051         drv->associated = 0;
3052         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DISASSOCIATE,
3053                                        reason_code, 0);
3054 }
3055
3056
3057 static int wpa_driver_nl80211_authenticate(
3058         void *priv, struct wpa_driver_auth_params *params)
3059 {
3060         struct i802_bss *bss = priv;
3061         struct wpa_driver_nl80211_data *drv = bss->drv;
3062         int ret = -1, i;
3063         struct nl_msg *msg;
3064         enum nl80211_auth_type type;
3065         int count = 0;
3066
3067         drv->associated = 0;
3068         os_memset(drv->auth_bssid, 0, ETH_ALEN);
3069         /* FIX: IBSS mode */
3070         if (drv->nlmode != NL80211_IFTYPE_STATION &&
3071             wpa_driver_nl80211_set_mode(priv, IEEE80211_MODE_INFRA) < 0)
3072                 return -1;
3073
3074 retry:
3075         msg = nlmsg_alloc();
3076         if (!msg)
3077                 return -1;
3078
3079         wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
3080                    drv->ifindex);
3081
3082         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
3083                     NL80211_CMD_AUTHENTICATE, 0);
3084
3085         for (i = 0; i < 4; i++) {
3086                 if (!params->wep_key[i])
3087                         continue;
3088                 wpa_driver_nl80211_set_key(bss->ifname, priv, WPA_ALG_WEP,
3089                                            NULL, i,
3090                                            i == params->wep_tx_keyidx, NULL, 0,
3091                                            params->wep_key[i],
3092                                            params->wep_key_len[i]);
3093                 if (params->wep_tx_keyidx != i)
3094                         continue;
3095                 if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
3096                                params->wep_key[i], params->wep_key_len[i])) {
3097                         nlmsg_free(msg);
3098                         return -1;
3099                 }
3100         }
3101
3102         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3103         if (params->bssid) {
3104                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
3105                            MAC2STR(params->bssid));
3106                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
3107         }
3108         if (params->freq) {
3109                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
3110                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
3111         }
3112         if (params->ssid) {
3113                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
3114                                   params->ssid, params->ssid_len);
3115                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
3116                         params->ssid);
3117         }
3118         wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
3119         if (params->ie)
3120                 NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
3121         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
3122                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
3123         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
3124                 type = NL80211_AUTHTYPE_SHARED_KEY;
3125         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
3126                 type = NL80211_AUTHTYPE_NETWORK_EAP;
3127         else if (params->auth_alg & WPA_AUTH_ALG_FT)
3128                 type = NL80211_AUTHTYPE_FT;
3129         else
3130                 goto nla_put_failure;
3131         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
3132         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
3133         if (params->local_state_change) {
3134                 wpa_printf(MSG_DEBUG, "  * Local state change only");
3135                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
3136         }
3137
3138         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3139         msg = NULL;
3140         if (ret) {
3141                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
3142                            "(%s)", ret, strerror(-ret));
3143                 count++;
3144                 if (ret == -EALREADY && count == 1 && params->bssid &&
3145                     !params->local_state_change) {
3146                         /*
3147                          * mac80211 does not currently accept new
3148                          * authentication if we are already authenticated. As a
3149                          * workaround, force deauthentication and try again.
3150                          */
3151                         wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
3152                                    "after forced deauthentication");
3153                         wpa_driver_nl80211_deauthenticate(
3154                                 bss, params->bssid,
3155                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
3156                         nlmsg_free(msg);
3157                         goto retry;
3158                 }
3159                 goto nla_put_failure;
3160         }
3161         ret = 0;
3162         wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
3163                    "successfully");
3164
3165 nla_put_failure:
3166         nlmsg_free(msg);
3167         return ret;
3168 }
3169
3170
3171 struct phy_info_arg {
3172         u16 *num_modes;
3173         struct hostapd_hw_modes *modes;
3174 };
3175
3176 static int phy_info_handler(struct nl_msg *msg, void *arg)
3177 {
3178         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
3179         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3180         struct phy_info_arg *phy_info = arg;
3181
3182         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
3183
3184         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
3185         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
3186                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
3187                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
3188                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
3189                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
3190                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
3191                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
3192         };
3193
3194         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
3195         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
3196                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
3197                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] = { .type = NLA_FLAG },
3198         };
3199
3200         struct nlattr *nl_band;
3201         struct nlattr *nl_freq;
3202         struct nlattr *nl_rate;
3203         int rem_band, rem_freq, rem_rate;
3204         struct hostapd_hw_modes *mode;
3205         int idx, mode_is_set;
3206
3207         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3208                   genlmsg_attrlen(gnlh, 0), NULL);
3209
3210         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
3211                 return NL_SKIP;
3212
3213         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band) {
3214                 mode = os_realloc(phy_info->modes, (*phy_info->num_modes + 1) * sizeof(*mode));
3215                 if (!mode)
3216                         return NL_SKIP;
3217                 phy_info->modes = mode;
3218
3219                 mode_is_set = 0;
3220
3221                 mode = &phy_info->modes[*(phy_info->num_modes)];
3222                 memset(mode, 0, sizeof(*mode));
3223                 *(phy_info->num_modes) += 1;
3224
3225                 nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
3226                           nla_len(nl_band), NULL);
3227
3228                 if (tb_band[NL80211_BAND_ATTR_HT_CAPA]) {
3229                         mode->ht_capab = nla_get_u16(
3230                                 tb_band[NL80211_BAND_ATTR_HT_CAPA]);
3231                 }
3232
3233                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) {
3234                         mode->a_mpdu_params |= nla_get_u8(
3235                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR]) &
3236                                 0x03;
3237                 }
3238
3239                 if (tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) {
3240                         mode->a_mpdu_params |= nla_get_u8(
3241                                 tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY]) <<
3242                                 2;
3243                 }
3244
3245                 if (tb_band[NL80211_BAND_ATTR_HT_MCS_SET] &&
3246                     nla_len(tb_band[NL80211_BAND_ATTR_HT_MCS_SET])) {
3247                         u8 *mcs;
3248                         mcs = nla_data(tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
3249                         os_memcpy(mode->mcs_set, mcs, 16);
3250                 }
3251
3252                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
3253                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
3254                                   nla_len(nl_freq), freq_policy);
3255                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
3256                                 continue;
3257                         mode->num_channels++;
3258                 }
3259
3260                 mode->channels = os_zalloc(mode->num_channels * sizeof(struct hostapd_channel_data));
3261                 if (!mode->channels)
3262                         return NL_SKIP;
3263
3264                 idx = 0;
3265
3266                 nla_for_each_nested(nl_freq, tb_band[NL80211_BAND_ATTR_FREQS], rem_freq) {
3267                         nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX, nla_data(nl_freq),
3268                                   nla_len(nl_freq), freq_policy);
3269                         if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
3270                                 continue;
3271
3272                         mode->channels[idx].freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
3273                         mode->channels[idx].flag = 0;
3274
3275                         if (!mode_is_set) {
3276                                 /* crude heuristic */
3277                                 if (mode->channels[idx].freq < 4000)
3278                                         mode->mode = HOSTAPD_MODE_IEEE80211B;
3279                                 else
3280                                         mode->mode = HOSTAPD_MODE_IEEE80211A;
3281                                 mode_is_set = 1;
3282                         }
3283
3284                         /* crude heuristic */
3285                         if (mode->channels[idx].freq < 4000)
3286                                 if (mode->channels[idx].freq == 2484)
3287                                         mode->channels[idx].chan = 14;
3288                                 else
3289                                         mode->channels[idx].chan = (mode->channels[idx].freq - 2407) / 5;
3290                         else
3291                                 mode->channels[idx].chan = mode->channels[idx].freq/5 - 1000;
3292
3293                         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
3294                                 mode->channels[idx].flag |=
3295                                         HOSTAPD_CHAN_DISABLED;
3296                         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
3297                                 mode->channels[idx].flag |=
3298                                         HOSTAPD_CHAN_PASSIVE_SCAN;
3299                         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
3300                                 mode->channels[idx].flag |=
3301                                         HOSTAPD_CHAN_NO_IBSS;
3302                         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
3303                                 mode->channels[idx].flag |=
3304                                         HOSTAPD_CHAN_RADAR;
3305
3306                         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
3307                             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
3308                                 mode->channels[idx].max_tx_power =
3309                                         nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
3310
3311                         idx++;
3312                 }
3313
3314                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
3315                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
3316                                   nla_len(nl_rate), rate_policy);
3317                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
3318                                 continue;
3319                         mode->num_rates++;
3320                 }
3321
3322                 mode->rates = os_zalloc(mode->num_rates * sizeof(int));
3323                 if (!mode->rates)
3324                         return NL_SKIP;
3325
3326                 idx = 0;
3327
3328                 nla_for_each_nested(nl_rate, tb_band[NL80211_BAND_ATTR_RATES], rem_rate) {
3329                         nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX, nla_data(nl_rate),
3330                                   nla_len(nl_rate), rate_policy);
3331                         if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
3332                                 continue;
3333                         mode->rates[idx] = nla_get_u32(tb_rate[NL80211_BITRATE_ATTR_RATE]);
3334
3335                         /* crude heuristic */
3336                         if (mode->mode == HOSTAPD_MODE_IEEE80211B &&
3337                             mode->rates[idx] > 200)
3338                                 mode->mode = HOSTAPD_MODE_IEEE80211G;
3339
3340                         idx++;
3341                 }
3342         }
3343
3344         return NL_SKIP;
3345 }
3346
3347 static struct hostapd_hw_modes *
3348 wpa_driver_nl80211_add_11b(struct hostapd_hw_modes *modes, u16 *num_modes)
3349 {
3350         u16 m;
3351         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
3352         int i, mode11g_idx = -1;
3353
3354         /* If only 802.11g mode is included, use it to construct matching
3355          * 802.11b mode data. */
3356
3357         for (m = 0; m < *num_modes; m++) {
3358                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
3359                         return modes; /* 802.11b already included */
3360                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
3361                         mode11g_idx = m;
3362         }
3363
3364         if (mode11g_idx < 0)
3365                 return modes; /* 2.4 GHz band not supported at all */
3366
3367         nmodes = os_realloc(modes, (*num_modes + 1) * sizeof(*nmodes));
3368         if (nmodes == NULL)
3369                 return modes; /* Could not add 802.11b mode */
3370
3371         mode = &nmodes[*num_modes];
3372         os_memset(mode, 0, sizeof(*mode));
3373         (*num_modes)++;
3374         modes = nmodes;
3375
3376         mode->mode = HOSTAPD_MODE_IEEE80211B;
3377
3378         mode11g = &modes[mode11g_idx];
3379         mode->num_channels = mode11g->num_channels;
3380         mode->channels = os_malloc(mode11g->num_channels *
3381                                    sizeof(struct hostapd_channel_data));
3382         if (mode->channels == NULL) {
3383                 (*num_modes)--;
3384                 return modes; /* Could not add 802.11b mode */
3385         }
3386         os_memcpy(mode->channels, mode11g->channels,
3387                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
3388
3389         mode->num_rates = 0;
3390         mode->rates = os_malloc(4 * sizeof(int));
3391         if (mode->rates == NULL) {
3392                 os_free(mode->channels);
3393                 (*num_modes)--;
3394                 return modes; /* Could not add 802.11b mode */
3395         }
3396
3397         for (i = 0; i < mode11g->num_rates; i++) {
3398                 if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 &&
3399                     mode11g->rates[i] != 55 && mode11g->rates[i] != 110)
3400                         continue;
3401                 mode->rates[mode->num_rates] = mode11g->rates[i];
3402                 mode->num_rates++;
3403                 if (mode->num_rates == 4)
3404                         break;
3405         }
3406
3407         if (mode->num_rates == 0) {
3408                 os_free(mode->channels);
3409                 os_free(mode->rates);
3410                 (*num_modes)--;
3411                 return modes; /* No 802.11b rates */
3412         }
3413
3414         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
3415                    "information");
3416
3417         return modes;
3418 }
3419
3420
3421 static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start,
3422                                   int end)
3423 {
3424         int c;
3425
3426         for (c = 0; c < mode->num_channels; c++) {
3427                 struct hostapd_channel_data *chan = &mode->channels[c];
3428                 if (chan->freq - 10 >= start && chan->freq + 10 <= end)
3429                         chan->flag |= HOSTAPD_CHAN_HT40;
3430         }
3431 }
3432
3433
3434 static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start,
3435                                       int end)
3436 {
3437         int c;
3438
3439         for (c = 0; c < mode->num_channels; c++) {
3440                 struct hostapd_channel_data *chan = &mode->channels[c];
3441                 if (!(chan->flag & HOSTAPD_CHAN_HT40))
3442                         continue;
3443                 if (chan->freq - 30 >= start && chan->freq - 10 <= end)
3444                         chan->flag |= HOSTAPD_CHAN_HT40MINUS;
3445                 if (chan->freq + 10 >= start && chan->freq + 30 <= end)
3446                         chan->flag |= HOSTAPD_CHAN_HT40PLUS;
3447         }
3448 }
3449
3450
3451 static void nl80211_reg_rule_ht40(struct nlattr *tb[],
3452                                   struct phy_info_arg *results)
3453 {
3454         u32 start, end, max_bw;
3455         u16 m;
3456
3457         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
3458             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
3459             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
3460                 return;
3461
3462         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
3463         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
3464         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
3465
3466         wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz",
3467                    start, end, max_bw);
3468         if (max_bw < 40)
3469                 return;
3470
3471         for (m = 0; m < *results->num_modes; m++) {
3472                 if (!(results->modes[m].ht_capab &
3473                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
3474                         continue;
3475                 nl80211_set_ht40_mode(&results->modes[m], start, end);
3476         }
3477 }
3478
3479
3480 static void nl80211_reg_rule_sec(struct nlattr *tb[],
3481                                  struct phy_info_arg *results)
3482 {
3483         u32 start, end, max_bw;
3484         u16 m;
3485
3486         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
3487             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
3488             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
3489                 return;
3490
3491         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
3492         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
3493         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
3494
3495         if (max_bw < 20)
3496                 return;
3497
3498         for (m = 0; m < *results->num_modes; m++) {
3499                 if (!(results->modes[m].ht_capab &
3500                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
3501                         continue;
3502                 nl80211_set_ht40_mode_sec(&results->modes[m], start, end);
3503         }
3504 }
3505
3506
3507 static int nl80211_get_reg(struct nl_msg *msg, void *arg)
3508 {
3509         struct phy_info_arg *results = arg;
3510         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
3511         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
3512         struct nlattr *nl_rule;
3513         struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1];
3514         int rem_rule;
3515         static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
3516                 [NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
3517                 [NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
3518                 [NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
3519                 [NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
3520                 [NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
3521                 [NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
3522         };
3523
3524         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
3525                   genlmsg_attrlen(gnlh, 0), NULL);
3526         if (!tb_msg[NL80211_ATTR_REG_ALPHA2] ||
3527             !tb_msg[NL80211_ATTR_REG_RULES]) {
3528                 wpa_printf(MSG_DEBUG, "nl80211: No regulatory information "
3529                            "available");
3530                 return NL_SKIP;
3531         }
3532
3533         wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s",
3534                    (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]));
3535
3536         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
3537         {
3538                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
3539                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
3540                 nl80211_reg_rule_ht40(tb_rule, results);
3541         }
3542
3543         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
3544         {
3545                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
3546                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
3547                 nl80211_reg_rule_sec(tb_rule, results);
3548         }
3549
3550         return NL_SKIP;
3551 }
3552
3553
3554 static int nl80211_set_ht40_flags(struct wpa_driver_nl80211_data *drv,
3555                                   struct phy_info_arg *results)
3556 {
3557         struct nl_msg *msg;
3558
3559         msg = nlmsg_alloc();
3560         if (!msg)
3561                 return -ENOMEM;
3562
3563         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3564                     0, NL80211_CMD_GET_REG, 0);
3565         return send_and_recv_msgs(drv, msg, nl80211_get_reg, results);
3566 }
3567
3568
3569 static struct hostapd_hw_modes *
3570 wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
3571 {
3572         struct i802_bss *bss = priv;
3573         struct wpa_driver_nl80211_data *drv = bss->drv;
3574         struct nl_msg *msg;
3575         struct phy_info_arg result = {
3576                 .num_modes = num_modes,
3577                 .modes = NULL,
3578         };
3579
3580         *num_modes = 0;
3581         *flags = 0;
3582
3583         msg = nlmsg_alloc();
3584         if (!msg)
3585                 return NULL;
3586
3587         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3588                     0, NL80211_CMD_GET_WIPHY, 0);
3589
3590         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3591
3592         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) {
3593                 nl80211_set_ht40_flags(drv, &result);
3594                 return wpa_driver_nl80211_add_11b(result.modes, num_modes);
3595         }
3596  nla_put_failure:
3597         return NULL;
3598 }
3599
3600
3601 static int wpa_driver_nl80211_send_frame(struct wpa_driver_nl80211_data *drv,
3602                                          const void *data, size_t len,
3603                                          int encrypt)
3604 {
3605         __u8 rtap_hdr[] = {
3606                 0x00, 0x00, /* radiotap version */
3607                 0x0e, 0x00, /* radiotap length */
3608                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
3609                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
3610                 0x00,       /* padding */
3611                 0x00, 0x00, /* RX and TX flags to indicate that */
3612                 0x00, 0x00, /* this is the injected frame directly */
3613         };
3614         struct iovec iov[2] = {
3615                 {
3616                         .iov_base = &rtap_hdr,
3617                         .iov_len = sizeof(rtap_hdr),
3618                 },
3619                 {
3620                         .iov_base = (void *) data,
3621                         .iov_len = len,
3622                 }
3623         };
3624         struct msghdr msg = {
3625                 .msg_name = NULL,
3626                 .msg_namelen = 0,
3627                 .msg_iov = iov,
3628                 .msg_iovlen = 2,
3629                 .msg_control = NULL,
3630                 .msg_controllen = 0,
3631                 .msg_flags = 0,
3632         };
3633         int res;
3634
3635         if (encrypt)
3636                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
3637
3638         res = sendmsg(drv->monitor_sock, &msg, 0);
3639         if (res < 0) {
3640                 wpa_printf(MSG_INFO, "nl80211: sendmsg: %s", strerror(errno));
3641                 return -1;
3642         }
3643         return 0;
3644 }
3645
3646
3647 static int wpa_driver_nl80211_send_mlme(void *priv, const u8 *data,
3648                                         size_t data_len)
3649 {
3650         struct i802_bss *bss = priv;
3651         struct wpa_driver_nl80211_data *drv = bss->drv;
3652         struct ieee80211_mgmt *mgmt;
3653         int encrypt = 1;
3654         u16 fc;
3655
3656         mgmt = (struct ieee80211_mgmt *) data;
3657         fc = le_to_host16(mgmt->frame_control);
3658
3659         if (drv->nlmode == NL80211_IFTYPE_STATION &&
3660             WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
3661             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_PROBE_RESP) {
3662                 /*
3663                  * The use of last_mgmt_freq is a bit of a hack,
3664                  * but it works due to the single-threaded nature
3665                  * of wpa_supplicant.
3666                  */
3667                 return nl80211_send_frame_cmd(drv, drv->last_mgmt_freq, 0,
3668                                               data, data_len, NULL);
3669         }
3670
3671         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
3672             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
3673                 /*
3674                  * Only one of the authentication frame types is encrypted.
3675                  * In order for static WEP encryption to work properly (i.e.,
3676                  * to not encrypt the frame), we need to tell mac80211 about
3677                  * the frames that must not be encrypted.
3678                  */
3679                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
3680                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
3681                 if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
3682                         encrypt = 0;
3683         }
3684
3685         return wpa_driver_nl80211_send_frame(drv, data, data_len, encrypt);
3686 }
3687
3688
3689 static int wpa_driver_nl80211_set_beacon(void *priv,
3690                                          const u8 *head, size_t head_len,
3691                                          const u8 *tail, size_t tail_len,
3692                                          int dtim_period, int beacon_int)
3693 {
3694         struct i802_bss *bss = priv;
3695         struct wpa_driver_nl80211_data *drv = bss->drv;
3696         struct nl_msg *msg;
3697         u8 cmd = NL80211_CMD_NEW_BEACON;
3698         int ret;
3699         int beacon_set;
3700         int ifindex = if_nametoindex(bss->ifname);
3701
3702         beacon_set = bss->beacon_set;
3703
3704         msg = nlmsg_alloc();
3705         if (!msg)
3706                 return -ENOMEM;
3707
3708         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
3709                    beacon_set);
3710         if (beacon_set)
3711                 cmd = NL80211_CMD_SET_BEACON;
3712
3713         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3714                     0, cmd, 0);
3715         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, head_len, head);
3716         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, tail_len, tail);
3717         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
3718         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, beacon_int);
3719         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, dtim_period);
3720
3721         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3722         if (ret) {
3723                 wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
3724                            ret, strerror(-ret));
3725         } else {
3726                 bss->beacon_set = 1;
3727         }
3728         return ret;
3729  nla_put_failure:
3730         return -ENOBUFS;
3731 }
3732
3733
3734 static int wpa_driver_nl80211_set_freq(struct wpa_driver_nl80211_data *drv,
3735                                        int freq, int ht_enabled,
3736                                        int sec_channel_offset)
3737 {
3738         struct nl_msg *msg;
3739         int ret;
3740
3741         msg = nlmsg_alloc();
3742         if (!msg)
3743                 return -1;
3744
3745         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
3746                     NL80211_CMD_SET_WIPHY, 0);
3747
3748         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3749         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
3750         if (ht_enabled) {
3751                 switch (sec_channel_offset) {
3752                 case -1:
3753                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3754                                     NL80211_CHAN_HT40MINUS);
3755                         break;
3756                 case 1:
3757                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3758                                     NL80211_CHAN_HT40PLUS);
3759                         break;
3760                 default:
3761                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
3762                                     NL80211_CHAN_HT20);
3763                         break;
3764                 }
3765         }
3766
3767         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3768         if (ret == 0)
3769                 return 0;
3770         wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
3771                    "%d (%s)", freq, ret, strerror(-ret));
3772 nla_put_failure:
3773         return -1;
3774 }
3775
3776
3777 static int wpa_driver_nl80211_sta_add(void *priv,
3778                                       struct hostapd_sta_add_params *params)
3779 {
3780         struct i802_bss *bss = priv;
3781         struct wpa_driver_nl80211_data *drv = bss->drv;
3782         struct nl_msg *msg;
3783         int ret = -ENOBUFS;
3784
3785         msg = nlmsg_alloc();
3786         if (!msg)
3787                 return -ENOMEM;
3788
3789         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3790                     0, NL80211_CMD_NEW_STATION, 0);
3791
3792         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
3793         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
3794         NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
3795         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
3796                 params->supp_rates);
3797         NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
3798                     params->listen_interval);
3799         if (params->ht_capabilities) {
3800                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
3801                         sizeof(*params->ht_capabilities),
3802                         params->ht_capabilities);
3803         }
3804
3805         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3806         if (ret)
3807                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_NEW_STATION "
3808                            "result: %d (%s)", ret, strerror(-ret));
3809         if (ret == -EEXIST)
3810                 ret = 0;
3811  nla_put_failure:
3812         return ret;
3813 }
3814
3815
3816 static int wpa_driver_nl80211_sta_remove(void *priv, const u8 *addr)
3817 {
3818         struct i802_bss *bss = priv;
3819         struct wpa_driver_nl80211_data *drv = bss->drv;
3820         struct nl_msg *msg;
3821         int ret;
3822
3823         msg = nlmsg_alloc();
3824         if (!msg)
3825                 return -ENOMEM;
3826
3827         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3828                     0, NL80211_CMD_DEL_STATION, 0);
3829
3830         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
3831                     if_nametoindex(bss->ifname));
3832         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
3833
3834         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3835         if (ret == -ENOENT)
3836                 return 0;
3837         return ret;
3838  nla_put_failure:
3839         return -ENOBUFS;
3840 }
3841
3842
3843 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
3844                                  int ifidx)
3845 {
3846         struct nl_msg *msg;
3847
3848         wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
3849
3850 #ifdef HOSTAPD
3851         /* stop listening for EAPOL on this interface */
3852         del_ifidx(drv, ifidx);
3853 #endif /* HOSTAPD */
3854
3855         msg = nlmsg_alloc();
3856         if (!msg)
3857                 goto nla_put_failure;
3858
3859         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3860                     0, NL80211_CMD_DEL_INTERFACE, 0);
3861         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
3862
3863         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
3864                 return;
3865  nla_put_failure:
3866         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
3867 }
3868
3869
3870 static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
3871                                      const char *ifname,
3872                                      enum nl80211_iftype iftype,
3873                                      const u8 *addr, int wds)
3874 {
3875         struct nl_msg *msg, *flags = NULL;
3876         int ifidx;
3877         int ret = -ENOBUFS;
3878
3879         msg = nlmsg_alloc();
3880         if (!msg)
3881                 return -1;
3882
3883         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
3884                     0, NL80211_CMD_NEW_INTERFACE, 0);
3885         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3886         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
3887         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
3888
3889         if (iftype == NL80211_IFTYPE_MONITOR) {
3890                 int err;
3891
3892                 flags = nlmsg_alloc();
3893                 if (!flags)
3894                         goto nla_put_failure;
3895
3896                 NLA_PUT_FLAG(flags, NL80211_MNTR_FLAG_COOK_FRAMES);
3897
3898                 err = nla_put_nested(msg, NL80211_ATTR_MNTR_FLAGS, flags);
3899
3900                 nlmsg_free(flags);
3901
3902                 if (err)
3903                         goto nla_put_failure;
3904         } else if (wds) {
3905                 NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
3906         }
3907
3908         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3909         if (ret) {
3910  nla_put_failure:
3911                 wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
3912                            ifname, ret, strerror(-ret));
3913                 return ret;
3914         }
3915
3916         ifidx = if_nametoindex(ifname);
3917         wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
3918                    ifname, ifidx);
3919
3920         if (ifidx <= 0)
3921                 return -1;
3922
3923 #ifdef HOSTAPD
3924         /* start listening for EAPOL on this interface */
3925         add_ifidx(drv, ifidx);
3926 #endif /* HOSTAPD */
3927
3928         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
3929             linux_set_ifhwaddr(drv->ioctl_sock, ifname, addr)) {
3930                 nl80211_remove_iface(drv, ifidx);
3931                 return -1;
3932         }
3933
3934         return ifidx;
3935 }
3936
3937
3938 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
3939                                 const char *ifname, enum nl80211_iftype iftype,
3940                                 const u8 *addr, int wds)
3941 {
3942         int ret;
3943
3944         ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds);
3945
3946         /* if error occured and interface exists already */
3947         if (ret == -ENFILE && if_nametoindex(ifname)) {
3948                 wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
3949
3950                 /* Try to remove the interface that was already there. */
3951                 nl80211_remove_iface(drv, if_nametoindex(ifname));
3952
3953                 /* Try to create the interface again */
3954                 ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
3955                                                 wds);
3956         }
3957
3958         if (ret >= 0 && drv->disable_11b_rates)
3959                 nl80211_disable_11b_rates(drv, ret, 1);
3960
3961         return ret;
3962 }
3963
3964
3965 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
3966 {
3967         struct ieee80211_hdr *hdr;
3968         u16 fc;
3969         union wpa_event_data event;
3970
3971         hdr = (struct ieee80211_hdr *) buf;
3972         fc = le_to_host16(hdr->frame_control);
3973
3974         os_memset(&event, 0, sizeof(event));
3975         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
3976         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
3977         event.tx_status.dst = hdr->addr1;
3978         event.tx_status.data = buf;
3979         event.tx_status.data_len = len;
3980         event.tx_status.ack = ok;
3981         wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
3982 }
3983
3984
3985 static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
3986                              u8 *buf, size_t len)
3987 {
3988         union wpa_event_data event;
3989         os_memset(&event, 0, sizeof(event));
3990         event.rx_from_unknown.frame = buf;
3991         event.rx_from_unknown.len = len;
3992         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
3993 }
3994
3995
3996 static void handle_frame(struct wpa_driver_nl80211_data *drv,
3997                          u8 *buf, size_t len, int datarate, int ssi_signal)
3998 {
3999         struct ieee80211_hdr *hdr;
4000         u16 fc;
4001         union wpa_event_data event;
4002
4003         hdr = (struct ieee80211_hdr *) buf;
4004         fc = le_to_host16(hdr->frame_control);
4005
4006         switch (WLAN_FC_GET_TYPE(fc)) {
4007         case WLAN_FC_TYPE_MGMT:
4008                 os_memset(&event, 0, sizeof(event));
4009                 event.rx_mgmt.frame = buf;
4010                 event.rx_mgmt.frame_len = len;
4011                 event.rx_mgmt.datarate = datarate;
4012                 event.rx_mgmt.ssi_signal = ssi_signal;
4013                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
4014                 break;
4015         case WLAN_FC_TYPE_CTRL:
4016                 /* can only get here with PS-Poll frames */
4017                 wpa_printf(MSG_DEBUG, "CTRL");
4018                 from_unknown_sta(drv, buf, len);
4019                 break;
4020         case WLAN_FC_TYPE_DATA:
4021                 from_unknown_sta(drv, buf, len);
4022                 break;
4023         }
4024 }
4025
4026
4027 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
4028 {
4029         struct wpa_driver_nl80211_data *drv = eloop_ctx;
4030         int len;
4031         unsigned char buf[3000];
4032         struct ieee80211_radiotap_iterator iter;
4033         int ret;
4034         int datarate = 0, ssi_signal = 0;
4035         int injected = 0, failed = 0, rxflags = 0;
4036
4037         len = recv(sock, buf, sizeof(buf), 0);
4038         if (len < 0) {
4039                 perror("recv");
4040                 return;
4041         }
4042
4043         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
4044                 printf("received invalid radiotap frame\n");
4045                 return;
4046         }
4047
4048         while (1) {
4049                 ret = ieee80211_radiotap_iterator_next(&iter);
4050                 if (ret == -ENOENT)
4051                         break;
4052                 if (ret) {
4053                         printf("received invalid radiotap frame (%d)\n", ret);
4054                         return;
4055                 }
4056                 switch (iter.this_arg_index) {
4057                 case IEEE80211_RADIOTAP_FLAGS:
4058                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
4059                                 len -= 4;
4060                         break;
4061                 case IEEE80211_RADIOTAP_RX_FLAGS:
4062                         rxflags = 1;
4063                         break;
4064                 case IEEE80211_RADIOTAP_TX_FLAGS:
4065                         injected = 1;
4066                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
4067                                         IEEE80211_RADIOTAP_F_TX_FAIL;
4068                         break;
4069                 case IEEE80211_RADIOTAP_DATA_RETRIES:
4070                         break;
4071                 case IEEE80211_RADIOTAP_CHANNEL:
4072                         /* TODO: convert from freq/flags to channel number */
4073                         break;
4074                 case IEEE80211_RADIOTAP_RATE:
4075                         datarate = *iter.this_arg * 5;
4076                         break;
4077                 case IEEE80211_RADIOTAP_DB_ANTSIGNAL:
4078                         ssi_signal = *iter.this_arg;
4079                         break;
4080                 }
4081         }
4082
4083         if (rxflags && injected)
4084                 return;
4085
4086         if (!injected)
4087                 handle_frame(drv, buf + iter.max_length,
4088                              len - iter.max_length, datarate, ssi_signal);
4089         else
4090                 handle_tx_callback(drv->ctx, buf + iter.max_length,
4091                                    len - iter.max_length, !failed);
4092 }
4093
4094
4095 /*
4096  * we post-process the filter code later and rewrite
4097  * this to the offset to the last instruction
4098  */
4099 #define PASS    0xFF
4100 #define FAIL    0xFE
4101
4102 static struct sock_filter msock_filter_insns[] = {
4103         /*
4104          * do a little-endian load of the radiotap length field
4105          */
4106         /* load lower byte into A */
4107         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
4108         /* put it into X (== index register) */
4109         BPF_STMT(BPF_MISC| BPF_TAX, 0),
4110         /* load upper byte into A */
4111         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
4112         /* left-shift it by 8 */
4113         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
4114         /* or with X */
4115         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
4116         /* put result into X */
4117         BPF_STMT(BPF_MISC| BPF_TAX, 0),
4118
4119         /*
4120          * Allow management frames through, this also gives us those
4121          * management frames that we sent ourselves with status
4122          */
4123         /* load the lower byte of the IEEE 802.11 frame control field */
4124         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
4125         /* mask off frame type and version */
4126         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
4127         /* accept frame if it's both 0, fall through otherwise */
4128         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
4129
4130         /*
4131          * TODO: add a bit to radiotap RX flags that indicates
4132          * that the sending station is not associated, then
4133          * add a filter here that filters on our DA and that flag
4134          * to allow us to deauth frames to that bad station.
4135          *
4136          * For now allow all To DS data frames through.
4137          */
4138         /* load the IEEE 802.11 frame control field */
4139         BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
4140         /* mask off frame type, version and DS status */
4141         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
4142         /* accept frame if version 0, type 2 and To DS, fall through otherwise
4143          */
4144         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
4145
4146 #if 0
4147         /*
4148          * drop non-data frames
4149          */
4150         /* load the lower byte of the frame control field */
4151         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
4152         /* mask off QoS bit */
4153         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
4154         /* drop non-data frames */
4155         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
4156 #endif
4157         /* load the upper byte of the frame control field */
4158         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
4159         /* mask off toDS/fromDS */
4160         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
4161         /* accept WDS frames */
4162         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
4163
4164         /*
4165          * add header length to index
4166          */
4167         /* load the lower byte of the frame control field */
4168         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
4169         /* mask off QoS bit */
4170         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
4171         /* right shift it by 6 to give 0 or 2 */
4172         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
4173         /* add data frame header length */
4174         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
4175         /* add index, was start of 802.11 header */
4176         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
4177         /* move to index, now start of LL header */
4178         BPF_STMT(BPF_MISC | BPF_TAX, 0),
4179
4180         /*
4181          * Accept empty data frames, we use those for
4182          * polling activity.
4183          */
4184         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
4185         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
4186
4187         /*
4188          * Accept EAPOL frames
4189          */
4190         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
4191         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
4192         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
4193         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
4194
4195         /* keep these last two statements or change the code below */
4196         /* return 0 == "DROP" */
4197         BPF_STMT(BPF_RET | BPF_K, 0),
4198         /* return ~0 == "keep all" */
4199         BPF_STMT(BPF_RET | BPF_K, ~0),
4200 };
4201
4202 static struct sock_fprog msock_filter = {
4203         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
4204         .filter = msock_filter_insns,
4205 };
4206
4207
4208 static int add_monitor_filter(int s)
4209 {
4210         int idx;
4211
4212         /* rewrite all PASS/FAIL jump offsets */
4213         for (idx = 0; idx < msock_filter.len; idx++) {
4214                 struct sock_filter *insn = &msock_filter_insns[idx];
4215
4216                 if (BPF_CLASS(insn->code) == BPF_JMP) {
4217                         if (insn->code == (BPF_JMP|BPF_JA)) {
4218                                 if (insn->k == PASS)
4219                                         insn->k = msock_filter.len - idx - 2;
4220                                 else if (insn->k == FAIL)
4221                                         insn->k = msock_filter.len - idx - 3;
4222                         }
4223
4224                         if (insn->jt == PASS)
4225                                 insn->jt = msock_filter.len - idx - 2;
4226                         else if (insn->jt == FAIL)
4227                                 insn->jt = msock_filter.len - idx - 3;
4228
4229                         if (insn->jf == PASS)
4230                                 insn->jf = msock_filter.len - idx - 2;
4231                         else if (insn->jf == FAIL)
4232                                 insn->jf = msock_filter.len - idx - 3;
4233                 }
4234         }
4235
4236         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
4237                        &msock_filter, sizeof(msock_filter))) {
4238                 perror("SO_ATTACH_FILTER");
4239                 return -1;
4240         }
4241
4242         return 0;
4243 }
4244
4245
4246 static void nl80211_remove_monitor_interface(
4247         struct wpa_driver_nl80211_data *drv)
4248 {
4249         if (drv->monitor_ifidx >= 0) {
4250                 nl80211_remove_iface(drv, drv->monitor_ifidx);
4251                 drv->monitor_ifidx = -1;
4252         }
4253         if (drv->monitor_sock >= 0) {
4254                 eloop_unregister_read_sock(drv->monitor_sock);
4255                 close(drv->monitor_sock);
4256                 drv->monitor_sock = -1;
4257         }
4258 }
4259
4260
4261 static int
4262 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
4263 {
4264         char buf[IFNAMSIZ];
4265         struct sockaddr_ll ll;
4266         int optval;
4267         socklen_t optlen;
4268
4269         snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss.ifname);
4270         buf[IFNAMSIZ - 1] = '\0';
4271
4272         drv->monitor_ifidx =
4273                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
4274                                      0);
4275
4276         if (drv->monitor_ifidx < 0)
4277                 return -1;
4278
4279         if (linux_set_iface_flags(drv->ioctl_sock, buf, 1))
4280                 goto error;
4281
4282         memset(&ll, 0, sizeof(ll));
4283         ll.sll_family = AF_PACKET;
4284         ll.sll_ifindex = drv->monitor_ifidx;
4285         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
4286         if (drv->monitor_sock < 0) {
4287                 perror("socket[PF_PACKET,SOCK_RAW]");
4288                 goto error;
4289         }
4290
4291         if (add_monitor_filter(drv->monitor_sock)) {
4292                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
4293                            "interface; do filtering in user space");
4294                 /* This works, but will cost in performance. */
4295         }
4296
4297         if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
4298                 perror("monitor socket bind");
4299                 goto error;
4300         }
4301
4302         optlen = sizeof(optval);
4303         optval = 20;
4304         if (setsockopt
4305             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
4306                 perror("Failed to set socket priority");
4307                 goto error;
4308         }
4309
4310         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
4311                                      drv, NULL)) {
4312                 printf("Could not register monitor read socket\n");
4313                 goto error;
4314         }
4315
4316         return 0;
4317  error:
4318         nl80211_remove_monitor_interface(drv);
4319         return -1;
4320 }
4321
4322
4323 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
4324
4325 static int wpa_driver_nl80211_hapd_send_eapol(
4326         void *priv, const u8 *addr, const u8 *data,
4327         size_t data_len, int encrypt, const u8 *own_addr, u32 flags)
4328 {
4329         struct i802_bss *bss = priv;
4330         struct wpa_driver_nl80211_data *drv = bss->drv;
4331         struct ieee80211_hdr *hdr;
4332         size_t len;
4333         u8 *pos;
4334         int res;
4335         int qos = flags & WPA_STA_WMM;
4336
4337         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
4338                 data_len;
4339         hdr = os_zalloc(len);
4340         if (hdr == NULL) {
4341                 printf("malloc() failed for i802_send_data(len=%lu)\n",
4342                        (unsigned long) len);
4343                 return -1;
4344         }
4345
4346         hdr->frame_control =
4347                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
4348         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
4349         if (encrypt)
4350                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
4351         if (qos) {
4352                 hdr->frame_control |=
4353                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
4354         }
4355
4356         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
4357         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
4358         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
4359         pos = (u8 *) (hdr + 1);
4360
4361         if (qos) {
4362                 /* add an empty QoS header if needed */
4363                 pos[0] = 0;
4364                 pos[1] = 0;
4365                 pos += 2;
4366         }
4367
4368         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
4369         pos += sizeof(rfc1042_header);
4370         WPA_PUT_BE16(pos, ETH_P_PAE);
4371         pos += 2;
4372         memcpy(pos, data, data_len);
4373
4374         res = wpa_driver_nl80211_send_frame(drv, (u8 *) hdr, len, encrypt);
4375         if (res < 0) {
4376                 wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
4377                            "failed: %d (%s)",
4378                            (unsigned long) len, errno, strerror(errno));
4379         }
4380         os_free(hdr);
4381
4382         return res;
4383 }
4384
4385
4386 static u32 sta_flags_nl80211(int flags)
4387 {
4388         u32 f = 0;
4389
4390         if (flags & WPA_STA_AUTHORIZED)
4391                 f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
4392         if (flags & WPA_STA_WMM)
4393                 f |= BIT(NL80211_STA_FLAG_WME);
4394         if (flags & WPA_STA_SHORT_PREAMBLE)
4395                 f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
4396         if (flags & WPA_STA_MFP)
4397                 f |= BIT(NL80211_STA_FLAG_MFP);
4398
4399         return f;
4400 }
4401
4402
4403 static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
4404                                             int total_flags,
4405                                             int flags_or, int flags_and)
4406 {
4407         struct i802_bss *bss = priv;
4408         struct wpa_driver_nl80211_data *drv = bss->drv;
4409         struct nl_msg *msg, *flags = NULL;
4410         struct nl80211_sta_flag_update upd;
4411
4412         msg = nlmsg_alloc();
4413         if (!msg)
4414                 return -ENOMEM;
4415
4416         flags = nlmsg_alloc();
4417         if (!flags) {
4418                 nlmsg_free(msg);
4419                 return -ENOMEM;
4420         }
4421
4422         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4423                     0, NL80211_CMD_SET_STATION, 0);
4424
4425         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
4426                     if_nametoindex(bss->ifname));
4427         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4428
4429         /*
4430          * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
4431          * can be removed eventually.
4432          */
4433         if (total_flags & WPA_STA_AUTHORIZED)
4434                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_AUTHORIZED);
4435
4436         if (total_flags & WPA_STA_WMM)
4437                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_WME);
4438
4439         if (total_flags & WPA_STA_SHORT_PREAMBLE)
4440                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_SHORT_PREAMBLE);
4441
4442         if (total_flags & WPA_STA_MFP)
4443                 NLA_PUT_FLAG(flags, NL80211_STA_FLAG_MFP);
4444
4445         if (nla_put_nested(msg, NL80211_ATTR_STA_FLAGS, flags))
4446                 goto nla_put_failure;
4447
4448         os_memset(&upd, 0, sizeof(upd));
4449         upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
4450         upd.set = sta_flags_nl80211(flags_or);
4451         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
4452
4453         nlmsg_free(flags);
4454
4455         return send_and_recv_msgs(drv, msg, NULL, NULL);
4456  nla_put_failure:
4457         nlmsg_free(flags);
4458         return -ENOBUFS;
4459 }
4460
4461
4462 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
4463                                  struct wpa_driver_associate_params *params)
4464 {
4465         if (params->p2p)
4466                 wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
4467                            "group (GO)");
4468         if (wpa_driver_nl80211_set_mode(&drv->first_bss, params->mode) ||
4469             wpa_driver_nl80211_set_freq(drv, params->freq, 0, 0)) {
4470                 nl80211_remove_monitor_interface(drv);
4471                 return -1;
4472         }
4473
4474         /* TODO: setup monitor interface (and add code somewhere to remove this
4475          * when AP mode is stopped; associate with mode != 2 or drv_deinit) */
4476
4477         return 0;
4478 }
4479
4480
4481 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
4482 {
4483         struct nl_msg *msg;
4484         int ret = -1;
4485
4486         msg = nlmsg_alloc();
4487         if (!msg)
4488                 return -1;
4489
4490         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4491                     NL80211_CMD_LEAVE_IBSS, 0);
4492         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4493         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4494         msg = NULL;
4495         if (ret) {
4496                 wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
4497                            "(%s)", ret, strerror(-ret));
4498                 goto nla_put_failure;
4499         }
4500
4501         ret = 0;
4502         wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
4503
4504 nla_put_failure:
4505         nlmsg_free(msg);
4506         return ret;
4507 }
4508
4509
4510 static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
4511                                    struct wpa_driver_associate_params *params)
4512 {
4513         struct nl_msg *msg;
4514         int ret = -1;
4515         int count = 0;
4516
4517         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
4518
4519         if (wpa_driver_nl80211_set_mode(&drv->first_bss, params->mode)) {
4520                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
4521                            "IBSS mode");
4522                 return -1;
4523         }
4524
4525 retry:
4526         msg = nlmsg_alloc();
4527         if (!msg)
4528                 return -1;
4529
4530         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4531                     NL80211_CMD_JOIN_IBSS, 0);
4532         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4533
4534         if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
4535                 goto nla_put_failure;
4536
4537         wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4538                           params->ssid, params->ssid_len);
4539         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4540                 params->ssid);
4541         os_memcpy(drv->ssid, params->ssid, params->ssid_len);
4542         drv->ssid_len = params->ssid_len;
4543
4544         wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4545         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4546
4547         ret = nl80211_set_conn_keys(params, msg);
4548         if (ret)
4549                 goto nla_put_failure;
4550
4551         if (params->wpa_ie) {
4552                 wpa_hexdump(MSG_DEBUG,
4553                             "  * Extra IEs for Beacon/Probe Response frames",
4554                             params->wpa_ie, params->wpa_ie_len);
4555                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
4556                         params->wpa_ie);
4557         }
4558
4559         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4560         msg = NULL;
4561         if (ret) {
4562                 wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
4563                            ret, strerror(-ret));
4564                 count++;
4565                 if (ret == -EALREADY && count == 1) {
4566                         wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
4567                                    "forced leave");
4568                         nl80211_leave_ibss(drv);
4569                         nlmsg_free(msg);
4570                         goto retry;
4571                 }
4572
4573                 goto nla_put_failure;
4574         }
4575         ret = 0;
4576         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
4577
4578 nla_put_failure:
4579         nlmsg_free(msg);
4580         return ret;
4581 }
4582
4583
4584 static int wpa_driver_nl80211_connect(
4585         struct wpa_driver_nl80211_data *drv,
4586         struct wpa_driver_associate_params *params)
4587 {
4588         struct nl_msg *msg;
4589         enum nl80211_auth_type type;
4590         int ret = 0;
4591         int algs;
4592
4593         msg = nlmsg_alloc();
4594         if (!msg)
4595                 return -1;
4596
4597         wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
4598         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4599                     NL80211_CMD_CONNECT, 0);
4600
4601         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4602         if (params->bssid) {
4603                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4604                            MAC2STR(params->bssid));
4605                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4606         }
4607         if (params->freq) {
4608                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4609                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4610         }
4611         if (params->ssid) {
4612                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4613                                   params->ssid, params->ssid_len);
4614                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4615                         params->ssid);
4616                 if (params->ssid_len > sizeof(drv->ssid))
4617                         goto nla_put_failure;
4618                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
4619                 drv->ssid_len = params->ssid_len;
4620         }
4621         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
4622         if (params->wpa_ie)
4623                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
4624                         params->wpa_ie);
4625
4626         algs = 0;
4627         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
4628                 algs++;
4629         if (params->auth_alg & WPA_AUTH_ALG_SHARED)
4630                 algs++;
4631         if (params->auth_alg & WPA_AUTH_ALG_LEAP)
4632                 algs++;
4633         if (algs > 1) {
4634                 wpa_printf(MSG_DEBUG, "  * Leave out Auth Type for automatic "
4635                            "selection");
4636                 goto skip_auth_type;
4637         }
4638
4639         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
4640                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
4641         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
4642                 type = NL80211_AUTHTYPE_SHARED_KEY;
4643         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
4644                 type = NL80211_AUTHTYPE_NETWORK_EAP;
4645         else if (params->auth_alg & WPA_AUTH_ALG_FT)
4646                 type = NL80211_AUTHTYPE_FT;
4647         else
4648                 goto nla_put_failure;
4649
4650         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
4651         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
4652
4653 skip_auth_type:
4654         if (params->wpa_ie && params->wpa_ie_len) {
4655                 enum nl80211_wpa_versions ver;
4656
4657                 if (params->wpa_ie[0] == WLAN_EID_RSN)
4658                         ver = NL80211_WPA_VERSION_2;
4659                 else
4660                         ver = NL80211_WPA_VERSION_1;
4661
4662                 wpa_printf(MSG_DEBUG, "  * WPA Version %d", ver);
4663                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
4664         }
4665
4666         if (params->pairwise_suite != CIPHER_NONE) {
4667                 int cipher;
4668
4669                 switch (params->pairwise_suite) {
4670                 case CIPHER_WEP40:
4671                         cipher = WLAN_CIPHER_SUITE_WEP40;
4672                         break;
4673                 case CIPHER_WEP104:
4674                         cipher = WLAN_CIPHER_SUITE_WEP104;
4675                         break;
4676                 case CIPHER_CCMP:
4677                         cipher = WLAN_CIPHER_SUITE_CCMP;
4678                         break;
4679                 case CIPHER_TKIP:
4680                 default:
4681                         cipher = WLAN_CIPHER_SUITE_TKIP;
4682                         break;
4683                 }
4684                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
4685         }
4686
4687         if (params->group_suite != CIPHER_NONE) {
4688                 int cipher;
4689
4690                 switch (params->group_suite) {
4691                 case CIPHER_WEP40:
4692                         cipher = WLAN_CIPHER_SUITE_WEP40;
4693                         break;
4694                 case CIPHER_WEP104:
4695                         cipher = WLAN_CIPHER_SUITE_WEP104;
4696                         break;
4697                 case CIPHER_CCMP:
4698                         cipher = WLAN_CIPHER_SUITE_CCMP;
4699                         break;
4700                 case CIPHER_TKIP:
4701                 default:
4702                         cipher = WLAN_CIPHER_SUITE_TKIP;
4703                         break;
4704                 }
4705                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
4706         }
4707
4708         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
4709             params->key_mgmt_suite == KEY_MGMT_PSK) {
4710                 int mgmt = WLAN_AKM_SUITE_PSK;
4711
4712                 switch (params->key_mgmt_suite) {
4713                 case KEY_MGMT_802_1X:
4714                         mgmt = WLAN_AKM_SUITE_8021X;
4715                         break;
4716                 case KEY_MGMT_PSK:
4717                 default:
4718                         mgmt = WLAN_AKM_SUITE_PSK;
4719                         break;
4720                 }
4721                 NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
4722         }
4723
4724         ret = nl80211_set_conn_keys(params, msg);
4725         if (ret)
4726                 goto nla_put_failure;
4727
4728         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4729         msg = NULL;
4730         if (ret) {
4731                 wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
4732                            "(%s)", ret, strerror(-ret));
4733                 goto nla_put_failure;
4734         }
4735         ret = 0;
4736         wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
4737
4738 nla_put_failure:
4739         nlmsg_free(msg);
4740         return ret;
4741
4742 }
4743
4744
4745 static int wpa_driver_nl80211_associate(
4746         void *priv, struct wpa_driver_associate_params *params)
4747 {
4748         struct i802_bss *bss = priv;
4749         struct wpa_driver_nl80211_data *drv = bss->drv;
4750         int ret = -1;
4751         struct nl_msg *msg;
4752
4753         if (params->mode == IEEE80211_MODE_AP)
4754                 return wpa_driver_nl80211_ap(drv, params);
4755
4756         if (params->mode == IEEE80211_MODE_IBSS)
4757                 return wpa_driver_nl80211_ibss(drv, params);
4758
4759         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
4760                 if (wpa_driver_nl80211_set_mode(priv, params->mode) < 0)
4761                         return -1;
4762                 return wpa_driver_nl80211_connect(drv, params);
4763         }
4764
4765         drv->associated = 0;
4766
4767         msg = nlmsg_alloc();
4768         if (!msg)
4769                 return -1;
4770
4771         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
4772                    drv->ifindex);
4773         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
4774                     NL80211_CMD_ASSOCIATE, 0);
4775
4776         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4777         if (params->bssid) {
4778                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4779                            MAC2STR(params->bssid));
4780                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4781         }
4782         if (params->freq) {
4783                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4784                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4785                 drv->assoc_freq = params->freq;
4786         } else
4787                 drv->assoc_freq = 0;
4788         if (params->ssid) {
4789                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4790                                   params->ssid, params->ssid_len);
4791                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4792                         params->ssid);
4793                 if (params->ssid_len > sizeof(drv->ssid))
4794                         goto nla_put_failure;
4795                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
4796                 drv->ssid_len = params->ssid_len;
4797         }
4798         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
4799         if (params->wpa_ie)
4800                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
4801                         params->wpa_ie);
4802
4803         if (params->pairwise_suite != CIPHER_NONE) {
4804                 int cipher;
4805
4806                 switch (params->pairwise_suite) {
4807                 case CIPHER_WEP40:
4808                         cipher = WLAN_CIPHER_SUITE_WEP40;
4809                         break;
4810                 case CIPHER_WEP104:
4811                         cipher = WLAN_CIPHER_SUITE_WEP104;
4812                         break;
4813                 case CIPHER_CCMP:
4814                         cipher = WLAN_CIPHER_SUITE_CCMP;
4815                         break;
4816                 case CIPHER_TKIP:
4817                 default:
4818                         cipher = WLAN_CIPHER_SUITE_TKIP;
4819                         break;
4820                 }
4821                 wpa_printf(MSG_DEBUG, "  * pairwise=0x%x", cipher);
4822                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
4823         }
4824
4825         if (params->group_suite != CIPHER_NONE) {
4826                 int cipher;
4827
4828                 switch (params->group_suite) {
4829                 case CIPHER_WEP40:
4830                         cipher = WLAN_CIPHER_SUITE_WEP40;
4831                         break;
4832                 case CIPHER_WEP104:
4833                         cipher = WLAN_CIPHER_SUITE_WEP104;
4834                         break;
4835                 case CIPHER_CCMP:
4836                         cipher = WLAN_CIPHER_SUITE_CCMP;
4837                         break;
4838                 case CIPHER_TKIP:
4839                 default:
4840                         cipher = WLAN_CIPHER_SUITE_TKIP;
4841                         break;
4842                 }
4843                 wpa_printf(MSG_DEBUG, "  * group=0x%x", cipher);
4844                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
4845         }
4846
4847 #ifdef CONFIG_IEEE80211W
4848         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
4849                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
4850 #endif /* CONFIG_IEEE80211W */
4851
4852         NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
4853
4854         if (params->prev_bssid) {
4855                 wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
4856                            MAC2STR(params->prev_bssid));
4857                 NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
4858                         params->prev_bssid);
4859         }
4860
4861         if (params->p2p)
4862                 wpa_printf(MSG_DEBUG, "  * P2P group");
4863
4864         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4865         msg = NULL;
4866         if (ret) {
4867                 wpa_printf(MSG_DEBUG, "nl80211: MLME command failed: ret=%d "
4868                            "(%s)", ret, strerror(-ret));
4869                 nl80211_dump_scan(drv);
4870                 goto nla_put_failure;
4871         }
4872         ret = 0;
4873         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
4874                    "successfully");
4875
4876 nla_put_failure:
4877         nlmsg_free(msg);
4878         return ret;
4879 }
4880
4881
4882 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
4883                             int ifindex, int mode)
4884 {
4885         struct nl_msg *msg;
4886         int ret = -ENOBUFS;
4887
4888         msg = nlmsg_alloc();
4889         if (!msg)
4890                 return -ENOMEM;
4891
4892         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
4893                     0, NL80211_CMD_SET_INTERFACE, 0);
4894         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4895         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
4896
4897         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4898         if (!ret)
4899                 return 0;
4900 nla_put_failure:
4901         wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
4902                    " %d (%s)", ifindex, mode, ret, strerror(-ret));
4903         return ret;
4904 }
4905
4906
4907 static int wpa_driver_nl80211_set_mode(void *priv, int mode)
4908 {
4909         struct i802_bss *bss = priv;
4910         struct wpa_driver_nl80211_data *drv = bss->drv;
4911         int ret = -1;
4912         int nlmode;
4913         int i;
4914
4915         switch (mode) {
4916         case 0:
4917                 nlmode = NL80211_IFTYPE_STATION;
4918                 break;
4919         case 1:
4920                 nlmode = NL80211_IFTYPE_ADHOC;
4921                 break;
4922         case 2:
4923                 nlmode = NL80211_IFTYPE_AP;
4924                 break;
4925         default:
4926                 return -1;
4927         }
4928
4929         if (nl80211_set_mode(drv, drv->ifindex, nlmode) == 0) {
4930                 drv->nlmode = nlmode;
4931                 ret = 0;
4932                 goto done;
4933         }
4934
4935         if (nlmode == drv->nlmode) {
4936                 wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
4937                            "requested mode - ignore error");
4938                 ret = 0;
4939                 goto done; /* Already in the requested mode */
4940         }
4941
4942         /* mac80211 doesn't allow mode changes while the device is up, so
4943          * take the device down, try to set the mode again, and bring the
4944          * device back up.
4945          */
4946         wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
4947                    "interface down");
4948         for (i = 0; i < 10; i++) {
4949                 if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 0) ==
4950                     0) {
4951                         /* Try to set the mode again while the interface is
4952                          * down */
4953                         ret = nl80211_set_mode(drv, drv->ifindex, nlmode);
4954                         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname,
4955                                                   1))
4956                                 ret = -1;
4957                         if (!ret)
4958                                 break;
4959                 } else
4960                         wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
4961                                    "interface down");
4962                 os_sleep(0, 100000);
4963         }
4964
4965         if (!ret) {
4966                 wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
4967                            "interface is down");
4968                 drv->nlmode = nlmode;
4969         }
4970
4971 done:
4972         if (!ret && nlmode == NL80211_IFTYPE_AP) {
4973                 /* Setup additional AP mode functionality if needed */
4974                 if (drv->monitor_ifidx < 0 &&
4975                     nl80211_create_monitor_interface(drv))
4976                         return -1;
4977         } else if (!ret && nlmode != NL80211_IFTYPE_AP) {
4978                 /* Remove additional AP mode functionality */
4979                 nl80211_remove_monitor_interface(drv);
4980                 bss->beacon_set = 0;
4981         }
4982
4983         if (ret)
4984                 wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
4985                            "from %d failed", nlmode, drv->nlmode);
4986
4987         return ret;
4988 }
4989
4990
4991 static int wpa_driver_nl80211_get_capa(void *priv,
4992                                        struct wpa_driver_capa *capa)
4993 {
4994         struct i802_bss *bss = priv;
4995         struct wpa_driver_nl80211_data *drv = bss->drv;
4996         if (!drv->has_capability)
4997                 return -1;
4998         os_memcpy(capa, &drv->capa, sizeof(*capa));
4999         return 0;
5000 }
5001
5002
5003 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
5004 {
5005         struct i802_bss *bss = priv;
5006         struct wpa_driver_nl80211_data *drv = bss->drv;
5007
5008         wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
5009                    __func__, drv->operstate, state, state ? "UP" : "DORMANT");
5010         drv->operstate = state;
5011         return netlink_send_oper_ifla(drv->netlink, drv->ifindex, -1,
5012                                       state ? IF_OPER_UP : IF_OPER_DORMANT);
5013 }
5014
5015
5016 static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
5017 {
5018         struct i802_bss *bss = priv;
5019         struct wpa_driver_nl80211_data *drv = bss->drv;
5020         struct nl_msg *msg;
5021         struct nl80211_sta_flag_update upd;
5022
5023         msg = nlmsg_alloc();
5024         if (!msg)
5025                 return -ENOMEM;
5026
5027         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5028                     0, NL80211_CMD_SET_STATION, 0);
5029
5030         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5031                     if_nametoindex(bss->ifname));
5032         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
5033
5034         os_memset(&upd, 0, sizeof(upd));
5035         upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
5036         if (authorized)
5037                 upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
5038         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
5039
5040         return send_and_recv_msgs(drv, msg, NULL, NULL);
5041  nla_put_failure:
5042         return -ENOBUFS;
5043 }
5044
5045
5046 #ifdef HOSTAPD
5047
5048 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
5049 {
5050         int i;
5051         int *old;
5052
5053         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
5054                    ifidx);
5055         for (i = 0; i < drv->num_if_indices; i++) {
5056                 if (drv->if_indices[i] == 0) {
5057                         drv->if_indices[i] = ifidx;
5058                         return;
5059                 }
5060         }
5061
5062         if (drv->if_indices != drv->default_if_indices)
5063                 old = drv->if_indices;
5064         else
5065                 old = NULL;
5066
5067         drv->if_indices = os_realloc(old,
5068                                      sizeof(int) * (drv->num_if_indices + 1));
5069         if (!drv->if_indices) {
5070                 if (!old)
5071                         drv->if_indices = drv->default_if_indices;
5072                 else
5073                         drv->if_indices = old;
5074                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
5075                            "interfaces");
5076                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
5077                 return;
5078         } else if (!old)
5079                 os_memcpy(drv->if_indices, drv->default_if_indices,
5080                           sizeof(drv->default_if_indices));
5081         drv->if_indices[drv->num_if_indices] = ifidx;
5082         drv->num_if_indices++;
5083 }
5084
5085
5086 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
5087 {
5088         int i;
5089
5090         for (i = 0; i < drv->num_if_indices; i++) {
5091                 if (drv->if_indices[i] == ifidx) {
5092                         drv->if_indices[i] = 0;
5093                         break;
5094                 }
5095         }
5096 }
5097
5098
5099 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
5100 {
5101         int i;
5102
5103         for (i = 0; i < drv->num_if_indices; i++)
5104                 if (drv->if_indices[i] == ifidx)
5105                         return 1;
5106
5107         return 0;
5108 }
5109
5110
5111 static inline int min_int(int a, int b)
5112 {
5113         if (a < b)
5114                 return a;
5115         return b;
5116 }
5117
5118
5119 static int get_key_handler(struct nl_msg *msg, void *arg)
5120 {
5121         struct nlattr *tb[NL80211_ATTR_MAX + 1];
5122         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5123
5124         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5125                   genlmsg_attrlen(gnlh, 0), NULL);
5126
5127         /*
5128          * TODO: validate the key index and mac address!
5129          * Otherwise, there's a race condition as soon as
5130          * the kernel starts sending key notifications.
5131          */
5132
5133         if (tb[NL80211_ATTR_KEY_SEQ])
5134                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
5135                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
5136         return NL_SKIP;
5137 }
5138
5139
5140 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
5141                            int idx, u8 *seq)
5142 {
5143         struct i802_bss *bss = priv;
5144         struct wpa_driver_nl80211_data *drv = bss->drv;
5145         struct nl_msg *msg;
5146
5147         msg = nlmsg_alloc();
5148         if (!msg)
5149                 return -ENOMEM;
5150
5151         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5152                     0, NL80211_CMD_GET_KEY, 0);
5153
5154         if (addr)
5155                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5156         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
5157         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
5158
5159         memset(seq, 0, 6);
5160
5161         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
5162  nla_put_failure:
5163         return -ENOBUFS;
5164 }
5165
5166 #endif /* HOSTAPD */
5167
5168 #if defined(HOSTAPD) || defined(CONFIG_AP)
5169
5170 static int i802_set_rate_sets(void *priv, int *supp_rates, int *basic_rates,
5171                               int mode)
5172 {
5173         struct i802_bss *bss = priv;
5174         struct wpa_driver_nl80211_data *drv = bss->drv;
5175         struct nl_msg *msg;
5176         u8 rates[NL80211_MAX_SUPP_RATES];
5177         u8 rates_len = 0;
5178         int i;
5179
5180         msg = nlmsg_alloc();
5181         if (!msg)
5182                 return -ENOMEM;
5183
5184         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5185                     NL80211_CMD_SET_BSS, 0);
5186
5187         for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0; i++)
5188                 rates[rates_len++] = basic_rates[i] / 5;
5189
5190         NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
5191
5192         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5193
5194         return send_and_recv_msgs(drv, msg, NULL, NULL);
5195  nla_put_failure:
5196         return -ENOBUFS;
5197 }
5198
5199 #endif /* HOSTAPD || CONFIG_AP */
5200
5201
5202 /* Set kernel driver on given frequency (MHz) */
5203 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
5204 {
5205         struct i802_bss *bss = priv;
5206         struct wpa_driver_nl80211_data *drv = bss->drv;
5207         return wpa_driver_nl80211_set_freq(drv, freq->freq, freq->ht_enabled,
5208                                            freq->sec_channel_offset);
5209 }
5210
5211
5212 #ifdef HOSTAPD
5213
5214 static int i802_set_rts(void *priv, int rts)
5215 {
5216         struct i802_bss *bss = priv;
5217         struct wpa_driver_nl80211_data *drv = bss->drv;
5218         struct nl_msg *msg;
5219         int ret = -ENOBUFS;
5220         u32 val;
5221
5222         msg = nlmsg_alloc();
5223         if (!msg)
5224                 return -ENOMEM;
5225
5226         if (rts >= 2347)
5227                 val = (u32) -1;
5228         else
5229                 val = rts;
5230
5231         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5232                     0, NL80211_CMD_SET_WIPHY, 0);
5233         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5234         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
5235
5236         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5237         if (!ret)
5238                 return 0;
5239 nla_put_failure:
5240         wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
5241                    "%d (%s)", rts, ret, strerror(-ret));
5242         return ret;
5243 }
5244
5245
5246 static int i802_set_frag(void *priv, int frag)
5247 {
5248         struct i802_bss *bss = priv;
5249         struct wpa_driver_nl80211_data *drv = bss->drv;
5250         struct nl_msg *msg;
5251         int ret = -ENOBUFS;
5252         u32 val;
5253
5254         msg = nlmsg_alloc();
5255         if (!msg)
5256                 return -ENOMEM;
5257
5258         if (frag >= 2346)
5259                 val = (u32) -1;
5260         else
5261                 val = frag;
5262
5263         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5264                     0, NL80211_CMD_SET_WIPHY, 0);
5265         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5266         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
5267
5268         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5269         if (!ret)
5270                 return 0;
5271 nla_put_failure:
5272         wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
5273                    "%d: %d (%s)", frag, ret, strerror(-ret));
5274         return ret;
5275 }
5276
5277
5278 static int i802_flush(void *priv)
5279 {
5280         struct i802_bss *bss = priv;
5281         struct wpa_driver_nl80211_data *drv = bss->drv;
5282         struct nl_msg *msg;
5283
5284         msg = nlmsg_alloc();
5285         if (!msg)
5286                 return -1;
5287
5288         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5289                     0, NL80211_CMD_DEL_STATION, 0);
5290
5291         /*
5292          * XXX: FIX! this needs to flush all VLANs too
5293          */
5294         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5295                     if_nametoindex(bss->ifname));
5296
5297         return send_and_recv_msgs(drv, msg, NULL, NULL);
5298  nla_put_failure:
5299         return -ENOBUFS;
5300 }
5301
5302
5303 static int get_sta_handler(struct nl_msg *msg, void *arg)
5304 {
5305         struct nlattr *tb[NL80211_ATTR_MAX + 1];
5306         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5307         struct hostap_sta_driver_data *data = arg;
5308         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
5309         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
5310                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
5311                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
5312                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
5313                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
5314                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
5315         };
5316
5317         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5318                   genlmsg_attrlen(gnlh, 0), NULL);
5319
5320         /*
5321          * TODO: validate the interface and mac address!
5322          * Otherwise, there's a race condition as soon as
5323          * the kernel starts sending station notifications.
5324          */
5325
5326         if (!tb[NL80211_ATTR_STA_INFO]) {
5327                 wpa_printf(MSG_DEBUG, "sta stats missing!");
5328                 return NL_SKIP;
5329         }
5330         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
5331                              tb[NL80211_ATTR_STA_INFO],
5332                              stats_policy)) {
5333                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
5334                 return NL_SKIP;
5335         }
5336
5337         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
5338                 data->inactive_msec =
5339                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
5340         if (stats[NL80211_STA_INFO_RX_BYTES])
5341                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
5342         if (stats[NL80211_STA_INFO_TX_BYTES])
5343                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
5344         if (stats[NL80211_STA_INFO_RX_PACKETS])
5345                 data->rx_packets =
5346                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
5347         if (stats[NL80211_STA_INFO_TX_PACKETS])
5348                 data->tx_packets =
5349                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
5350
5351         return NL_SKIP;
5352 }
5353
5354 static int i802_read_sta_data(void *priv, struct hostap_sta_driver_data *data,
5355                               const u8 *addr)
5356 {
5357         struct i802_bss *bss = priv;
5358         struct wpa_driver_nl80211_data *drv = bss->drv;
5359         struct nl_msg *msg;
5360
5361         os_memset(data, 0, sizeof(*data));
5362         msg = nlmsg_alloc();
5363         if (!msg)
5364                 return -ENOMEM;
5365
5366         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5367                     0, NL80211_CMD_GET_STATION, 0);
5368
5369         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5370         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5371
5372         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
5373  nla_put_failure:
5374         return -ENOBUFS;
5375 }
5376
5377
5378 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
5379                                     int cw_min, int cw_max, int burst_time)
5380 {
5381         struct i802_bss *bss = priv;
5382         struct wpa_driver_nl80211_data *drv = bss->drv;
5383         struct nl_msg *msg;
5384         struct nlattr *txq, *params;
5385
5386         msg = nlmsg_alloc();
5387         if (!msg)
5388                 return -1;
5389
5390         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5391                     0, NL80211_CMD_SET_WIPHY, 0);
5392
5393         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5394
5395         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
5396         if (!txq)
5397                 goto nla_put_failure;
5398
5399         /* We are only sending parameters for a single TXQ at a time */
5400         params = nla_nest_start(msg, 1);
5401         if (!params)
5402                 goto nla_put_failure;
5403
5404         switch (queue) {
5405         case 0:
5406                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
5407                 break;
5408         case 1:
5409                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
5410                 break;
5411         case 2:
5412                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
5413                 break;
5414         case 3:
5415                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
5416                 break;
5417         }
5418         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
5419          * 32 usec, so need to convert the value here. */
5420         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
5421         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
5422         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
5423         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
5424
5425         nla_nest_end(msg, params);
5426
5427         nla_nest_end(msg, txq);
5428
5429         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
5430                 return 0;
5431  nla_put_failure:
5432         return -1;
5433 }
5434
5435
5436 static int i802_set_bss(void *priv, int cts, int preamble, int slot,
5437                         int ht_opmode)
5438 {
5439         struct i802_bss *bss = priv;
5440         struct wpa_driver_nl80211_data *drv = bss->drv;
5441         struct nl_msg *msg;
5442
5443         msg = nlmsg_alloc();
5444         if (!msg)
5445                 return -ENOMEM;
5446
5447         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
5448                     NL80211_CMD_SET_BSS, 0);
5449
5450         if (cts >= 0)
5451                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
5452         if (preamble >= 0)
5453                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
5454         if (slot >= 0)
5455                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
5456         if (ht_opmode >= 0)
5457                 NLA_PUT_U16(msg, NL80211_ATTR_BSS_HT_OPMODE, ht_opmode);
5458         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5459
5460         return send_and_recv_msgs(drv, msg, NULL, NULL);
5461  nla_put_failure:
5462         return -ENOBUFS;
5463 }
5464
5465
5466 static int i802_set_cts_protect(void *priv, int value)
5467 {
5468         return i802_set_bss(priv, value, -1, -1, -1);
5469 }
5470
5471
5472 static int i802_set_preamble(void *priv, int value)
5473 {
5474         return i802_set_bss(priv, -1, value, -1, -1);
5475 }
5476
5477
5478 static int i802_set_short_slot_time(void *priv, int value)
5479 {
5480         return i802_set_bss(priv, -1, -1, value, -1);
5481 }
5482
5483
5484 static int i802_set_sta_vlan(void *priv, const u8 *addr,
5485                              const char *ifname, int vlan_id)
5486 {
5487         struct i802_bss *bss = priv;
5488         struct wpa_driver_nl80211_data *drv = bss->drv;
5489         struct nl_msg *msg;
5490         int ret = -ENOBUFS;
5491
5492         msg = nlmsg_alloc();
5493         if (!msg)
5494                 return -ENOMEM;
5495
5496         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
5497                     0, NL80211_CMD_SET_STATION, 0);
5498
5499         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
5500                     if_nametoindex(bss->ifname));
5501         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
5502         NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
5503                     if_nametoindex(ifname));
5504
5505         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5506         if (ret < 0) {
5507                 wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
5508                            MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
5509                            MAC2STR(addr), ifname, vlan_id, ret,
5510                            strerror(-ret));
5511         }
5512  nla_put_failure:
5513         return ret;
5514 }
5515
5516
5517 static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
5518                             const char *bridge_ifname)
5519 {
5520         struct i802_bss *bss = priv;
5521         struct wpa_driver_nl80211_data *drv = bss->drv;
5522         char name[IFNAMSIZ + 1];
5523
5524         os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
5525         wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
5526                    " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
5527         if (val) {
5528                 if (!if_nametoindex(name)) {
5529                         if (nl80211_create_iface(drv, name,
5530                                                  NL80211_IFTYPE_AP_VLAN,
5531                                                  NULL, 1) < 0)
5532                                 return -1;
5533                         if (bridge_ifname &&
5534                             linux_br_add_if(drv->ioctl_sock, bridge_ifname,
5535                                             name) < 0)
5536                                 return -1;
5537                 }
5538                 linux_set_iface_flags(drv->ioctl_sock, name, 1);
5539                 return i802_set_sta_vlan(priv, addr, name, 0);
5540         } else {
5541                 i802_set_sta_vlan(priv, addr, bss->ifname, 0);
5542                 return wpa_driver_nl80211_if_remove(priv, WPA_IF_AP_VLAN,
5543                                                     name);
5544         }
5545 }
5546
5547
5548 static int i802_set_ht_params(void *priv, const u8 *ht_capab,
5549                               size_t ht_capab_len, const u8 *ht_oper,
5550                               size_t ht_oper_len)
5551 {
5552         if (ht_oper_len >= 6) {
5553                 /* ht opmode uses 16bit in octet 5 & 6 */
5554                 u16 ht_opmode = le_to_host16(((u16 *) ht_oper)[2]);
5555                 return i802_set_bss(priv, -1, -1, -1, ht_opmode);
5556         } else
5557                 return -1;
5558 }
5559
5560
5561 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
5562 {
5563         struct wpa_driver_nl80211_data *drv = eloop_ctx;
5564         struct sockaddr_ll lladdr;
5565         unsigned char buf[3000];
5566         int len;
5567         socklen_t fromlen = sizeof(lladdr);
5568
5569         len = recvfrom(sock, buf, sizeof(buf), 0,
5570                        (struct sockaddr *)&lladdr, &fromlen);
5571         if (len < 0) {
5572                 perror("recv");
5573                 return;
5574         }
5575
5576         if (have_ifidx(drv, lladdr.sll_ifindex))
5577                 drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
5578 }
5579
5580
5581 static int i802_get_inact_sec(void *priv, const u8 *addr)
5582 {
5583         struct hostap_sta_driver_data data;
5584         int ret;
5585
5586         data.inactive_msec = (unsigned long) -1;
5587         ret = i802_read_sta_data(priv, &data, addr);
5588         if (ret || data.inactive_msec == (unsigned long) -1)
5589                 return -1;
5590         return data.inactive_msec / 1000;
5591 }
5592
5593
5594 static int i802_sta_clear_stats(void *priv, const u8 *addr)
5595 {
5596 #if 0
5597         /* TODO */
5598 #endif
5599         return 0;
5600 }
5601
5602 #endif /* HOSTAPD */
5603
5604 #if defined(HOSTAPD) || defined(CONFIG_AP)
5605
5606 static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
5607                            int reason)
5608 {
5609         struct i802_bss *bss = priv;
5610         struct ieee80211_mgmt mgmt;
5611
5612         memset(&mgmt, 0, sizeof(mgmt));
5613         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
5614                                           WLAN_FC_STYPE_DEAUTH);
5615         memcpy(mgmt.da, addr, ETH_ALEN);
5616         memcpy(mgmt.sa, own_addr, ETH_ALEN);
5617         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
5618         mgmt.u.deauth.reason_code = host_to_le16(reason);
5619         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
5620                                             IEEE80211_HDRLEN +
5621                                             sizeof(mgmt.u.deauth));
5622 }
5623
5624
5625 static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
5626                              int reason)
5627 {
5628         struct i802_bss *bss = priv;
5629         struct ieee80211_mgmt mgmt;
5630
5631         memset(&mgmt, 0, sizeof(mgmt));
5632         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
5633                                           WLAN_FC_STYPE_DISASSOC);
5634         memcpy(mgmt.da, addr, ETH_ALEN);
5635         memcpy(mgmt.sa, own_addr, ETH_ALEN);
5636         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
5637         mgmt.u.disassoc.reason_code = host_to_le16(reason);
5638         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
5639                                             IEEE80211_HDRLEN +
5640                                             sizeof(mgmt.u.disassoc));
5641 }
5642
5643 #endif /* HOSTAPD || CONFIG_AP */
5644
5645 #ifdef HOSTAPD
5646
5647 static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
5648                              struct i802_bss *bss,
5649                              const char *brname, const char *ifname)
5650 {
5651         int ifindex;
5652         char in_br[IFNAMSIZ];
5653
5654         os_strlcpy(bss->brname, brname, IFNAMSIZ);
5655         ifindex = if_nametoindex(brname);
5656         if (ifindex == 0) {
5657                 /*
5658                  * Bridge was configured, but the bridge device does
5659                  * not exist. Try to add it now.
5660                  */
5661                 if (linux_br_add(drv->ioctl_sock, brname) < 0) {
5662                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
5663                                    "bridge interface %s: %s",
5664                                    brname, strerror(errno));
5665                         return -1;
5666                 }
5667                 bss->added_bridge = 1;
5668                 add_ifidx(drv, if_nametoindex(brname));
5669         }
5670
5671         if (linux_br_get(in_br, ifname) == 0) {
5672                 if (os_strcmp(in_br, brname) == 0)
5673                         return 0; /* already in the bridge */
5674
5675                 wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
5676                            "bridge %s", ifname, in_br);
5677                 if (linux_br_del_if(drv->ioctl_sock, in_br, ifname) < 0) {
5678                         wpa_printf(MSG_ERROR, "nl80211: Failed to "
5679                                    "remove interface %s from bridge "
5680                                    "%s: %s",
5681                                    ifname, brname, strerror(errno));
5682                         return -1;
5683                 }
5684         }
5685
5686         wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
5687                    ifname, brname);
5688         if (linux_br_add_if(drv->ioctl_sock, brname, ifname) < 0) {
5689                 wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
5690                            "into bridge %s: %s",
5691                            ifname, brname, strerror(errno));
5692                 return -1;
5693         }
5694         bss->added_if_into_bridge = 1;
5695
5696         return 0;
5697 }
5698
5699
5700 static void *i802_init(struct hostapd_data *hapd,
5701                        struct wpa_init_params *params)
5702 {
5703         struct wpa_driver_nl80211_data *drv;
5704         struct i802_bss *bss;
5705         size_t i;
5706         char brname[IFNAMSIZ];
5707         int ifindex, br_ifindex;
5708         int br_added = 0;
5709
5710         bss = wpa_driver_nl80211_init(hapd, params->ifname, NULL);
5711         if (bss == NULL)
5712                 return NULL;
5713
5714         drv = bss->drv;
5715         drv->nlmode = NL80211_IFTYPE_AP;
5716         if (linux_br_get(brname, params->ifname) == 0) {
5717                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
5718                            params->ifname, brname);
5719                 br_ifindex = if_nametoindex(brname);
5720         } else {
5721                 brname[0] = '\0';
5722                 br_ifindex = 0;
5723         }
5724
5725         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
5726         drv->if_indices = drv->default_if_indices;
5727         for (i = 0; i < params->num_bridge; i++) {
5728                 if (params->bridge[i]) {
5729                         ifindex = if_nametoindex(params->bridge[i]);
5730                         if (ifindex)
5731                                 add_ifidx(drv, ifindex);
5732                         if (ifindex == br_ifindex)
5733                                 br_added = 1;
5734                 }
5735         }
5736         if (!br_added && br_ifindex &&
5737             (params->num_bridge == 0 || !params->bridge[0]))
5738                 add_ifidx(drv, br_ifindex);
5739
5740         /* start listening for EAPOL on the default AP interface */
5741         add_ifidx(drv, drv->ifindex);
5742
5743         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 0))
5744                 goto failed;
5745
5746         if (params->bssid) {
5747                 if (linux_set_ifhwaddr(drv->ioctl_sock, bss->ifname,
5748                                        params->bssid))
5749                         goto failed;
5750         }
5751
5752         if (wpa_driver_nl80211_set_mode(bss, IEEE80211_MODE_AP)) {
5753                 wpa_printf(MSG_ERROR, "nl80211: Failed to set interface %s "
5754                            "into AP mode", bss->ifname);
5755                 goto failed;
5756         }
5757
5758         if (params->num_bridge && params->bridge[0] &&
5759             i802_check_bridge(drv, bss, params->bridge[0], params->ifname) < 0)
5760                 goto failed;
5761
5762         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 1))
5763                 goto failed;
5764
5765         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
5766         if (drv->eapol_sock < 0) {
5767                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
5768                 goto failed;
5769         }
5770
5771         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
5772         {
5773                 printf("Could not register read socket for eapol\n");
5774                 goto failed;
5775         }
5776
5777         if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, params->own_addr))
5778                 goto failed;
5779
5780         return bss;
5781
5782 failed:
5783         nl80211_remove_monitor_interface(drv);
5784         rfkill_deinit(drv->rfkill);
5785         netlink_deinit(drv->netlink);
5786         if (drv->ioctl_sock >= 0)
5787                 close(drv->ioctl_sock);
5788
5789         genl_family_put(drv->nl80211);
5790         nl_cache_free(drv->nl_cache);
5791         nl80211_handle_destroy(drv->nl_handle);
5792         nl_cb_put(drv->nl_cb);
5793         eloop_unregister_read_sock(nl_socket_get_fd(drv->nl_handle_event));
5794
5795         os_free(drv);
5796         return NULL;
5797 }
5798
5799
5800 static void i802_deinit(void *priv)
5801 {
5802         wpa_driver_nl80211_deinit(priv);
5803 }
5804
5805 #endif /* HOSTAPD */
5806
5807
5808 static enum nl80211_iftype wpa_driver_nl80211_if_type(
5809         enum wpa_driver_if_type type)
5810 {
5811         switch (type) {
5812         case WPA_IF_STATION:
5813                 return NL80211_IFTYPE_STATION;
5814         case WPA_IF_P2P_CLIENT:
5815         case WPA_IF_P2P_GROUP:
5816                 return NL80211_IFTYPE_P2P_CLIENT;
5817         case WPA_IF_AP_VLAN:
5818                 return NL80211_IFTYPE_AP_VLAN;
5819         case WPA_IF_AP_BSS:
5820                 return NL80211_IFTYPE_AP;
5821         case WPA_IF_P2P_GO:
5822                 return NL80211_IFTYPE_P2P_GO;
5823         }
5824         return -1;
5825 }
5826
5827
5828 #ifdef CONFIG_P2P
5829
5830 static int nl80211_addr_in_use(struct nl80211_global *global, const u8 *addr)
5831 {
5832         struct wpa_driver_nl80211_data *drv;
5833         dl_list_for_each(drv, &global->interfaces,
5834                          struct wpa_driver_nl80211_data, list) {
5835                 if (os_memcmp(addr, drv->addr, ETH_ALEN) == 0)
5836                         return 1;
5837         }
5838         return 0;
5839 }
5840
5841
5842 static int nl80211_p2p_interface_addr(struct wpa_driver_nl80211_data *drv,
5843                                       u8 *new_addr)
5844 {
5845         unsigned int idx;
5846
5847         if (!drv->global)
5848                 return -1;
5849
5850         os_memcpy(new_addr, drv->addr, ETH_ALEN);
5851         for (idx = 0; idx < 64; idx++) {
5852                 new_addr[0] = drv->addr[0] | 0x02;
5853                 new_addr[0] ^= idx << 2;
5854                 if (!nl80211_addr_in_use(drv->global, new_addr))
5855                         break;
5856         }
5857         if (idx == 64)
5858                 return -1;
5859
5860         wpa_printf(MSG_DEBUG, "nl80211: Assigned new P2P Interface Address "
5861                    MACSTR, MAC2STR(new_addr));
5862
5863         return 0;
5864 }
5865
5866 #endif /* CONFIG_P2P */
5867
5868
5869 static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
5870                                      const char *ifname, const u8 *addr,
5871                                      void *bss_ctx, void **drv_priv,
5872                                      char *force_ifname, u8 *if_addr,
5873                                      const char *bridge)
5874 {
5875         struct i802_bss *bss = priv;
5876         struct wpa_driver_nl80211_data *drv = bss->drv;
5877         int ifidx;
5878 #ifdef HOSTAPD
5879         struct i802_bss *new_bss = NULL;
5880
5881         if (type == WPA_IF_AP_BSS) {
5882                 new_bss = os_zalloc(sizeof(*new_bss));
5883                 if (new_bss == NULL)
5884                         return -1;
5885         }
5886 #endif /* HOSTAPD */
5887
5888         if (addr)
5889                 os_memcpy(if_addr, addr, ETH_ALEN);
5890         ifidx = nl80211_create_iface(drv, ifname,
5891                                      wpa_driver_nl80211_if_type(type), addr,
5892                                      0);
5893         if (ifidx < 0) {
5894 #ifdef HOSTAPD
5895                 os_free(new_bss);
5896 #endif /* HOSTAPD */
5897                 return -1;
5898         }
5899
5900         if (!addr &&
5901             linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, if_addr) < 0) {
5902                 nl80211_remove_iface(drv, ifidx);
5903                 return -1;
5904         }
5905
5906 #ifdef CONFIG_P2P
5907         if (!addr &&
5908             (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
5909              type == WPA_IF_P2P_GO)) {
5910                 /* Enforce unique P2P Interface Address */
5911                 u8 new_addr[ETH_ALEN], own_addr[ETH_ALEN];
5912
5913                 if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, own_addr)
5914                     < 0 ||
5915                     linux_get_ifhwaddr(drv->ioctl_sock, ifname, new_addr) < 0)
5916                 {
5917                         nl80211_remove_iface(drv, ifidx);
5918                         return -1;
5919                 }
5920                 if (os_memcmp(own_addr, new_addr, ETH_ALEN) == 0) {
5921                         wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
5922                                    "for P2P group interface");
5923                         if (nl80211_p2p_interface_addr(drv, new_addr) < 0) {
5924                                 nl80211_remove_iface(drv, ifidx);
5925                                 return -1;
5926                         }
5927                         if (linux_set_ifhwaddr(drv->ioctl_sock, ifname,
5928                                                new_addr) < 0) {
5929                                 nl80211_remove_iface(drv, ifidx);
5930                                 return -1;
5931                         }
5932                         os_memcpy(if_addr, new_addr, ETH_ALEN);
5933                 }
5934         }
5935 #endif /* CONFIG_P2P */
5936
5937 #ifdef HOSTAPD
5938         if (bridge &&
5939             i802_check_bridge(drv, new_bss, bridge, ifname) < 0) {
5940                 wpa_printf(MSG_ERROR, "nl80211: Failed to add the new "
5941                            "interface %s to a bridge %s", ifname, bridge);
5942                 nl80211_remove_iface(drv, ifidx);
5943                 os_free(new_bss);
5944                 return -1;
5945         }
5946
5947         if (type == WPA_IF_AP_BSS) {
5948                 if (linux_set_iface_flags(drv->ioctl_sock, ifname, 1)) {
5949                         nl80211_remove_iface(drv, ifidx);
5950                         os_free(new_bss);
5951                         return -1;
5952                 }
5953                 os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
5954                 new_bss->ifindex = ifidx;
5955                 new_bss->drv = drv;
5956                 new_bss->next = drv->first_bss.next;
5957                 drv->first_bss.next = new_bss;
5958                 if (drv_priv)
5959                         *drv_priv = new_bss;
5960         }
5961 #endif /* HOSTAPD */
5962
5963         return 0;
5964 }
5965
5966
5967 static int wpa_driver_nl80211_if_remove(void *priv,
5968                                         enum wpa_driver_if_type type,
5969                                         const char *ifname)
5970 {
5971         struct i802_bss *bss = priv;
5972         struct wpa_driver_nl80211_data *drv = bss->drv;
5973         int ifindex = if_nametoindex(ifname);
5974
5975         wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d",
5976                    __func__, type, ifname, ifindex);
5977         if (ifindex <= 0)
5978                 return -1;
5979
5980 #ifdef HOSTAPD
5981         if (bss->added_if_into_bridge) {
5982                 if (linux_br_del_if(drv->ioctl_sock, bss->brname, bss->ifname)
5983                     < 0)
5984                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
5985                                    "interface %s from bridge %s: %s",
5986                                    bss->ifname, bss->brname, strerror(errno));
5987         }
5988         if (bss->added_bridge) {
5989                 if (linux_br_del(drv->ioctl_sock, bss->brname) < 0)
5990                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
5991                                    "bridge %s: %s",
5992                                    bss->brname, strerror(errno));
5993         }
5994 #endif /* HOSTAPD */
5995
5996         nl80211_remove_iface(drv, ifindex);
5997
5998 #ifdef HOSTAPD
5999         if (type != WPA_IF_AP_BSS)
6000                 return 0;
6001
6002         if (bss != &drv->first_bss) {
6003                 struct i802_bss *tbss;
6004
6005                 for (tbss = &drv->first_bss; tbss; tbss = tbss->next) {
6006                         if (tbss->next == bss) {
6007                                 tbss->next = bss->next;
6008                                 os_free(bss);
6009                                 bss = NULL;
6010                                 break;
6011                         }
6012                 }
6013                 if (bss)
6014                         wpa_printf(MSG_INFO, "nl80211: %s - could not find "
6015                                    "BSS %p in the list", __func__, bss);
6016         }
6017 #endif /* HOSTAPD */
6018
6019         return 0;
6020 }
6021
6022
6023 static int cookie_handler(struct nl_msg *msg, void *arg)
6024 {
6025         struct nlattr *tb[NL80211_ATTR_MAX + 1];
6026         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
6027         u64 *cookie = arg;
6028         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
6029                   genlmsg_attrlen(gnlh, 0), NULL);
6030         if (tb[NL80211_ATTR_COOKIE])
6031                 *cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
6032         return NL_SKIP;
6033 }
6034
6035
6036 static int nl80211_send_frame_cmd(struct wpa_driver_nl80211_data *drv,
6037                                   unsigned int freq, unsigned int wait,
6038                                   const u8 *buf, size_t buf_len,
6039                                   u64 *cookie_out)
6040 {
6041         struct nl_msg *msg;
6042         u64 cookie;
6043         int ret = -1;
6044
6045         msg = nlmsg_alloc();
6046         if (!msg)
6047                 return -1;
6048
6049         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6050                     NL80211_CMD_FRAME, 0);
6051
6052         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6053         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
6054         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, wait);
6055         NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
6056         NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
6057
6058         cookie = 0;
6059         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
6060         msg = NULL;
6061         if (ret) {
6062                 wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
6063                            "(%s)", ret, strerror(-ret));
6064                 goto nla_put_failure;
6065         }
6066         wpa_printf(MSG_DEBUG, "nl80211: Frame TX command accepted; "
6067                    "cookie 0x%llx", (long long unsigned int) cookie);
6068
6069         if (cookie_out)
6070                 *cookie_out = cookie;
6071
6072 nla_put_failure:
6073         nlmsg_free(msg);
6074         return ret;
6075 }
6076
6077
6078 static int wpa_driver_nl80211_send_action(void *priv, unsigned int freq,
6079                                           unsigned int wait_time,
6080                                           const u8 *dst, const u8 *src,
6081                                           const u8 *bssid,
6082                                           const u8 *data, size_t data_len)
6083 {
6084         struct i802_bss *bss = priv;
6085         struct wpa_driver_nl80211_data *drv = bss->drv;
6086         int ret = -1;
6087         u8 *buf;
6088         struct ieee80211_hdr *hdr;
6089
6090         wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d, "
6091                    "wait=%d ms)", drv->ifindex, wait_time);
6092
6093         buf = os_zalloc(24 + data_len);
6094         if (buf == NULL)
6095                 return ret;
6096         os_memcpy(buf + 24, data, data_len);
6097         hdr = (struct ieee80211_hdr *) buf;
6098         hdr->frame_control =
6099                 IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
6100         os_memcpy(hdr->addr1, dst, ETH_ALEN);
6101         os_memcpy(hdr->addr2, src, ETH_ALEN);
6102         os_memcpy(hdr->addr3, bssid, ETH_ALEN);
6103
6104         if (drv->nlmode == NL80211_IFTYPE_AP)
6105                 ret = wpa_driver_nl80211_send_mlme(priv, buf, 24 + data_len);
6106         else
6107                 ret = nl80211_send_frame_cmd(drv, freq, wait_time, buf,
6108                                              24 + data_len,
6109                                              &drv->send_action_cookie);
6110
6111         os_free(buf);
6112         return ret;
6113 }
6114
6115
6116 static void wpa_driver_nl80211_send_action_cancel_wait(void *priv)
6117 {
6118         struct i802_bss *bss = priv;
6119         struct wpa_driver_nl80211_data *drv = bss->drv;
6120         struct nl_msg *msg;
6121         int ret;
6122
6123         msg = nlmsg_alloc();
6124         if (!msg)
6125                 return;
6126
6127         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6128                     NL80211_CMD_FRAME_WAIT_CANCEL, 0);
6129
6130         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6131         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->send_action_cookie);
6132
6133         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6134         msg = NULL;
6135         if (ret)
6136                 wpa_printf(MSG_DEBUG, "nl80211: wait cancel failed: ret=%d "
6137                            "(%s)", ret, strerror(-ret));
6138
6139  nla_put_failure:
6140         nlmsg_free(msg);
6141 }
6142
6143
6144 static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
6145                                                 unsigned int duration)
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         u64 cookie;
6152
6153         msg = nlmsg_alloc();
6154         if (!msg)
6155                 return -1;
6156
6157         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6158                     NL80211_CMD_REMAIN_ON_CHANNEL, 0);
6159
6160         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6161         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
6162         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
6163
6164         cookie = 0;
6165         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
6166         if (ret == 0) {
6167                 wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
6168                            "0x%llx for freq=%u MHz duration=%u",
6169                            (long long unsigned int) cookie, freq, duration);
6170                 drv->remain_on_chan_cookie = cookie;
6171                 return 0;
6172         }
6173         wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
6174                    "(freq=%d duration=%u): %d (%s)",
6175                    freq, duration, ret, strerror(-ret));
6176 nla_put_failure:
6177         return -1;
6178 }
6179
6180
6181 static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
6182 {
6183         struct i802_bss *bss = priv;
6184         struct wpa_driver_nl80211_data *drv = bss->drv;
6185         struct nl_msg *msg;
6186         int ret;
6187
6188         if (!drv->pending_remain_on_chan) {
6189                 wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
6190                            "to cancel");
6191                 return -1;
6192         }
6193
6194         wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
6195                    "0x%llx",
6196                    (long long unsigned int) drv->remain_on_chan_cookie);
6197
6198         msg = nlmsg_alloc();
6199         if (!msg)
6200                 return -1;
6201
6202         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6203                     NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL, 0);
6204
6205         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6206         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
6207
6208         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6209         if (ret == 0)
6210                 return 0;
6211         wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
6212                    "%d (%s)", ret, strerror(-ret));
6213 nla_put_failure:
6214         return -1;
6215 }
6216
6217
6218 static int wpa_driver_nl80211_probe_req_report(void *priv, int report)
6219 {
6220         struct i802_bss *bss = priv;
6221         struct wpa_driver_nl80211_data *drv = bss->drv;
6222
6223         if (drv->nlmode != NL80211_IFTYPE_STATION) {
6224                 wpa_printf(MSG_DEBUG, "nl80211: probe_req_report control only "
6225                            "allowed in station mode (iftype=%d)",
6226                            drv->nlmode);
6227                 return -1;
6228         }
6229
6230         if (!report) {
6231                 if (drv->nl_handle_preq) {
6232                         eloop_unregister_read_sock(
6233                                 nl_socket_get_fd(drv->nl_handle_preq));
6234                         nl_cache_free(drv->nl_cache_preq);
6235                         nl80211_handle_destroy(drv->nl_handle_preq);
6236                         drv->nl_handle_preq = NULL;
6237                 }
6238                 return 0;
6239         }
6240
6241         if (drv->nl_handle_preq) {
6242                 wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
6243                            "already on!");
6244                 return 0;
6245         }
6246
6247         drv->nl_handle_preq = nl80211_handle_alloc(drv->nl_cb);
6248         if (drv->nl_handle_preq == NULL) {
6249                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate "
6250                            "netlink callbacks (preq)");
6251                 goto out_err1;
6252         }
6253
6254         if (genl_connect(drv->nl_handle_preq)) {
6255                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to "
6256                            "generic netlink (preq)");
6257                 goto out_err2;
6258                 return -1;
6259         }
6260
6261 #ifdef CONFIG_LIBNL20
6262         if (genl_ctrl_alloc_cache(drv->nl_handle_preq,
6263                                   &drv->nl_cache_preq) < 0) {
6264                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
6265                            "netlink cache (preq)");
6266                 goto out_err2;
6267         }
6268 #else /* CONFIG_LIBNL20 */
6269         drv->nl_cache_preq = genl_ctrl_alloc_cache(drv->nl_handle_preq);
6270         if (drv->nl_cache_preq == NULL) {
6271                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
6272                            "netlink cache (preq)");
6273                 goto out_err2;
6274         }
6275 #endif /* CONFIG_LIBNL20 */
6276
6277         if (nl80211_register_frame(drv, drv->nl_handle_preq,
6278                                    (WLAN_FC_TYPE_MGMT << 2) |
6279                                    (WLAN_FC_STYPE_PROBE_REQ << 4),
6280                                    NULL, 0) < 0) {
6281                 goto out_err3;
6282         }
6283
6284         eloop_register_read_sock(nl_socket_get_fd(drv->nl_handle_preq),
6285                                  wpa_driver_nl80211_event_receive, drv,
6286                                  drv->nl_handle_preq);
6287
6288         return 0;
6289
6290  out_err3:
6291         nl_cache_free(drv->nl_cache_preq);
6292  out_err2:
6293         nl80211_handle_destroy(drv->nl_handle_preq);
6294         drv->nl_handle_preq = NULL;
6295  out_err1:
6296         return -1;
6297 }
6298
6299
6300 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
6301                                      int ifindex, int disabled)
6302 {
6303         struct nl_msg *msg;
6304         struct nlattr *bands, *band;
6305         int ret;
6306
6307         msg = nlmsg_alloc();
6308         if (!msg)
6309                 return -1;
6310
6311         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6312                     NL80211_CMD_SET_TX_BITRATE_MASK, 0);
6313         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
6314
6315         bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
6316         if (!bands)
6317                 goto nla_put_failure;
6318
6319         /*
6320          * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
6321          * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
6322          * rates. All 5 GHz rates are left enabled.
6323          */
6324         band = nla_nest_start(msg, NL80211_BAND_2GHZ);
6325         if (!band)
6326                 goto nla_put_failure;
6327         NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
6328                 "\x0c\x12\x18\x24\x30\x48\x60\x6c");
6329         nla_nest_end(msg, band);
6330
6331         nla_nest_end(msg, bands);
6332
6333         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6334         msg = NULL;
6335         if (ret) {
6336                 wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
6337                            "(%s)", ret, strerror(-ret));
6338         }
6339
6340         return ret;
6341
6342 nla_put_failure:
6343         nlmsg_free(msg);
6344         return -1;
6345 }
6346
6347
6348 static int wpa_driver_nl80211_disable_11b_rates(void *priv, int disabled)
6349 {
6350         struct i802_bss *bss = priv;
6351         struct wpa_driver_nl80211_data *drv = bss->drv;
6352         drv->disable_11b_rates = disabled;
6353         return nl80211_disable_11b_rates(drv, drv->ifindex, disabled);
6354 }
6355
6356
6357 static int wpa_driver_nl80211_deinit_ap(void *priv)
6358 {
6359         struct i802_bss *bss = priv;
6360         struct wpa_driver_nl80211_data *drv = bss->drv;
6361         if (drv->nlmode != NL80211_IFTYPE_AP)
6362                 return -1;
6363         wpa_driver_nl80211_del_beacon(drv);
6364         return wpa_driver_nl80211_set_mode(priv, IEEE80211_MODE_INFRA);
6365 }
6366
6367
6368 static void wpa_driver_nl80211_resume(void *priv)
6369 {
6370         struct i802_bss *bss = priv;
6371         struct wpa_driver_nl80211_data *drv = bss->drv;
6372         if (linux_set_iface_flags(drv->ioctl_sock, bss->ifname, 1)) {
6373                 wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on "
6374                            "resume event");
6375         }
6376 }
6377
6378
6379 static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
6380                                   const u8 *ies, size_t ies_len)
6381 {
6382         struct i802_bss *bss = priv;
6383         struct wpa_driver_nl80211_data *drv = bss->drv;
6384         int ret;
6385         u8 *data, *pos;
6386         size_t data_len;
6387         u8 own_addr[ETH_ALEN];
6388
6389         if (linux_get_ifhwaddr(drv->ioctl_sock, bss->ifname, own_addr) < 0)
6390                 return -1;
6391
6392         if (action != 1) {
6393                 wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
6394                            "action %d", action);
6395                 return -1;
6396         }
6397
6398         /*
6399          * Action frame payload:
6400          * Category[1] = 6 (Fast BSS Transition)
6401          * Action[1] = 1 (Fast BSS Transition Request)
6402          * STA Address
6403          * Target AP Address
6404          * FT IEs
6405          */
6406
6407         data_len = 2 + 2 * ETH_ALEN + ies_len;
6408         data = os_malloc(data_len);
6409         if (data == NULL)
6410                 return -1;
6411         pos = data;
6412         *pos++ = 0x06; /* FT Action category */
6413         *pos++ = action;
6414         os_memcpy(pos, own_addr, ETH_ALEN);
6415         pos += ETH_ALEN;
6416         os_memcpy(pos, target_ap, ETH_ALEN);
6417         pos += ETH_ALEN;
6418         os_memcpy(pos, ies, ies_len);
6419
6420         ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, 0,
6421                                              drv->bssid, own_addr, drv->bssid,
6422                                              data, data_len);
6423         os_free(data);
6424
6425         return ret;
6426 }
6427
6428
6429 static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
6430 {
6431         struct i802_bss *bss = priv;
6432         struct wpa_driver_nl80211_data *drv = bss->drv;
6433         struct nl_msg *msg, *cqm = NULL;
6434
6435         wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
6436                    "hysteresis=%d", threshold, hysteresis);
6437
6438         msg = nlmsg_alloc();
6439         if (!msg)
6440                 return -1;
6441
6442         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0,
6443                     0, NL80211_CMD_SET_CQM, 0);
6444
6445         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
6446
6447         cqm = nlmsg_alloc();
6448         if (cqm == NULL)
6449                 return -1;
6450
6451         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
6452         NLA_PUT_U32(cqm, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
6453         nla_put_nested(msg, NL80211_ATTR_CQM, cqm);
6454
6455         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
6456                 return 0;
6457         msg = NULL;
6458
6459 nla_put_failure:
6460         if (cqm)
6461                 nlmsg_free(cqm);
6462         nlmsg_free(msg);
6463         return -1;
6464 }
6465
6466
6467 static int nl80211_signal_poll(void *priv, struct wpa_signal_info *si)
6468 {
6469         struct i802_bss *bss = priv;
6470         struct wpa_driver_nl80211_data *drv = bss->drv;
6471         int res;
6472
6473         os_memset(si, 0, sizeof(*si));
6474         res = nl80211_get_link_signal(drv, si);
6475         if (res != 0)
6476                 return res;
6477
6478         return nl80211_get_link_noise(drv, si);
6479 }
6480
6481
6482 static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
6483                               int encrypt)
6484 {
6485         struct i802_bss *bss = priv;
6486         struct wpa_driver_nl80211_data *drv = bss->drv;
6487         return wpa_driver_nl80211_send_frame(drv, data, data_len, encrypt);
6488 }
6489
6490
6491 static int nl80211_set_intra_bss(void *priv, int enabled)
6492 {
6493         struct i802_bss *bss = priv;
6494         struct wpa_driver_nl80211_data *drv = bss->drv;
6495         struct nl_msg *msg;
6496
6497         msg = nlmsg_alloc();
6498         if (!msg)
6499                 return -ENOMEM;
6500
6501         genlmsg_put(msg, 0, 0, genl_family_get_id(drv->nl80211), 0, 0,
6502                     NL80211_CMD_SET_BSS, 0);
6503
6504         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
6505         NLA_PUT_U8(msg, NL80211_ATTR_AP_ISOLATE, !enabled);
6506
6507         return send_and_recv_msgs(drv, msg, NULL, NULL);
6508  nla_put_failure:
6509         return -ENOBUFS;
6510 }
6511
6512
6513 static int nl80211_set_param(void *priv, const char *param)
6514 {
6515         wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
6516         if (param == NULL)
6517                 return 0;
6518
6519 #ifdef CONFIG_P2P
6520         if (os_strstr(param, "use_p2p_group_interface=1")) {
6521                 struct i802_bss *bss = priv;
6522                 struct wpa_driver_nl80211_data *drv = bss->drv;
6523
6524                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
6525                            "interface");
6526                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
6527                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
6528         }
6529 #endif /* CONFIG_P2P */
6530
6531         return 0;
6532 }
6533
6534
6535 static void * nl80211_global_init(void)
6536 {
6537         struct nl80211_global *global;
6538         global = os_zalloc(sizeof(*global));
6539         if (global == NULL)
6540                 return NULL;
6541         dl_list_init(&global->interfaces);
6542         return global;
6543 }
6544
6545
6546 static void nl80211_global_deinit(void *priv)
6547 {
6548         struct nl80211_global *global = priv;
6549         if (global == NULL)
6550                 return;
6551         if (!dl_list_empty(&global->interfaces)) {
6552                 wpa_printf(MSG_ERROR, "nl80211: %u interface(s) remain at "
6553                            "nl80211_global_deinit",
6554                            dl_list_len(&global->interfaces));
6555         }
6556         os_free(global);
6557 }
6558
6559
6560 static const char * nl80211_get_radio_name(void *priv)
6561 {
6562         struct i802_bss *bss = priv;
6563         struct wpa_driver_nl80211_data *drv = bss->drv;
6564         return drv->phyname;
6565 }
6566
6567
6568 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
6569         .name = "nl80211",
6570         .desc = "Linux nl80211/cfg80211",
6571         .get_bssid = wpa_driver_nl80211_get_bssid,
6572         .get_ssid = wpa_driver_nl80211_get_ssid,
6573         .set_key = wpa_driver_nl80211_set_key,
6574         .scan2 = wpa_driver_nl80211_scan,
6575         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
6576         .deauthenticate = wpa_driver_nl80211_deauthenticate,
6577         .disassociate = wpa_driver_nl80211_disassociate,
6578         .authenticate = wpa_driver_nl80211_authenticate,
6579         .associate = wpa_driver_nl80211_associate,
6580         .global_init = nl80211_global_init,
6581         .global_deinit = nl80211_global_deinit,
6582         .init2 = wpa_driver_nl80211_init,
6583         .deinit = wpa_driver_nl80211_deinit,
6584         .get_capa = wpa_driver_nl80211_get_capa,
6585         .set_operstate = wpa_driver_nl80211_set_operstate,
6586         .set_supp_port = wpa_driver_nl80211_set_supp_port,
6587         .set_country = wpa_driver_nl80211_set_country,
6588         .set_beacon = wpa_driver_nl80211_set_beacon,
6589         .if_add = wpa_driver_nl80211_if_add,
6590         .if_remove = wpa_driver_nl80211_if_remove,
6591         .send_mlme = wpa_driver_nl80211_send_mlme,
6592         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
6593         .sta_add = wpa_driver_nl80211_sta_add,
6594         .sta_remove = wpa_driver_nl80211_sta_remove,
6595         .hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
6596         .sta_set_flags = wpa_driver_nl80211_sta_set_flags,
6597 #ifdef HOSTAPD
6598         .hapd_init = i802_init,
6599         .hapd_deinit = i802_deinit,
6600         .get_seqnum = i802_get_seqnum,
6601         .flush = i802_flush,
6602         .read_sta_data = i802_read_sta_data,
6603         .get_inact_sec = i802_get_inact_sec,
6604         .sta_clear_stats = i802_sta_clear_stats,
6605         .set_rts = i802_set_rts,
6606         .set_frag = i802_set_frag,
6607         .set_cts_protect = i802_set_cts_protect,
6608         .set_preamble = i802_set_preamble,
6609         .set_short_slot_time = i802_set_short_slot_time,
6610         .set_tx_queue_params = i802_set_tx_queue_params,
6611         .set_sta_vlan = i802_set_sta_vlan,
6612         .set_wds_sta = i802_set_wds_sta,
6613         .set_ht_params = i802_set_ht_params,
6614 #endif /* HOSTAPD */
6615 #if defined(HOSTAPD) || defined(CONFIG_AP)
6616         .set_rate_sets = i802_set_rate_sets,
6617         .sta_deauth = i802_sta_deauth,
6618         .sta_disassoc = i802_sta_disassoc,
6619 #endif /* HOSTAPD || CONFIG_AP */
6620         .set_freq = i802_set_freq,
6621         .send_action = wpa_driver_nl80211_send_action,
6622         .send_action_cancel_wait = wpa_driver_nl80211_send_action_cancel_wait,
6623         .remain_on_channel = wpa_driver_nl80211_remain_on_channel,
6624         .cancel_remain_on_channel =
6625         wpa_driver_nl80211_cancel_remain_on_channel,
6626         .probe_req_report = wpa_driver_nl80211_probe_req_report,
6627         .disable_11b_rates = wpa_driver_nl80211_disable_11b_rates,
6628         .deinit_ap = wpa_driver_nl80211_deinit_ap,
6629         .resume = wpa_driver_nl80211_resume,
6630         .send_ft_action = nl80211_send_ft_action,
6631         .signal_monitor = nl80211_signal_monitor,
6632         .signal_poll = nl80211_signal_poll,
6633         .send_frame = nl80211_send_frame,
6634         .set_intra_bss = nl80211_set_intra_bss,
6635         .set_param = nl80211_set_param,
6636         .get_radio_name = nl80211_get_radio_name,
6637 };