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