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