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