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