hostapd/wpa_s: Use driver's extended capabilities
[mech_eap.git] / src / drivers / driver_nl80211.c
1 /*
2  * Driver interaction with Linux nl80211/cfg80211
3  * Copyright (c) 2002-2012, 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 software may be distributed under the terms of the BSD license.
10  * See README for more details.
11  */
12
13 #include "includes.h"
14 #include <sys/ioctl.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 #include <fcntl.h>
18 #include <net/if.h>
19 #include <netlink/genl/genl.h>
20 #include <netlink/genl/family.h>
21 #include <netlink/genl/ctrl.h>
22 #include <linux/rtnetlink.h>
23 #include <netpacket/packet.h>
24 #include <linux/filter.h>
25 #include <linux/errqueue.h>
26 #include "nl80211_copy.h"
27
28 #include "common.h"
29 #include "eloop.h"
30 #include "utils/list.h"
31 #include "common/ieee802_11_defs.h"
32 #include "common/ieee802_11_common.h"
33 #include "l2_packet/l2_packet.h"
34 #include "netlink.h"
35 #include "linux_ioctl.h"
36 #include "radiotap.h"
37 #include "radiotap_iter.h"
38 #include "rfkill.h"
39 #include "driver.h"
40
41 #ifndef SO_WIFI_STATUS
42 # if defined(__sparc__)
43 #  define SO_WIFI_STATUS        0x0025
44 # elif defined(__parisc__)
45 #  define SO_WIFI_STATUS        0x4022
46 # else
47 #  define SO_WIFI_STATUS        41
48 # endif
49
50 # define SCM_WIFI_STATUS        SO_WIFI_STATUS
51 #endif
52
53 #ifndef SO_EE_ORIGIN_TXSTATUS
54 #define SO_EE_ORIGIN_TXSTATUS   4
55 #endif
56
57 #ifndef PACKET_TX_TIMESTAMP
58 #define PACKET_TX_TIMESTAMP     16
59 #endif
60
61 #ifdef ANDROID
62 #include "android_drv.h"
63
64 /* system/core/libnl_2 in AOSP does not include nla_put_u32() */
65 int nla_put_u32(struct nl_msg *msg, int attrtype, uint32_t value)
66 {
67         return nla_put(msg, attrtype, sizeof(uint32_t), &value);
68 }
69 #endif /* ANDROID */
70 #ifdef CONFIG_LIBNL20
71 /* libnl 2.0 compatibility code */
72 #define nl_handle nl_sock
73 #define nl80211_handle_alloc nl_socket_alloc_cb
74 #define nl80211_handle_destroy nl_socket_free
75 #else
76 /*
77  * libnl 1.1 has a bug, it tries to allocate socket numbers densely
78  * but when you free a socket again it will mess up its bitmap and
79  * and use the wrong number the next time it needs a socket ID.
80  * Therefore, we wrap the handle alloc/destroy and add our own pid
81  * accounting.
82  */
83 static uint32_t port_bitmap[32] = { 0 };
84
85 static struct nl_handle *nl80211_handle_alloc(void *cb)
86 {
87         struct nl_handle *handle;
88         uint32_t pid = getpid() & 0x3FFFFF;
89         int i;
90
91         handle = nl_handle_alloc_cb(cb);
92
93         for (i = 0; i < 1024; i++) {
94                 if (port_bitmap[i / 32] & (1 << (i % 32)))
95                         continue;
96                 port_bitmap[i / 32] |= 1 << (i % 32);
97                 pid += i << 22;
98                 break;
99         }
100
101         nl_socket_set_local_port(handle, pid);
102
103         return handle;
104 }
105
106 static void nl80211_handle_destroy(struct nl_handle *handle)
107 {
108         uint32_t port = nl_socket_get_local_port(handle);
109
110         port >>= 22;
111         port_bitmap[port / 32] &= ~(1 << (port % 32));
112
113         nl_handle_destroy(handle);
114 }
115 #endif /* CONFIG_LIBNL20 */
116
117
118 static struct nl_handle * nl_create_handle(struct nl_cb *cb, const char *dbg)
119 {
120         struct nl_handle *handle;
121
122         handle = nl80211_handle_alloc(cb);
123         if (handle == NULL) {
124                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
125                            "callbacks (%s)", dbg);
126                 return NULL;
127         }
128
129         if (genl_connect(handle)) {
130                 wpa_printf(MSG_ERROR, "nl80211: Failed to connect to generic "
131                            "netlink (%s)", dbg);
132                 nl80211_handle_destroy(handle);
133                 return NULL;
134         }
135
136         return handle;
137 }
138
139
140 static void nl_destroy_handles(struct nl_handle **handle)
141 {
142         if (*handle == NULL)
143                 return;
144         nl80211_handle_destroy(*handle);
145         *handle = NULL;
146 }
147
148
149 #ifndef IFF_LOWER_UP
150 #define IFF_LOWER_UP   0x10000         /* driver signals L1 up         */
151 #endif
152 #ifndef IFF_DORMANT
153 #define IFF_DORMANT    0x20000         /* driver signals dormant       */
154 #endif
155
156 #ifndef IF_OPER_DORMANT
157 #define IF_OPER_DORMANT 5
158 #endif
159 #ifndef IF_OPER_UP
160 #define IF_OPER_UP 6
161 #endif
162
163 struct nl80211_global {
164         struct dl_list interfaces;
165         int if_add_ifindex;
166         struct netlink_data *netlink;
167         struct nl_cb *nl_cb;
168         struct nl_handle *nl;
169         int nl80211_id;
170         int ioctl_sock; /* socket for ioctl() use */
171
172         struct nl_handle *nl_event;
173 };
174
175 struct nl80211_wiphy_data {
176         struct dl_list list;
177         struct dl_list bsss;
178         struct dl_list drvs;
179
180         struct nl_handle *nl_beacons;
181         struct nl_cb *nl_cb;
182
183         int wiphy_idx;
184 };
185
186 static void nl80211_global_deinit(void *priv);
187
188 struct i802_bss {
189         struct wpa_driver_nl80211_data *drv;
190         struct i802_bss *next;
191         int ifindex;
192         char ifname[IFNAMSIZ + 1];
193         char brname[IFNAMSIZ];
194         unsigned int beacon_set:1;
195         unsigned int added_if_into_bridge:1;
196         unsigned int added_bridge:1;
197         unsigned int in_deinit:1;
198
199         u8 addr[ETH_ALEN];
200
201         int freq;
202
203         void *ctx;
204         struct nl_handle *nl_preq, *nl_mgmt;
205         struct nl_cb *nl_cb;
206
207         struct nl80211_wiphy_data *wiphy_data;
208         struct dl_list wiphy_list;
209 };
210
211 struct wpa_driver_nl80211_data {
212         struct nl80211_global *global;
213         struct dl_list list;
214         struct dl_list wiphy_list;
215         char phyname[32];
216         void *ctx;
217         int ifindex;
218         int if_removed;
219         int if_disabled;
220         int ignore_if_down_event;
221         struct rfkill_data *rfkill;
222         struct wpa_driver_capa capa;
223         u8 *extended_capa, *extended_capa_mask;
224         unsigned int extended_capa_len;
225         int has_capability;
226
227         int operstate;
228
229         int scan_complete_events;
230
231         struct nl_cb *nl_cb;
232
233         u8 auth_bssid[ETH_ALEN];
234         u8 bssid[ETH_ALEN];
235         int associated;
236         u8 ssid[32];
237         size_t ssid_len;
238         enum nl80211_iftype nlmode;
239         enum nl80211_iftype ap_scan_as_station;
240         unsigned int assoc_freq;
241
242         int monitor_sock;
243         int monitor_ifidx;
244         int monitor_refcount;
245
246         unsigned int disabled_11b_rates:1;
247         unsigned int pending_remain_on_chan:1;
248         unsigned int in_interface_list:1;
249         unsigned int device_ap_sme:1;
250         unsigned int poll_command_supported:1;
251         unsigned int data_tx_status:1;
252         unsigned int scan_for_auth:1;
253         unsigned int retry_auth:1;
254         unsigned int use_monitor:1;
255         unsigned int ignore_next_local_disconnect:1;
256
257         u64 remain_on_chan_cookie;
258         u64 send_action_cookie;
259
260         unsigned int last_mgmt_freq;
261
262         struct wpa_driver_scan_filter *filter_ssids;
263         size_t num_filter_ssids;
264
265         struct i802_bss first_bss;
266
267         int eapol_tx_sock;
268
269 #ifdef HOSTAPD
270         int eapol_sock; /* socket for EAPOL frames */
271
272         int default_if_indices[16];
273         int *if_indices;
274         int num_if_indices;
275
276         int last_freq;
277         int last_freq_ht;
278 #endif /* HOSTAPD */
279
280         /* From failed authentication command */
281         int auth_freq;
282         u8 auth_bssid_[ETH_ALEN];
283         u8 auth_ssid[32];
284         size_t auth_ssid_len;
285         int auth_alg;
286         u8 *auth_ie;
287         size_t auth_ie_len;
288         u8 auth_wep_key[4][16];
289         size_t auth_wep_key_len[4];
290         int auth_wep_tx_keyidx;
291         int auth_local_state_change;
292         int auth_p2p;
293 };
294
295
296 static void wpa_driver_nl80211_deinit(struct i802_bss *bss);
297 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx,
298                                             void *timeout_ctx);
299 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
300                                        enum nl80211_iftype nlmode);
301 static int
302 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv);
303 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
304                                    const u8 *addr, int cmd, u16 reason_code,
305                                    int local_state_change);
306 static void nl80211_remove_monitor_interface(
307         struct wpa_driver_nl80211_data *drv);
308 static int nl80211_send_frame_cmd(struct i802_bss *bss,
309                                   unsigned int freq, unsigned int wait,
310                                   const u8 *buf, size_t buf_len, u64 *cookie,
311                                   int no_cck, int no_ack, int offchanok);
312 static int wpa_driver_nl80211_probe_req_report(struct i802_bss *bss,
313                                                int report);
314 #ifdef ANDROID
315 static int android_pno_start(struct i802_bss *bss,
316                              struct wpa_driver_scan_params *params);
317 static int android_pno_stop(struct i802_bss *bss);
318 #endif /* ANDROID */
319
320 #ifdef HOSTAPD
321 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
322 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
323 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx);
324 static int wpa_driver_nl80211_if_remove(struct i802_bss *bss,
325                                         enum wpa_driver_if_type type,
326                                         const char *ifname);
327 #else /* HOSTAPD */
328 static inline void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
329 {
330 }
331
332 static inline void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
333 {
334 }
335
336 static inline int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
337 {
338         return 0;
339 }
340 #endif /* HOSTAPD */
341
342 static int wpa_driver_nl80211_set_freq(struct i802_bss *bss,
343                                        struct hostapd_freq_params *freq);
344 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
345                                      int ifindex, int disabled);
346
347 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv);
348 static int wpa_driver_nl80211_authenticate_retry(
349         struct wpa_driver_nl80211_data *drv);
350
351
352 static int is_ap_interface(enum nl80211_iftype nlmode)
353 {
354         return (nlmode == NL80211_IFTYPE_AP ||
355                 nlmode == NL80211_IFTYPE_P2P_GO);
356 }
357
358
359 static int is_sta_interface(enum nl80211_iftype nlmode)
360 {
361         return (nlmode == NL80211_IFTYPE_STATION ||
362                 nlmode == NL80211_IFTYPE_P2P_CLIENT);
363 }
364
365
366 static int is_p2p_interface(enum nl80211_iftype nlmode)
367 {
368         return (nlmode == NL80211_IFTYPE_P2P_CLIENT ||
369                 nlmode == NL80211_IFTYPE_P2P_GO);
370 }
371
372
373 struct nl80211_bss_info_arg {
374         struct wpa_driver_nl80211_data *drv;
375         struct wpa_scan_results *res;
376         unsigned int assoc_freq;
377         u8 assoc_bssid[ETH_ALEN];
378 };
379
380 static int bss_info_handler(struct nl_msg *msg, void *arg);
381
382
383 /* nl80211 code */
384 static int ack_handler(struct nl_msg *msg, void *arg)
385 {
386         int *err = arg;
387         *err = 0;
388         return NL_STOP;
389 }
390
391 static int finish_handler(struct nl_msg *msg, void *arg)
392 {
393         int *ret = arg;
394         *ret = 0;
395         return NL_SKIP;
396 }
397
398 static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err,
399                          void *arg)
400 {
401         int *ret = arg;
402         *ret = err->error;
403         return NL_SKIP;
404 }
405
406
407 static int no_seq_check(struct nl_msg *msg, void *arg)
408 {
409         return NL_OK;
410 }
411
412
413 static int send_and_recv(struct nl80211_global *global,
414                          struct nl_handle *nl_handle, struct nl_msg *msg,
415                          int (*valid_handler)(struct nl_msg *, void *),
416                          void *valid_data)
417 {
418         struct nl_cb *cb;
419         int err = -ENOMEM;
420
421         cb = nl_cb_clone(global->nl_cb);
422         if (!cb)
423                 goto out;
424
425         err = nl_send_auto_complete(nl_handle, msg);
426         if (err < 0)
427                 goto out;
428
429         err = 1;
430
431         nl_cb_err(cb, NL_CB_CUSTOM, error_handler, &err);
432         nl_cb_set(cb, NL_CB_FINISH, NL_CB_CUSTOM, finish_handler, &err);
433         nl_cb_set(cb, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, &err);
434
435         if (valid_handler)
436                 nl_cb_set(cb, NL_CB_VALID, NL_CB_CUSTOM,
437                           valid_handler, valid_data);
438
439         while (err > 0)
440                 nl_recvmsgs(nl_handle, cb);
441  out:
442         nl_cb_put(cb);
443         nlmsg_free(msg);
444         return err;
445 }
446
447
448 static int send_and_recv_msgs_global(struct nl80211_global *global,
449                                      struct nl_msg *msg,
450                                      int (*valid_handler)(struct nl_msg *, void *),
451                                      void *valid_data)
452 {
453         return send_and_recv(global, global->nl, msg, valid_handler,
454                              valid_data);
455 }
456
457
458 static int send_and_recv_msgs(struct wpa_driver_nl80211_data *drv,
459                               struct nl_msg *msg,
460                               int (*valid_handler)(struct nl_msg *, void *),
461                               void *valid_data)
462 {
463         return send_and_recv(drv->global, drv->global->nl, msg,
464                              valid_handler, valid_data);
465 }
466
467
468 struct family_data {
469         const char *group;
470         int id;
471 };
472
473
474 static int family_handler(struct nl_msg *msg, void *arg)
475 {
476         struct family_data *res = arg;
477         struct nlattr *tb[CTRL_ATTR_MAX + 1];
478         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
479         struct nlattr *mcgrp;
480         int i;
481
482         nla_parse(tb, CTRL_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
483                   genlmsg_attrlen(gnlh, 0), NULL);
484         if (!tb[CTRL_ATTR_MCAST_GROUPS])
485                 return NL_SKIP;
486
487         nla_for_each_nested(mcgrp, tb[CTRL_ATTR_MCAST_GROUPS], i) {
488                 struct nlattr *tb2[CTRL_ATTR_MCAST_GRP_MAX + 1];
489                 nla_parse(tb2, CTRL_ATTR_MCAST_GRP_MAX, nla_data(mcgrp),
490                           nla_len(mcgrp), NULL);
491                 if (!tb2[CTRL_ATTR_MCAST_GRP_NAME] ||
492                     !tb2[CTRL_ATTR_MCAST_GRP_ID] ||
493                     os_strncmp(nla_data(tb2[CTRL_ATTR_MCAST_GRP_NAME]),
494                                res->group,
495                                nla_len(tb2[CTRL_ATTR_MCAST_GRP_NAME])) != 0)
496                         continue;
497                 res->id = nla_get_u32(tb2[CTRL_ATTR_MCAST_GRP_ID]);
498                 break;
499         };
500
501         return NL_SKIP;
502 }
503
504
505 static int nl_get_multicast_id(struct nl80211_global *global,
506                                const char *family, const char *group)
507 {
508         struct nl_msg *msg;
509         int ret = -1;
510         struct family_data res = { group, -ENOENT };
511
512         msg = nlmsg_alloc();
513         if (!msg)
514                 return -ENOMEM;
515         genlmsg_put(msg, 0, 0, genl_ctrl_resolve(global->nl, "nlctrl"),
516                     0, 0, CTRL_CMD_GETFAMILY, 0);
517         NLA_PUT_STRING(msg, CTRL_ATTR_FAMILY_NAME, family);
518
519         ret = send_and_recv_msgs_global(global, msg, family_handler, &res);
520         msg = NULL;
521         if (ret == 0)
522                 ret = res.id;
523
524 nla_put_failure:
525         nlmsg_free(msg);
526         return ret;
527 }
528
529
530 static void * nl80211_cmd(struct wpa_driver_nl80211_data *drv,
531                           struct nl_msg *msg, int flags, uint8_t cmd)
532 {
533         return genlmsg_put(msg, 0, 0, drv->global->nl80211_id,
534                            0, flags, cmd, 0);
535 }
536
537
538 struct wiphy_idx_data {
539         int wiphy_idx;
540 };
541
542
543 static int netdev_info_handler(struct nl_msg *msg, void *arg)
544 {
545         struct nlattr *tb[NL80211_ATTR_MAX + 1];
546         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
547         struct wiphy_idx_data *info = arg;
548
549         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
550                   genlmsg_attrlen(gnlh, 0), NULL);
551
552         if (tb[NL80211_ATTR_WIPHY])
553                 info->wiphy_idx = nla_get_u32(tb[NL80211_ATTR_WIPHY]);
554
555         return NL_SKIP;
556 }
557
558
559 static int nl80211_get_wiphy_index(struct i802_bss *bss)
560 {
561         struct nl_msg *msg;
562         struct wiphy_idx_data data = {
563                 .wiphy_idx = -1,
564         };
565
566         msg = nlmsg_alloc();
567         if (!msg)
568                 return -1;
569
570         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_GET_INTERFACE);
571
572         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
573
574         if (send_and_recv_msgs(bss->drv, msg, netdev_info_handler, &data) == 0)
575                 return data.wiphy_idx;
576         msg = NULL;
577 nla_put_failure:
578         nlmsg_free(msg);
579         return -1;
580 }
581
582
583 static int nl80211_register_beacons(struct wpa_driver_nl80211_data *drv,
584                                     struct nl80211_wiphy_data *w)
585 {
586         struct nl_msg *msg;
587         int ret = -1;
588
589         msg = nlmsg_alloc();
590         if (!msg)
591                 return -1;
592
593         nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_BEACONS);
594
595         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY, w->wiphy_idx);
596
597         ret = send_and_recv(drv->global, w->nl_beacons, msg, NULL, NULL);
598         msg = NULL;
599         if (ret) {
600                 wpa_printf(MSG_DEBUG, "nl80211: Register beacons command "
601                            "failed: ret=%d (%s)",
602                            ret, strerror(-ret));
603                 goto nla_put_failure;
604         }
605         ret = 0;
606 nla_put_failure:
607         nlmsg_free(msg);
608         return ret;
609 }
610
611
612 static void nl80211_recv_beacons(int sock, void *eloop_ctx, void *handle)
613 {
614         struct nl80211_wiphy_data *w = eloop_ctx;
615
616         wpa_printf(MSG_EXCESSIVE, "nl80211: Beacon event message available");
617
618         nl_recvmsgs(handle, w->nl_cb);
619 }
620
621
622 static int process_beacon_event(struct nl_msg *msg, void *arg)
623 {
624         struct nl80211_wiphy_data *w = arg;
625         struct wpa_driver_nl80211_data *drv;
626         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
627         struct nlattr *tb[NL80211_ATTR_MAX + 1];
628         union wpa_event_data event;
629
630         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
631                   genlmsg_attrlen(gnlh, 0), NULL);
632
633         if (gnlh->cmd != NL80211_CMD_FRAME) {
634                 wpa_printf(MSG_DEBUG, "nl80211: Unexpected beacon event? (%d)",
635                            gnlh->cmd);
636                 return NL_SKIP;
637         }
638
639         if (!tb[NL80211_ATTR_FRAME])
640                 return NL_SKIP;
641
642         dl_list_for_each(drv, &w->drvs, struct wpa_driver_nl80211_data,
643                          wiphy_list) {
644                 os_memset(&event, 0, sizeof(event));
645                 event.rx_mgmt.frame = nla_data(tb[NL80211_ATTR_FRAME]);
646                 event.rx_mgmt.frame_len = nla_len(tb[NL80211_ATTR_FRAME]);
647                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
648         }
649
650         return NL_SKIP;
651 }
652
653
654 static struct nl80211_wiphy_data *
655 nl80211_get_wiphy_data_ap(struct i802_bss *bss)
656 {
657         static DEFINE_DL_LIST(nl80211_wiphys);
658         struct nl80211_wiphy_data *w;
659         int wiphy_idx, found = 0;
660         struct i802_bss *tmp_bss;
661
662         if (bss->wiphy_data != NULL)
663                 return bss->wiphy_data;
664
665         wiphy_idx = nl80211_get_wiphy_index(bss);
666
667         dl_list_for_each(w, &nl80211_wiphys, struct nl80211_wiphy_data, list) {
668                 if (w->wiphy_idx == wiphy_idx)
669                         goto add;
670         }
671
672         /* alloc new one */
673         w = os_zalloc(sizeof(*w));
674         if (w == NULL)
675                 return NULL;
676         w->wiphy_idx = wiphy_idx;
677         dl_list_init(&w->bsss);
678         dl_list_init(&w->drvs);
679
680         w->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
681         if (!w->nl_cb) {
682                 os_free(w);
683                 return NULL;
684         }
685         nl_cb_set(w->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM, no_seq_check, NULL);
686         nl_cb_set(w->nl_cb, NL_CB_VALID, NL_CB_CUSTOM, process_beacon_event,
687                   w);
688
689         w->nl_beacons = nl_create_handle(bss->drv->global->nl_cb,
690                                          "wiphy beacons");
691         if (w->nl_beacons == NULL) {
692                 os_free(w);
693                 return NULL;
694         }
695
696         if (nl80211_register_beacons(bss->drv, w)) {
697                 nl_destroy_handles(&w->nl_beacons);
698                 os_free(w);
699                 return NULL;
700         }
701
702         eloop_register_read_sock(nl_socket_get_fd(w->nl_beacons),
703                                  nl80211_recv_beacons, w, w->nl_beacons);
704
705         dl_list_add(&nl80211_wiphys, &w->list);
706
707 add:
708         /* drv entry for this bss already there? */
709         dl_list_for_each(tmp_bss, &w->bsss, struct i802_bss, wiphy_list) {
710                 if (tmp_bss->drv == bss->drv) {
711                         found = 1;
712                         break;
713                 }
714         }
715         /* if not add it */
716         if (!found)
717                 dl_list_add(&w->drvs, &bss->drv->wiphy_list);
718
719         dl_list_add(&w->bsss, &bss->wiphy_list);
720         bss->wiphy_data = w;
721         return w;
722 }
723
724
725 static void nl80211_put_wiphy_data_ap(struct i802_bss *bss)
726 {
727         struct nl80211_wiphy_data *w = bss->wiphy_data;
728         struct i802_bss *tmp_bss;
729         int found = 0;
730
731         if (w == NULL)
732                 return;
733         bss->wiphy_data = NULL;
734         dl_list_del(&bss->wiphy_list);
735
736         /* still any for this drv present? */
737         dl_list_for_each(tmp_bss, &w->bsss, struct i802_bss, wiphy_list) {
738                 if (tmp_bss->drv == bss->drv) {
739                         found = 1;
740                         break;
741                 }
742         }
743         /* if not remove it */
744         if (!found)
745                 dl_list_del(&bss->drv->wiphy_list);
746
747         if (!dl_list_empty(&w->bsss))
748                 return;
749
750         eloop_unregister_read_sock(nl_socket_get_fd(w->nl_beacons));
751
752         nl_cb_put(w->nl_cb);
753         nl_destroy_handles(&w->nl_beacons);
754         dl_list_del(&w->list);
755         os_free(w);
756 }
757
758
759 static int wpa_driver_nl80211_get_bssid(void *priv, u8 *bssid)
760 {
761         struct i802_bss *bss = priv;
762         struct wpa_driver_nl80211_data *drv = bss->drv;
763         if (!drv->associated)
764                 return -1;
765         os_memcpy(bssid, drv->bssid, ETH_ALEN);
766         return 0;
767 }
768
769
770 static int wpa_driver_nl80211_get_ssid(void *priv, u8 *ssid)
771 {
772         struct i802_bss *bss = priv;
773         struct wpa_driver_nl80211_data *drv = bss->drv;
774         if (!drv->associated)
775                 return -1;
776         os_memcpy(ssid, drv->ssid, drv->ssid_len);
777         return drv->ssid_len;
778 }
779
780
781 static void wpa_driver_nl80211_event_link(struct wpa_driver_nl80211_data *drv,
782                                           char *buf, size_t len, int del)
783 {
784         union wpa_event_data event;
785
786         os_memset(&event, 0, sizeof(event));
787         if (len > sizeof(event.interface_status.ifname))
788                 len = sizeof(event.interface_status.ifname) - 1;
789         os_memcpy(event.interface_status.ifname, buf, len);
790         event.interface_status.ievent = del ? EVENT_INTERFACE_REMOVED :
791                 EVENT_INTERFACE_ADDED;
792
793         wpa_printf(MSG_DEBUG, "RTM_%sLINK, IFLA_IFNAME: Interface '%s' %s",
794                    del ? "DEL" : "NEW",
795                    event.interface_status.ifname,
796                    del ? "removed" : "added");
797
798         if (os_strcmp(drv->first_bss.ifname, event.interface_status.ifname) == 0) {
799                 if (del) {
800                         if (drv->if_removed) {
801                                 wpa_printf(MSG_DEBUG, "nl80211: if_removed "
802                                            "already set - ignore event");
803                                 return;
804                         }
805                         drv->if_removed = 1;
806                 } else {
807                         if (if_nametoindex(drv->first_bss.ifname) == 0) {
808                                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s "
809                                            "does not exist - ignore "
810                                            "RTM_NEWLINK",
811                                            drv->first_bss.ifname);
812                                 return;
813                         }
814                         if (!drv->if_removed) {
815                                 wpa_printf(MSG_DEBUG, "nl80211: if_removed "
816                                            "already cleared - ignore event");
817                                 return;
818                         }
819                         drv->if_removed = 0;
820                 }
821         }
822
823         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_STATUS, &event);
824 }
825
826
827 static int wpa_driver_nl80211_own_ifname(struct wpa_driver_nl80211_data *drv,
828                                          u8 *buf, size_t len)
829 {
830         int attrlen, rta_len;
831         struct rtattr *attr;
832
833         attrlen = len;
834         attr = (struct rtattr *) buf;
835
836         rta_len = RTA_ALIGN(sizeof(struct rtattr));
837         while (RTA_OK(attr, attrlen)) {
838                 if (attr->rta_type == IFLA_IFNAME) {
839                         if (os_strcmp(((char *) attr) + rta_len, drv->first_bss.ifname)
840                             == 0)
841                                 return 1;
842                         else
843                                 break;
844                 }
845                 attr = RTA_NEXT(attr, attrlen);
846         }
847
848         return 0;
849 }
850
851
852 static int wpa_driver_nl80211_own_ifindex(struct wpa_driver_nl80211_data *drv,
853                                           int ifindex, u8 *buf, size_t len)
854 {
855         if (drv->ifindex == ifindex)
856                 return 1;
857
858         if (drv->if_removed && wpa_driver_nl80211_own_ifname(drv, buf, len)) {
859                 drv->first_bss.ifindex = if_nametoindex(drv->first_bss.ifname);
860                 wpa_printf(MSG_DEBUG, "nl80211: Update ifindex for a removed "
861                            "interface");
862                 wpa_driver_nl80211_finish_drv_init(drv);
863                 return 1;
864         }
865
866         return 0;
867 }
868
869
870 static struct wpa_driver_nl80211_data *
871 nl80211_find_drv(struct nl80211_global *global, int idx, u8 *buf, size_t len)
872 {
873         struct wpa_driver_nl80211_data *drv;
874         dl_list_for_each(drv, &global->interfaces,
875                          struct wpa_driver_nl80211_data, list) {
876                 if (wpa_driver_nl80211_own_ifindex(drv, idx, buf, len) ||
877                     have_ifidx(drv, idx))
878                         return drv;
879         }
880         return NULL;
881 }
882
883
884 static void wpa_driver_nl80211_event_rtm_newlink(void *ctx,
885                                                  struct ifinfomsg *ifi,
886                                                  u8 *buf, size_t len)
887 {
888         struct nl80211_global *global = ctx;
889         struct wpa_driver_nl80211_data *drv;
890         int attrlen, rta_len;
891         struct rtattr *attr;
892         u32 brid = 0;
893         char namebuf[IFNAMSIZ];
894
895         drv = nl80211_find_drv(global, ifi->ifi_index, buf, len);
896         if (!drv) {
897                 wpa_printf(MSG_DEBUG, "nl80211: Ignore event for foreign "
898                            "ifindex %d", ifi->ifi_index);
899                 return;
900         }
901
902         wpa_printf(MSG_DEBUG, "RTM_NEWLINK: operstate=%d ifi_flags=0x%x "
903                    "(%s%s%s%s)",
904                    drv->operstate, ifi->ifi_flags,
905                    (ifi->ifi_flags & IFF_UP) ? "[UP]" : "",
906                    (ifi->ifi_flags & IFF_RUNNING) ? "[RUNNING]" : "",
907                    (ifi->ifi_flags & IFF_LOWER_UP) ? "[LOWER_UP]" : "",
908                    (ifi->ifi_flags & IFF_DORMANT) ? "[DORMANT]" : "");
909
910         if (!drv->if_disabled && !(ifi->ifi_flags & IFF_UP)) {
911                 if (if_indextoname(ifi->ifi_index, namebuf) &&
912                     linux_iface_up(drv->global->ioctl_sock,
913                                    drv->first_bss.ifname) > 0) {
914                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface down "
915                                    "event since interface %s is up", namebuf);
916                         return;
917                 }
918                 wpa_printf(MSG_DEBUG, "nl80211: Interface down");
919                 if (drv->ignore_if_down_event) {
920                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface down "
921                                    "event generated by mode change");
922                         drv->ignore_if_down_event = 0;
923                 } else {
924                         drv->if_disabled = 1;
925                         wpa_supplicant_event(drv->ctx,
926                                              EVENT_INTERFACE_DISABLED, NULL);
927                 }
928         }
929
930         if (drv->if_disabled && (ifi->ifi_flags & IFF_UP)) {
931                 if (if_indextoname(ifi->ifi_index, namebuf) &&
932                     linux_iface_up(drv->global->ioctl_sock,
933                                    drv->first_bss.ifname) == 0) {
934                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
935                                    "event since interface %s is down",
936                                    namebuf);
937                 } else if (if_nametoindex(drv->first_bss.ifname) == 0) {
938                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
939                                    "event since interface %s does not exist",
940                                    drv->first_bss.ifname);
941                 } else if (drv->if_removed) {
942                         wpa_printf(MSG_DEBUG, "nl80211: Ignore interface up "
943                                    "event since interface %s is marked "
944                                    "removed", drv->first_bss.ifname);
945                 } else {
946                         wpa_printf(MSG_DEBUG, "nl80211: Interface up");
947                         drv->if_disabled = 0;
948                         wpa_supplicant_event(drv->ctx, EVENT_INTERFACE_ENABLED,
949                                              NULL);
950                 }
951         }
952
953         /*
954          * Some drivers send the association event before the operup event--in
955          * this case, lifting operstate in wpa_driver_nl80211_set_operstate()
956          * fails. This will hit us when wpa_supplicant does not need to do
957          * IEEE 802.1X authentication
958          */
959         if (drv->operstate == 1 &&
960             (ifi->ifi_flags & (IFF_LOWER_UP | IFF_DORMANT)) == IFF_LOWER_UP &&
961             !(ifi->ifi_flags & IFF_RUNNING))
962                 netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
963                                        -1, IF_OPER_UP);
964
965         attrlen = len;
966         attr = (struct rtattr *) buf;
967         rta_len = RTA_ALIGN(sizeof(struct rtattr));
968         while (RTA_OK(attr, attrlen)) {
969                 if (attr->rta_type == IFLA_IFNAME) {
970                         wpa_driver_nl80211_event_link(
971                                 drv,
972                                 ((char *) attr) + rta_len,
973                                 attr->rta_len - rta_len, 0);
974                 } else if (attr->rta_type == IFLA_MASTER)
975                         brid = nla_get_u32((struct nlattr *) attr);
976                 attr = RTA_NEXT(attr, attrlen);
977         }
978
979         if (ifi->ifi_family == AF_BRIDGE && brid) {
980                 /* device has been added to bridge */
981                 if_indextoname(brid, namebuf);
982                 wpa_printf(MSG_DEBUG, "nl80211: Add ifindex %u for bridge %s",
983                            brid, namebuf);
984                 add_ifidx(drv, brid);
985         }
986 }
987
988
989 static void wpa_driver_nl80211_event_rtm_dellink(void *ctx,
990                                                  struct ifinfomsg *ifi,
991                                                  u8 *buf, size_t len)
992 {
993         struct nl80211_global *global = ctx;
994         struct wpa_driver_nl80211_data *drv;
995         int attrlen, rta_len;
996         struct rtattr *attr;
997         u32 brid = 0;
998
999         drv = nl80211_find_drv(global, ifi->ifi_index, buf, len);
1000         if (!drv) {
1001                 wpa_printf(MSG_DEBUG, "nl80211: Ignore dellink event for "
1002                            "foreign ifindex %d", ifi->ifi_index);
1003                 return;
1004         }
1005
1006         attrlen = len;
1007         attr = (struct rtattr *) buf;
1008
1009         rta_len = RTA_ALIGN(sizeof(struct rtattr));
1010         while (RTA_OK(attr, attrlen)) {
1011                 if (attr->rta_type == IFLA_IFNAME) {
1012                         wpa_driver_nl80211_event_link(
1013                                 drv,
1014                                 ((char *) attr) + rta_len,
1015                                 attr->rta_len - rta_len, 1);
1016                 } else if (attr->rta_type == IFLA_MASTER)
1017                         brid = nla_get_u32((struct nlattr *) attr);
1018                 attr = RTA_NEXT(attr, attrlen);
1019         }
1020
1021         if (ifi->ifi_family == AF_BRIDGE && brid) {
1022                 /* device has been removed from bridge */
1023                 char namebuf[IFNAMSIZ];
1024                 if_indextoname(brid, namebuf);
1025                 wpa_printf(MSG_DEBUG, "nl80211: Remove ifindex %u for bridge "
1026                            "%s", brid, namebuf);
1027                 del_ifidx(drv, brid);
1028         }
1029 }
1030
1031
1032 static void mlme_event_auth(struct wpa_driver_nl80211_data *drv,
1033                             const u8 *frame, size_t len)
1034 {
1035         const struct ieee80211_mgmt *mgmt;
1036         union wpa_event_data event;
1037
1038         wpa_printf(MSG_DEBUG, "nl80211: Authenticate event");
1039         mgmt = (const struct ieee80211_mgmt *) frame;
1040         if (len < 24 + sizeof(mgmt->u.auth)) {
1041                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1042                            "frame");
1043                 return;
1044         }
1045
1046         os_memcpy(drv->auth_bssid, mgmt->sa, ETH_ALEN);
1047         os_memset(&event, 0, sizeof(event));
1048         os_memcpy(event.auth.peer, mgmt->sa, ETH_ALEN);
1049         event.auth.auth_type = le_to_host16(mgmt->u.auth.auth_alg);
1050         event.auth.auth_transaction =
1051                 le_to_host16(mgmt->u.auth.auth_transaction);
1052         event.auth.status_code = le_to_host16(mgmt->u.auth.status_code);
1053         if (len > 24 + sizeof(mgmt->u.auth)) {
1054                 event.auth.ies = mgmt->u.auth.variable;
1055                 event.auth.ies_len = len - 24 - sizeof(mgmt->u.auth);
1056         }
1057
1058         wpa_supplicant_event(drv->ctx, EVENT_AUTH, &event);
1059 }
1060
1061
1062 static unsigned int nl80211_get_assoc_freq(struct wpa_driver_nl80211_data *drv)
1063 {
1064         struct nl_msg *msg;
1065         int ret;
1066         struct nl80211_bss_info_arg arg;
1067
1068         os_memset(&arg, 0, sizeof(arg));
1069         msg = nlmsg_alloc();
1070         if (!msg)
1071                 goto nla_put_failure;
1072
1073         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
1074         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1075
1076         arg.drv = drv;
1077         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
1078         msg = NULL;
1079         if (ret == 0) {
1080                 wpa_printf(MSG_DEBUG, "nl80211: Operating frequency for the "
1081                            "associated BSS from scan results: %u MHz",
1082                            arg.assoc_freq);
1083                 return arg.assoc_freq ? arg.assoc_freq : drv->assoc_freq;
1084         }
1085         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
1086                    "(%s)", ret, strerror(-ret));
1087 nla_put_failure:
1088         nlmsg_free(msg);
1089         return drv->assoc_freq;
1090 }
1091
1092
1093 static void mlme_event_assoc(struct wpa_driver_nl80211_data *drv,
1094                             const u8 *frame, size_t len)
1095 {
1096         const struct ieee80211_mgmt *mgmt;
1097         union wpa_event_data event;
1098         u16 status;
1099
1100         wpa_printf(MSG_DEBUG, "nl80211: Associate event");
1101         mgmt = (const struct ieee80211_mgmt *) frame;
1102         if (len < 24 + sizeof(mgmt->u.assoc_resp)) {
1103                 wpa_printf(MSG_DEBUG, "nl80211: Too short association event "
1104                            "frame");
1105                 return;
1106         }
1107
1108         status = le_to_host16(mgmt->u.assoc_resp.status_code);
1109         if (status != WLAN_STATUS_SUCCESS) {
1110                 os_memset(&event, 0, sizeof(event));
1111                 event.assoc_reject.bssid = mgmt->bssid;
1112                 if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
1113                         event.assoc_reject.resp_ies =
1114                                 (u8 *) mgmt->u.assoc_resp.variable;
1115                         event.assoc_reject.resp_ies_len =
1116                                 len - 24 - sizeof(mgmt->u.assoc_resp);
1117                 }
1118                 event.assoc_reject.status_code = status;
1119
1120                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
1121                 return;
1122         }
1123
1124         drv->associated = 1;
1125         os_memcpy(drv->bssid, mgmt->sa, ETH_ALEN);
1126
1127         os_memset(&event, 0, sizeof(event));
1128         if (len > 24 + sizeof(mgmt->u.assoc_resp)) {
1129                 event.assoc_info.resp_ies = (u8 *) mgmt->u.assoc_resp.variable;
1130                 event.assoc_info.resp_ies_len =
1131                         len - 24 - sizeof(mgmt->u.assoc_resp);
1132         }
1133
1134         event.assoc_info.freq = drv->assoc_freq;
1135
1136         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
1137 }
1138
1139
1140 static void mlme_event_connect(struct wpa_driver_nl80211_data *drv,
1141                                enum nl80211_commands cmd, struct nlattr *status,
1142                                struct nlattr *addr, struct nlattr *req_ie,
1143                                struct nlattr *resp_ie)
1144 {
1145         union wpa_event_data event;
1146
1147         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1148                 /*
1149                  * Avoid reporting two association events that would confuse
1150                  * the core code.
1151                  */
1152                 wpa_printf(MSG_DEBUG, "nl80211: Ignore connect event (cmd=%d) "
1153                            "when using userspace SME", cmd);
1154                 return;
1155         }
1156
1157         if (cmd == NL80211_CMD_CONNECT)
1158                 wpa_printf(MSG_DEBUG, "nl80211: Connect event");
1159         else if (cmd == NL80211_CMD_ROAM)
1160                 wpa_printf(MSG_DEBUG, "nl80211: Roam event");
1161
1162         os_memset(&event, 0, sizeof(event));
1163         if (cmd == NL80211_CMD_CONNECT &&
1164             nla_get_u16(status) != WLAN_STATUS_SUCCESS) {
1165                 if (addr)
1166                         event.assoc_reject.bssid = nla_data(addr);
1167                 if (resp_ie) {
1168                         event.assoc_reject.resp_ies = nla_data(resp_ie);
1169                         event.assoc_reject.resp_ies_len = nla_len(resp_ie);
1170                 }
1171                 event.assoc_reject.status_code = nla_get_u16(status);
1172                 wpa_supplicant_event(drv->ctx, EVENT_ASSOC_REJECT, &event);
1173                 return;
1174         }
1175
1176         drv->associated = 1;
1177         if (addr)
1178                 os_memcpy(drv->bssid, nla_data(addr), ETH_ALEN);
1179
1180         if (req_ie) {
1181                 event.assoc_info.req_ies = nla_data(req_ie);
1182                 event.assoc_info.req_ies_len = nla_len(req_ie);
1183         }
1184         if (resp_ie) {
1185                 event.assoc_info.resp_ies = nla_data(resp_ie);
1186                 event.assoc_info.resp_ies_len = nla_len(resp_ie);
1187         }
1188
1189         event.assoc_info.freq = nl80211_get_assoc_freq(drv);
1190
1191         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, &event);
1192 }
1193
1194
1195 static void mlme_event_disconnect(struct wpa_driver_nl80211_data *drv,
1196                                   struct nlattr *reason, struct nlattr *addr,
1197                                   struct nlattr *by_ap)
1198 {
1199         union wpa_event_data data;
1200         unsigned int locally_generated = by_ap == NULL;
1201
1202         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
1203                 /*
1204                  * Avoid reporting two disassociation events that could
1205                  * confuse the core code.
1206                  */
1207                 wpa_printf(MSG_DEBUG, "nl80211: Ignore disconnect "
1208                            "event when using userspace SME");
1209                 return;
1210         }
1211
1212         if (drv->ignore_next_local_disconnect) {
1213                 drv->ignore_next_local_disconnect = 0;
1214                 if (locally_generated) {
1215                         wpa_printf(MSG_DEBUG, "nl80211: Ignore disconnect "
1216                                    "event triggered during reassociation");
1217                         return;
1218                 }
1219                 wpa_printf(MSG_WARNING, "nl80211: Was expecting local "
1220                            "disconnect but got another disconnect "
1221                            "event first");
1222         }
1223
1224         wpa_printf(MSG_DEBUG, "nl80211: Disconnect event");
1225         drv->associated = 0;
1226         os_memset(&data, 0, sizeof(data));
1227         if (reason)
1228                 data.deauth_info.reason_code = nla_get_u16(reason);
1229         data.deauth_info.locally_generated = by_ap == NULL;
1230         wpa_supplicant_event(drv->ctx, EVENT_DEAUTH, &data);
1231 }
1232
1233
1234 static void mlme_event_ch_switch(struct wpa_driver_nl80211_data *drv,
1235                                  struct nlattr *freq, struct nlattr *type)
1236 {
1237         union wpa_event_data data;
1238         int ht_enabled = 1;
1239         int chan_offset = 0;
1240
1241         wpa_printf(MSG_DEBUG, "nl80211: Channel switch event");
1242
1243         if (!freq || !type)
1244                 return;
1245
1246         switch (nla_get_u32(type)) {
1247         case NL80211_CHAN_NO_HT:
1248                 ht_enabled = 0;
1249                 break;
1250         case NL80211_CHAN_HT20:
1251                 break;
1252         case NL80211_CHAN_HT40PLUS:
1253                 chan_offset = 1;
1254                 break;
1255         case NL80211_CHAN_HT40MINUS:
1256                 chan_offset = -1;
1257                 break;
1258         }
1259
1260         data.ch_switch.freq = nla_get_u32(freq);
1261         data.ch_switch.ht_enabled = ht_enabled;
1262         data.ch_switch.ch_offset = chan_offset;
1263
1264         wpa_supplicant_event(drv->ctx, EVENT_CH_SWITCH, &data);
1265 }
1266
1267
1268 static void mlme_timeout_event(struct wpa_driver_nl80211_data *drv,
1269                                enum nl80211_commands cmd, struct nlattr *addr)
1270 {
1271         union wpa_event_data event;
1272         enum wpa_event_type ev;
1273
1274         if (nla_len(addr) != ETH_ALEN)
1275                 return;
1276
1277         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d; timeout with " MACSTR,
1278                    cmd, MAC2STR((u8 *) nla_data(addr)));
1279
1280         if (cmd == NL80211_CMD_AUTHENTICATE)
1281                 ev = EVENT_AUTH_TIMED_OUT;
1282         else if (cmd == NL80211_CMD_ASSOCIATE)
1283                 ev = EVENT_ASSOC_TIMED_OUT;
1284         else
1285                 return;
1286
1287         os_memset(&event, 0, sizeof(event));
1288         os_memcpy(event.timeout_event.addr, nla_data(addr), ETH_ALEN);
1289         wpa_supplicant_event(drv->ctx, ev, &event);
1290 }
1291
1292
1293 static void mlme_event_mgmt(struct wpa_driver_nl80211_data *drv,
1294                             struct nlattr *freq, struct nlattr *sig,
1295                             const u8 *frame, size_t len)
1296 {
1297         const struct ieee80211_mgmt *mgmt;
1298         union wpa_event_data event;
1299         u16 fc, stype;
1300         int ssi_signal = 0;
1301
1302         wpa_printf(MSG_DEBUG, "nl80211: Frame event");
1303         mgmt = (const struct ieee80211_mgmt *) frame;
1304         if (len < 24) {
1305                 wpa_printf(MSG_DEBUG, "nl80211: Too short action frame");
1306                 return;
1307         }
1308
1309         fc = le_to_host16(mgmt->frame_control);
1310         stype = WLAN_FC_GET_STYPE(fc);
1311
1312         if (sig)
1313                 ssi_signal = (s32) nla_get_u32(sig);
1314
1315         os_memset(&event, 0, sizeof(event));
1316         if (freq) {
1317                 event.rx_action.freq = nla_get_u32(freq);
1318                 drv->last_mgmt_freq = event.rx_action.freq;
1319         }
1320         if (stype == WLAN_FC_STYPE_ACTION) {
1321                 event.rx_action.da = mgmt->da;
1322                 event.rx_action.sa = mgmt->sa;
1323                 event.rx_action.bssid = mgmt->bssid;
1324                 event.rx_action.category = mgmt->u.action.category;
1325                 event.rx_action.data = &mgmt->u.action.category + 1;
1326                 event.rx_action.len = frame + len - event.rx_action.data;
1327                 wpa_supplicant_event(drv->ctx, EVENT_RX_ACTION, &event);
1328         } else {
1329                 event.rx_mgmt.frame = frame;
1330                 event.rx_mgmt.frame_len = len;
1331                 event.rx_mgmt.ssi_signal = ssi_signal;
1332                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
1333         }
1334 }
1335
1336
1337 static void mlme_event_mgmt_tx_status(struct wpa_driver_nl80211_data *drv,
1338                                       struct nlattr *cookie, const u8 *frame,
1339                                       size_t len, struct nlattr *ack)
1340 {
1341         union wpa_event_data event;
1342         const struct ieee80211_hdr *hdr;
1343         u16 fc;
1344
1345         wpa_printf(MSG_DEBUG, "nl80211: Frame TX status event");
1346         if (!is_ap_interface(drv->nlmode)) {
1347                 u64 cookie_val;
1348
1349                 if (!cookie)
1350                         return;
1351
1352                 cookie_val = nla_get_u64(cookie);
1353                 wpa_printf(MSG_DEBUG, "nl80211: Action TX status:"
1354                            " cookie=0%llx%s (ack=%d)",
1355                            (long long unsigned int) cookie_val,
1356                            cookie_val == drv->send_action_cookie ?
1357                            " (match)" : " (unknown)", ack != NULL);
1358                 if (cookie_val != drv->send_action_cookie)
1359                         return;
1360         }
1361
1362         hdr = (const struct ieee80211_hdr *) frame;
1363         fc = le_to_host16(hdr->frame_control);
1364
1365         os_memset(&event, 0, sizeof(event));
1366         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
1367         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
1368         event.tx_status.dst = hdr->addr1;
1369         event.tx_status.data = frame;
1370         event.tx_status.data_len = len;
1371         event.tx_status.ack = ack != NULL;
1372         wpa_supplicant_event(drv->ctx, EVENT_TX_STATUS, &event);
1373 }
1374
1375
1376 static void mlme_event_deauth_disassoc(struct wpa_driver_nl80211_data *drv,
1377                                        enum wpa_event_type type,
1378                                        const u8 *frame, size_t len)
1379 {
1380         const struct ieee80211_mgmt *mgmt;
1381         union wpa_event_data event;
1382         const u8 *bssid = NULL;
1383         u16 reason_code = 0;
1384
1385         if (type == EVENT_DEAUTH)
1386                 wpa_printf(MSG_DEBUG, "nl80211: Deauthenticate event");
1387         else
1388                 wpa_printf(MSG_DEBUG, "nl80211: Disassociate event");
1389
1390         mgmt = (const struct ieee80211_mgmt *) frame;
1391         if (len >= 24) {
1392                 bssid = mgmt->bssid;
1393
1394                 if (drv->associated != 0 &&
1395                     os_memcmp(bssid, drv->bssid, ETH_ALEN) != 0 &&
1396                     os_memcmp(bssid, drv->auth_bssid, ETH_ALEN) != 0) {
1397                         /*
1398                          * We have presumably received this deauth as a
1399                          * response to a clear_state_mismatch() outgoing
1400                          * deauth.  Don't let it take us offline!
1401                          */
1402                         wpa_printf(MSG_DEBUG, "nl80211: Deauth received "
1403                                    "from Unknown BSSID " MACSTR " -- ignoring",
1404                                    MAC2STR(bssid));
1405                         return;
1406                 }
1407         }
1408
1409         drv->associated = 0;
1410         os_memset(&event, 0, sizeof(event));
1411
1412         /* Note: Same offset for Reason Code in both frame subtypes */
1413         if (len >= 24 + sizeof(mgmt->u.deauth))
1414                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
1415
1416         if (type == EVENT_DISASSOC) {
1417                 event.disassoc_info.locally_generated =
1418                         !os_memcmp(mgmt->sa, drv->first_bss.addr, ETH_ALEN);
1419                 event.disassoc_info.addr = bssid;
1420                 event.disassoc_info.reason_code = reason_code;
1421                 if (frame + len > mgmt->u.disassoc.variable) {
1422                         event.disassoc_info.ie = mgmt->u.disassoc.variable;
1423                         event.disassoc_info.ie_len = frame + len -
1424                                 mgmt->u.disassoc.variable;
1425                 }
1426         } else {
1427                 event.deauth_info.locally_generated =
1428                         !os_memcmp(mgmt->sa, drv->first_bss.addr, ETH_ALEN);
1429                 event.deauth_info.addr = bssid;
1430                 event.deauth_info.reason_code = reason_code;
1431                 if (frame + len > mgmt->u.deauth.variable) {
1432                         event.deauth_info.ie = mgmt->u.deauth.variable;
1433                         event.deauth_info.ie_len = frame + len -
1434                                 mgmt->u.deauth.variable;
1435                 }
1436         }
1437
1438         wpa_supplicant_event(drv->ctx, type, &event);
1439 }
1440
1441
1442 static void mlme_event_unprot_disconnect(struct wpa_driver_nl80211_data *drv,
1443                                          enum wpa_event_type type,
1444                                          const u8 *frame, size_t len)
1445 {
1446         const struct ieee80211_mgmt *mgmt;
1447         union wpa_event_data event;
1448         u16 reason_code = 0;
1449
1450         if (type == EVENT_UNPROT_DEAUTH)
1451                 wpa_printf(MSG_DEBUG, "nl80211: Unprot Deauthenticate event");
1452         else
1453                 wpa_printf(MSG_DEBUG, "nl80211: Unprot Disassociate event");
1454
1455         if (len < 24)
1456                 return;
1457
1458         mgmt = (const struct ieee80211_mgmt *) frame;
1459
1460         os_memset(&event, 0, sizeof(event));
1461         /* Note: Same offset for Reason Code in both frame subtypes */
1462         if (len >= 24 + sizeof(mgmt->u.deauth))
1463                 reason_code = le_to_host16(mgmt->u.deauth.reason_code);
1464
1465         if (type == EVENT_UNPROT_DISASSOC) {
1466                 event.unprot_disassoc.sa = mgmt->sa;
1467                 event.unprot_disassoc.da = mgmt->da;
1468                 event.unprot_disassoc.reason_code = reason_code;
1469         } else {
1470                 event.unprot_deauth.sa = mgmt->sa;
1471                 event.unprot_deauth.da = mgmt->da;
1472                 event.unprot_deauth.reason_code = reason_code;
1473         }
1474
1475         wpa_supplicant_event(drv->ctx, type, &event);
1476 }
1477
1478
1479 static void mlme_event(struct wpa_driver_nl80211_data *drv,
1480                        enum nl80211_commands cmd, struct nlattr *frame,
1481                        struct nlattr *addr, struct nlattr *timed_out,
1482                        struct nlattr *freq, struct nlattr *ack,
1483                        struct nlattr *cookie, struct nlattr *sig)
1484 {
1485         if (timed_out && addr) {
1486                 mlme_timeout_event(drv, cmd, addr);
1487                 return;
1488         }
1489
1490         if (frame == NULL) {
1491                 wpa_printf(MSG_DEBUG, "nl80211: MLME event %d without frame "
1492                            "data", cmd);
1493                 return;
1494         }
1495
1496         wpa_printf(MSG_DEBUG, "nl80211: MLME event %d", cmd);
1497         wpa_hexdump(MSG_MSGDUMP, "nl80211: MLME event frame",
1498                     nla_data(frame), nla_len(frame));
1499
1500         switch (cmd) {
1501         case NL80211_CMD_AUTHENTICATE:
1502                 mlme_event_auth(drv, nla_data(frame), nla_len(frame));
1503                 break;
1504         case NL80211_CMD_ASSOCIATE:
1505                 mlme_event_assoc(drv, nla_data(frame), nla_len(frame));
1506                 break;
1507         case NL80211_CMD_DEAUTHENTICATE:
1508                 mlme_event_deauth_disassoc(drv, EVENT_DEAUTH,
1509                                            nla_data(frame), nla_len(frame));
1510                 break;
1511         case NL80211_CMD_DISASSOCIATE:
1512                 mlme_event_deauth_disassoc(drv, EVENT_DISASSOC,
1513                                            nla_data(frame), nla_len(frame));
1514                 break;
1515         case NL80211_CMD_FRAME:
1516                 mlme_event_mgmt(drv, freq, sig, nla_data(frame),
1517                                 nla_len(frame));
1518                 break;
1519         case NL80211_CMD_FRAME_TX_STATUS:
1520                 mlme_event_mgmt_tx_status(drv, cookie, nla_data(frame),
1521                                           nla_len(frame), ack);
1522                 break;
1523         case NL80211_CMD_UNPROT_DEAUTHENTICATE:
1524                 mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DEAUTH,
1525                                              nla_data(frame), nla_len(frame));
1526                 break;
1527         case NL80211_CMD_UNPROT_DISASSOCIATE:
1528                 mlme_event_unprot_disconnect(drv, EVENT_UNPROT_DISASSOC,
1529                                              nla_data(frame), nla_len(frame));
1530                 break;
1531         default:
1532                 break;
1533         }
1534 }
1535
1536
1537 static void mlme_event_michael_mic_failure(struct i802_bss *bss,
1538                                            struct nlattr *tb[])
1539 {
1540         union wpa_event_data data;
1541
1542         wpa_printf(MSG_DEBUG, "nl80211: MLME event Michael MIC failure");
1543         os_memset(&data, 0, sizeof(data));
1544         if (tb[NL80211_ATTR_MAC]) {
1545                 wpa_hexdump(MSG_DEBUG, "nl80211: Source MAC address",
1546                             nla_data(tb[NL80211_ATTR_MAC]),
1547                             nla_len(tb[NL80211_ATTR_MAC]));
1548                 data.michael_mic_failure.src = nla_data(tb[NL80211_ATTR_MAC]);
1549         }
1550         if (tb[NL80211_ATTR_KEY_SEQ]) {
1551                 wpa_hexdump(MSG_DEBUG, "nl80211: TSC",
1552                             nla_data(tb[NL80211_ATTR_KEY_SEQ]),
1553                             nla_len(tb[NL80211_ATTR_KEY_SEQ]));
1554         }
1555         if (tb[NL80211_ATTR_KEY_TYPE]) {
1556                 enum nl80211_key_type key_type =
1557                         nla_get_u32(tb[NL80211_ATTR_KEY_TYPE]);
1558                 wpa_printf(MSG_DEBUG, "nl80211: Key Type %d", key_type);
1559                 if (key_type == NL80211_KEYTYPE_PAIRWISE)
1560                         data.michael_mic_failure.unicast = 1;
1561         } else
1562                 data.michael_mic_failure.unicast = 1;
1563
1564         if (tb[NL80211_ATTR_KEY_IDX]) {
1565                 u8 key_id = nla_get_u8(tb[NL80211_ATTR_KEY_IDX]);
1566                 wpa_printf(MSG_DEBUG, "nl80211: Key Id %d", key_id);
1567         }
1568
1569         wpa_supplicant_event(bss->ctx, EVENT_MICHAEL_MIC_FAILURE, &data);
1570 }
1571
1572
1573 static void mlme_event_join_ibss(struct wpa_driver_nl80211_data *drv,
1574                                  struct nlattr *tb[])
1575 {
1576         if (tb[NL80211_ATTR_MAC] == NULL) {
1577                 wpa_printf(MSG_DEBUG, "nl80211: No address in IBSS joined "
1578                            "event");
1579                 return;
1580         }
1581         os_memcpy(drv->bssid, nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
1582         drv->associated = 1;
1583         wpa_printf(MSG_DEBUG, "nl80211: IBSS " MACSTR " joined",
1584                    MAC2STR(drv->bssid));
1585
1586         wpa_supplicant_event(drv->ctx, EVENT_ASSOC, NULL);
1587 }
1588
1589
1590 static void mlme_event_remain_on_channel(struct wpa_driver_nl80211_data *drv,
1591                                          int cancel_event, struct nlattr *tb[])
1592 {
1593         unsigned int freq, chan_type, duration;
1594         union wpa_event_data data;
1595         u64 cookie;
1596
1597         if (tb[NL80211_ATTR_WIPHY_FREQ])
1598                 freq = nla_get_u32(tb[NL80211_ATTR_WIPHY_FREQ]);
1599         else
1600                 freq = 0;
1601
1602         if (tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE])
1603                 chan_type = nla_get_u32(tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
1604         else
1605                 chan_type = 0;
1606
1607         if (tb[NL80211_ATTR_DURATION])
1608                 duration = nla_get_u32(tb[NL80211_ATTR_DURATION]);
1609         else
1610                 duration = 0;
1611
1612         if (tb[NL80211_ATTR_COOKIE])
1613                 cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
1614         else
1615                 cookie = 0;
1616
1617         wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel event (cancel=%d "
1618                    "freq=%u channel_type=%u duration=%u cookie=0x%llx (%s))",
1619                    cancel_event, freq, chan_type, duration,
1620                    (long long unsigned int) cookie,
1621                    cookie == drv->remain_on_chan_cookie ? "match" : "unknown");
1622
1623         if (cookie != drv->remain_on_chan_cookie)
1624                 return; /* not for us */
1625
1626         if (cancel_event)
1627                 drv->pending_remain_on_chan = 0;
1628
1629         os_memset(&data, 0, sizeof(data));
1630         data.remain_on_channel.freq = freq;
1631         data.remain_on_channel.duration = duration;
1632         wpa_supplicant_event(drv->ctx, cancel_event ?
1633                              EVENT_CANCEL_REMAIN_ON_CHANNEL :
1634                              EVENT_REMAIN_ON_CHANNEL, &data);
1635 }
1636
1637
1638 static void mlme_event_ft_event(struct wpa_driver_nl80211_data *drv,
1639                                 struct nlattr *tb[])
1640 {
1641         union wpa_event_data data;
1642
1643         os_memset(&data, 0, sizeof(data));
1644
1645         if (tb[NL80211_ATTR_IE]) {
1646                 data.ft_ies.ies = nla_data(tb[NL80211_ATTR_IE]);
1647                 data.ft_ies.ies_len = nla_len(tb[NL80211_ATTR_IE]);
1648         }
1649
1650         if (tb[NL80211_ATTR_IE_RIC]) {
1651                 data.ft_ies.ric_ies = nla_data(tb[NL80211_ATTR_IE_RIC]);
1652                 data.ft_ies.ric_ies_len = nla_len(tb[NL80211_ATTR_IE_RIC]);
1653         }
1654
1655         if (tb[NL80211_ATTR_MAC])
1656                 os_memcpy(data.ft_ies.target_ap,
1657                           nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
1658
1659         wpa_printf(MSG_DEBUG, "nl80211: FT event target_ap " MACSTR,
1660                    MAC2STR(data.ft_ies.target_ap));
1661
1662         wpa_supplicant_event(drv->ctx, EVENT_FT_RESPONSE, &data);
1663 }
1664
1665
1666 static void send_scan_event(struct wpa_driver_nl80211_data *drv, int aborted,
1667                             struct nlattr *tb[])
1668 {
1669         union wpa_event_data event;
1670         struct nlattr *nl;
1671         int rem;
1672         struct scan_info *info;
1673 #define MAX_REPORT_FREQS 50
1674         int freqs[MAX_REPORT_FREQS];
1675         int num_freqs = 0;
1676
1677         if (drv->scan_for_auth) {
1678                 drv->scan_for_auth = 0;
1679                 wpa_printf(MSG_DEBUG, "nl80211: Scan results for missing "
1680                            "cfg80211 BSS entry");
1681                 wpa_driver_nl80211_authenticate_retry(drv);
1682                 return;
1683         }
1684
1685         os_memset(&event, 0, sizeof(event));
1686         info = &event.scan_info;
1687         info->aborted = aborted;
1688
1689         if (tb[NL80211_ATTR_SCAN_SSIDS]) {
1690                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_SSIDS], rem) {
1691                         struct wpa_driver_scan_ssid *s =
1692                                 &info->ssids[info->num_ssids];
1693                         s->ssid = nla_data(nl);
1694                         s->ssid_len = nla_len(nl);
1695                         info->num_ssids++;
1696                         if (info->num_ssids == WPAS_MAX_SCAN_SSIDS)
1697                                 break;
1698                 }
1699         }
1700         if (tb[NL80211_ATTR_SCAN_FREQUENCIES]) {
1701                 nla_for_each_nested(nl, tb[NL80211_ATTR_SCAN_FREQUENCIES], rem)
1702                 {
1703                         freqs[num_freqs] = nla_get_u32(nl);
1704                         num_freqs++;
1705                         if (num_freqs == MAX_REPORT_FREQS - 1)
1706                                 break;
1707                 }
1708                 info->freqs = freqs;
1709                 info->num_freqs = num_freqs;
1710         }
1711         wpa_supplicant_event(drv->ctx, EVENT_SCAN_RESULTS, &event);
1712 }
1713
1714
1715 static int get_link_signal(struct nl_msg *msg, void *arg)
1716 {
1717         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1718         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1719         struct nlattr *sinfo[NL80211_STA_INFO_MAX + 1];
1720         static struct nla_policy policy[NL80211_STA_INFO_MAX + 1] = {
1721                 [NL80211_STA_INFO_SIGNAL] = { .type = NLA_U8 },
1722         };
1723         struct nlattr *rinfo[NL80211_RATE_INFO_MAX + 1];
1724         static struct nla_policy rate_policy[NL80211_RATE_INFO_MAX + 1] = {
1725                 [NL80211_RATE_INFO_BITRATE] = { .type = NLA_U16 },
1726                 [NL80211_RATE_INFO_MCS] = { .type = NLA_U8 },
1727                 [NL80211_RATE_INFO_40_MHZ_WIDTH] = { .type = NLA_FLAG },
1728                 [NL80211_RATE_INFO_SHORT_GI] = { .type = NLA_FLAG },
1729         };
1730         struct wpa_signal_info *sig_change = arg;
1731
1732         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1733                   genlmsg_attrlen(gnlh, 0), NULL);
1734         if (!tb[NL80211_ATTR_STA_INFO] ||
1735             nla_parse_nested(sinfo, NL80211_STA_INFO_MAX,
1736                              tb[NL80211_ATTR_STA_INFO], policy))
1737                 return NL_SKIP;
1738         if (!sinfo[NL80211_STA_INFO_SIGNAL])
1739                 return NL_SKIP;
1740
1741         sig_change->current_signal =
1742                 (s8) nla_get_u8(sinfo[NL80211_STA_INFO_SIGNAL]);
1743
1744         if (sinfo[NL80211_STA_INFO_TX_BITRATE]) {
1745                 if (nla_parse_nested(rinfo, NL80211_RATE_INFO_MAX,
1746                                      sinfo[NL80211_STA_INFO_TX_BITRATE],
1747                                      rate_policy)) {
1748                         sig_change->current_txrate = 0;
1749                 } else {
1750                         if (rinfo[NL80211_RATE_INFO_BITRATE]) {
1751                                 sig_change->current_txrate =
1752                                         nla_get_u16(rinfo[
1753                                              NL80211_RATE_INFO_BITRATE]) * 100;
1754                         }
1755                 }
1756         }
1757
1758         return NL_SKIP;
1759 }
1760
1761
1762 static int nl80211_get_link_signal(struct wpa_driver_nl80211_data *drv,
1763                                    struct wpa_signal_info *sig)
1764 {
1765         struct nl_msg *msg;
1766
1767         sig->current_signal = -9999;
1768         sig->current_txrate = 0;
1769
1770         msg = nlmsg_alloc();
1771         if (!msg)
1772                 return -ENOMEM;
1773
1774         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
1775
1776         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1777         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
1778
1779         return send_and_recv_msgs(drv, msg, get_link_signal, sig);
1780  nla_put_failure:
1781         nlmsg_free(msg);
1782         return -ENOBUFS;
1783 }
1784
1785
1786 static int get_link_noise(struct nl_msg *msg, void *arg)
1787 {
1788         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1789         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1790         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1791         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1792                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1793                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
1794         };
1795         struct wpa_signal_info *sig_change = arg;
1796
1797         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1798                   genlmsg_attrlen(gnlh, 0), NULL);
1799
1800         if (!tb[NL80211_ATTR_SURVEY_INFO]) {
1801                 wpa_printf(MSG_DEBUG, "nl80211: survey data missing!");
1802                 return NL_SKIP;
1803         }
1804
1805         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1806                              tb[NL80211_ATTR_SURVEY_INFO],
1807                              survey_policy)) {
1808                 wpa_printf(MSG_DEBUG, "nl80211: failed to parse nested "
1809                            "attributes!");
1810                 return NL_SKIP;
1811         }
1812
1813         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1814                 return NL_SKIP;
1815
1816         if (nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
1817             sig_change->frequency)
1818                 return NL_SKIP;
1819
1820         if (!sinfo[NL80211_SURVEY_INFO_NOISE])
1821                 return NL_SKIP;
1822
1823         sig_change->current_noise =
1824                 (s8) nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1825
1826         return NL_SKIP;
1827 }
1828
1829
1830 static int nl80211_get_link_noise(struct wpa_driver_nl80211_data *drv,
1831                                   struct wpa_signal_info *sig_change)
1832 {
1833         struct nl_msg *msg;
1834
1835         sig_change->current_noise = 9999;
1836         sig_change->frequency = drv->assoc_freq;
1837
1838         msg = nlmsg_alloc();
1839         if (!msg)
1840                 return -ENOMEM;
1841
1842         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
1843
1844         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1845
1846         return send_and_recv_msgs(drv, msg, get_link_noise, sig_change);
1847  nla_put_failure:
1848         nlmsg_free(msg);
1849         return -ENOBUFS;
1850 }
1851
1852
1853 static int get_noise_for_scan_results(struct nl_msg *msg, void *arg)
1854 {
1855         struct nlattr *tb[NL80211_ATTR_MAX + 1];
1856         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
1857         struct nlattr *sinfo[NL80211_SURVEY_INFO_MAX + 1];
1858         static struct nla_policy survey_policy[NL80211_SURVEY_INFO_MAX + 1] = {
1859                 [NL80211_SURVEY_INFO_FREQUENCY] = { .type = NLA_U32 },
1860                 [NL80211_SURVEY_INFO_NOISE] = { .type = NLA_U8 },
1861         };
1862         struct wpa_scan_results *scan_results = arg;
1863         struct wpa_scan_res *scan_res;
1864         size_t i;
1865
1866         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
1867                   genlmsg_attrlen(gnlh, 0), NULL);
1868
1869         if (!tb[NL80211_ATTR_SURVEY_INFO]) {
1870                 wpa_printf(MSG_DEBUG, "nl80211: Survey data missing");
1871                 return NL_SKIP;
1872         }
1873
1874         if (nla_parse_nested(sinfo, NL80211_SURVEY_INFO_MAX,
1875                              tb[NL80211_ATTR_SURVEY_INFO],
1876                              survey_policy)) {
1877                 wpa_printf(MSG_DEBUG, "nl80211: Failed to parse nested "
1878                            "attributes");
1879                 return NL_SKIP;
1880         }
1881
1882         if (!sinfo[NL80211_SURVEY_INFO_NOISE])
1883                 return NL_SKIP;
1884
1885         if (!sinfo[NL80211_SURVEY_INFO_FREQUENCY])
1886                 return NL_SKIP;
1887
1888         for (i = 0; i < scan_results->num; ++i) {
1889                 scan_res = scan_results->res[i];
1890                 if (!scan_res)
1891                         continue;
1892                 if ((int) nla_get_u32(sinfo[NL80211_SURVEY_INFO_FREQUENCY]) !=
1893                     scan_res->freq)
1894                         continue;
1895                 if (!(scan_res->flags & WPA_SCAN_NOISE_INVALID))
1896                         continue;
1897                 scan_res->noise = (s8)
1898                         nla_get_u8(sinfo[NL80211_SURVEY_INFO_NOISE]);
1899                 scan_res->flags &= ~WPA_SCAN_NOISE_INVALID;
1900         }
1901
1902         return NL_SKIP;
1903 }
1904
1905
1906 static int nl80211_get_noise_for_scan_results(
1907         struct wpa_driver_nl80211_data *drv,
1908         struct wpa_scan_results *scan_res)
1909 {
1910         struct nl_msg *msg;
1911
1912         msg = nlmsg_alloc();
1913         if (!msg)
1914                 return -ENOMEM;
1915
1916         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SURVEY);
1917
1918         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
1919
1920         return send_and_recv_msgs(drv, msg, get_noise_for_scan_results,
1921                                   scan_res);
1922  nla_put_failure:
1923         nlmsg_free(msg);
1924         return -ENOBUFS;
1925 }
1926
1927
1928 static void nl80211_cqm_event(struct wpa_driver_nl80211_data *drv,
1929                               struct nlattr *tb[])
1930 {
1931         static struct nla_policy cqm_policy[NL80211_ATTR_CQM_MAX + 1] = {
1932                 [NL80211_ATTR_CQM_RSSI_THOLD] = { .type = NLA_U32 },
1933                 [NL80211_ATTR_CQM_RSSI_HYST] = { .type = NLA_U8 },
1934                 [NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] = { .type = NLA_U32 },
1935                 [NL80211_ATTR_CQM_PKT_LOSS_EVENT] = { .type = NLA_U32 },
1936         };
1937         struct nlattr *cqm[NL80211_ATTR_CQM_MAX + 1];
1938         enum nl80211_cqm_rssi_threshold_event event;
1939         union wpa_event_data ed;
1940         struct wpa_signal_info sig;
1941         int res;
1942
1943         if (tb[NL80211_ATTR_CQM] == NULL ||
1944             nla_parse_nested(cqm, NL80211_ATTR_CQM_MAX, tb[NL80211_ATTR_CQM],
1945                              cqm_policy)) {
1946                 wpa_printf(MSG_DEBUG, "nl80211: Ignore invalid CQM event");
1947                 return;
1948         }
1949
1950         os_memset(&ed, 0, sizeof(ed));
1951
1952         if (cqm[NL80211_ATTR_CQM_PKT_LOSS_EVENT]) {
1953                 if (!tb[NL80211_ATTR_MAC])
1954                         return;
1955                 os_memcpy(ed.low_ack.addr, nla_data(tb[NL80211_ATTR_MAC]),
1956                           ETH_ALEN);
1957                 wpa_supplicant_event(drv->ctx, EVENT_STATION_LOW_ACK, &ed);
1958                 return;
1959         }
1960
1961         if (cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] == NULL)
1962                 return;
1963         event = nla_get_u32(cqm[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT]);
1964
1965         if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_HIGH) {
1966                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1967                            "event: RSSI high");
1968                 ed.signal_change.above_threshold = 1;
1969         } else if (event == NL80211_CQM_RSSI_THRESHOLD_EVENT_LOW) {
1970                 wpa_printf(MSG_DEBUG, "nl80211: Connection quality monitor "
1971                            "event: RSSI low");
1972                 ed.signal_change.above_threshold = 0;
1973         } else
1974                 return;
1975
1976         res = nl80211_get_link_signal(drv, &sig);
1977         if (res == 0) {
1978                 ed.signal_change.current_signal = sig.current_signal;
1979                 ed.signal_change.current_txrate = sig.current_txrate;
1980                 wpa_printf(MSG_DEBUG, "nl80211: Signal: %d dBm  txrate: %d",
1981                            sig.current_signal, sig.current_txrate);
1982         }
1983
1984         res = nl80211_get_link_noise(drv, &sig);
1985         if (res == 0) {
1986                 ed.signal_change.current_noise = sig.current_noise;
1987                 wpa_printf(MSG_DEBUG, "nl80211: Noise: %d dBm",
1988                            sig.current_noise);
1989         }
1990
1991         wpa_supplicant_event(drv->ctx, EVENT_SIGNAL_CHANGE, &ed);
1992 }
1993
1994
1995 static void nl80211_new_station_event(struct wpa_driver_nl80211_data *drv,
1996                                       struct nlattr **tb)
1997 {
1998         u8 *addr;
1999         union wpa_event_data data;
2000
2001         if (tb[NL80211_ATTR_MAC] == NULL)
2002                 return;
2003         addr = nla_data(tb[NL80211_ATTR_MAC]);
2004         wpa_printf(MSG_DEBUG, "nl80211: New station " MACSTR, MAC2STR(addr));
2005
2006         if (is_ap_interface(drv->nlmode) && drv->device_ap_sme) {
2007                 u8 *ies = NULL;
2008                 size_t ies_len = 0;
2009                 if (tb[NL80211_ATTR_IE]) {
2010                         ies = nla_data(tb[NL80211_ATTR_IE]);
2011                         ies_len = nla_len(tb[NL80211_ATTR_IE]);
2012                 }
2013                 wpa_hexdump(MSG_DEBUG, "nl80211: Assoc Req IEs", ies, ies_len);
2014                 drv_event_assoc(drv->ctx, addr, ies, ies_len, 0);
2015                 return;
2016         }
2017
2018         if (drv->nlmode != NL80211_IFTYPE_ADHOC)
2019                 return;
2020
2021         os_memset(&data, 0, sizeof(data));
2022         os_memcpy(data.ibss_rsn_start.peer, addr, ETH_ALEN);
2023         wpa_supplicant_event(drv->ctx, EVENT_IBSS_RSN_START, &data);
2024 }
2025
2026
2027 static void nl80211_del_station_event(struct wpa_driver_nl80211_data *drv,
2028                                       struct nlattr **tb)
2029 {
2030         u8 *addr;
2031         union wpa_event_data data;
2032
2033         if (tb[NL80211_ATTR_MAC] == NULL)
2034                 return;
2035         addr = nla_data(tb[NL80211_ATTR_MAC]);
2036         wpa_printf(MSG_DEBUG, "nl80211: Delete station " MACSTR,
2037                    MAC2STR(addr));
2038
2039         if (is_ap_interface(drv->nlmode) && drv->device_ap_sme) {
2040                 drv_event_disassoc(drv->ctx, addr);
2041                 return;
2042         }
2043
2044         if (drv->nlmode != NL80211_IFTYPE_ADHOC)
2045                 return;
2046
2047         os_memset(&data, 0, sizeof(data));
2048         os_memcpy(data.ibss_peer_lost.peer, addr, ETH_ALEN);
2049         wpa_supplicant_event(drv->ctx, EVENT_IBSS_PEER_LOST, &data);
2050 }
2051
2052
2053 static void nl80211_rekey_offload_event(struct wpa_driver_nl80211_data *drv,
2054                                         struct nlattr **tb)
2055 {
2056         struct nlattr *rekey_info[NUM_NL80211_REKEY_DATA];
2057         static struct nla_policy rekey_policy[NUM_NL80211_REKEY_DATA] = {
2058                 [NL80211_REKEY_DATA_KEK] = {
2059                         .minlen = NL80211_KEK_LEN,
2060                         .maxlen = NL80211_KEK_LEN,
2061                 },
2062                 [NL80211_REKEY_DATA_KCK] = {
2063                         .minlen = NL80211_KCK_LEN,
2064                         .maxlen = NL80211_KCK_LEN,
2065                 },
2066                 [NL80211_REKEY_DATA_REPLAY_CTR] = {
2067                         .minlen = NL80211_REPLAY_CTR_LEN,
2068                         .maxlen = NL80211_REPLAY_CTR_LEN,
2069                 },
2070         };
2071         union wpa_event_data data;
2072
2073         if (!tb[NL80211_ATTR_MAC])
2074                 return;
2075         if (!tb[NL80211_ATTR_REKEY_DATA])
2076                 return;
2077         if (nla_parse_nested(rekey_info, MAX_NL80211_REKEY_DATA,
2078                              tb[NL80211_ATTR_REKEY_DATA], rekey_policy))
2079                 return;
2080         if (!rekey_info[NL80211_REKEY_DATA_REPLAY_CTR])
2081                 return;
2082
2083         os_memset(&data, 0, sizeof(data));
2084         data.driver_gtk_rekey.bssid = nla_data(tb[NL80211_ATTR_MAC]);
2085         wpa_printf(MSG_DEBUG, "nl80211: Rekey offload event for BSSID " MACSTR,
2086                    MAC2STR(data.driver_gtk_rekey.bssid));
2087         data.driver_gtk_rekey.replay_ctr =
2088                 nla_data(rekey_info[NL80211_REKEY_DATA_REPLAY_CTR]);
2089         wpa_hexdump(MSG_DEBUG, "nl80211: Rekey offload - Replay Counter",
2090                     data.driver_gtk_rekey.replay_ctr, NL80211_REPLAY_CTR_LEN);
2091         wpa_supplicant_event(drv->ctx, EVENT_DRIVER_GTK_REKEY, &data);
2092 }
2093
2094
2095 static void nl80211_pmksa_candidate_event(struct wpa_driver_nl80211_data *drv,
2096                                           struct nlattr **tb)
2097 {
2098         struct nlattr *cand[NUM_NL80211_PMKSA_CANDIDATE];
2099         static struct nla_policy cand_policy[NUM_NL80211_PMKSA_CANDIDATE] = {
2100                 [NL80211_PMKSA_CANDIDATE_INDEX] = { .type = NLA_U32 },
2101                 [NL80211_PMKSA_CANDIDATE_BSSID] = {
2102                         .minlen = ETH_ALEN,
2103                         .maxlen = ETH_ALEN,
2104                 },
2105                 [NL80211_PMKSA_CANDIDATE_PREAUTH] = { .type = NLA_FLAG },
2106         };
2107         union wpa_event_data data;
2108
2109         wpa_printf(MSG_DEBUG, "nl80211: PMKSA candidate event");
2110
2111         if (!tb[NL80211_ATTR_PMKSA_CANDIDATE])
2112                 return;
2113         if (nla_parse_nested(cand, MAX_NL80211_PMKSA_CANDIDATE,
2114                              tb[NL80211_ATTR_PMKSA_CANDIDATE], cand_policy))
2115                 return;
2116         if (!cand[NL80211_PMKSA_CANDIDATE_INDEX] ||
2117             !cand[NL80211_PMKSA_CANDIDATE_BSSID])
2118                 return;
2119
2120         os_memset(&data, 0, sizeof(data));
2121         os_memcpy(data.pmkid_candidate.bssid,
2122                   nla_data(cand[NL80211_PMKSA_CANDIDATE_BSSID]), ETH_ALEN);
2123         data.pmkid_candidate.index =
2124                 nla_get_u32(cand[NL80211_PMKSA_CANDIDATE_INDEX]);
2125         data.pmkid_candidate.preauth =
2126                 cand[NL80211_PMKSA_CANDIDATE_PREAUTH] != NULL;
2127         wpa_supplicant_event(drv->ctx, EVENT_PMKID_CANDIDATE, &data);
2128 }
2129
2130
2131 static void nl80211_client_probe_event(struct wpa_driver_nl80211_data *drv,
2132                                        struct nlattr **tb)
2133 {
2134         union wpa_event_data data;
2135
2136         wpa_printf(MSG_DEBUG, "nl80211: Probe client event");
2137
2138         if (!tb[NL80211_ATTR_MAC] || !tb[NL80211_ATTR_ACK])
2139                 return;
2140
2141         os_memset(&data, 0, sizeof(data));
2142         os_memcpy(data.client_poll.addr,
2143                   nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2144
2145         wpa_supplicant_event(drv->ctx, EVENT_DRIVER_CLIENT_POLL_OK, &data);
2146 }
2147
2148
2149 static void nl80211_tdls_oper_event(struct wpa_driver_nl80211_data *drv,
2150                                     struct nlattr **tb)
2151 {
2152         union wpa_event_data data;
2153
2154         wpa_printf(MSG_DEBUG, "nl80211: TDLS operation event");
2155
2156         if (!tb[NL80211_ATTR_MAC] || !tb[NL80211_ATTR_TDLS_OPERATION])
2157                 return;
2158
2159         os_memset(&data, 0, sizeof(data));
2160         os_memcpy(data.tdls.peer, nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2161         switch (nla_get_u8(tb[NL80211_ATTR_TDLS_OPERATION])) {
2162         case NL80211_TDLS_SETUP:
2163                 wpa_printf(MSG_DEBUG, "nl80211: TDLS setup request for peer "
2164                            MACSTR, MAC2STR(data.tdls.peer));
2165                 data.tdls.oper = TDLS_REQUEST_SETUP;
2166                 break;
2167         case NL80211_TDLS_TEARDOWN:
2168                 wpa_printf(MSG_DEBUG, "nl80211: TDLS teardown request for peer "
2169                            MACSTR, MAC2STR(data.tdls.peer));
2170                 data.tdls.oper = TDLS_REQUEST_TEARDOWN;
2171                 break;
2172         default:
2173                 wpa_printf(MSG_DEBUG, "nl80211: Unsupported TDLS operatione "
2174                            "event");
2175                 return;
2176         }
2177         if (tb[NL80211_ATTR_REASON_CODE]) {
2178                 data.tdls.reason_code =
2179                         nla_get_u16(tb[NL80211_ATTR_REASON_CODE]);
2180         }
2181
2182         wpa_supplicant_event(drv->ctx, EVENT_TDLS, &data);
2183 }
2184
2185
2186 static void nl80211_connect_failed_event(struct wpa_driver_nl80211_data *drv,
2187                                          struct nlattr **tb)
2188 {
2189         union wpa_event_data data;
2190         u32 reason;
2191
2192         wpa_printf(MSG_DEBUG, "nl80211: Connect failed event");
2193
2194         if (!tb[NL80211_ATTR_MAC] || !tb[NL80211_ATTR_CONN_FAILED_REASON])
2195                 return;
2196
2197         os_memset(&data, 0, sizeof(data));
2198         os_memcpy(data.connect_failed_reason.addr,
2199                   nla_data(tb[NL80211_ATTR_MAC]), ETH_ALEN);
2200
2201         reason = nla_get_u32(tb[NL80211_ATTR_CONN_FAILED_REASON]);
2202         switch (reason) {
2203         case NL80211_CONN_FAIL_MAX_CLIENTS:
2204                 wpa_printf(MSG_DEBUG, "nl80211: Max client reached");
2205                 data.connect_failed_reason.code = MAX_CLIENT_REACHED;
2206                 break;
2207         case NL80211_CONN_FAIL_BLOCKED_CLIENT:
2208                 wpa_printf(MSG_DEBUG, "nl80211: Blocked client " MACSTR
2209                            " tried to connect",
2210                            MAC2STR(data.connect_failed_reason.addr));
2211                 data.connect_failed_reason.code = BLOCKED_CLIENT;
2212                 break;
2213         default:
2214                 wpa_printf(MSG_DEBUG, "nl8021l: Unknown connect failed reason "
2215                            "%u", reason);
2216                 return;
2217         }
2218
2219         wpa_supplicant_event(drv->ctx, EVENT_CONNECT_FAILED_REASON, &data);
2220 }
2221
2222
2223 static void nl80211_spurious_frame(struct i802_bss *bss, struct nlattr **tb,
2224                                    int wds)
2225 {
2226         struct wpa_driver_nl80211_data *drv = bss->drv;
2227         union wpa_event_data event;
2228
2229         if (!tb[NL80211_ATTR_MAC])
2230                 return;
2231
2232         os_memset(&event, 0, sizeof(event));
2233         event.rx_from_unknown.bssid = bss->addr;
2234         event.rx_from_unknown.addr = nla_data(tb[NL80211_ATTR_MAC]);
2235         event.rx_from_unknown.wds = wds;
2236
2237         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
2238 }
2239
2240
2241 static void do_process_drv_event(struct i802_bss *bss, int cmd,
2242                                  struct nlattr **tb)
2243 {
2244         struct wpa_driver_nl80211_data *drv = bss->drv;
2245
2246         if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED &&
2247             (cmd == NL80211_CMD_NEW_SCAN_RESULTS ||
2248              cmd == NL80211_CMD_SCAN_ABORTED)) {
2249                 wpa_driver_nl80211_set_mode(&drv->first_bss,
2250                                             drv->ap_scan_as_station);
2251                 drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
2252         }
2253
2254         switch (cmd) {
2255         case NL80211_CMD_TRIGGER_SCAN:
2256                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Scan trigger");
2257                 break;
2258         case NL80211_CMD_START_SCHED_SCAN:
2259                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Sched scan started");
2260                 break;
2261         case NL80211_CMD_SCHED_SCAN_STOPPED:
2262                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Sched scan stopped");
2263                 wpa_supplicant_event(drv->ctx, EVENT_SCHED_SCAN_STOPPED, NULL);
2264                 break;
2265         case NL80211_CMD_NEW_SCAN_RESULTS:
2266                 wpa_dbg(drv->ctx, MSG_DEBUG,
2267                         "nl80211: New scan results available");
2268                 drv->scan_complete_events = 1;
2269                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
2270                                      drv->ctx);
2271                 send_scan_event(drv, 0, tb);
2272                 break;
2273         case NL80211_CMD_SCHED_SCAN_RESULTS:
2274                 wpa_dbg(drv->ctx, MSG_DEBUG,
2275                         "nl80211: New sched scan results available");
2276                 send_scan_event(drv, 0, tb);
2277                 break;
2278         case NL80211_CMD_SCAN_ABORTED:
2279                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Scan aborted");
2280                 /*
2281                  * Need to indicate that scan results are available in order
2282                  * not to make wpa_supplicant stop its scanning.
2283                  */
2284                 eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv,
2285                                      drv->ctx);
2286                 send_scan_event(drv, 1, tb);
2287                 break;
2288         case NL80211_CMD_AUTHENTICATE:
2289         case NL80211_CMD_ASSOCIATE:
2290         case NL80211_CMD_DEAUTHENTICATE:
2291         case NL80211_CMD_DISASSOCIATE:
2292         case NL80211_CMD_FRAME_TX_STATUS:
2293         case NL80211_CMD_UNPROT_DEAUTHENTICATE:
2294         case NL80211_CMD_UNPROT_DISASSOCIATE:
2295                 mlme_event(drv, cmd, tb[NL80211_ATTR_FRAME],
2296                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
2297                            tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
2298                            tb[NL80211_ATTR_COOKIE],
2299                            tb[NL80211_ATTR_RX_SIGNAL_DBM]);
2300                 break;
2301         case NL80211_CMD_CONNECT:
2302         case NL80211_CMD_ROAM:
2303                 mlme_event_connect(drv, cmd,
2304                                    tb[NL80211_ATTR_STATUS_CODE],
2305                                    tb[NL80211_ATTR_MAC],
2306                                    tb[NL80211_ATTR_REQ_IE],
2307                                    tb[NL80211_ATTR_RESP_IE]);
2308                 break;
2309         case NL80211_CMD_CH_SWITCH_NOTIFY:
2310                 mlme_event_ch_switch(drv, tb[NL80211_ATTR_WIPHY_FREQ],
2311                                      tb[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
2312                 break;
2313         case NL80211_CMD_DISCONNECT:
2314                 mlme_event_disconnect(drv, tb[NL80211_ATTR_REASON_CODE],
2315                                       tb[NL80211_ATTR_MAC],
2316                                       tb[NL80211_ATTR_DISCONNECTED_BY_AP]);
2317                 break;
2318         case NL80211_CMD_MICHAEL_MIC_FAILURE:
2319                 mlme_event_michael_mic_failure(bss, tb);
2320                 break;
2321         case NL80211_CMD_JOIN_IBSS:
2322                 mlme_event_join_ibss(drv, tb);
2323                 break;
2324         case NL80211_CMD_REMAIN_ON_CHANNEL:
2325                 mlme_event_remain_on_channel(drv, 0, tb);
2326                 break;
2327         case NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL:
2328                 mlme_event_remain_on_channel(drv, 1, tb);
2329                 break;
2330         case NL80211_CMD_NOTIFY_CQM:
2331                 nl80211_cqm_event(drv, tb);
2332                 break;
2333         case NL80211_CMD_REG_CHANGE:
2334                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory domain change");
2335                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
2336                                      NULL);
2337                 break;
2338         case NL80211_CMD_REG_BEACON_HINT:
2339                 wpa_printf(MSG_DEBUG, "nl80211: Regulatory beacon hint");
2340                 wpa_supplicant_event(drv->ctx, EVENT_CHANNEL_LIST_CHANGED,
2341                                      NULL);
2342                 break;
2343         case NL80211_CMD_NEW_STATION:
2344                 nl80211_new_station_event(drv, tb);
2345                 break;
2346         case NL80211_CMD_DEL_STATION:
2347                 nl80211_del_station_event(drv, tb);
2348                 break;
2349         case NL80211_CMD_SET_REKEY_OFFLOAD:
2350                 nl80211_rekey_offload_event(drv, tb);
2351                 break;
2352         case NL80211_CMD_PMKSA_CANDIDATE:
2353                 nl80211_pmksa_candidate_event(drv, tb);
2354                 break;
2355         case NL80211_CMD_PROBE_CLIENT:
2356                 nl80211_client_probe_event(drv, tb);
2357                 break;
2358         case NL80211_CMD_TDLS_OPER:
2359                 nl80211_tdls_oper_event(drv, tb);
2360                 break;
2361         case NL80211_CMD_CONN_FAILED:
2362                 nl80211_connect_failed_event(drv, tb);
2363                 break;
2364         case NL80211_CMD_FT_EVENT:
2365                 mlme_event_ft_event(drv, tb);
2366                 break;
2367         default:
2368                 wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: Ignored unknown event "
2369                         "(cmd=%d)", cmd);
2370                 break;
2371         }
2372 }
2373
2374
2375 static int process_drv_event(struct nl_msg *msg, void *arg)
2376 {
2377         struct wpa_driver_nl80211_data *drv = arg;
2378         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2379         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2380         struct i802_bss *bss;
2381         int ifidx = -1;
2382
2383         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2384                   genlmsg_attrlen(gnlh, 0), NULL);
2385
2386         if (tb[NL80211_ATTR_IFINDEX])
2387                 ifidx = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
2388
2389         for (bss = &drv->first_bss; bss; bss = bss->next) {
2390                 if (ifidx == -1 || ifidx == bss->ifindex) {
2391                         do_process_drv_event(bss, gnlh->cmd, tb);
2392                         return NL_SKIP;
2393                 }
2394         }
2395
2396         wpa_printf(MSG_DEBUG, "nl80211: Ignored event (cmd=%d) for foreign "
2397                    "interface (ifindex %d)", gnlh->cmd, ifidx);
2398
2399         return NL_SKIP;
2400 }
2401
2402
2403 static int process_global_event(struct nl_msg *msg, void *arg)
2404 {
2405         struct nl80211_global *global = arg;
2406         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2407         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2408         struct wpa_driver_nl80211_data *drv, *tmp;
2409         int ifidx = -1;
2410         struct i802_bss *bss;
2411
2412         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2413                   genlmsg_attrlen(gnlh, 0), NULL);
2414
2415         if (tb[NL80211_ATTR_IFINDEX])
2416                 ifidx = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
2417
2418         dl_list_for_each_safe(drv, tmp, &global->interfaces,
2419                               struct wpa_driver_nl80211_data, list) {
2420                 for (bss = &drv->first_bss; bss; bss = bss->next) {
2421                         if (ifidx == -1 || ifidx == bss->ifindex) {
2422                                 do_process_drv_event(bss, gnlh->cmd, tb);
2423                                 return NL_SKIP;
2424                         }
2425                 }
2426         }
2427
2428         return NL_SKIP;
2429 }
2430
2431
2432 static int process_bss_event(struct nl_msg *msg, void *arg)
2433 {
2434         struct i802_bss *bss = arg;
2435         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2436         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2437
2438         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2439                   genlmsg_attrlen(gnlh, 0), NULL);
2440
2441         switch (gnlh->cmd) {
2442         case NL80211_CMD_FRAME:
2443         case NL80211_CMD_FRAME_TX_STATUS:
2444                 mlme_event(bss->drv, gnlh->cmd, tb[NL80211_ATTR_FRAME],
2445                            tb[NL80211_ATTR_MAC], tb[NL80211_ATTR_TIMED_OUT],
2446                            tb[NL80211_ATTR_WIPHY_FREQ], tb[NL80211_ATTR_ACK],
2447                            tb[NL80211_ATTR_COOKIE],
2448                            tb[NL80211_ATTR_RX_SIGNAL_DBM]);
2449                 break;
2450         case NL80211_CMD_UNEXPECTED_FRAME:
2451                 nl80211_spurious_frame(bss, tb, 0);
2452                 break;
2453         case NL80211_CMD_UNEXPECTED_4ADDR_FRAME:
2454                 nl80211_spurious_frame(bss, tb, 1);
2455                 break;
2456         default:
2457                 wpa_printf(MSG_DEBUG, "nl80211: Ignored unknown event "
2458                            "(cmd=%d)", gnlh->cmd);
2459                 break;
2460         }
2461
2462         return NL_SKIP;
2463 }
2464
2465
2466 static void wpa_driver_nl80211_event_receive(int sock, void *eloop_ctx,
2467                                              void *handle)
2468 {
2469         struct nl_cb *cb = eloop_ctx;
2470
2471         wpa_printf(MSG_DEBUG, "nl80211: Event message available");
2472
2473         nl_recvmsgs(handle, cb);
2474 }
2475
2476
2477 /**
2478  * wpa_driver_nl80211_set_country - ask nl80211 to set the regulatory domain
2479  * @priv: driver_nl80211 private data
2480  * @alpha2_arg: country to which to switch to
2481  * Returns: 0 on success, -1 on failure
2482  *
2483  * This asks nl80211 to set the regulatory domain for given
2484  * country ISO / IEC alpha2.
2485  */
2486 static int wpa_driver_nl80211_set_country(void *priv, const char *alpha2_arg)
2487 {
2488         struct i802_bss *bss = priv;
2489         struct wpa_driver_nl80211_data *drv = bss->drv;
2490         char alpha2[3];
2491         struct nl_msg *msg;
2492
2493         msg = nlmsg_alloc();
2494         if (!msg)
2495                 return -ENOMEM;
2496
2497         alpha2[0] = alpha2_arg[0];
2498         alpha2[1] = alpha2_arg[1];
2499         alpha2[2] = '\0';
2500
2501         nl80211_cmd(drv, msg, 0, NL80211_CMD_REQ_SET_REG);
2502
2503         NLA_PUT_STRING(msg, NL80211_ATTR_REG_ALPHA2, alpha2);
2504         if (send_and_recv_msgs(drv, msg, NULL, NULL))
2505                 return -EINVAL;
2506         return 0;
2507 nla_put_failure:
2508         nlmsg_free(msg);
2509         return -EINVAL;
2510 }
2511
2512
2513 static int protocol_feature_handler(struct nl_msg *msg, void *arg)
2514 {
2515         u32 *feat = arg;
2516         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
2517         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2518
2519         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2520                   genlmsg_attrlen(gnlh, 0), NULL);
2521
2522         if (tb_msg[NL80211_ATTR_PROTOCOL_FEATURES])
2523                 *feat = nla_get_u32(tb_msg[NL80211_ATTR_PROTOCOL_FEATURES]);
2524
2525         return NL_SKIP;
2526 }
2527
2528
2529 static u32 get_nl80211_protocol_features(struct wpa_driver_nl80211_data *drv)
2530 {
2531         u32 feat = 0;
2532         struct nl_msg *msg;
2533
2534         msg = nlmsg_alloc();
2535         if (!msg)
2536                 goto nla_put_failure;
2537
2538         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_PROTOCOL_FEATURES);
2539         if (send_and_recv_msgs(drv, msg, protocol_feature_handler, &feat) == 0)
2540                 return feat;
2541
2542         msg = NULL;
2543 nla_put_failure:
2544         nlmsg_free(msg);
2545         return 0;
2546 }
2547
2548
2549 struct wiphy_info_data {
2550         struct wpa_driver_nl80211_data *drv;
2551         struct wpa_driver_capa *capa;
2552
2553         unsigned int error:1;
2554         unsigned int device_ap_sme:1;
2555         unsigned int poll_command_supported:1;
2556         unsigned int data_tx_status:1;
2557         unsigned int monitor_supported:1;
2558         unsigned int auth_supported:1;
2559         unsigned int connect_supported:1;
2560         unsigned int p2p_go_supported:1;
2561         unsigned int p2p_client_supported:1;
2562         unsigned int p2p_concurrent:1;
2563         unsigned int p2p_multichan_concurrent:1;
2564 };
2565
2566
2567 static unsigned int probe_resp_offload_support(int supp_protocols)
2568 {
2569         unsigned int prot = 0;
2570
2571         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS)
2572                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS;
2573         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_WPS2)
2574                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_WPS2;
2575         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_P2P)
2576                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_P2P;
2577         if (supp_protocols & NL80211_PROBE_RESP_OFFLOAD_SUPPORT_80211U)
2578                 prot |= WPA_DRIVER_PROBE_RESP_OFFLOAD_INTERWORKING;
2579
2580         return prot;
2581 }
2582
2583
2584 static void wiphy_info_supported_iftypes(struct wiphy_info_data *info,
2585                                          struct nlattr *tb)
2586 {
2587         struct nlattr *nl_mode;
2588         int i;
2589
2590         if (tb == NULL)
2591                 return;
2592
2593         nla_for_each_nested(nl_mode, tb, i) {
2594                 switch (nla_type(nl_mode)) {
2595                 case NL80211_IFTYPE_AP:
2596                         info->capa->flags |= WPA_DRIVER_FLAGS_AP;
2597                         break;
2598                 case NL80211_IFTYPE_ADHOC:
2599                         info->capa->flags |= WPA_DRIVER_FLAGS_IBSS;
2600                         break;
2601                 case NL80211_IFTYPE_P2P_GO:
2602                         info->p2p_go_supported = 1;
2603                         break;
2604                 case NL80211_IFTYPE_P2P_CLIENT:
2605                         info->p2p_client_supported = 1;
2606                         break;
2607                 case NL80211_IFTYPE_MONITOR:
2608                         info->monitor_supported = 1;
2609                         break;
2610                 }
2611         }
2612 }
2613
2614
2615 static int wiphy_info_iface_comb_process(struct wiphy_info_data *info,
2616                                          struct nlattr *nl_combi)
2617 {
2618         struct nlattr *tb_comb[NUM_NL80211_IFACE_COMB];
2619         struct nlattr *tb_limit[NUM_NL80211_IFACE_LIMIT];
2620         struct nlattr *nl_limit, *nl_mode;
2621         int err, rem_limit, rem_mode;
2622         int combination_has_p2p = 0, combination_has_mgd = 0;
2623         static struct nla_policy
2624         iface_combination_policy[NUM_NL80211_IFACE_COMB] = {
2625                 [NL80211_IFACE_COMB_LIMITS] = { .type = NLA_NESTED },
2626                 [NL80211_IFACE_COMB_MAXNUM] = { .type = NLA_U32 },
2627                 [NL80211_IFACE_COMB_STA_AP_BI_MATCH] = { .type = NLA_FLAG },
2628                 [NL80211_IFACE_COMB_NUM_CHANNELS] = { .type = NLA_U32 },
2629         },
2630         iface_limit_policy[NUM_NL80211_IFACE_LIMIT] = {
2631                 [NL80211_IFACE_LIMIT_TYPES] = { .type = NLA_NESTED },
2632                 [NL80211_IFACE_LIMIT_MAX] = { .type = NLA_U32 },
2633         };
2634
2635         err = nla_parse_nested(tb_comb, MAX_NL80211_IFACE_COMB,
2636                                nl_combi, iface_combination_policy);
2637         if (err || !tb_comb[NL80211_IFACE_COMB_LIMITS] ||
2638             !tb_comb[NL80211_IFACE_COMB_MAXNUM] ||
2639             !tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS])
2640                 return 0; /* broken combination */
2641
2642         nla_for_each_nested(nl_limit, tb_comb[NL80211_IFACE_COMB_LIMITS],
2643                             rem_limit) {
2644                 err = nla_parse_nested(tb_limit, MAX_NL80211_IFACE_LIMIT,
2645                                        nl_limit, iface_limit_policy);
2646                 if (err || !tb_limit[NL80211_IFACE_LIMIT_TYPES])
2647                         return 0; /* broken combination */
2648
2649                 nla_for_each_nested(nl_mode,
2650                                     tb_limit[NL80211_IFACE_LIMIT_TYPES],
2651                                     rem_mode) {
2652                         int ift = nla_type(nl_mode);
2653                         if (ift == NL80211_IFTYPE_P2P_GO ||
2654                             ift == NL80211_IFTYPE_P2P_CLIENT)
2655                                 combination_has_p2p = 1;
2656                         if (ift == NL80211_IFTYPE_STATION)
2657                                 combination_has_mgd = 1;
2658                 }
2659                 if (combination_has_p2p && combination_has_mgd)
2660                         break;
2661         }
2662
2663         if (combination_has_p2p && combination_has_mgd) {
2664                 info->p2p_concurrent = 1;
2665                 if (nla_get_u32(tb_comb[NL80211_IFACE_COMB_NUM_CHANNELS]) > 1)
2666                         info->p2p_multichan_concurrent = 1;
2667                 return 1;
2668         }
2669
2670         return 0;
2671 }
2672
2673
2674 static void wiphy_info_iface_comb(struct wiphy_info_data *info,
2675                                   struct nlattr *tb)
2676 {
2677         struct nlattr *nl_combi;
2678         int rem_combi;
2679
2680         if (tb == NULL)
2681                 return;
2682
2683         nla_for_each_nested(nl_combi, tb, rem_combi) {
2684                 if (wiphy_info_iface_comb_process(info, nl_combi) > 0)
2685                         break;
2686         }
2687 }
2688
2689
2690 static void wiphy_info_supp_cmds(struct wiphy_info_data *info,
2691                                  struct nlattr *tb)
2692 {
2693         struct nlattr *nl_cmd;
2694         int i;
2695
2696         if (tb == NULL)
2697                 return;
2698
2699         nla_for_each_nested(nl_cmd, tb, i) {
2700                 switch (nla_get_u32(nl_cmd)) {
2701                 case NL80211_CMD_AUTHENTICATE:
2702                         info->auth_supported = 1;
2703                         break;
2704                 case NL80211_CMD_CONNECT:
2705                         info->connect_supported = 1;
2706                         break;
2707                 case NL80211_CMD_START_SCHED_SCAN:
2708                         info->capa->sched_scan_supported = 1;
2709                         break;
2710                 case NL80211_CMD_PROBE_CLIENT:
2711                         info->poll_command_supported = 1;
2712                         break;
2713                 }
2714         }
2715 }
2716
2717
2718 static void wiphy_info_max_roc(struct wpa_driver_capa *capa,
2719                                struct nlattr *tb)
2720 {
2721         /* default to 5000 since early versions of mac80211 don't set it */
2722         capa->max_remain_on_chan = 5000;
2723
2724         if (tb)
2725                 capa->max_remain_on_chan = nla_get_u32(tb);
2726 }
2727
2728
2729 static void wiphy_info_tdls(struct wpa_driver_capa *capa, struct nlattr *tdls,
2730                             struct nlattr *ext_setup)
2731 {
2732         if (tdls == NULL)
2733                 return;
2734
2735         wpa_printf(MSG_DEBUG, "nl80211: TDLS supported");
2736         capa->flags |= WPA_DRIVER_FLAGS_TDLS_SUPPORT;
2737
2738         if (ext_setup) {
2739                 wpa_printf(MSG_DEBUG, "nl80211: TDLS external setup");
2740                 capa->flags |= WPA_DRIVER_FLAGS_TDLS_EXTERNAL_SETUP;
2741         }
2742 }
2743
2744
2745 static void wiphy_info_feature_flags(struct wiphy_info_data *info,
2746                                      struct nlattr *tb)
2747 {
2748         u32 flags;
2749         struct wpa_driver_capa *capa = info->capa;
2750
2751         if (tb == NULL)
2752                 return;
2753
2754         flags = nla_get_u32(tb);
2755
2756         if (flags & NL80211_FEATURE_SK_TX_STATUS)
2757                 info->data_tx_status = 1;
2758
2759         if (flags & NL80211_FEATURE_INACTIVITY_TIMER)
2760                 capa->flags |= WPA_DRIVER_FLAGS_INACTIVITY_TIMER;
2761
2762         if (flags & NL80211_FEATURE_SAE)
2763                 capa->flags |= WPA_DRIVER_FLAGS_SAE;
2764
2765         if (flags & NL80211_FEATURE_NEED_OBSS_SCAN)
2766                 capa->flags |= WPA_DRIVER_FLAGS_OBSS_SCAN;
2767 }
2768
2769
2770 static void wiphy_info_probe_resp_offload(struct wpa_driver_capa *capa,
2771                                           struct nlattr *tb)
2772 {
2773         u32 protocols;
2774
2775         if (tb == NULL)
2776                 return;
2777
2778         protocols = nla_get_u32(tb);
2779         wpa_printf(MSG_DEBUG, "nl80211: Supports Probe Response offload in AP "
2780                    "mode");
2781         capa->flags |= WPA_DRIVER_FLAGS_PROBE_RESP_OFFLOAD;
2782         capa->probe_resp_offloads = probe_resp_offload_support(protocols);
2783 }
2784
2785
2786 static int wiphy_info_handler(struct nl_msg *msg, void *arg)
2787 {
2788         struct nlattr *tb[NL80211_ATTR_MAX + 1];
2789         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
2790         struct wiphy_info_data *info = arg;
2791         struct wpa_driver_capa *capa = info->capa;
2792         struct wpa_driver_nl80211_data *drv = info->drv;
2793
2794         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
2795                   genlmsg_attrlen(gnlh, 0), NULL);
2796
2797         if (tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS])
2798                 capa->max_scan_ssids =
2799                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCAN_SSIDS]);
2800
2801         if (tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS])
2802                 capa->max_sched_scan_ssids =
2803                         nla_get_u8(tb[NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS]);
2804
2805         if (tb[NL80211_ATTR_MAX_MATCH_SETS])
2806                 capa->max_match_sets =
2807                         nla_get_u8(tb[NL80211_ATTR_MAX_MATCH_SETS]);
2808
2809         wiphy_info_supported_iftypes(info, tb[NL80211_ATTR_SUPPORTED_IFTYPES]);
2810         wiphy_info_iface_comb(info, tb[NL80211_ATTR_INTERFACE_COMBINATIONS]);
2811         wiphy_info_supp_cmds(info, tb[NL80211_ATTR_SUPPORTED_COMMANDS]);
2812
2813         if (tb[NL80211_ATTR_OFFCHANNEL_TX_OK]) {
2814                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based "
2815                            "off-channel TX");
2816                 capa->flags |= WPA_DRIVER_FLAGS_OFFCHANNEL_TX;
2817         }
2818
2819         if (tb[NL80211_ATTR_ROAM_SUPPORT]) {
2820                 wpa_printf(MSG_DEBUG, "nl80211: Using driver-based roaming");
2821                 capa->flags |= WPA_DRIVER_FLAGS_BSS_SELECTION;
2822         }
2823
2824         wiphy_info_max_roc(capa,
2825                            tb[NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION]);
2826
2827         if (tb[NL80211_ATTR_SUPPORT_AP_UAPSD])
2828                 capa->flags |= WPA_DRIVER_FLAGS_AP_UAPSD;
2829
2830         wiphy_info_tdls(capa, tb[NL80211_ATTR_TDLS_SUPPORT],
2831                         tb[NL80211_ATTR_TDLS_EXTERNAL_SETUP]);
2832
2833         if (tb[NL80211_ATTR_DEVICE_AP_SME])
2834                 info->device_ap_sme = 1;
2835
2836         wiphy_info_feature_flags(info, tb[NL80211_ATTR_FEATURE_FLAGS]);
2837         wiphy_info_probe_resp_offload(capa,
2838                                       tb[NL80211_ATTR_PROBE_RESP_OFFLOAD]);
2839
2840         if (tb[NL80211_ATTR_EXT_CAPA] && tb[NL80211_ATTR_EXT_CAPA_MASK] &&
2841             drv->extended_capa == NULL) {
2842                 drv->extended_capa =
2843                         os_malloc(nla_len(tb[NL80211_ATTR_EXT_CAPA]));
2844                 if (drv->extended_capa) {
2845                         os_memcpy(drv->extended_capa,
2846                                   nla_data(tb[NL80211_ATTR_EXT_CAPA]),
2847                                   nla_len(tb[NL80211_ATTR_EXT_CAPA]));
2848                         drv->extended_capa_len =
2849                                 nla_len(tb[NL80211_ATTR_EXT_CAPA]);
2850                 }
2851                 drv->extended_capa_mask =
2852                         os_malloc(nla_len(tb[NL80211_ATTR_EXT_CAPA]));
2853                 if (drv->extended_capa_mask) {
2854                         os_memcpy(drv->extended_capa_mask,
2855                                   nla_data(tb[NL80211_ATTR_EXT_CAPA]),
2856                                   nla_len(tb[NL80211_ATTR_EXT_CAPA]));
2857                 } else {
2858                         os_free(drv->extended_capa);
2859                         drv->extended_capa = NULL;
2860                         drv->extended_capa_len = 0;
2861                 }
2862         }
2863
2864         return NL_SKIP;
2865 }
2866
2867
2868 static int wpa_driver_nl80211_get_info(struct wpa_driver_nl80211_data *drv,
2869                                        struct wiphy_info_data *info)
2870 {
2871         u32 feat;
2872         struct nl_msg *msg;
2873
2874         os_memset(info, 0, sizeof(*info));
2875         info->capa = &drv->capa;
2876         info->drv = drv;
2877
2878         msg = nlmsg_alloc();
2879         if (!msg)
2880                 return -1;
2881
2882         feat = get_nl80211_protocol_features(drv);
2883         if (feat & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP)
2884                 nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_WIPHY);
2885         else
2886                 nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
2887
2888         NLA_PUT_FLAG(msg, NL80211_ATTR_SPLIT_WIPHY_DUMP);
2889         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->first_bss.ifindex);
2890
2891         if (send_and_recv_msgs(drv, msg, wiphy_info_handler, info))
2892                 return -1;
2893
2894         if (info->auth_supported)
2895                 drv->capa.flags |= WPA_DRIVER_FLAGS_SME;
2896         else if (!info->connect_supported) {
2897                 wpa_printf(MSG_INFO, "nl80211: Driver does not support "
2898                            "authentication/association or connect commands");
2899                 info->error = 1;
2900         }
2901
2902         if (info->p2p_go_supported && info->p2p_client_supported)
2903                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CAPABLE;
2904         if (info->p2p_concurrent) {
2905                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
2906                            "interface (driver advertised support)");
2907                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
2908                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
2909         }
2910         if (info->p2p_multichan_concurrent) {
2911                 wpa_printf(MSG_DEBUG, "nl80211: Enable multi-channel "
2912                            "concurrent (driver advertised support)");
2913                 drv->capa.flags |= WPA_DRIVER_FLAGS_MULTI_CHANNEL_CONCURRENT;
2914         }
2915         return 0;
2916 nla_put_failure:
2917         nlmsg_free(msg);
2918         return -1;
2919 }
2920
2921
2922 static int wpa_driver_nl80211_capa(struct wpa_driver_nl80211_data *drv)
2923 {
2924         struct wiphy_info_data info;
2925         if (wpa_driver_nl80211_get_info(drv, &info))
2926                 return -1;
2927
2928         if (info.error)
2929                 return -1;
2930
2931         drv->has_capability = 1;
2932         /* For now, assume TKIP, CCMP, WPA, WPA2 are supported */
2933         drv->capa.key_mgmt = WPA_DRIVER_CAPA_KEY_MGMT_WPA |
2934                 WPA_DRIVER_CAPA_KEY_MGMT_WPA_PSK |
2935                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2 |
2936                 WPA_DRIVER_CAPA_KEY_MGMT_WPA2_PSK;
2937         drv->capa.enc = WPA_DRIVER_CAPA_ENC_WEP40 |
2938                 WPA_DRIVER_CAPA_ENC_WEP104 |
2939                 WPA_DRIVER_CAPA_ENC_TKIP |
2940                 WPA_DRIVER_CAPA_ENC_CCMP;
2941         drv->capa.auth = WPA_DRIVER_AUTH_OPEN |
2942                 WPA_DRIVER_AUTH_SHARED |
2943                 WPA_DRIVER_AUTH_LEAP;
2944
2945         drv->capa.flags |= WPA_DRIVER_FLAGS_SANE_ERROR_CODES;
2946         drv->capa.flags |= WPA_DRIVER_FLAGS_SET_KEYS_AFTER_ASSOC_DONE;
2947         drv->capa.flags |= WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2948
2949         if (!info.device_ap_sme) {
2950                 drv->capa.flags |= WPA_DRIVER_FLAGS_DEAUTH_TX_STATUS;
2951
2952                 /*
2953                  * No AP SME is currently assumed to also indicate no AP MLME
2954                  * in the driver/firmware.
2955                  */
2956                 drv->capa.flags |= WPA_DRIVER_FLAGS_AP_MLME;
2957         }
2958
2959         drv->device_ap_sme = info.device_ap_sme;
2960         drv->poll_command_supported = info.poll_command_supported;
2961         drv->data_tx_status = info.data_tx_status;
2962
2963         /*
2964          * If poll command and tx status are supported, mac80211 is new enough
2965          * to have everything we need to not need monitor interfaces.
2966          */
2967         drv->use_monitor = !info.poll_command_supported || !info.data_tx_status;
2968
2969         if (drv->device_ap_sme && drv->use_monitor) {
2970                 /*
2971                  * Non-mac80211 drivers may not support monitor interface.
2972                  * Make sure we do not get stuck with incorrect capability here
2973                  * by explicitly testing this.
2974                  */
2975                 if (!info.monitor_supported) {
2976                         wpa_printf(MSG_DEBUG, "nl80211: Disable use_monitor "
2977                                    "with device_ap_sme since no monitor mode "
2978                                    "support detected");
2979                         drv->use_monitor = 0;
2980                 }
2981         }
2982
2983         /*
2984          * If we aren't going to use monitor interfaces, but the
2985          * driver doesn't support data TX status, we won't get TX
2986          * status for EAPOL frames.
2987          */
2988         if (!drv->use_monitor && !info.data_tx_status)
2989                 drv->capa.flags &= ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
2990
2991         return 0;
2992 }
2993
2994
2995 #ifdef ANDROID
2996 static int android_genl_ctrl_resolve(struct nl_handle *handle,
2997                                      const char *name)
2998 {
2999         /*
3000          * Android ICS has very minimal genl_ctrl_resolve() implementation, so
3001          * need to work around that.
3002          */
3003         struct nl_cache *cache = NULL;
3004         struct genl_family *nl80211 = NULL;
3005         int id = -1;
3006
3007         if (genl_ctrl_alloc_cache(handle, &cache) < 0) {
3008                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate generic "
3009                            "netlink cache");
3010                 goto fail;
3011         }
3012
3013         nl80211 = genl_ctrl_search_by_name(cache, name);
3014         if (nl80211 == NULL)
3015                 goto fail;
3016
3017         id = genl_family_get_id(nl80211);
3018
3019 fail:
3020         if (nl80211)
3021                 genl_family_put(nl80211);
3022         if (cache)
3023                 nl_cache_free(cache);
3024
3025         return id;
3026 }
3027 #define genl_ctrl_resolve android_genl_ctrl_resolve
3028 #endif /* ANDROID */
3029
3030
3031 static int wpa_driver_nl80211_init_nl_global(struct nl80211_global *global)
3032 {
3033         int ret;
3034
3035         global->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
3036         if (global->nl_cb == NULL) {
3037                 wpa_printf(MSG_ERROR, "nl80211: Failed to allocate netlink "
3038                            "callbacks");
3039                 return -1;
3040         }
3041
3042         global->nl = nl_create_handle(global->nl_cb, "nl");
3043         if (global->nl == NULL)
3044                 goto err;
3045
3046         global->nl80211_id = genl_ctrl_resolve(global->nl, "nl80211");
3047         if (global->nl80211_id < 0) {
3048                 wpa_printf(MSG_ERROR, "nl80211: 'nl80211' generic netlink not "
3049                            "found");
3050                 goto err;
3051         }
3052
3053         global->nl_event = nl_create_handle(global->nl_cb, "event");
3054         if (global->nl_event == NULL)
3055                 goto err;
3056
3057         ret = nl_get_multicast_id(global, "nl80211", "scan");
3058         if (ret >= 0)
3059                 ret = nl_socket_add_membership(global->nl_event, ret);
3060         if (ret < 0) {
3061                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
3062                            "membership for scan events: %d (%s)",
3063                            ret, strerror(-ret));
3064                 goto err;
3065         }
3066
3067         ret = nl_get_multicast_id(global, "nl80211", "mlme");
3068         if (ret >= 0)
3069                 ret = nl_socket_add_membership(global->nl_event, ret);
3070         if (ret < 0) {
3071                 wpa_printf(MSG_ERROR, "nl80211: Could not add multicast "
3072                            "membership for mlme events: %d (%s)",
3073                            ret, strerror(-ret));
3074                 goto err;
3075         }
3076
3077         ret = nl_get_multicast_id(global, "nl80211", "regulatory");
3078         if (ret >= 0)
3079                 ret = nl_socket_add_membership(global->nl_event, ret);
3080         if (ret < 0) {
3081                 wpa_printf(MSG_DEBUG, "nl80211: Could not add multicast "
3082                            "membership for regulatory events: %d (%s)",
3083                            ret, strerror(-ret));
3084                 /* Continue without regulatory events */
3085         }
3086
3087         nl_cb_set(global->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
3088                   no_seq_check, NULL);
3089         nl_cb_set(global->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
3090                   process_global_event, global);
3091
3092         eloop_register_read_sock(nl_socket_get_fd(global->nl_event),
3093                                  wpa_driver_nl80211_event_receive,
3094                                  global->nl_cb, global->nl_event);
3095
3096         return 0;
3097
3098 err:
3099         nl_destroy_handles(&global->nl_event);
3100         nl_destroy_handles(&global->nl);
3101         nl_cb_put(global->nl_cb);
3102         global->nl_cb = NULL;
3103         return -1;
3104 }
3105
3106
3107 static int wpa_driver_nl80211_init_nl(struct wpa_driver_nl80211_data *drv)
3108 {
3109         drv->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
3110         if (!drv->nl_cb) {
3111                 wpa_printf(MSG_ERROR, "nl80211: Failed to alloc cb struct");
3112                 return -1;
3113         }
3114
3115         nl_cb_set(drv->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
3116                   no_seq_check, NULL);
3117         nl_cb_set(drv->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
3118                   process_drv_event, drv);
3119
3120         return 0;
3121 }
3122
3123
3124 static void wpa_driver_nl80211_rfkill_blocked(void *ctx)
3125 {
3126         wpa_printf(MSG_DEBUG, "nl80211: RFKILL blocked");
3127         /*
3128          * This may be for any interface; use ifdown event to disable
3129          * interface.
3130          */
3131 }
3132
3133
3134 static void wpa_driver_nl80211_rfkill_unblocked(void *ctx)
3135 {
3136         struct wpa_driver_nl80211_data *drv = ctx;
3137         wpa_printf(MSG_DEBUG, "nl80211: RFKILL unblocked");
3138         if (linux_set_iface_flags(drv->global->ioctl_sock,
3139                                   drv->first_bss.ifname, 1)) {
3140                 wpa_printf(MSG_DEBUG, "nl80211: Could not set interface UP "
3141                            "after rfkill unblock");
3142                 return;
3143         }
3144         /* rtnetlink ifup handler will report interface as enabled */
3145 }
3146
3147
3148 static void nl80211_get_phy_name(struct wpa_driver_nl80211_data *drv)
3149 {
3150         /* Find phy (radio) to which this interface belongs */
3151         char buf[90], *pos;
3152         int f, rv;
3153
3154         drv->phyname[0] = '\0';
3155         snprintf(buf, sizeof(buf) - 1, "/sys/class/net/%s/phy80211/name",
3156                  drv->first_bss.ifname);
3157         f = open(buf, O_RDONLY);
3158         if (f < 0) {
3159                 wpa_printf(MSG_DEBUG, "Could not open file %s: %s",
3160                            buf, strerror(errno));
3161                 return;
3162         }
3163
3164         rv = read(f, drv->phyname, sizeof(drv->phyname) - 1);
3165         close(f);
3166         if (rv < 0) {
3167                 wpa_printf(MSG_DEBUG, "Could not read file %s: %s",
3168                            buf, strerror(errno));
3169                 return;
3170         }
3171
3172         drv->phyname[rv] = '\0';
3173         pos = os_strchr(drv->phyname, '\n');
3174         if (pos)
3175                 *pos = '\0';
3176         wpa_printf(MSG_DEBUG, "nl80211: interface %s in phy %s",
3177                    drv->first_bss.ifname, drv->phyname);
3178 }
3179
3180
3181 static void wpa_driver_nl80211_handle_eapol_tx_status(int sock,
3182                                                       void *eloop_ctx,
3183                                                       void *handle)
3184 {
3185         struct wpa_driver_nl80211_data *drv = eloop_ctx;
3186         u8 data[2048];
3187         struct msghdr msg;
3188         struct iovec entry;
3189         u8 control[512];
3190         struct cmsghdr *cmsg;
3191         int res, found_ee = 0, found_wifi = 0, acked = 0;
3192         union wpa_event_data event;
3193
3194         memset(&msg, 0, sizeof(msg));
3195         msg.msg_iov = &entry;
3196         msg.msg_iovlen = 1;
3197         entry.iov_base = data;
3198         entry.iov_len = sizeof(data);
3199         msg.msg_control = &control;
3200         msg.msg_controllen = sizeof(control);
3201
3202         res = recvmsg(sock, &msg, MSG_ERRQUEUE);
3203         /* if error or not fitting 802.3 header, return */
3204         if (res < 14)
3205                 return;
3206
3207         for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg))
3208         {
3209                 if (cmsg->cmsg_level == SOL_SOCKET &&
3210                     cmsg->cmsg_type == SCM_WIFI_STATUS) {
3211                         int *ack;
3212
3213                         found_wifi = 1;
3214                         ack = (void *)CMSG_DATA(cmsg);
3215                         acked = *ack;
3216                 }
3217
3218                 if (cmsg->cmsg_level == SOL_PACKET &&
3219                     cmsg->cmsg_type == PACKET_TX_TIMESTAMP) {
3220                         struct sock_extended_err *err =
3221                                 (struct sock_extended_err *)CMSG_DATA(cmsg);
3222
3223                         if (err->ee_origin == SO_EE_ORIGIN_TXSTATUS)
3224                                 found_ee = 1;
3225                 }
3226         }
3227
3228         if (!found_ee || !found_wifi)
3229                 return;
3230
3231         memset(&event, 0, sizeof(event));
3232         event.eapol_tx_status.dst = data;
3233         event.eapol_tx_status.data = data + 14;
3234         event.eapol_tx_status.data_len = res - 14;
3235         event.eapol_tx_status.ack = acked;
3236         wpa_supplicant_event(drv->ctx, EVENT_EAPOL_TX_STATUS, &event);
3237 }
3238
3239
3240 static int nl80211_init_bss(struct i802_bss *bss)
3241 {
3242         bss->nl_cb = nl_cb_alloc(NL_CB_DEFAULT);
3243         if (!bss->nl_cb)
3244                 return -1;
3245
3246         nl_cb_set(bss->nl_cb, NL_CB_SEQ_CHECK, NL_CB_CUSTOM,
3247                   no_seq_check, NULL);
3248         nl_cb_set(bss->nl_cb, NL_CB_VALID, NL_CB_CUSTOM,
3249                   process_bss_event, bss);
3250
3251         return 0;
3252 }
3253
3254
3255 static void nl80211_destroy_bss(struct i802_bss *bss)
3256 {
3257         nl_cb_put(bss->nl_cb);
3258         bss->nl_cb = NULL;
3259 }
3260
3261
3262 /**
3263  * wpa_driver_nl80211_init - Initialize nl80211 driver interface
3264  * @ctx: context to be used when calling wpa_supplicant functions,
3265  * e.g., wpa_supplicant_event()
3266  * @ifname: interface name, e.g., wlan0
3267  * @global_priv: private driver global data from global_init()
3268  * Returns: Pointer to private data, %NULL on failure
3269  */
3270 static void * wpa_driver_nl80211_init(void *ctx, const char *ifname,
3271                                       void *global_priv)
3272 {
3273         struct wpa_driver_nl80211_data *drv;
3274         struct rfkill_config *rcfg;
3275         struct i802_bss *bss;
3276
3277         if (global_priv == NULL)
3278                 return NULL;
3279         drv = os_zalloc(sizeof(*drv));
3280         if (drv == NULL)
3281                 return NULL;
3282         drv->global = global_priv;
3283         drv->ctx = ctx;
3284         bss = &drv->first_bss;
3285         bss->drv = drv;
3286         bss->ctx = ctx;
3287
3288         os_strlcpy(bss->ifname, ifname, sizeof(bss->ifname));
3289         drv->monitor_ifidx = -1;
3290         drv->monitor_sock = -1;
3291         drv->eapol_tx_sock = -1;
3292         drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
3293
3294         if (wpa_driver_nl80211_init_nl(drv)) {
3295                 os_free(drv);
3296                 return NULL;
3297         }
3298
3299         if (nl80211_init_bss(bss))
3300                 goto failed;
3301
3302         nl80211_get_phy_name(drv);
3303
3304         rcfg = os_zalloc(sizeof(*rcfg));
3305         if (rcfg == NULL)
3306                 goto failed;
3307         rcfg->ctx = drv;
3308         os_strlcpy(rcfg->ifname, ifname, sizeof(rcfg->ifname));
3309         rcfg->blocked_cb = wpa_driver_nl80211_rfkill_blocked;
3310         rcfg->unblocked_cb = wpa_driver_nl80211_rfkill_unblocked;
3311         drv->rfkill = rfkill_init(rcfg);
3312         if (drv->rfkill == NULL) {
3313                 wpa_printf(MSG_DEBUG, "nl80211: RFKILL status not available");
3314                 os_free(rcfg);
3315         }
3316
3317         if (wpa_driver_nl80211_finish_drv_init(drv))
3318                 goto failed;
3319
3320         drv->eapol_tx_sock = socket(PF_PACKET, SOCK_DGRAM, 0);
3321         if (drv->eapol_tx_sock < 0)
3322                 goto failed;
3323
3324         if (drv->data_tx_status) {
3325                 int enabled = 1;
3326
3327                 if (setsockopt(drv->eapol_tx_sock, SOL_SOCKET, SO_WIFI_STATUS,
3328                                &enabled, sizeof(enabled)) < 0) {
3329                         wpa_printf(MSG_DEBUG,
3330                                 "nl80211: wifi status sockopt failed\n");
3331                         drv->data_tx_status = 0;
3332                         if (!drv->use_monitor)
3333                                 drv->capa.flags &=
3334                                         ~WPA_DRIVER_FLAGS_EAPOL_TX_STATUS;
3335                 } else {
3336                         eloop_register_read_sock(drv->eapol_tx_sock,
3337                                 wpa_driver_nl80211_handle_eapol_tx_status,
3338                                 drv, NULL);
3339                 }
3340         }
3341
3342         if (drv->global) {
3343                 dl_list_add(&drv->global->interfaces, &drv->list);
3344                 drv->in_interface_list = 1;
3345         }
3346
3347         return bss;
3348
3349 failed:
3350         wpa_driver_nl80211_deinit(bss);
3351         return NULL;
3352 }
3353
3354
3355 static int nl80211_register_frame(struct i802_bss *bss,
3356                                   struct nl_handle *nl_handle,
3357                                   u16 type, const u8 *match, size_t match_len)
3358 {
3359         struct wpa_driver_nl80211_data *drv = bss->drv;
3360         struct nl_msg *msg;
3361         int ret = -1;
3362
3363         msg = nlmsg_alloc();
3364         if (!msg)
3365                 return -1;
3366
3367         wpa_printf(MSG_DEBUG, "nl80211: Register frame type=0x%x nl_handle=%p",
3368                    type, nl_handle);
3369         wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
3370                     match, match_len);
3371
3372         nl80211_cmd(drv, msg, 0, NL80211_CMD_REGISTER_ACTION);
3373
3374         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3375         NLA_PUT_U16(msg, NL80211_ATTR_FRAME_TYPE, type);
3376         NLA_PUT(msg, NL80211_ATTR_FRAME_MATCH, match_len, match);
3377
3378         ret = send_and_recv(drv->global, nl_handle, msg, NULL, NULL);
3379         msg = NULL;
3380         if (ret) {
3381                 wpa_printf(MSG_DEBUG, "nl80211: Register frame command "
3382                            "failed (type=%u): ret=%d (%s)",
3383                            type, ret, strerror(-ret));
3384                 wpa_hexdump(MSG_DEBUG, "nl80211: Register frame match",
3385                             match, match_len);
3386                 goto nla_put_failure;
3387         }
3388         ret = 0;
3389 nla_put_failure:
3390         nlmsg_free(msg);
3391         return ret;
3392 }
3393
3394
3395 static int nl80211_alloc_mgmt_handle(struct i802_bss *bss)
3396 {
3397         struct wpa_driver_nl80211_data *drv = bss->drv;
3398
3399         if (bss->nl_mgmt) {
3400                 wpa_printf(MSG_DEBUG, "nl80211: Mgmt reporting "
3401                            "already on! (nl_mgmt=%p)", bss->nl_mgmt);
3402                 return -1;
3403         }
3404
3405         bss->nl_mgmt = nl_create_handle(drv->nl_cb, "mgmt");
3406         if (bss->nl_mgmt == NULL)
3407                 return -1;
3408
3409         eloop_register_read_sock(nl_socket_get_fd(bss->nl_mgmt),
3410                                  wpa_driver_nl80211_event_receive, bss->nl_cb,
3411                                  bss->nl_mgmt);
3412
3413         return 0;
3414 }
3415
3416
3417 static int nl80211_register_action_frame(struct i802_bss *bss,
3418                                          const u8 *match, size_t match_len)
3419 {
3420         u16 type = (WLAN_FC_TYPE_MGMT << 2) | (WLAN_FC_STYPE_ACTION << 4);
3421         return nl80211_register_frame(bss, bss->nl_mgmt,
3422                                       type, match, match_len);
3423 }
3424
3425
3426 static int nl80211_mgmt_subscribe_non_ap(struct i802_bss *bss)
3427 {
3428         struct wpa_driver_nl80211_data *drv = bss->drv;
3429
3430         if (nl80211_alloc_mgmt_handle(bss))
3431                 return -1;
3432         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with non-AP "
3433                    "handle %p", bss->nl_mgmt);
3434
3435 #if defined(CONFIG_P2P) || defined(CONFIG_INTERWORKING)
3436         /* GAS Initial Request */
3437         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0a", 2) < 0)
3438                 return -1;
3439         /* GAS Initial Response */
3440         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0b", 2) < 0)
3441                 return -1;
3442         /* GAS Comeback Request */
3443         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0c", 2) < 0)
3444                 return -1;
3445         /* GAS Comeback Response */
3446         if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0d", 2) < 0)
3447                 return -1;
3448 #endif /* CONFIG_P2P || CONFIG_INTERWORKING */
3449 #ifdef CONFIG_P2P
3450         /* P2P Public Action */
3451         if (nl80211_register_action_frame(bss,
3452                                           (u8 *) "\x04\x09\x50\x6f\x9a\x09",
3453                                           6) < 0)
3454                 return -1;
3455         /* P2P Action */
3456         if (nl80211_register_action_frame(bss,
3457                                           (u8 *) "\x7f\x50\x6f\x9a\x09",
3458                                           5) < 0)
3459                 return -1;
3460 #endif /* CONFIG_P2P */
3461 #ifdef CONFIG_IEEE80211W
3462         /* SA Query Response */
3463         if (nl80211_register_action_frame(bss, (u8 *) "\x08\x01", 2) < 0)
3464                 return -1;
3465 #endif /* CONFIG_IEEE80211W */
3466 #ifdef CONFIG_TDLS
3467         if ((drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT)) {
3468                 /* TDLS Discovery Response */
3469                 if (nl80211_register_action_frame(bss, (u8 *) "\x04\x0e", 2) <
3470                     0)
3471                         return -1;
3472         }
3473 #endif /* CONFIG_TDLS */
3474
3475         /* FT Action frames */
3476         if (nl80211_register_action_frame(bss, (u8 *) "\x06", 1) < 0)
3477                 return -1;
3478         else
3479                 drv->capa.key_mgmt |= WPA_DRIVER_CAPA_KEY_MGMT_FT |
3480                         WPA_DRIVER_CAPA_KEY_MGMT_FT_PSK;
3481
3482         /* WNM - BSS Transition Management Request */
3483         if (nl80211_register_action_frame(bss, (u8 *) "\x0a\x07", 2) < 0)
3484                 return -1;
3485         /* WNM-Sleep Mode Response */
3486         if (nl80211_register_action_frame(bss, (u8 *) "\x0a\x11", 2) < 0)
3487                 return -1;
3488
3489         return 0;
3490 }
3491
3492
3493 static int nl80211_register_spurious_class3(struct i802_bss *bss)
3494 {
3495         struct wpa_driver_nl80211_data *drv = bss->drv;
3496         struct nl_msg *msg;
3497         int ret = -1;
3498
3499         msg = nlmsg_alloc();
3500         if (!msg)
3501                 return -1;
3502
3503         nl80211_cmd(drv, msg, 0, NL80211_CMD_UNEXPECTED_FRAME);
3504
3505         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
3506
3507         ret = send_and_recv(drv->global, bss->nl_mgmt, msg, NULL, NULL);
3508         msg = NULL;
3509         if (ret) {
3510                 wpa_printf(MSG_DEBUG, "nl80211: Register spurious class3 "
3511                            "failed: ret=%d (%s)",
3512                            ret, strerror(-ret));
3513                 goto nla_put_failure;
3514         }
3515         ret = 0;
3516 nla_put_failure:
3517         nlmsg_free(msg);
3518         return ret;
3519 }
3520
3521
3522 static int nl80211_mgmt_subscribe_ap(struct i802_bss *bss)
3523 {
3524         static const int stypes[] = {
3525                 WLAN_FC_STYPE_AUTH,
3526                 WLAN_FC_STYPE_ASSOC_REQ,
3527                 WLAN_FC_STYPE_REASSOC_REQ,
3528                 WLAN_FC_STYPE_DISASSOC,
3529                 WLAN_FC_STYPE_DEAUTH,
3530                 WLAN_FC_STYPE_ACTION,
3531                 WLAN_FC_STYPE_PROBE_REQ,
3532 /* Beacon doesn't work as mac80211 doesn't currently allow
3533  * it, but it wouldn't really be the right thing anyway as
3534  * it isn't per interface ... maybe just dump the scan
3535  * results periodically for OLBC?
3536  */
3537 //              WLAN_FC_STYPE_BEACON,
3538         };
3539         unsigned int i;
3540
3541         if (nl80211_alloc_mgmt_handle(bss))
3542                 return -1;
3543         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3544                    "handle %p", bss->nl_mgmt);
3545
3546         for (i = 0; i < sizeof(stypes) / sizeof(stypes[0]); i++) {
3547                 if (nl80211_register_frame(bss, bss->nl_mgmt,
3548                                            (WLAN_FC_TYPE_MGMT << 2) |
3549                                            (stypes[i] << 4),
3550                                            NULL, 0) < 0) {
3551                         goto out_err;
3552                 }
3553         }
3554
3555         if (nl80211_register_spurious_class3(bss))
3556                 goto out_err;
3557
3558         if (nl80211_get_wiphy_data_ap(bss) == NULL)
3559                 goto out_err;
3560
3561         return 0;
3562
3563 out_err:
3564         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3565         nl_destroy_handles(&bss->nl_mgmt);
3566         return -1;
3567 }
3568
3569
3570 static int nl80211_mgmt_subscribe_ap_dev_sme(struct i802_bss *bss)
3571 {
3572         if (nl80211_alloc_mgmt_handle(bss))
3573                 return -1;
3574         wpa_printf(MSG_DEBUG, "nl80211: Subscribe to mgmt frames with AP "
3575                    "handle %p (device SME)", bss->nl_mgmt);
3576
3577         if (nl80211_register_frame(bss, bss->nl_mgmt,
3578                                    (WLAN_FC_TYPE_MGMT << 2) |
3579                                    (WLAN_FC_STYPE_ACTION << 4),
3580                                    NULL, 0) < 0)
3581                 goto out_err;
3582
3583         return 0;
3584
3585 out_err:
3586         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3587         nl_destroy_handles(&bss->nl_mgmt);
3588         return -1;
3589 }
3590
3591
3592 static void nl80211_mgmt_unsubscribe(struct i802_bss *bss, const char *reason)
3593 {
3594         if (bss->nl_mgmt == NULL)
3595                 return;
3596         wpa_printf(MSG_DEBUG, "nl80211: Unsubscribe mgmt frames handle %p "
3597                    "(%s)", bss->nl_mgmt, reason);
3598         eloop_unregister_read_sock(nl_socket_get_fd(bss->nl_mgmt));
3599         nl_destroy_handles(&bss->nl_mgmt);
3600
3601         nl80211_put_wiphy_data_ap(bss);
3602 }
3603
3604
3605 static void wpa_driver_nl80211_send_rfkill(void *eloop_ctx, void *timeout_ctx)
3606 {
3607         wpa_supplicant_event(timeout_ctx, EVENT_INTERFACE_DISABLED, NULL);
3608 }
3609
3610
3611 static int
3612 wpa_driver_nl80211_finish_drv_init(struct wpa_driver_nl80211_data *drv)
3613 {
3614         struct i802_bss *bss = &drv->first_bss;
3615         int send_rfkill_event = 0;
3616
3617         drv->ifindex = if_nametoindex(bss->ifname);
3618         drv->first_bss.ifindex = drv->ifindex;
3619
3620 #ifndef HOSTAPD
3621         /*
3622          * Make sure the interface starts up in station mode unless this is a
3623          * dynamically added interface (e.g., P2P) that was already configured
3624          * with proper iftype.
3625          */
3626         if (drv->ifindex != drv->global->if_add_ifindex &&
3627             wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION) < 0) {
3628                 wpa_printf(MSG_ERROR, "nl80211: Could not configure driver to "
3629                            "use managed mode");
3630                 return -1;
3631         }
3632
3633         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
3634                 if (rfkill_is_blocked(drv->rfkill)) {
3635                         wpa_printf(MSG_DEBUG, "nl80211: Could not yet enable "
3636                                    "interface '%s' due to rfkill",
3637                                    bss->ifname);
3638                         drv->if_disabled = 1;
3639                         send_rfkill_event = 1;
3640                 } else {
3641                         wpa_printf(MSG_ERROR, "nl80211: Could not set "
3642                                    "interface '%s' UP", bss->ifname);
3643                         return -1;
3644                 }
3645         }
3646
3647         netlink_send_oper_ifla(drv->global->netlink, drv->ifindex,
3648                                1, IF_OPER_DORMANT);
3649 #endif /* HOSTAPD */
3650
3651         if (wpa_driver_nl80211_capa(drv))
3652                 return -1;
3653
3654         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
3655                                bss->addr))
3656                 return -1;
3657
3658         if (send_rfkill_event) {
3659                 eloop_register_timeout(0, 0, wpa_driver_nl80211_send_rfkill,
3660                                        drv, drv->ctx);
3661         }
3662
3663         return 0;
3664 }
3665
3666
3667 static int wpa_driver_nl80211_del_beacon(struct wpa_driver_nl80211_data *drv)
3668 {
3669         struct nl_msg *msg;
3670
3671         msg = nlmsg_alloc();
3672         if (!msg)
3673                 return -ENOMEM;
3674
3675         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_BEACON);
3676         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
3677
3678         return send_and_recv_msgs(drv, msg, NULL, NULL);
3679  nla_put_failure:
3680         nlmsg_free(msg);
3681         return -ENOBUFS;
3682 }
3683
3684
3685 /**
3686  * wpa_driver_nl80211_deinit - Deinitialize nl80211 driver interface
3687  * @bss: Pointer to private nl80211 data from wpa_driver_nl80211_init()
3688  *
3689  * Shut down driver interface and processing of driver events. Free
3690  * private data buffer if one was allocated in wpa_driver_nl80211_init().
3691  */
3692 static void wpa_driver_nl80211_deinit(struct i802_bss *bss)
3693 {
3694         struct wpa_driver_nl80211_data *drv = bss->drv;
3695
3696         bss->in_deinit = 1;
3697         if (drv->data_tx_status)
3698                 eloop_unregister_read_sock(drv->eapol_tx_sock);
3699         if (drv->eapol_tx_sock >= 0)
3700                 close(drv->eapol_tx_sock);
3701
3702         if (bss->nl_preq)
3703                 wpa_driver_nl80211_probe_req_report(bss, 0);
3704         if (bss->added_if_into_bridge) {
3705                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
3706                                     bss->ifname) < 0)
3707                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3708                                    "interface %s from bridge %s: %s",
3709                                    bss->ifname, bss->brname, strerror(errno));
3710         }
3711         if (bss->added_bridge) {
3712                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
3713                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
3714                                    "bridge %s: %s",
3715                                    bss->brname, strerror(errno));
3716         }
3717
3718         nl80211_remove_monitor_interface(drv);
3719
3720         if (is_ap_interface(drv->nlmode))
3721                 wpa_driver_nl80211_del_beacon(drv);
3722
3723 #ifdef HOSTAPD
3724         if (drv->last_freq_ht) {
3725                 /* Clear HT flags from the driver */
3726                 struct hostapd_freq_params freq;
3727                 os_memset(&freq, 0, sizeof(freq));
3728                 freq.freq = drv->last_freq;
3729                 wpa_driver_nl80211_set_freq(bss, &freq);
3730         }
3731
3732         if (drv->eapol_sock >= 0) {
3733                 eloop_unregister_read_sock(drv->eapol_sock);
3734                 close(drv->eapol_sock);
3735         }
3736
3737         if (drv->if_indices != drv->default_if_indices)
3738                 os_free(drv->if_indices);
3739 #endif /* HOSTAPD */
3740
3741         if (drv->disabled_11b_rates)
3742                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
3743
3744         netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, 0,
3745                                IF_OPER_UP);
3746         rfkill_deinit(drv->rfkill);
3747
3748         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3749
3750         (void) linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0);
3751         wpa_driver_nl80211_set_mode(bss, NL80211_IFTYPE_STATION);
3752         nl80211_mgmt_unsubscribe(bss, "deinit");
3753
3754         nl_cb_put(drv->nl_cb);
3755
3756         nl80211_destroy_bss(&drv->first_bss);
3757
3758         os_free(drv->filter_ssids);
3759
3760         os_free(drv->auth_ie);
3761
3762         if (drv->in_interface_list)
3763                 dl_list_del(&drv->list);
3764
3765         os_free(drv->extended_capa);
3766         os_free(drv->extended_capa_mask);
3767         os_free(drv);
3768 }
3769
3770
3771 /**
3772  * wpa_driver_nl80211_scan_timeout - Scan timeout to report scan completion
3773  * @eloop_ctx: Driver private data
3774  * @timeout_ctx: ctx argument given to wpa_driver_nl80211_init()
3775  *
3776  * This function can be used as registered timeout when starting a scan to
3777  * generate a scan completed event if the driver does not report this.
3778  */
3779 static void wpa_driver_nl80211_scan_timeout(void *eloop_ctx, void *timeout_ctx)
3780 {
3781         struct wpa_driver_nl80211_data *drv = eloop_ctx;
3782         if (drv->ap_scan_as_station != NL80211_IFTYPE_UNSPECIFIED) {
3783                 wpa_driver_nl80211_set_mode(&drv->first_bss,
3784                                             drv->ap_scan_as_station);
3785                 drv->ap_scan_as_station = NL80211_IFTYPE_UNSPECIFIED;
3786         }
3787         wpa_printf(MSG_DEBUG, "Scan timeout - try to get results");
3788         wpa_supplicant_event(timeout_ctx, EVENT_SCAN_RESULTS, NULL);
3789 }
3790
3791
3792 static struct nl_msg *
3793 nl80211_scan_common(struct wpa_driver_nl80211_data *drv, u8 cmd,
3794                     struct wpa_driver_scan_params *params)
3795 {
3796         struct nl_msg *msg;
3797         size_t i;
3798
3799         msg = nlmsg_alloc();
3800         if (!msg)
3801                 return NULL;
3802
3803         nl80211_cmd(drv, msg, 0, cmd);
3804
3805         if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, drv->ifindex) < 0)
3806                 goto fail;
3807
3808         if (params->num_ssids) {
3809                 struct nlattr *ssids;
3810
3811                 ssids = nla_nest_start(msg, NL80211_ATTR_SCAN_SSIDS);
3812                 if (ssids == NULL)
3813                         goto fail;
3814                 for (i = 0; i < params->num_ssids; i++) {
3815                         wpa_hexdump_ascii(MSG_MSGDUMP, "nl80211: Scan SSID",
3816                                           params->ssids[i].ssid,
3817                                           params->ssids[i].ssid_len);
3818                         if (nla_put(msg, i + 1, params->ssids[i].ssid_len,
3819                                     params->ssids[i].ssid) < 0)
3820                                 goto fail;
3821                 }
3822                 nla_nest_end(msg, ssids);
3823         }
3824
3825         if (params->extra_ies) {
3826                 wpa_hexdump(MSG_MSGDUMP, "nl80211: Scan extra IEs",
3827                             params->extra_ies, params->extra_ies_len);
3828                 if (nla_put(msg, NL80211_ATTR_IE, params->extra_ies_len,
3829                             params->extra_ies) < 0)
3830                         goto fail;
3831         }
3832
3833         if (params->freqs) {
3834                 struct nlattr *freqs;
3835                 freqs = nla_nest_start(msg, NL80211_ATTR_SCAN_FREQUENCIES);
3836                 if (freqs == NULL)
3837                         goto fail;
3838                 for (i = 0; params->freqs[i]; i++) {
3839                         wpa_printf(MSG_MSGDUMP, "nl80211: Scan frequency %u "
3840                                    "MHz", params->freqs[i]);
3841                         if (nla_put_u32(msg, i + 1, params->freqs[i]) < 0)
3842                                 goto fail;
3843                 }
3844                 nla_nest_end(msg, freqs);
3845         }
3846
3847         os_free(drv->filter_ssids);
3848         drv->filter_ssids = params->filter_ssids;
3849         params->filter_ssids = NULL;
3850         drv->num_filter_ssids = params->num_filter_ssids;
3851
3852         return msg;
3853
3854 fail:
3855         nlmsg_free(msg);
3856         return NULL;
3857 }
3858
3859
3860 /**
3861  * wpa_driver_nl80211_scan - Request the driver to initiate scan
3862  * @bss: Pointer to private driver data from wpa_driver_nl80211_init()
3863  * @params: Scan parameters
3864  * Returns: 0 on success, -1 on failure
3865  */
3866 static int wpa_driver_nl80211_scan(struct i802_bss *bss,
3867                                    struct wpa_driver_scan_params *params)
3868 {
3869         struct wpa_driver_nl80211_data *drv = bss->drv;
3870         int ret = -1, timeout;
3871         struct nl_msg *msg = NULL;
3872
3873         wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: scan request");
3874         drv->scan_for_auth = 0;
3875
3876         msg = nl80211_scan_common(drv, NL80211_CMD_TRIGGER_SCAN, params);
3877         if (!msg)
3878                 return -1;
3879
3880         if (params->p2p_probe) {
3881                 struct nlattr *rates;
3882
3883                 wpa_printf(MSG_DEBUG, "nl80211: P2P probe - mask SuppRates");
3884
3885                 rates = nla_nest_start(msg, NL80211_ATTR_SCAN_SUPP_RATES);
3886                 if (rates == NULL)
3887                         goto nla_put_failure;
3888
3889                 /*
3890                  * Remove 2.4 GHz rates 1, 2, 5.5, 11 Mbps from supported rates
3891                  * by masking out everything else apart from the OFDM rates 6,
3892                  * 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS rates. All 5 GHz
3893                  * rates are left enabled.
3894                  */
3895                 NLA_PUT(msg, NL80211_BAND_2GHZ, 8,
3896                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
3897                 nla_nest_end(msg, rates);
3898
3899                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
3900         }
3901
3902         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
3903         msg = NULL;
3904         if (ret) {
3905                 wpa_printf(MSG_DEBUG, "nl80211: Scan trigger failed: ret=%d "
3906                            "(%s)", ret, strerror(-ret));
3907 #ifdef HOSTAPD
3908                 if (is_ap_interface(drv->nlmode)) {
3909                         /*
3910                          * mac80211 does not allow scan requests in AP mode, so
3911                          * try to do this in station mode.
3912                          */
3913                         if (wpa_driver_nl80211_set_mode(
3914                                     bss, NL80211_IFTYPE_STATION))
3915                                 goto nla_put_failure;
3916
3917                         if (wpa_driver_nl80211_scan(bss, params)) {
3918                                 wpa_driver_nl80211_set_mode(bss, drv->nlmode);
3919                                 goto nla_put_failure;
3920                         }
3921
3922                         /* Restore AP mode when processing scan results */
3923                         drv->ap_scan_as_station = drv->nlmode;
3924                         ret = 0;
3925                 } else
3926                         goto nla_put_failure;
3927 #else /* HOSTAPD */
3928                 goto nla_put_failure;
3929 #endif /* HOSTAPD */
3930         }
3931
3932         /* Not all drivers generate "scan completed" wireless event, so try to
3933          * read results after a timeout. */
3934         timeout = 10;
3935         if (drv->scan_complete_events) {
3936                 /*
3937                  * The driver seems to deliver events to notify when scan is
3938                  * complete, so use longer timeout to avoid race conditions
3939                  * with scanning and following association request.
3940                  */
3941                 timeout = 30;
3942         }
3943         wpa_printf(MSG_DEBUG, "Scan requested (ret=%d) - scan timeout %d "
3944                    "seconds", ret, timeout);
3945         eloop_cancel_timeout(wpa_driver_nl80211_scan_timeout, drv, drv->ctx);
3946         eloop_register_timeout(timeout, 0, wpa_driver_nl80211_scan_timeout,
3947                                drv, drv->ctx);
3948
3949 nla_put_failure:
3950         nlmsg_free(msg);
3951         return ret;
3952 }
3953
3954
3955 /**
3956  * wpa_driver_nl80211_sched_scan - Initiate a scheduled scan
3957  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
3958  * @params: Scan parameters
3959  * @interval: Interval between scan cycles in milliseconds
3960  * Returns: 0 on success, -1 on failure or if not supported
3961  */
3962 static int wpa_driver_nl80211_sched_scan(void *priv,
3963                                          struct wpa_driver_scan_params *params,
3964                                          u32 interval)
3965 {
3966         struct i802_bss *bss = priv;
3967         struct wpa_driver_nl80211_data *drv = bss->drv;
3968         int ret = -1;
3969         struct nl_msg *msg;
3970         size_t i;
3971
3972         wpa_dbg(drv->ctx, MSG_DEBUG, "nl80211: sched_scan request");
3973
3974 #ifdef ANDROID
3975         if (!drv->capa.sched_scan_supported)
3976                 return android_pno_start(bss, params);
3977 #endif /* ANDROID */
3978
3979         msg = nl80211_scan_common(drv, NL80211_CMD_START_SCHED_SCAN, params);
3980         if (!msg)
3981                 goto nla_put_failure;
3982
3983         NLA_PUT_U32(msg, NL80211_ATTR_SCHED_SCAN_INTERVAL, interval);
3984
3985         if ((drv->num_filter_ssids &&
3986             (int) drv->num_filter_ssids <= drv->capa.max_match_sets) ||
3987             params->filter_rssi) {
3988                 struct nlattr *match_sets;
3989                 match_sets = nla_nest_start(msg, NL80211_ATTR_SCHED_SCAN_MATCH);
3990                 if (match_sets == NULL)
3991                         goto nla_put_failure;
3992
3993                 for (i = 0; i < drv->num_filter_ssids; i++) {
3994                         struct nlattr *match_set_ssid;
3995                         wpa_hexdump_ascii(MSG_MSGDUMP,
3996                                           "nl80211: Sched scan filter SSID",
3997                                           drv->filter_ssids[i].ssid,
3998                                           drv->filter_ssids[i].ssid_len);
3999
4000                         match_set_ssid = nla_nest_start(msg, i + 1);
4001                         if (match_set_ssid == NULL)
4002                                 goto nla_put_failure;
4003                         NLA_PUT(msg, NL80211_ATTR_SCHED_SCAN_MATCH_SSID,
4004                                 drv->filter_ssids[i].ssid_len,
4005                                 drv->filter_ssids[i].ssid);
4006
4007                         nla_nest_end(msg, match_sets);
4008                 }
4009
4010                 if (params->filter_rssi) {
4011                         struct nlattr *match_set_rssi;
4012                         match_set_rssi = nla_nest_start(msg, 0);
4013                         if (match_set_rssi == NULL)
4014                                 goto nla_put_failure;
4015                         NLA_PUT_U32(msg, NL80211_SCHED_SCAN_MATCH_ATTR_RSSI,
4016                                     params->filter_rssi);
4017                         wpa_printf(MSG_MSGDUMP,
4018                                    "nl80211: Sched scan RSSI filter %d dBm",
4019                                    params->filter_rssi);
4020                         nla_nest_end(msg, match_set_rssi);
4021                 }
4022
4023                 nla_nest_end(msg, match_sets);
4024         }
4025
4026         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4027
4028         /* TODO: if we get an error here, we should fall back to normal scan */
4029
4030         msg = NULL;
4031         if (ret) {
4032                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan start failed: "
4033                            "ret=%d (%s)", ret, strerror(-ret));
4034                 goto nla_put_failure;
4035         }
4036
4037         wpa_printf(MSG_DEBUG, "nl80211: Sched scan requested (ret=%d) - "
4038                    "scan interval %d msec", ret, interval);
4039
4040 nla_put_failure:
4041         nlmsg_free(msg);
4042         return ret;
4043 }
4044
4045
4046 /**
4047  * wpa_driver_nl80211_stop_sched_scan - Stop a scheduled scan
4048  * @priv: Pointer to private driver data from wpa_driver_nl80211_init()
4049  * Returns: 0 on success, -1 on failure or if not supported
4050  */
4051 static int wpa_driver_nl80211_stop_sched_scan(void *priv)
4052 {
4053         struct i802_bss *bss = priv;
4054         struct wpa_driver_nl80211_data *drv = bss->drv;
4055         int ret = 0;
4056         struct nl_msg *msg;
4057
4058 #ifdef ANDROID
4059         if (!drv->capa.sched_scan_supported)
4060                 return android_pno_stop(bss);
4061 #endif /* ANDROID */
4062
4063         msg = nlmsg_alloc();
4064         if (!msg)
4065                 return -1;
4066
4067         nl80211_cmd(drv, msg, 0, NL80211_CMD_STOP_SCHED_SCAN);
4068
4069         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4070
4071         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4072         msg = NULL;
4073         if (ret) {
4074                 wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop failed: "
4075                            "ret=%d (%s)", ret, strerror(-ret));
4076                 goto nla_put_failure;
4077         }
4078
4079         wpa_printf(MSG_DEBUG, "nl80211: Sched scan stop sent (ret=%d)", ret);
4080
4081 nla_put_failure:
4082         nlmsg_free(msg);
4083         return ret;
4084 }
4085
4086
4087 static const u8 * nl80211_get_ie(const u8 *ies, size_t ies_len, u8 ie)
4088 {
4089         const u8 *end, *pos;
4090
4091         if (ies == NULL)
4092                 return NULL;
4093
4094         pos = ies;
4095         end = ies + ies_len;
4096
4097         while (pos + 1 < end) {
4098                 if (pos + 2 + pos[1] > end)
4099                         break;
4100                 if (pos[0] == ie)
4101                         return pos;
4102                 pos += 2 + pos[1];
4103         }
4104
4105         return NULL;
4106 }
4107
4108
4109 static int nl80211_scan_filtered(struct wpa_driver_nl80211_data *drv,
4110                                  const u8 *ie, size_t ie_len)
4111 {
4112         const u8 *ssid;
4113         size_t i;
4114
4115         if (drv->filter_ssids == NULL)
4116                 return 0;
4117
4118         ssid = nl80211_get_ie(ie, ie_len, WLAN_EID_SSID);
4119         if (ssid == NULL)
4120                 return 1;
4121
4122         for (i = 0; i < drv->num_filter_ssids; i++) {
4123                 if (ssid[1] == drv->filter_ssids[i].ssid_len &&
4124                     os_memcmp(ssid + 2, drv->filter_ssids[i].ssid, ssid[1]) ==
4125                     0)
4126                         return 0;
4127         }
4128
4129         return 1;
4130 }
4131
4132
4133 static int bss_info_handler(struct nl_msg *msg, void *arg)
4134 {
4135         struct nlattr *tb[NL80211_ATTR_MAX + 1];
4136         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
4137         struct nlattr *bss[NL80211_BSS_MAX + 1];
4138         static struct nla_policy bss_policy[NL80211_BSS_MAX + 1] = {
4139                 [NL80211_BSS_BSSID] = { .type = NLA_UNSPEC },
4140                 [NL80211_BSS_FREQUENCY] = { .type = NLA_U32 },
4141                 [NL80211_BSS_TSF] = { .type = NLA_U64 },
4142                 [NL80211_BSS_BEACON_INTERVAL] = { .type = NLA_U16 },
4143                 [NL80211_BSS_CAPABILITY] = { .type = NLA_U16 },
4144                 [NL80211_BSS_INFORMATION_ELEMENTS] = { .type = NLA_UNSPEC },
4145                 [NL80211_BSS_SIGNAL_MBM] = { .type = NLA_U32 },
4146                 [NL80211_BSS_SIGNAL_UNSPEC] = { .type = NLA_U8 },
4147                 [NL80211_BSS_STATUS] = { .type = NLA_U32 },
4148                 [NL80211_BSS_SEEN_MS_AGO] = { .type = NLA_U32 },
4149                 [NL80211_BSS_BEACON_IES] = { .type = NLA_UNSPEC },
4150         };
4151         struct nl80211_bss_info_arg *_arg = arg;
4152         struct wpa_scan_results *res = _arg->res;
4153         struct wpa_scan_res **tmp;
4154         struct wpa_scan_res *r;
4155         const u8 *ie, *beacon_ie;
4156         size_t ie_len, beacon_ie_len;
4157         u8 *pos;
4158         size_t i;
4159
4160         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
4161                   genlmsg_attrlen(gnlh, 0), NULL);
4162         if (!tb[NL80211_ATTR_BSS])
4163                 return NL_SKIP;
4164         if (nla_parse_nested(bss, NL80211_BSS_MAX, tb[NL80211_ATTR_BSS],
4165                              bss_policy))
4166                 return NL_SKIP;
4167         if (bss[NL80211_BSS_STATUS]) {
4168                 enum nl80211_bss_status status;
4169                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
4170                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
4171                     bss[NL80211_BSS_FREQUENCY]) {
4172                         _arg->assoc_freq =
4173                                 nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
4174                         wpa_printf(MSG_DEBUG, "nl80211: Associated on %u MHz",
4175                                    _arg->assoc_freq);
4176                 }
4177                 if (status == NL80211_BSS_STATUS_ASSOCIATED &&
4178                     bss[NL80211_BSS_BSSID]) {
4179                         os_memcpy(_arg->assoc_bssid,
4180                                   nla_data(bss[NL80211_BSS_BSSID]), ETH_ALEN);
4181                         wpa_printf(MSG_DEBUG, "nl80211: Associated with "
4182                                    MACSTR, MAC2STR(_arg->assoc_bssid));
4183                 }
4184         }
4185         if (!res)
4186                 return NL_SKIP;
4187         if (bss[NL80211_BSS_INFORMATION_ELEMENTS]) {
4188                 ie = nla_data(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
4189                 ie_len = nla_len(bss[NL80211_BSS_INFORMATION_ELEMENTS]);
4190         } else {
4191                 ie = NULL;
4192                 ie_len = 0;
4193         }
4194         if (bss[NL80211_BSS_BEACON_IES]) {
4195                 beacon_ie = nla_data(bss[NL80211_BSS_BEACON_IES]);
4196                 beacon_ie_len = nla_len(bss[NL80211_BSS_BEACON_IES]);
4197         } else {
4198                 beacon_ie = NULL;
4199                 beacon_ie_len = 0;
4200         }
4201
4202         if (nl80211_scan_filtered(_arg->drv, ie ? ie : beacon_ie,
4203                                   ie ? ie_len : beacon_ie_len))
4204                 return NL_SKIP;
4205
4206         r = os_zalloc(sizeof(*r) + ie_len + beacon_ie_len);
4207         if (r == NULL)
4208                 return NL_SKIP;
4209         if (bss[NL80211_BSS_BSSID])
4210                 os_memcpy(r->bssid, nla_data(bss[NL80211_BSS_BSSID]),
4211                           ETH_ALEN);
4212         if (bss[NL80211_BSS_FREQUENCY])
4213                 r->freq = nla_get_u32(bss[NL80211_BSS_FREQUENCY]);
4214         if (bss[NL80211_BSS_BEACON_INTERVAL])
4215                 r->beacon_int = nla_get_u16(bss[NL80211_BSS_BEACON_INTERVAL]);
4216         if (bss[NL80211_BSS_CAPABILITY])
4217                 r->caps = nla_get_u16(bss[NL80211_BSS_CAPABILITY]);
4218         r->flags |= WPA_SCAN_NOISE_INVALID;
4219         if (bss[NL80211_BSS_SIGNAL_MBM]) {
4220                 r->level = nla_get_u32(bss[NL80211_BSS_SIGNAL_MBM]);
4221                 r->level /= 100; /* mBm to dBm */
4222                 r->flags |= WPA_SCAN_LEVEL_DBM | WPA_SCAN_QUAL_INVALID;
4223         } else if (bss[NL80211_BSS_SIGNAL_UNSPEC]) {
4224                 r->level = nla_get_u8(bss[NL80211_BSS_SIGNAL_UNSPEC]);
4225                 r->flags |= WPA_SCAN_QUAL_INVALID;
4226         } else
4227                 r->flags |= WPA_SCAN_LEVEL_INVALID | WPA_SCAN_QUAL_INVALID;
4228         if (bss[NL80211_BSS_TSF])
4229                 r->tsf = nla_get_u64(bss[NL80211_BSS_TSF]);
4230         if (bss[NL80211_BSS_SEEN_MS_AGO])
4231                 r->age = nla_get_u32(bss[NL80211_BSS_SEEN_MS_AGO]);
4232         r->ie_len = ie_len;
4233         pos = (u8 *) (r + 1);
4234         if (ie) {
4235                 os_memcpy(pos, ie, ie_len);
4236                 pos += ie_len;
4237         }
4238         r->beacon_ie_len = beacon_ie_len;
4239         if (beacon_ie)
4240                 os_memcpy(pos, beacon_ie, beacon_ie_len);
4241
4242         if (bss[NL80211_BSS_STATUS]) {
4243                 enum nl80211_bss_status status;
4244                 status = nla_get_u32(bss[NL80211_BSS_STATUS]);
4245                 switch (status) {
4246                 case NL80211_BSS_STATUS_AUTHENTICATED:
4247                         r->flags |= WPA_SCAN_AUTHENTICATED;
4248                         break;
4249                 case NL80211_BSS_STATUS_ASSOCIATED:
4250                         r->flags |= WPA_SCAN_ASSOCIATED;
4251                         break;
4252                 default:
4253                         break;
4254                 }
4255         }
4256
4257         /*
4258          * cfg80211 maintains separate BSS table entries for APs if the same
4259          * BSSID,SSID pair is seen on multiple channels. wpa_supplicant does
4260          * not use frequency as a separate key in the BSS table, so filter out
4261          * duplicated entries. Prefer associated BSS entry in such a case in
4262          * order to get the correct frequency into the BSS table.
4263          */
4264         for (i = 0; i < res->num; i++) {
4265                 const u8 *s1, *s2;
4266                 if (os_memcmp(res->res[i]->bssid, r->bssid, ETH_ALEN) != 0)
4267                         continue;
4268
4269                 s1 = nl80211_get_ie((u8 *) (res->res[i] + 1),
4270                                     res->res[i]->ie_len, WLAN_EID_SSID);
4271                 s2 = nl80211_get_ie((u8 *) (r + 1), r->ie_len, WLAN_EID_SSID);
4272                 if (s1 == NULL || s2 == NULL || s1[1] != s2[1] ||
4273                     os_memcmp(s1, s2, 2 + s1[1]) != 0)
4274                         continue;
4275
4276                 /* Same BSSID,SSID was already included in scan results */
4277                 wpa_printf(MSG_DEBUG, "nl80211: Remove duplicated scan result "
4278                            "for " MACSTR, MAC2STR(r->bssid));
4279
4280                 if ((r->flags & WPA_SCAN_ASSOCIATED) &&
4281                     !(res->res[i]->flags & WPA_SCAN_ASSOCIATED)) {
4282                         os_free(res->res[i]);
4283                         res->res[i] = r;
4284                 } else
4285                         os_free(r);
4286                 return NL_SKIP;
4287         }
4288
4289         tmp = os_realloc_array(res->res, res->num + 1,
4290                                sizeof(struct wpa_scan_res *));
4291         if (tmp == NULL) {
4292                 os_free(r);
4293                 return NL_SKIP;
4294         }
4295         tmp[res->num++] = r;
4296         res->res = tmp;
4297
4298         return NL_SKIP;
4299 }
4300
4301
4302 static void clear_state_mismatch(struct wpa_driver_nl80211_data *drv,
4303                                  const u8 *addr)
4304 {
4305         if (drv->capa.flags & WPA_DRIVER_FLAGS_SME) {
4306                 wpa_printf(MSG_DEBUG, "nl80211: Clear possible state "
4307                            "mismatch (" MACSTR ")", MAC2STR(addr));
4308                 wpa_driver_nl80211_mlme(drv, addr,
4309                                         NL80211_CMD_DEAUTHENTICATE,
4310                                         WLAN_REASON_PREV_AUTH_NOT_VALID, 1);
4311         }
4312 }
4313
4314
4315 static void wpa_driver_nl80211_check_bss_status(
4316         struct wpa_driver_nl80211_data *drv, struct wpa_scan_results *res)
4317 {
4318         size_t i;
4319
4320         for (i = 0; i < res->num; i++) {
4321                 struct wpa_scan_res *r = res->res[i];
4322                 if (r->flags & WPA_SCAN_AUTHENTICATED) {
4323                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
4324                                    "indicates BSS status with " MACSTR
4325                                    " as authenticated",
4326                                    MAC2STR(r->bssid));
4327                         if (is_sta_interface(drv->nlmode) &&
4328                             os_memcmp(r->bssid, drv->bssid, ETH_ALEN) != 0 &&
4329                             os_memcmp(r->bssid, drv->auth_bssid, ETH_ALEN) !=
4330                             0) {
4331                                 wpa_printf(MSG_DEBUG, "nl80211: Unknown BSSID"
4332                                            " in local state (auth=" MACSTR
4333                                            " assoc=" MACSTR ")",
4334                                            MAC2STR(drv->auth_bssid),
4335                                            MAC2STR(drv->bssid));
4336                                 clear_state_mismatch(drv, r->bssid);
4337                         }
4338                 }
4339
4340                 if (r->flags & WPA_SCAN_ASSOCIATED) {
4341                         wpa_printf(MSG_DEBUG, "nl80211: Scan results "
4342                                    "indicate BSS status with " MACSTR
4343                                    " as associated",
4344                                    MAC2STR(r->bssid));
4345                         if (is_sta_interface(drv->nlmode) &&
4346                             !drv->associated) {
4347                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
4348                                            "(not associated) does not match "
4349                                            "with BSS state");
4350                                 clear_state_mismatch(drv, r->bssid);
4351                         } else if (is_sta_interface(drv->nlmode) &&
4352                                    os_memcmp(drv->bssid, r->bssid, ETH_ALEN) !=
4353                                    0) {
4354                                 wpa_printf(MSG_DEBUG, "nl80211: Local state "
4355                                            "(associated with " MACSTR ") does "
4356                                            "not match with BSS state",
4357                                            MAC2STR(drv->bssid));
4358                                 clear_state_mismatch(drv, r->bssid);
4359                                 clear_state_mismatch(drv, drv->bssid);
4360                         }
4361                 }
4362         }
4363 }
4364
4365
4366 static struct wpa_scan_results *
4367 nl80211_get_scan_results(struct wpa_driver_nl80211_data *drv)
4368 {
4369         struct nl_msg *msg;
4370         struct wpa_scan_results *res;
4371         int ret;
4372         struct nl80211_bss_info_arg arg;
4373
4374         res = os_zalloc(sizeof(*res));
4375         if (res == NULL)
4376                 return NULL;
4377         msg = nlmsg_alloc();
4378         if (!msg)
4379                 goto nla_put_failure;
4380
4381         nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_SCAN);
4382         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4383
4384         arg.drv = drv;
4385         arg.res = res;
4386         ret = send_and_recv_msgs(drv, msg, bss_info_handler, &arg);
4387         msg = NULL;
4388         if (ret == 0) {
4389                 wpa_printf(MSG_DEBUG, "nl80211: Received scan results (%lu "
4390                            "BSSes)", (unsigned long) res->num);
4391                 nl80211_get_noise_for_scan_results(drv, res);
4392                 return res;
4393         }
4394         wpa_printf(MSG_DEBUG, "nl80211: Scan result fetch failed: ret=%d "
4395                    "(%s)", ret, strerror(-ret));
4396 nla_put_failure:
4397         nlmsg_free(msg);
4398         wpa_scan_results_free(res);
4399         return NULL;
4400 }
4401
4402
4403 /**
4404  * wpa_driver_nl80211_get_scan_results - Fetch the latest scan results
4405  * @priv: Pointer to private wext data from wpa_driver_nl80211_init()
4406  * Returns: Scan results on success, -1 on failure
4407  */
4408 static struct wpa_scan_results *
4409 wpa_driver_nl80211_get_scan_results(void *priv)
4410 {
4411         struct i802_bss *bss = priv;
4412         struct wpa_driver_nl80211_data *drv = bss->drv;
4413         struct wpa_scan_results *res;
4414
4415         res = nl80211_get_scan_results(drv);
4416         if (res)
4417                 wpa_driver_nl80211_check_bss_status(drv, res);
4418         return res;
4419 }
4420
4421
4422 static void nl80211_dump_scan(struct wpa_driver_nl80211_data *drv)
4423 {
4424         struct wpa_scan_results *res;
4425         size_t i;
4426
4427         res = nl80211_get_scan_results(drv);
4428         if (res == NULL) {
4429                 wpa_printf(MSG_DEBUG, "nl80211: Failed to get scan results");
4430                 return;
4431         }
4432
4433         wpa_printf(MSG_DEBUG, "nl80211: Scan result dump");
4434         for (i = 0; i < res->num; i++) {
4435                 struct wpa_scan_res *r = res->res[i];
4436                 wpa_printf(MSG_DEBUG, "nl80211: %d/%d " MACSTR "%s%s",
4437                            (int) i, (int) res->num, MAC2STR(r->bssid),
4438                            r->flags & WPA_SCAN_AUTHENTICATED ? " [auth]" : "",
4439                            r->flags & WPA_SCAN_ASSOCIATED ? " [assoc]" : "");
4440         }
4441
4442         wpa_scan_results_free(res);
4443 }
4444
4445
4446 static int wpa_driver_nl80211_set_key(const char *ifname, struct i802_bss *bss,
4447                                       enum wpa_alg alg, const u8 *addr,
4448                                       int key_idx, int set_tx,
4449                                       const u8 *seq, size_t seq_len,
4450                                       const u8 *key, size_t key_len)
4451 {
4452         struct wpa_driver_nl80211_data *drv = bss->drv;
4453         int ifindex = if_nametoindex(ifname);
4454         struct nl_msg *msg;
4455         int ret;
4456
4457         wpa_printf(MSG_DEBUG, "%s: ifindex=%d alg=%d addr=%p key_idx=%d "
4458                    "set_tx=%d seq_len=%lu key_len=%lu",
4459                    __func__, ifindex, alg, addr, key_idx, set_tx,
4460                    (unsigned long) seq_len, (unsigned long) key_len);
4461 #ifdef CONFIG_TDLS
4462         if (key_idx == -1)
4463                 key_idx = 0;
4464 #endif /* CONFIG_TDLS */
4465
4466         msg = nlmsg_alloc();
4467         if (!msg)
4468                 return -ENOMEM;
4469
4470         if (alg == WPA_ALG_NONE) {
4471                 nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_KEY);
4472         } else {
4473                 nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_KEY);
4474                 NLA_PUT(msg, NL80211_ATTR_KEY_DATA, key_len, key);
4475                 switch (alg) {
4476                 case WPA_ALG_WEP:
4477                         if (key_len == 5)
4478                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4479                                             WLAN_CIPHER_SUITE_WEP40);
4480                         else
4481                                 NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4482                                             WLAN_CIPHER_SUITE_WEP104);
4483                         break;
4484                 case WPA_ALG_TKIP:
4485                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4486                                     WLAN_CIPHER_SUITE_TKIP);
4487                         break;
4488                 case WPA_ALG_CCMP:
4489                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4490                                     WLAN_CIPHER_SUITE_CCMP);
4491                         break;
4492                 case WPA_ALG_GCMP:
4493                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4494                                     WLAN_CIPHER_SUITE_GCMP);
4495                         break;
4496                 case WPA_ALG_IGTK:
4497                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4498                                     WLAN_CIPHER_SUITE_AES_CMAC);
4499                         break;
4500                 case WPA_ALG_SMS4:
4501                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4502                                     WLAN_CIPHER_SUITE_SMS4);
4503                         break;
4504                 case WPA_ALG_KRK:
4505                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_CIPHER,
4506                                     WLAN_CIPHER_SUITE_KRK);
4507                         break;
4508                 default:
4509                         wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4510                                    "algorithm %d", __func__, alg);
4511                         nlmsg_free(msg);
4512                         return -1;
4513                 }
4514         }
4515
4516         if (seq && seq_len)
4517                 NLA_PUT(msg, NL80211_ATTR_KEY_SEQ, seq_len, seq);
4518
4519         if (addr && !is_broadcast_ether_addr(addr)) {
4520                 wpa_printf(MSG_DEBUG, "   addr=" MACSTR, MAC2STR(addr));
4521                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4522
4523                 if (alg != WPA_ALG_WEP && key_idx && !set_tx) {
4524                         wpa_printf(MSG_DEBUG, "   RSN IBSS RX GTK");
4525                         NLA_PUT_U32(msg, NL80211_ATTR_KEY_TYPE,
4526                                     NL80211_KEYTYPE_GROUP);
4527                 }
4528         } else if (addr && is_broadcast_ether_addr(addr)) {
4529                 struct nlattr *types;
4530
4531                 wpa_printf(MSG_DEBUG, "   broadcast key");
4532
4533                 types = nla_nest_start(msg, NL80211_ATTR_KEY_DEFAULT_TYPES);
4534                 if (!types)
4535                         goto nla_put_failure;
4536                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4537                 nla_nest_end(msg, types);
4538         }
4539         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4540         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4541
4542         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4543         if ((ret == -ENOENT || ret == -ENOLINK) && alg == WPA_ALG_NONE)
4544                 ret = 0;
4545         if (ret)
4546                 wpa_printf(MSG_DEBUG, "nl80211: set_key failed; err=%d %s)",
4547                            ret, strerror(-ret));
4548
4549         /*
4550          * If we failed or don't need to set the default TX key (below),
4551          * we're done here.
4552          */
4553         if (ret || !set_tx || alg == WPA_ALG_NONE)
4554                 return ret;
4555         if (is_ap_interface(drv->nlmode) && addr &&
4556             !is_broadcast_ether_addr(addr))
4557                 return ret;
4558
4559         msg = nlmsg_alloc();
4560         if (!msg)
4561                 return -ENOMEM;
4562
4563         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_KEY);
4564         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, key_idx);
4565         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
4566         if (alg == WPA_ALG_IGTK)
4567                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT_MGMT);
4568         else
4569                 NLA_PUT_FLAG(msg, NL80211_ATTR_KEY_DEFAULT);
4570         if (addr && is_broadcast_ether_addr(addr)) {
4571                 struct nlattr *types;
4572
4573                 types = nla_nest_start(msg, NL80211_ATTR_KEY_DEFAULT_TYPES);
4574                 if (!types)
4575                         goto nla_put_failure;
4576                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_TYPE_MULTICAST);
4577                 nla_nest_end(msg, types);
4578         } else if (addr) {
4579                 struct nlattr *types;
4580
4581                 types = nla_nest_start(msg, NL80211_ATTR_KEY_DEFAULT_TYPES);
4582                 if (!types)
4583                         goto nla_put_failure;
4584                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_TYPE_UNICAST);
4585                 nla_nest_end(msg, types);
4586         }
4587
4588         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4589         if (ret == -ENOENT)
4590                 ret = 0;
4591         if (ret)
4592                 wpa_printf(MSG_DEBUG, "nl80211: set_key default failed; "
4593                            "err=%d %s)", ret, strerror(-ret));
4594         return ret;
4595
4596 nla_put_failure:
4597         nlmsg_free(msg);
4598         return -ENOBUFS;
4599 }
4600
4601
4602 static int nl_add_key(struct nl_msg *msg, enum wpa_alg alg,
4603                       int key_idx, int defkey,
4604                       const u8 *seq, size_t seq_len,
4605                       const u8 *key, size_t key_len)
4606 {
4607         struct nlattr *key_attr = nla_nest_start(msg, NL80211_ATTR_KEY);
4608         if (!key_attr)
4609                 return -1;
4610
4611         if (defkey && alg == WPA_ALG_IGTK)
4612                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT_MGMT);
4613         else if (defkey)
4614                 NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4615
4616         NLA_PUT_U8(msg, NL80211_KEY_IDX, key_idx);
4617
4618         switch (alg) {
4619         case WPA_ALG_WEP:
4620                 if (key_len == 5)
4621                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4622                                     WLAN_CIPHER_SUITE_WEP40);
4623                 else
4624                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4625                                     WLAN_CIPHER_SUITE_WEP104);
4626                 break;
4627         case WPA_ALG_TKIP:
4628                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_TKIP);
4629                 break;
4630         case WPA_ALG_CCMP:
4631                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_CCMP);
4632                 break;
4633         case WPA_ALG_GCMP:
4634                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER, WLAN_CIPHER_SUITE_GCMP);
4635                 break;
4636         case WPA_ALG_IGTK:
4637                 NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4638                             WLAN_CIPHER_SUITE_AES_CMAC);
4639                 break;
4640         default:
4641                 wpa_printf(MSG_ERROR, "%s: Unsupported encryption "
4642                            "algorithm %d", __func__, alg);
4643                 return -1;
4644         }
4645
4646         if (seq && seq_len)
4647                 NLA_PUT(msg, NL80211_KEY_SEQ, seq_len, seq);
4648
4649         NLA_PUT(msg, NL80211_KEY_DATA, key_len, key);
4650
4651         nla_nest_end(msg, key_attr);
4652
4653         return 0;
4654  nla_put_failure:
4655         return -1;
4656 }
4657
4658
4659 static int nl80211_set_conn_keys(struct wpa_driver_associate_params *params,
4660                                  struct nl_msg *msg)
4661 {
4662         int i, privacy = 0;
4663         struct nlattr *nl_keys, *nl_key;
4664
4665         for (i = 0; i < 4; i++) {
4666                 if (!params->wep_key[i])
4667                         continue;
4668                 privacy = 1;
4669                 break;
4670         }
4671         if (params->wps == WPS_MODE_PRIVACY)
4672                 privacy = 1;
4673         if (params->pairwise_suite &&
4674             params->pairwise_suite != WPA_CIPHER_NONE)
4675                 privacy = 1;
4676
4677         if (!privacy)
4678                 return 0;
4679
4680         NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
4681
4682         nl_keys = nla_nest_start(msg, NL80211_ATTR_KEYS);
4683         if (!nl_keys)
4684                 goto nla_put_failure;
4685
4686         for (i = 0; i < 4; i++) {
4687                 if (!params->wep_key[i])
4688                         continue;
4689
4690                 nl_key = nla_nest_start(msg, i);
4691                 if (!nl_key)
4692                         goto nla_put_failure;
4693
4694                 NLA_PUT(msg, NL80211_KEY_DATA, params->wep_key_len[i],
4695                         params->wep_key[i]);
4696                 if (params->wep_key_len[i] == 5)
4697                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4698                                     WLAN_CIPHER_SUITE_WEP40);
4699                 else
4700                         NLA_PUT_U32(msg, NL80211_KEY_CIPHER,
4701                                     WLAN_CIPHER_SUITE_WEP104);
4702
4703                 NLA_PUT_U8(msg, NL80211_KEY_IDX, i);
4704
4705                 if (i == params->wep_tx_keyidx)
4706                         NLA_PUT_FLAG(msg, NL80211_KEY_DEFAULT);
4707
4708                 nla_nest_end(msg, nl_key);
4709         }
4710         nla_nest_end(msg, nl_keys);
4711
4712         return 0;
4713
4714 nla_put_failure:
4715         return -ENOBUFS;
4716 }
4717
4718
4719 static int wpa_driver_nl80211_mlme(struct wpa_driver_nl80211_data *drv,
4720                                    const u8 *addr, int cmd, u16 reason_code,
4721                                    int local_state_change)
4722 {
4723         int ret = -1;
4724         struct nl_msg *msg;
4725
4726         msg = nlmsg_alloc();
4727         if (!msg)
4728                 return -1;
4729
4730         nl80211_cmd(drv, msg, 0, cmd);
4731
4732         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4733         NLA_PUT_U16(msg, NL80211_ATTR_REASON_CODE, reason_code);
4734         if (addr)
4735                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
4736         if (local_state_change)
4737                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4738
4739         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4740         msg = NULL;
4741         if (ret) {
4742                 wpa_dbg(drv->ctx, MSG_DEBUG,
4743                         "nl80211: MLME command failed: reason=%u ret=%d (%s)",
4744                         reason_code, ret, strerror(-ret));
4745                 goto nla_put_failure;
4746         }
4747         ret = 0;
4748
4749 nla_put_failure:
4750         nlmsg_free(msg);
4751         return ret;
4752 }
4753
4754
4755 static int wpa_driver_nl80211_disconnect(struct wpa_driver_nl80211_data *drv,
4756                                          int reason_code)
4757 {
4758         wpa_printf(MSG_DEBUG, "%s(reason_code=%d)", __func__, reason_code);
4759         drv->associated = 0;
4760         drv->ignore_next_local_disconnect = 0;
4761         /* Disconnect command doesn't need BSSID - it uses cached value */
4762         return wpa_driver_nl80211_mlme(drv, NULL, NL80211_CMD_DISCONNECT,
4763                                        reason_code, 0);
4764 }
4765
4766
4767 static int wpa_driver_nl80211_deauthenticate(struct i802_bss *bss,
4768                                              const u8 *addr, int reason_code)
4769 {
4770         struct wpa_driver_nl80211_data *drv = bss->drv;
4771         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME))
4772                 return wpa_driver_nl80211_disconnect(drv, reason_code);
4773         wpa_printf(MSG_DEBUG, "%s(addr=" MACSTR " reason_code=%d)",
4774                    __func__, MAC2STR(addr), reason_code);
4775         drv->associated = 0;
4776         if (drv->nlmode == NL80211_IFTYPE_ADHOC)
4777                 return nl80211_leave_ibss(drv);
4778         return wpa_driver_nl80211_mlme(drv, addr, NL80211_CMD_DEAUTHENTICATE,
4779                                        reason_code, 0);
4780 }
4781
4782
4783 static void nl80211_copy_auth_params(struct wpa_driver_nl80211_data *drv,
4784                                      struct wpa_driver_auth_params *params)
4785 {
4786         int i;
4787
4788         drv->auth_freq = params->freq;
4789         drv->auth_alg = params->auth_alg;
4790         drv->auth_wep_tx_keyidx = params->wep_tx_keyidx;
4791         drv->auth_local_state_change = params->local_state_change;
4792         drv->auth_p2p = params->p2p;
4793
4794         if (params->bssid)
4795                 os_memcpy(drv->auth_bssid_, params->bssid, ETH_ALEN);
4796         else
4797                 os_memset(drv->auth_bssid_, 0, ETH_ALEN);
4798
4799         if (params->ssid) {
4800                 os_memcpy(drv->auth_ssid, params->ssid, params->ssid_len);
4801                 drv->auth_ssid_len = params->ssid_len;
4802         } else
4803                 drv->auth_ssid_len = 0;
4804
4805
4806         os_free(drv->auth_ie);
4807         drv->auth_ie = NULL;
4808         drv->auth_ie_len = 0;
4809         if (params->ie) {
4810                 drv->auth_ie = os_malloc(params->ie_len);
4811                 if (drv->auth_ie) {
4812                         os_memcpy(drv->auth_ie, params->ie, params->ie_len);
4813                         drv->auth_ie_len = params->ie_len;
4814                 }
4815         }
4816
4817         for (i = 0; i < 4; i++) {
4818                 if (params->wep_key[i] && params->wep_key_len[i] &&
4819                     params->wep_key_len[i] <= 16) {
4820                         os_memcpy(drv->auth_wep_key[i], params->wep_key[i],
4821                                   params->wep_key_len[i]);
4822                         drv->auth_wep_key_len[i] = params->wep_key_len[i];
4823                 } else
4824                         drv->auth_wep_key_len[i] = 0;
4825         }
4826 }
4827
4828
4829 static int wpa_driver_nl80211_authenticate(
4830         struct i802_bss *bss, struct wpa_driver_auth_params *params)
4831 {
4832         struct wpa_driver_nl80211_data *drv = bss->drv;
4833         int ret = -1, i;
4834         struct nl_msg *msg;
4835         enum nl80211_auth_type type;
4836         enum nl80211_iftype nlmode;
4837         int count = 0;
4838         int is_retry;
4839
4840         is_retry = drv->retry_auth;
4841         drv->retry_auth = 0;
4842
4843         drv->associated = 0;
4844         os_memset(drv->auth_bssid, 0, ETH_ALEN);
4845         /* FIX: IBSS mode */
4846         nlmode = params->p2p ?
4847                 NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
4848         if (drv->nlmode != nlmode &&
4849             wpa_driver_nl80211_set_mode(bss, nlmode) < 0)
4850                 return -1;
4851
4852 retry:
4853         msg = nlmsg_alloc();
4854         if (!msg)
4855                 return -1;
4856
4857         wpa_printf(MSG_DEBUG, "nl80211: Authenticate (ifindex=%d)",
4858                    drv->ifindex);
4859
4860         nl80211_cmd(drv, msg, 0, NL80211_CMD_AUTHENTICATE);
4861
4862         for (i = 0; i < 4; i++) {
4863                 if (!params->wep_key[i])
4864                         continue;
4865                 wpa_driver_nl80211_set_key(bss->ifname, bss, WPA_ALG_WEP,
4866                                            NULL, i,
4867                                            i == params->wep_tx_keyidx, NULL, 0,
4868                                            params->wep_key[i],
4869                                            params->wep_key_len[i]);
4870                 if (params->wep_tx_keyidx != i)
4871                         continue;
4872                 if (nl_add_key(msg, WPA_ALG_WEP, i, 1, NULL, 0,
4873                                params->wep_key[i], params->wep_key_len[i])) {
4874                         nlmsg_free(msg);
4875                         return -1;
4876                 }
4877         }
4878
4879         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
4880         if (params->bssid) {
4881                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
4882                            MAC2STR(params->bssid));
4883                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
4884         }
4885         if (params->freq) {
4886                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
4887                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
4888         }
4889         if (params->ssid) {
4890                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
4891                                   params->ssid, params->ssid_len);
4892                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
4893                         params->ssid);
4894         }
4895         wpa_hexdump(MSG_DEBUG, "  * IEs", params->ie, params->ie_len);
4896         if (params->ie)
4897                 NLA_PUT(msg, NL80211_ATTR_IE, params->ie_len, params->ie);
4898         if (params->sae_data) {
4899                 wpa_hexdump(MSG_DEBUG, "  * SAE data", params->sae_data,
4900                             params->sae_data_len);
4901                 NLA_PUT(msg, NL80211_ATTR_SAE_DATA, params->sae_data_len,
4902                         params->sae_data);
4903         }
4904         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
4905                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
4906         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
4907                 type = NL80211_AUTHTYPE_SHARED_KEY;
4908         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
4909                 type = NL80211_AUTHTYPE_NETWORK_EAP;
4910         else if (params->auth_alg & WPA_AUTH_ALG_FT)
4911                 type = NL80211_AUTHTYPE_FT;
4912         else if (params->auth_alg & WPA_AUTH_ALG_SAE)
4913                 type = NL80211_AUTHTYPE_SAE;
4914         else
4915                 goto nla_put_failure;
4916         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
4917         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
4918         if (params->local_state_change) {
4919                 wpa_printf(MSG_DEBUG, "  * Local state change only");
4920                 NLA_PUT_FLAG(msg, NL80211_ATTR_LOCAL_STATE_CHANGE);
4921         }
4922
4923         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
4924         msg = NULL;
4925         if (ret) {
4926                 wpa_dbg(drv->ctx, MSG_DEBUG,
4927                         "nl80211: MLME command failed (auth): ret=%d (%s)",
4928                         ret, strerror(-ret));
4929                 count++;
4930                 if (ret == -EALREADY && count == 1 && params->bssid &&
4931                     !params->local_state_change) {
4932                         /*
4933                          * mac80211 does not currently accept new
4934                          * authentication if we are already authenticated. As a
4935                          * workaround, force deauthentication and try again.
4936                          */
4937                         wpa_printf(MSG_DEBUG, "nl80211: Retry authentication "
4938                                    "after forced deauthentication");
4939                         wpa_driver_nl80211_deauthenticate(
4940                                 bss, params->bssid,
4941                                 WLAN_REASON_PREV_AUTH_NOT_VALID);
4942                         nlmsg_free(msg);
4943                         goto retry;
4944                 }
4945
4946                 if (ret == -ENOENT && params->freq && !is_retry) {
4947                         /*
4948                          * cfg80211 has likely expired the BSS entry even
4949                          * though it was previously available in our internal
4950                          * BSS table. To recover quickly, start a single
4951                          * channel scan on the specified channel.
4952                          */
4953                         struct wpa_driver_scan_params scan;
4954                         int freqs[2];
4955
4956                         os_memset(&scan, 0, sizeof(scan));
4957                         scan.num_ssids = 1;
4958                         if (params->ssid) {
4959                                 scan.ssids[0].ssid = params->ssid;
4960                                 scan.ssids[0].ssid_len = params->ssid_len;
4961                         }
4962                         freqs[0] = params->freq;
4963                         freqs[1] = 0;
4964                         scan.freqs = freqs;
4965                         wpa_printf(MSG_DEBUG, "nl80211: Trigger single "
4966                                    "channel scan to refresh cfg80211 BSS "
4967                                    "entry");
4968                         ret = wpa_driver_nl80211_scan(bss, &scan);
4969                         if (ret == 0) {
4970                                 nl80211_copy_auth_params(drv, params);
4971                                 drv->scan_for_auth = 1;
4972                         }
4973                 } else if (is_retry) {
4974                         /*
4975                          * Need to indicate this with an event since the return
4976                          * value from the retry is not delivered to core code.
4977                          */
4978                         union wpa_event_data event;
4979                         wpa_printf(MSG_DEBUG, "nl80211: Authentication retry "
4980                                    "failed");
4981                         os_memset(&event, 0, sizeof(event));
4982                         os_memcpy(event.timeout_event.addr, drv->auth_bssid_,
4983                                   ETH_ALEN);
4984                         wpa_supplicant_event(drv->ctx, EVENT_AUTH_TIMED_OUT,
4985                                              &event);
4986                 }
4987
4988                 goto nla_put_failure;
4989         }
4990         ret = 0;
4991         wpa_printf(MSG_DEBUG, "nl80211: Authentication request send "
4992                    "successfully");
4993
4994 nla_put_failure:
4995         nlmsg_free(msg);
4996         return ret;
4997 }
4998
4999
5000 static int wpa_driver_nl80211_authenticate_retry(
5001         struct wpa_driver_nl80211_data *drv)
5002 {
5003         struct wpa_driver_auth_params params;
5004         struct i802_bss *bss = &drv->first_bss;
5005         int i;
5006
5007         wpa_printf(MSG_DEBUG, "nl80211: Try to authenticate again");
5008
5009         os_memset(&params, 0, sizeof(params));
5010         params.freq = drv->auth_freq;
5011         params.auth_alg = drv->auth_alg;
5012         params.wep_tx_keyidx = drv->auth_wep_tx_keyidx;
5013         params.local_state_change = drv->auth_local_state_change;
5014         params.p2p = drv->auth_p2p;
5015
5016         if (!is_zero_ether_addr(drv->auth_bssid_))
5017                 params.bssid = drv->auth_bssid_;
5018
5019         if (drv->auth_ssid_len) {
5020                 params.ssid = drv->auth_ssid;
5021                 params.ssid_len = drv->auth_ssid_len;
5022         }
5023
5024         params.ie = drv->auth_ie;
5025         params.ie_len = drv->auth_ie_len;
5026
5027         for (i = 0; i < 4; i++) {
5028                 if (drv->auth_wep_key_len[i]) {
5029                         params.wep_key[i] = drv->auth_wep_key[i];
5030                         params.wep_key_len[i] = drv->auth_wep_key_len[i];
5031                 }
5032         }
5033
5034         drv->retry_auth = 1;
5035         return wpa_driver_nl80211_authenticate(bss, &params);
5036 }
5037
5038
5039 struct phy_info_arg {
5040         u16 *num_modes;
5041         struct hostapd_hw_modes *modes;
5042         int last_mode, last_chan_idx;
5043 };
5044
5045 static void phy_info_ht_capa(struct hostapd_hw_modes *mode, struct nlattr *capa,
5046                              struct nlattr *ampdu_factor,
5047                              struct nlattr *ampdu_density,
5048                              struct nlattr *mcs_set)
5049 {
5050         if (capa)
5051                 mode->ht_capab = nla_get_u16(capa);
5052
5053         if (ampdu_factor)
5054                 mode->a_mpdu_params |= nla_get_u8(ampdu_factor) & 0x03;
5055
5056         if (ampdu_density)
5057                 mode->a_mpdu_params |= nla_get_u8(ampdu_density) << 2;
5058
5059         if (mcs_set && nla_len(mcs_set) >= 16) {
5060                 u8 *mcs;
5061                 mcs = nla_data(mcs_set);
5062                 os_memcpy(mode->mcs_set, mcs, 16);
5063         }
5064 }
5065
5066
5067 static void phy_info_vht_capa(struct hostapd_hw_modes *mode,
5068                               struct nlattr *capa,
5069                               struct nlattr *mcs_set)
5070 {
5071         if (capa)
5072                 mode->vht_capab = nla_get_u32(capa);
5073
5074         if (mcs_set && nla_len(mcs_set) >= 8) {
5075                 u8 *mcs;
5076                 mcs = nla_data(mcs_set);
5077                 os_memcpy(mode->vht_mcs_set, mcs, 8);
5078         }
5079 }
5080
5081
5082 static void phy_info_freq(struct hostapd_hw_modes *mode,
5083                           struct hostapd_channel_data *chan,
5084                           struct nlattr *tb_freq[])
5085 {
5086         enum hostapd_hw_mode m;
5087
5088         chan->freq = nla_get_u32(tb_freq[NL80211_FREQUENCY_ATTR_FREQ]);
5089         chan->flag = 0;
5090
5091         if (chan->freq < 4000)
5092                 m = HOSTAPD_MODE_IEEE80211B;
5093         else if (chan->freq > 50000)
5094                 m = HOSTAPD_MODE_IEEE80211AD;
5095         else
5096                 m = HOSTAPD_MODE_IEEE80211A;
5097
5098         switch (m) {
5099         case HOSTAPD_MODE_IEEE80211AD:
5100                 chan->chan = (chan->freq - 56160) / 2160;
5101                 break;
5102         case HOSTAPD_MODE_IEEE80211A:
5103                 chan->chan = chan->freq / 5 - 1000;
5104                 break;
5105         case HOSTAPD_MODE_IEEE80211B:
5106         case HOSTAPD_MODE_IEEE80211G:
5107                 if (chan->freq == 2484)
5108                         chan->chan = 14;
5109                 else
5110                         chan->chan = (chan->freq - 2407) / 5;
5111                 break;
5112         default:
5113                 break;
5114         }
5115
5116         if (tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
5117                 chan->flag |= HOSTAPD_CHAN_DISABLED;
5118         if (tb_freq[NL80211_FREQUENCY_ATTR_PASSIVE_SCAN])
5119                 chan->flag |= HOSTAPD_CHAN_PASSIVE_SCAN;
5120         if (tb_freq[NL80211_FREQUENCY_ATTR_NO_IBSS])
5121                 chan->flag |= HOSTAPD_CHAN_NO_IBSS;
5122         if (tb_freq[NL80211_FREQUENCY_ATTR_RADAR])
5123                 chan->flag |= HOSTAPD_CHAN_RADAR;
5124
5125         if (tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER] &&
5126             !tb_freq[NL80211_FREQUENCY_ATTR_DISABLED])
5127                 chan->max_tx_power = nla_get_u32(
5128                         tb_freq[NL80211_FREQUENCY_ATTR_MAX_TX_POWER]) / 100;
5129 }
5130
5131
5132 static int phy_info_freqs(struct phy_info_arg *phy_info,
5133                           struct hostapd_hw_modes *mode, struct nlattr *tb)
5134 {
5135         static struct nla_policy freq_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
5136                 [NL80211_FREQUENCY_ATTR_FREQ] = { .type = NLA_U32 },
5137                 [NL80211_FREQUENCY_ATTR_DISABLED] = { .type = NLA_FLAG },
5138                 [NL80211_FREQUENCY_ATTR_PASSIVE_SCAN] = { .type = NLA_FLAG },
5139                 [NL80211_FREQUENCY_ATTR_NO_IBSS] = { .type = NLA_FLAG },
5140                 [NL80211_FREQUENCY_ATTR_RADAR] = { .type = NLA_FLAG },
5141                 [NL80211_FREQUENCY_ATTR_MAX_TX_POWER] = { .type = NLA_U32 },
5142         };
5143         int new_channels = 0;
5144         struct hostapd_channel_data *channel;
5145         struct nlattr *tb_freq[NL80211_FREQUENCY_ATTR_MAX + 1];
5146         struct nlattr *nl_freq;
5147         int rem_freq, idx;
5148
5149         if (tb == NULL)
5150                 return NL_OK;
5151
5152         nla_for_each_nested(nl_freq, tb, rem_freq) {
5153                 nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX,
5154                           nla_data(nl_freq), nla_len(nl_freq), freq_policy);
5155                 if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
5156                         continue;
5157                 new_channels++;
5158         }
5159
5160         channel = os_realloc_array(mode->channels,
5161                                    mode->num_channels + new_channels,
5162                                    sizeof(struct hostapd_channel_data));
5163         if (!channel)
5164                 return NL_SKIP;
5165
5166         mode->channels = channel;
5167         mode->num_channels += new_channels;
5168
5169         idx = phy_info->last_chan_idx;
5170
5171         nla_for_each_nested(nl_freq, tb, rem_freq) {
5172                 nla_parse(tb_freq, NL80211_FREQUENCY_ATTR_MAX,
5173                           nla_data(nl_freq), nla_len(nl_freq), freq_policy);
5174                 if (!tb_freq[NL80211_FREQUENCY_ATTR_FREQ])
5175                         continue;
5176                 phy_info_freq(mode, &mode->channels[idx], tb_freq);
5177                 idx++;
5178         }
5179         phy_info->last_chan_idx = idx;
5180
5181         return NL_OK;
5182 }
5183
5184
5185 static int phy_info_rates(struct hostapd_hw_modes *mode, struct nlattr *tb)
5186 {
5187         static struct nla_policy rate_policy[NL80211_BITRATE_ATTR_MAX + 1] = {
5188                 [NL80211_BITRATE_ATTR_RATE] = { .type = NLA_U32 },
5189                 [NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE] =
5190                 { .type = NLA_FLAG },
5191         };
5192         struct nlattr *tb_rate[NL80211_BITRATE_ATTR_MAX + 1];
5193         struct nlattr *nl_rate;
5194         int rem_rate, idx;
5195
5196         if (tb == NULL)
5197                 return NL_OK;
5198
5199         nla_for_each_nested(nl_rate, tb, rem_rate) {
5200                 nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX,
5201                           nla_data(nl_rate), nla_len(nl_rate),
5202                           rate_policy);
5203                 if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
5204                         continue;
5205                 mode->num_rates++;
5206         }
5207
5208         mode->rates = os_calloc(mode->num_rates, sizeof(int));
5209         if (!mode->rates)
5210                 return NL_SKIP;
5211
5212         idx = 0;
5213
5214         nla_for_each_nested(nl_rate, tb, rem_rate) {
5215                 nla_parse(tb_rate, NL80211_BITRATE_ATTR_MAX,
5216                           nla_data(nl_rate), nla_len(nl_rate),
5217                           rate_policy);
5218                 if (!tb_rate[NL80211_BITRATE_ATTR_RATE])
5219                         continue;
5220                 mode->rates[idx] = nla_get_u32(
5221                         tb_rate[NL80211_BITRATE_ATTR_RATE]);
5222                 idx++;
5223         }
5224
5225         return NL_OK;
5226 }
5227
5228
5229 static int phy_info_band(struct phy_info_arg *phy_info, struct nlattr *nl_band)
5230 {
5231         struct nlattr *tb_band[NL80211_BAND_ATTR_MAX + 1];
5232         struct hostapd_hw_modes *mode;
5233         int ret;
5234
5235         if (phy_info->last_mode != nl_band->nla_type) {
5236                 mode = os_realloc_array(phy_info->modes,
5237                                         *phy_info->num_modes + 1,
5238                                         sizeof(*mode));
5239                 if (!mode)
5240                         return NL_SKIP;
5241                 phy_info->modes = mode;
5242
5243                 mode = &phy_info->modes[*(phy_info->num_modes)];
5244                 os_memset(mode, 0, sizeof(*mode));
5245                 mode->mode = NUM_HOSTAPD_MODES;
5246                 mode->flags = HOSTAPD_MODE_FLAG_HT_INFO_KNOWN;
5247                 *(phy_info->num_modes) += 1;
5248                 phy_info->last_mode = nl_band->nla_type;
5249                 phy_info->last_chan_idx = 0;
5250         } else
5251                 mode = &phy_info->modes[*(phy_info->num_modes) - 1];
5252
5253         nla_parse(tb_band, NL80211_BAND_ATTR_MAX, nla_data(nl_band),
5254                   nla_len(nl_band), NULL);
5255
5256         phy_info_ht_capa(mode, tb_band[NL80211_BAND_ATTR_HT_CAPA],
5257                          tb_band[NL80211_BAND_ATTR_HT_AMPDU_FACTOR],
5258                          tb_band[NL80211_BAND_ATTR_HT_AMPDU_DENSITY],
5259                          tb_band[NL80211_BAND_ATTR_HT_MCS_SET]);
5260         phy_info_vht_capa(mode, tb_band[NL80211_BAND_ATTR_VHT_CAPA],
5261                           tb_band[NL80211_BAND_ATTR_VHT_MCS_SET]);
5262         ret = phy_info_freqs(phy_info, mode, tb_band[NL80211_BAND_ATTR_FREQS]);
5263         if (ret != NL_OK)
5264                 return ret;
5265         ret = phy_info_rates(mode, tb_band[NL80211_BAND_ATTR_RATES]);
5266         if (ret != NL_OK)
5267                 return ret;
5268
5269         return NL_OK;
5270 }
5271
5272
5273 static int phy_info_handler(struct nl_msg *msg, void *arg)
5274 {
5275         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
5276         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5277         struct phy_info_arg *phy_info = arg;
5278         struct nlattr *nl_band;
5279         int rem_band;
5280
5281         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5282                   genlmsg_attrlen(gnlh, 0), NULL);
5283
5284         if (!tb_msg[NL80211_ATTR_WIPHY_BANDS])
5285                 return NL_SKIP;
5286
5287         nla_for_each_nested(nl_band, tb_msg[NL80211_ATTR_WIPHY_BANDS], rem_band)
5288         {
5289                 int res = phy_info_band(phy_info, nl_band);
5290                 if (res != NL_OK)
5291                         return res;
5292         }
5293
5294         return NL_SKIP;
5295 }
5296
5297
5298 static struct hostapd_hw_modes *
5299 wpa_driver_nl80211_postprocess_modes(struct hostapd_hw_modes *modes,
5300                                      u16 *num_modes)
5301 {
5302         u16 m;
5303         struct hostapd_hw_modes *mode11g = NULL, *nmodes, *mode;
5304         int i, mode11g_idx = -1;
5305
5306         /* heuristic to set up modes */
5307         for (m = 0; m < *num_modes; m++) {
5308                 if (!modes[m].num_channels)
5309                         continue;
5310                 if (modes[m].channels[0].freq < 4000) {
5311                         modes[m].mode = HOSTAPD_MODE_IEEE80211B;
5312                         for (i = 0; i < modes[m].num_rates; i++) {
5313                                 if (modes[m].rates[i] > 200) {
5314                                         modes[m].mode = HOSTAPD_MODE_IEEE80211G;
5315                                         break;
5316                                 }
5317                         }
5318                 } else if (modes[m].channels[0].freq > 50000)
5319                         modes[m].mode = HOSTAPD_MODE_IEEE80211AD;
5320                 else
5321                         modes[m].mode = HOSTAPD_MODE_IEEE80211A;
5322         }
5323
5324         /* If only 802.11g mode is included, use it to construct matching
5325          * 802.11b mode data. */
5326
5327         for (m = 0; m < *num_modes; m++) {
5328                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211B)
5329                         return modes; /* 802.11b already included */
5330                 if (modes[m].mode == HOSTAPD_MODE_IEEE80211G)
5331                         mode11g_idx = m;
5332         }
5333
5334         if (mode11g_idx < 0)
5335                 return modes; /* 2.4 GHz band not supported at all */
5336
5337         nmodes = os_realloc_array(modes, *num_modes + 1, sizeof(*nmodes));
5338         if (nmodes == NULL)
5339                 return modes; /* Could not add 802.11b mode */
5340
5341         mode = &nmodes[*num_modes];
5342         os_memset(mode, 0, sizeof(*mode));
5343         (*num_modes)++;
5344         modes = nmodes;
5345
5346         mode->mode = HOSTAPD_MODE_IEEE80211B;
5347
5348         mode11g = &modes[mode11g_idx];
5349         mode->num_channels = mode11g->num_channels;
5350         mode->channels = os_malloc(mode11g->num_channels *
5351                                    sizeof(struct hostapd_channel_data));
5352         if (mode->channels == NULL) {
5353                 (*num_modes)--;
5354                 return modes; /* Could not add 802.11b mode */
5355         }
5356         os_memcpy(mode->channels, mode11g->channels,
5357                   mode11g->num_channels * sizeof(struct hostapd_channel_data));
5358
5359         mode->num_rates = 0;
5360         mode->rates = os_malloc(4 * sizeof(int));
5361         if (mode->rates == NULL) {
5362                 os_free(mode->channels);
5363                 (*num_modes)--;
5364                 return modes; /* Could not add 802.11b mode */
5365         }
5366
5367         for (i = 0; i < mode11g->num_rates; i++) {
5368                 if (mode11g->rates[i] != 10 && mode11g->rates[i] != 20 &&
5369                     mode11g->rates[i] != 55 && mode11g->rates[i] != 110)
5370                         continue;
5371                 mode->rates[mode->num_rates] = mode11g->rates[i];
5372                 mode->num_rates++;
5373                 if (mode->num_rates == 4)
5374                         break;
5375         }
5376
5377         if (mode->num_rates == 0) {
5378                 os_free(mode->channels);
5379                 os_free(mode->rates);
5380                 (*num_modes)--;
5381                 return modes; /* No 802.11b rates */
5382         }
5383
5384         wpa_printf(MSG_DEBUG, "nl80211: Added 802.11b mode based on 802.11g "
5385                    "information");
5386
5387         return modes;
5388 }
5389
5390
5391 static void nl80211_set_ht40_mode(struct hostapd_hw_modes *mode, int start,
5392                                   int end)
5393 {
5394         int c;
5395
5396         for (c = 0; c < mode->num_channels; c++) {
5397                 struct hostapd_channel_data *chan = &mode->channels[c];
5398                 if (chan->freq - 10 >= start && chan->freq + 10 <= end)
5399                         chan->flag |= HOSTAPD_CHAN_HT40;
5400         }
5401 }
5402
5403
5404 static void nl80211_set_ht40_mode_sec(struct hostapd_hw_modes *mode, int start,
5405                                       int end)
5406 {
5407         int c;
5408
5409         for (c = 0; c < mode->num_channels; c++) {
5410                 struct hostapd_channel_data *chan = &mode->channels[c];
5411                 if (!(chan->flag & HOSTAPD_CHAN_HT40))
5412                         continue;
5413                 if (chan->freq - 30 >= start && chan->freq - 10 <= end)
5414                         chan->flag |= HOSTAPD_CHAN_HT40MINUS;
5415                 if (chan->freq + 10 >= start && chan->freq + 30 <= end)
5416                         chan->flag |= HOSTAPD_CHAN_HT40PLUS;
5417         }
5418 }
5419
5420
5421 static void nl80211_reg_rule_ht40(struct nlattr *tb[],
5422                                   struct phy_info_arg *results)
5423 {
5424         u32 start, end, max_bw;
5425         u16 m;
5426
5427         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
5428             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
5429             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
5430                 return;
5431
5432         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
5433         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
5434         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
5435
5436         wpa_printf(MSG_DEBUG, "nl80211: %u-%u @ %u MHz",
5437                    start, end, max_bw);
5438         if (max_bw < 40)
5439                 return;
5440
5441         for (m = 0; m < *results->num_modes; m++) {
5442                 if (!(results->modes[m].ht_capab &
5443                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
5444                         continue;
5445                 nl80211_set_ht40_mode(&results->modes[m], start, end);
5446         }
5447 }
5448
5449
5450 static void nl80211_reg_rule_sec(struct nlattr *tb[],
5451                                  struct phy_info_arg *results)
5452 {
5453         u32 start, end, max_bw;
5454         u16 m;
5455
5456         if (tb[NL80211_ATTR_FREQ_RANGE_START] == NULL ||
5457             tb[NL80211_ATTR_FREQ_RANGE_END] == NULL ||
5458             tb[NL80211_ATTR_FREQ_RANGE_MAX_BW] == NULL)
5459                 return;
5460
5461         start = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]) / 1000;
5462         end = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]) / 1000;
5463         max_bw = nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]) / 1000;
5464
5465         if (max_bw < 20)
5466                 return;
5467
5468         for (m = 0; m < *results->num_modes; m++) {
5469                 if (!(results->modes[m].ht_capab &
5470                       HT_CAP_INFO_SUPP_CHANNEL_WIDTH_SET))
5471                         continue;
5472                 nl80211_set_ht40_mode_sec(&results->modes[m], start, end);
5473         }
5474 }
5475
5476
5477 static int nl80211_get_reg(struct nl_msg *msg, void *arg)
5478 {
5479         struct phy_info_arg *results = arg;
5480         struct nlattr *tb_msg[NL80211_ATTR_MAX + 1];
5481         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
5482         struct nlattr *nl_rule;
5483         struct nlattr *tb_rule[NL80211_FREQUENCY_ATTR_MAX + 1];
5484         int rem_rule;
5485         static struct nla_policy reg_policy[NL80211_FREQUENCY_ATTR_MAX + 1] = {
5486                 [NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
5487                 [NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
5488                 [NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
5489                 [NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
5490                 [NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
5491                 [NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
5492         };
5493
5494         nla_parse(tb_msg, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
5495                   genlmsg_attrlen(gnlh, 0), NULL);
5496         if (!tb_msg[NL80211_ATTR_REG_ALPHA2] ||
5497             !tb_msg[NL80211_ATTR_REG_RULES]) {
5498                 wpa_printf(MSG_DEBUG, "nl80211: No regulatory information "
5499                            "available");
5500                 return NL_SKIP;
5501         }
5502
5503         wpa_printf(MSG_DEBUG, "nl80211: Regulatory information - country=%s",
5504                    (char *) nla_data(tb_msg[NL80211_ATTR_REG_ALPHA2]));
5505
5506         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5507         {
5508                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5509                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5510                 nl80211_reg_rule_ht40(tb_rule, results);
5511         }
5512
5513         nla_for_each_nested(nl_rule, tb_msg[NL80211_ATTR_REG_RULES], rem_rule)
5514         {
5515                 nla_parse(tb_rule, NL80211_FREQUENCY_ATTR_MAX,
5516                           nla_data(nl_rule), nla_len(nl_rule), reg_policy);
5517                 nl80211_reg_rule_sec(tb_rule, results);
5518         }
5519
5520         return NL_SKIP;
5521 }
5522
5523
5524 static int nl80211_set_ht40_flags(struct wpa_driver_nl80211_data *drv,
5525                                   struct phy_info_arg *results)
5526 {
5527         struct nl_msg *msg;
5528
5529         msg = nlmsg_alloc();
5530         if (!msg)
5531                 return -ENOMEM;
5532
5533         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_REG);
5534         return send_and_recv_msgs(drv, msg, nl80211_get_reg, results);
5535 }
5536
5537
5538 static struct hostapd_hw_modes *
5539 wpa_driver_nl80211_get_hw_feature_data(void *priv, u16 *num_modes, u16 *flags)
5540 {
5541         u32 feat;
5542         struct i802_bss *bss = priv;
5543         struct wpa_driver_nl80211_data *drv = bss->drv;
5544         struct nl_msg *msg;
5545         struct phy_info_arg result = {
5546                 .num_modes = num_modes,
5547                 .modes = NULL,
5548                 .last_mode = -1,
5549         };
5550
5551         *num_modes = 0;
5552         *flags = 0;
5553
5554         msg = nlmsg_alloc();
5555         if (!msg)
5556                 return NULL;
5557
5558         feat = get_nl80211_protocol_features(drv);
5559         if (feat & NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP)
5560                 nl80211_cmd(drv, msg, NLM_F_DUMP, NL80211_CMD_GET_WIPHY);
5561         else
5562                 nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_WIPHY);
5563
5564         NLA_PUT_FLAG(msg, NL80211_ATTR_SPLIT_WIPHY_DUMP);
5565         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5566
5567         if (send_and_recv_msgs(drv, msg, phy_info_handler, &result) == 0) {
5568                 nl80211_set_ht40_flags(drv, &result);
5569                 return wpa_driver_nl80211_postprocess_modes(result.modes,
5570                                                             num_modes);
5571         }
5572         msg = NULL;
5573  nla_put_failure:
5574         nlmsg_free(msg);
5575         return NULL;
5576 }
5577
5578
5579 static int wpa_driver_nl80211_send_mntr(struct wpa_driver_nl80211_data *drv,
5580                                         const void *data, size_t len,
5581                                         int encrypt, int noack)
5582 {
5583         __u8 rtap_hdr[] = {
5584                 0x00, 0x00, /* radiotap version */
5585                 0x0e, 0x00, /* radiotap length */
5586                 0x02, 0xc0, 0x00, 0x00, /* bmap: flags, tx and rx flags */
5587                 IEEE80211_RADIOTAP_F_FRAG, /* F_FRAG (fragment if required) */
5588                 0x00,       /* padding */
5589                 0x00, 0x00, /* RX and TX flags to indicate that */
5590                 0x00, 0x00, /* this is the injected frame directly */
5591         };
5592         struct iovec iov[2] = {
5593                 {
5594                         .iov_base = &rtap_hdr,
5595                         .iov_len = sizeof(rtap_hdr),
5596                 },
5597                 {
5598                         .iov_base = (void *) data,
5599                         .iov_len = len,
5600                 }
5601         };
5602         struct msghdr msg = {
5603                 .msg_name = NULL,
5604                 .msg_namelen = 0,
5605                 .msg_iov = iov,
5606                 .msg_iovlen = 2,
5607                 .msg_control = NULL,
5608                 .msg_controllen = 0,
5609                 .msg_flags = 0,
5610         };
5611         int res;
5612         u16 txflags = 0;
5613
5614         if (encrypt)
5615                 rtap_hdr[8] |= IEEE80211_RADIOTAP_F_WEP;
5616
5617         if (drv->monitor_sock < 0) {
5618                 wpa_printf(MSG_DEBUG, "nl80211: No monitor socket available "
5619                            "for %s", __func__);
5620                 return -1;
5621         }
5622
5623         if (noack)
5624                 txflags |= IEEE80211_RADIOTAP_F_TX_NOACK;
5625         WPA_PUT_LE16(&rtap_hdr[12], txflags);
5626
5627         res = sendmsg(drv->monitor_sock, &msg, 0);
5628         if (res < 0) {
5629                 wpa_printf(MSG_INFO, "nl80211: sendmsg: %s", strerror(errno));
5630                 return -1;
5631         }
5632         return 0;
5633 }
5634
5635
5636 static int wpa_driver_nl80211_send_frame(struct i802_bss *bss,
5637                                          const void *data, size_t len,
5638                                          int encrypt, int noack,
5639                                          unsigned int freq, int no_cck,
5640                                          int offchanok, unsigned int wait_time)
5641 {
5642         struct wpa_driver_nl80211_data *drv = bss->drv;
5643         u64 cookie;
5644
5645         if (freq == 0)
5646                 freq = bss->freq;
5647
5648         if (drv->use_monitor)
5649                 return wpa_driver_nl80211_send_mntr(drv, data, len,
5650                                                     encrypt, noack);
5651
5652         return nl80211_send_frame_cmd(bss, freq, wait_time, data, len,
5653                                       &cookie, no_cck, noack, offchanok);
5654 }
5655
5656
5657 static int wpa_driver_nl80211_send_mlme(struct i802_bss *bss, const u8 *data,
5658                                         size_t data_len, int noack,
5659                                         unsigned int freq, int no_cck,
5660                                         int offchanok,
5661                                         unsigned int wait_time)
5662 {
5663         struct wpa_driver_nl80211_data *drv = bss->drv;
5664         struct ieee80211_mgmt *mgmt;
5665         int encrypt = 1;
5666         u16 fc;
5667
5668         mgmt = (struct ieee80211_mgmt *) data;
5669         fc = le_to_host16(mgmt->frame_control);
5670
5671         if (is_sta_interface(drv->nlmode) &&
5672             WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5673             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_PROBE_RESP) {
5674                 /*
5675                  * The use of last_mgmt_freq is a bit of a hack,
5676                  * but it works due to the single-threaded nature
5677                  * of wpa_supplicant.
5678                  */
5679                 if (freq == 0)
5680                         freq = drv->last_mgmt_freq;
5681                 return nl80211_send_frame_cmd(bss, freq, 0,
5682                                               data, data_len, NULL, 1, noack,
5683                                               1);
5684         }
5685
5686         if (drv->device_ap_sme && is_ap_interface(drv->nlmode)) {
5687                 if (freq == 0)
5688                         freq = bss->freq;
5689                 return nl80211_send_frame_cmd(bss, freq,
5690                                               (int) freq == bss->freq ? 0 :
5691                                               wait_time,
5692                                               data, data_len,
5693                                               &drv->send_action_cookie,
5694                                               no_cck, noack, offchanok);
5695         }
5696
5697         if (WLAN_FC_GET_TYPE(fc) == WLAN_FC_TYPE_MGMT &&
5698             WLAN_FC_GET_STYPE(fc) == WLAN_FC_STYPE_AUTH) {
5699                 /*
5700                  * Only one of the authentication frame types is encrypted.
5701                  * In order for static WEP encryption to work properly (i.e.,
5702                  * to not encrypt the frame), we need to tell mac80211 about
5703                  * the frames that must not be encrypted.
5704                  */
5705                 u16 auth_alg = le_to_host16(mgmt->u.auth.auth_alg);
5706                 u16 auth_trans = le_to_host16(mgmt->u.auth.auth_transaction);
5707                 if (auth_alg != WLAN_AUTH_SHARED_KEY || auth_trans != 3)
5708                         encrypt = 0;
5709         }
5710
5711         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt,
5712                                              noack, freq, no_cck, offchanok,
5713                                              wait_time);
5714 }
5715
5716
5717 static int nl80211_set_bss(struct i802_bss *bss, int cts, int preamble,
5718                            int slot, int ht_opmode, int ap_isolate,
5719                            int *basic_rates)
5720 {
5721         struct wpa_driver_nl80211_data *drv = bss->drv;
5722         struct nl_msg *msg;
5723
5724         msg = nlmsg_alloc();
5725         if (!msg)
5726                 return -ENOMEM;
5727
5728         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_BSS);
5729
5730         if (cts >= 0)
5731                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_CTS_PROT, cts);
5732         if (preamble >= 0)
5733                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_PREAMBLE, preamble);
5734         if (slot >= 0)
5735                 NLA_PUT_U8(msg, NL80211_ATTR_BSS_SHORT_SLOT_TIME, slot);
5736         if (ht_opmode >= 0)
5737                 NLA_PUT_U16(msg, NL80211_ATTR_BSS_HT_OPMODE, ht_opmode);
5738         if (ap_isolate >= 0)
5739                 NLA_PUT_U8(msg, NL80211_ATTR_AP_ISOLATE, ap_isolate);
5740
5741         if (basic_rates) {
5742                 u8 rates[NL80211_MAX_SUPP_RATES];
5743                 u8 rates_len = 0;
5744                 int i;
5745
5746                 for (i = 0; i < NL80211_MAX_SUPP_RATES && basic_rates[i] >= 0;
5747                      i++)
5748                         rates[rates_len++] = basic_rates[i] / 5;
5749
5750                 NLA_PUT(msg, NL80211_ATTR_BSS_BASIC_RATES, rates_len, rates);
5751         }
5752
5753         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
5754
5755         return send_and_recv_msgs(drv, msg, NULL, NULL);
5756  nla_put_failure:
5757         nlmsg_free(msg);
5758         return -ENOBUFS;
5759 }
5760
5761
5762 static int wpa_driver_nl80211_set_ap(void *priv,
5763                                      struct wpa_driver_ap_params *params)
5764 {
5765         struct i802_bss *bss = priv;
5766         struct wpa_driver_nl80211_data *drv = bss->drv;
5767         struct nl_msg *msg;
5768         u8 cmd = NL80211_CMD_NEW_BEACON;
5769         int ret;
5770         int beacon_set;
5771         int ifindex = if_nametoindex(bss->ifname);
5772         int num_suites;
5773         u32 suites[10];
5774         u32 ver;
5775
5776         beacon_set = bss->beacon_set;
5777
5778         msg = nlmsg_alloc();
5779         if (!msg)
5780                 return -ENOMEM;
5781
5782         wpa_printf(MSG_DEBUG, "nl80211: Set beacon (beacon_set=%d)",
5783                    beacon_set);
5784         if (beacon_set)
5785                 cmd = NL80211_CMD_SET_BEACON;
5786
5787         nl80211_cmd(drv, msg, 0, cmd);
5788         wpa_hexdump(MSG_DEBUG, "nl80211: Beacon head",
5789                     params->head, params->head_len);
5790         NLA_PUT(msg, NL80211_ATTR_BEACON_HEAD, params->head_len, params->head);
5791         wpa_hexdump(MSG_DEBUG, "nl80211: Beacon tail",
5792                     params->tail, params->tail_len);
5793         NLA_PUT(msg, NL80211_ATTR_BEACON_TAIL, params->tail_len, params->tail);
5794         wpa_printf(MSG_DEBUG, "nl80211: ifindex=%d", ifindex);
5795         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
5796         wpa_printf(MSG_DEBUG, "nl80211: beacon_int=%d", params->beacon_int);
5797         NLA_PUT_U32(msg, NL80211_ATTR_BEACON_INTERVAL, params->beacon_int);
5798         wpa_printf(MSG_DEBUG, "nl80211: dtim_period=%d", params->dtim_period);
5799         NLA_PUT_U32(msg, NL80211_ATTR_DTIM_PERIOD, params->dtim_period);
5800         wpa_hexdump_ascii(MSG_DEBUG, "nl80211: ssid",
5801                           params->ssid, params->ssid_len);
5802         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
5803                 params->ssid);
5804         if (params->proberesp && params->proberesp_len) {
5805                 wpa_hexdump(MSG_DEBUG, "nl80211: proberesp (offload)",
5806                             params->proberesp, params->proberesp_len);
5807                 NLA_PUT(msg, NL80211_ATTR_PROBE_RESP, params->proberesp_len,
5808                         params->proberesp);
5809         }
5810         switch (params->hide_ssid) {
5811         case NO_SSID_HIDING:
5812                 wpa_printf(MSG_DEBUG, "nl80211: hidden SSID not in use");
5813                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5814                             NL80211_HIDDEN_SSID_NOT_IN_USE);
5815                 break;
5816         case HIDDEN_SSID_ZERO_LEN:
5817                 wpa_printf(MSG_DEBUG, "nl80211: hidden SSID zero len");
5818                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5819                             NL80211_HIDDEN_SSID_ZERO_LEN);
5820                 break;
5821         case HIDDEN_SSID_ZERO_CONTENTS:
5822                 wpa_printf(MSG_DEBUG, "nl80211: hidden SSID zero contents");
5823                 NLA_PUT_U32(msg, NL80211_ATTR_HIDDEN_SSID,
5824                             NL80211_HIDDEN_SSID_ZERO_CONTENTS);
5825                 break;
5826         }
5827         wpa_printf(MSG_DEBUG, "nl80211: privacy=%d", params->privacy);
5828         if (params->privacy)
5829                 NLA_PUT_FLAG(msg, NL80211_ATTR_PRIVACY);
5830         wpa_printf(MSG_DEBUG, "nl80211: auth_algs=0x%x", params->auth_algs);
5831         if ((params->auth_algs & (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) ==
5832             (WPA_AUTH_ALG_OPEN | WPA_AUTH_ALG_SHARED)) {
5833                 /* Leave out the attribute */
5834         } else if (params->auth_algs & WPA_AUTH_ALG_SHARED)
5835                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5836                             NL80211_AUTHTYPE_SHARED_KEY);
5837         else
5838                 NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE,
5839                             NL80211_AUTHTYPE_OPEN_SYSTEM);
5840
5841         wpa_printf(MSG_DEBUG, "nl80211: wpa_version=0x%x", params->wpa_version);
5842         ver = 0;
5843         if (params->wpa_version & WPA_PROTO_WPA)
5844                 ver |= NL80211_WPA_VERSION_1;
5845         if (params->wpa_version & WPA_PROTO_RSN)
5846                 ver |= NL80211_WPA_VERSION_2;
5847         if (ver)
5848                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
5849
5850         wpa_printf(MSG_DEBUG, "nl80211: key_mgmt_suites=0x%x",
5851                    params->key_mgmt_suites);
5852         num_suites = 0;
5853         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X)
5854                 suites[num_suites++] = WLAN_AKM_SUITE_8021X;
5855         if (params->key_mgmt_suites & WPA_KEY_MGMT_PSK)
5856                 suites[num_suites++] = WLAN_AKM_SUITE_PSK;
5857         if (num_suites) {
5858                 NLA_PUT(msg, NL80211_ATTR_AKM_SUITES,
5859                         num_suites * sizeof(u32), suites);
5860         }
5861
5862         if (params->key_mgmt_suites & WPA_KEY_MGMT_IEEE8021X &&
5863             params->pairwise_ciphers & (WPA_CIPHER_WEP104 | WPA_CIPHER_WEP40))
5864                 NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT);
5865
5866         wpa_printf(MSG_DEBUG, "nl80211: pairwise_ciphers=0x%x",
5867                    params->pairwise_ciphers);
5868         num_suites = 0;
5869         if (params->pairwise_ciphers & WPA_CIPHER_CCMP)
5870                 suites[num_suites++] = WLAN_CIPHER_SUITE_CCMP;
5871         if (params->pairwise_ciphers & WPA_CIPHER_GCMP)
5872                 suites[num_suites++] = WLAN_CIPHER_SUITE_GCMP;
5873         if (params->pairwise_ciphers & WPA_CIPHER_TKIP)
5874                 suites[num_suites++] = WLAN_CIPHER_SUITE_TKIP;
5875         if (params->pairwise_ciphers & WPA_CIPHER_WEP104)
5876                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP104;
5877         if (params->pairwise_ciphers & WPA_CIPHER_WEP40)
5878                 suites[num_suites++] = WLAN_CIPHER_SUITE_WEP40;
5879         if (num_suites) {
5880                 NLA_PUT(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE,
5881                         num_suites * sizeof(u32), suites);
5882         }
5883
5884         wpa_printf(MSG_DEBUG, "nl80211: group_cipher=0x%x",
5885                    params->group_cipher);
5886         switch (params->group_cipher) {
5887         case WPA_CIPHER_CCMP:
5888                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5889                             WLAN_CIPHER_SUITE_CCMP);
5890                 break;
5891         case WPA_CIPHER_GCMP:
5892                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5893                             WLAN_CIPHER_SUITE_GCMP);
5894                 break;
5895         case WPA_CIPHER_TKIP:
5896                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5897                             WLAN_CIPHER_SUITE_TKIP);
5898                 break;
5899         case WPA_CIPHER_WEP104:
5900                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5901                             WLAN_CIPHER_SUITE_WEP104);
5902                 break;
5903         case WPA_CIPHER_WEP40:
5904                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP,
5905                             WLAN_CIPHER_SUITE_WEP40);
5906                 break;
5907         }
5908
5909         if (params->beacon_ies) {
5910                 wpa_hexdump_buf(MSG_DEBUG, "nl80211: beacon_ies",
5911                                 params->beacon_ies);
5912                 NLA_PUT(msg, NL80211_ATTR_IE, wpabuf_len(params->beacon_ies),
5913                         wpabuf_head(params->beacon_ies));
5914         }
5915         if (params->proberesp_ies) {
5916                 wpa_hexdump_buf(MSG_DEBUG, "nl80211: proberesp_ies",
5917                                 params->proberesp_ies);
5918                 NLA_PUT(msg, NL80211_ATTR_IE_PROBE_RESP,
5919                         wpabuf_len(params->proberesp_ies),
5920                         wpabuf_head(params->proberesp_ies));
5921         }
5922         if (params->assocresp_ies) {
5923                 wpa_hexdump_buf(MSG_DEBUG, "nl80211: assocresp_ies",
5924                                 params->assocresp_ies);
5925                 NLA_PUT(msg, NL80211_ATTR_IE_ASSOC_RESP,
5926                         wpabuf_len(params->assocresp_ies),
5927                         wpabuf_head(params->assocresp_ies));
5928         }
5929
5930         if (drv->capa.flags & WPA_DRIVER_FLAGS_INACTIVITY_TIMER)  {
5931                 wpa_printf(MSG_DEBUG, "nl80211: ap_max_inactivity=%d",
5932                            params->ap_max_inactivity);
5933                 NLA_PUT_U16(msg, NL80211_ATTR_INACTIVITY_TIMEOUT,
5934                             params->ap_max_inactivity);
5935         }
5936
5937         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
5938         if (ret) {
5939                 wpa_printf(MSG_DEBUG, "nl80211: Beacon set failed: %d (%s)",
5940                            ret, strerror(-ret));
5941         } else {
5942                 bss->beacon_set = 1;
5943                 nl80211_set_bss(bss, params->cts_protect, params->preamble,
5944                                 params->short_slot_time, params->ht_opmode,
5945                                 params->isolate, params->basic_rates);
5946         }
5947         return ret;
5948  nla_put_failure:
5949         nlmsg_free(msg);
5950         return -ENOBUFS;
5951 }
5952
5953
5954 static int wpa_driver_nl80211_set_freq(struct i802_bss *bss,
5955                                        struct hostapd_freq_params *freq)
5956 {
5957         struct wpa_driver_nl80211_data *drv = bss->drv;
5958         struct nl_msg *msg;
5959         int ret;
5960
5961         wpa_printf(MSG_DEBUG, "nl80211: Set freq %d (ht_enabled=%d, vht_enabled=%d,"
5962                    " bandwidth=%d MHz, cf1=%d MHz, cf2=%d MHz)",
5963                    freq->freq, freq->ht_enabled, freq->vht_enabled,
5964                    freq->bandwidth, freq->center_freq1, freq->center_freq2);
5965         msg = nlmsg_alloc();
5966         if (!msg)
5967                 return -1;
5968
5969         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
5970
5971         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
5972         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq->freq);
5973         if (freq->vht_enabled) {
5974                 switch (freq->bandwidth) {
5975                 case 20:
5976                         NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
5977                                     NL80211_CHAN_WIDTH_20);
5978                         break;
5979                 case 40:
5980                         NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
5981                                     NL80211_CHAN_WIDTH_40);
5982                         break;
5983                 case 80:
5984                         if (freq->center_freq2)
5985                                 NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
5986                                             NL80211_CHAN_WIDTH_80P80);
5987                         else
5988                                 NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
5989                                             NL80211_CHAN_WIDTH_80);
5990                         break;
5991                 case 160:
5992                         NLA_PUT_U32(msg, NL80211_ATTR_CHANNEL_WIDTH,
5993                                     NL80211_CHAN_WIDTH_160);
5994                         break;
5995                 default:
5996                         return -1;
5997                 }
5998                 NLA_PUT_U32(msg, NL80211_ATTR_CENTER_FREQ1, freq->center_freq1);
5999                 if (freq->center_freq2)
6000                         NLA_PUT_U32(msg, NL80211_ATTR_CENTER_FREQ2,
6001                                     freq->center_freq2);
6002         } else if (freq->ht_enabled) {
6003                 switch (freq->sec_channel_offset) {
6004                 case -1:
6005                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
6006                                     NL80211_CHAN_HT40MINUS);
6007                         break;
6008                 case 1:
6009                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
6010                                     NL80211_CHAN_HT40PLUS);
6011                         break;
6012                 default:
6013                         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
6014                                     NL80211_CHAN_HT20);
6015                         break;
6016                 }
6017         }
6018
6019         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6020         msg = NULL;
6021         if (ret == 0) {
6022                 bss->freq = freq->freq;
6023                 return 0;
6024         }
6025         wpa_printf(MSG_DEBUG, "nl80211: Failed to set channel (freq=%d): "
6026                    "%d (%s)", freq->freq, ret, strerror(-ret));
6027 nla_put_failure:
6028         nlmsg_free(msg);
6029         return -1;
6030 }
6031
6032
6033 static u32 sta_flags_nl80211(int flags)
6034 {
6035         u32 f = 0;
6036
6037         if (flags & WPA_STA_AUTHORIZED)
6038                 f |= BIT(NL80211_STA_FLAG_AUTHORIZED);
6039         if (flags & WPA_STA_WMM)
6040                 f |= BIT(NL80211_STA_FLAG_WME);
6041         if (flags & WPA_STA_SHORT_PREAMBLE)
6042                 f |= BIT(NL80211_STA_FLAG_SHORT_PREAMBLE);
6043         if (flags & WPA_STA_MFP)
6044                 f |= BIT(NL80211_STA_FLAG_MFP);
6045         if (flags & WPA_STA_TDLS_PEER)
6046                 f |= BIT(NL80211_STA_FLAG_TDLS_PEER);
6047
6048         return f;
6049 }
6050
6051
6052 static int wpa_driver_nl80211_sta_add(void *priv,
6053                                       struct hostapd_sta_add_params *params)
6054 {
6055         struct i802_bss *bss = priv;
6056         struct wpa_driver_nl80211_data *drv = bss->drv;
6057         struct nl_msg *msg;
6058         struct nl80211_sta_flag_update upd;
6059         int ret = -ENOBUFS;
6060
6061         if ((params->flags & WPA_STA_TDLS_PEER) &&
6062             !(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
6063                 return -EOPNOTSUPP;
6064
6065         msg = nlmsg_alloc();
6066         if (!msg)
6067                 return -ENOMEM;
6068
6069         wpa_printf(MSG_DEBUG, "nl80211: %s STA " MACSTR,
6070                    params->set ? "Set" : "Add", MAC2STR(params->addr));
6071         nl80211_cmd(drv, msg, 0, params->set ? NL80211_CMD_SET_STATION :
6072                     NL80211_CMD_NEW_STATION);
6073
6074         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
6075         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->addr);
6076         NLA_PUT(msg, NL80211_ATTR_STA_SUPPORTED_RATES, params->supp_rates_len,
6077                 params->supp_rates);
6078         wpa_hexdump(MSG_DEBUG, "  * supported rates", params->supp_rates,
6079                     params->supp_rates_len);
6080         if (!params->set) {
6081                 wpa_printf(MSG_DEBUG, "  * aid=%u", params->aid);
6082                 NLA_PUT_U16(msg, NL80211_ATTR_STA_AID, params->aid);
6083                 wpa_printf(MSG_DEBUG, "  * listen_interval=%u",
6084                            params->listen_interval);
6085                 NLA_PUT_U16(msg, NL80211_ATTR_STA_LISTEN_INTERVAL,
6086                             params->listen_interval);
6087         }
6088         if (params->ht_capabilities) {
6089                 wpa_hexdump(MSG_DEBUG, "  * ht_capabilities",
6090                             (u8 *) params->ht_capabilities,
6091                             sizeof(*params->ht_capabilities));
6092                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY,
6093                         sizeof(*params->ht_capabilities),
6094                         params->ht_capabilities);
6095         }
6096
6097         if (params->vht_capabilities) {
6098                 wpa_hexdump(MSG_DEBUG, "  * vht_capabilities",
6099                             (u8 *) params->vht_capabilities,
6100                             sizeof(*params->vht_capabilities));
6101                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY,
6102                         sizeof(*params->vht_capabilities),
6103                         params->vht_capabilities);
6104         }
6105
6106         wpa_printf(MSG_DEBUG, "  * capability=0x%x", params->capability);
6107         NLA_PUT_U16(msg, NL80211_ATTR_STA_CAPABILITY, params->capability);
6108
6109         if (params->ext_capab) {
6110                 wpa_hexdump(MSG_DEBUG, "  * ext_capab",
6111                             params->ext_capab, params->ext_capab_len);
6112                 NLA_PUT(msg, NL80211_ATTR_STA_EXT_CAPABILITY,
6113                         params->ext_capab_len, params->ext_capab);
6114         }
6115
6116         os_memset(&upd, 0, sizeof(upd));
6117         upd.mask = sta_flags_nl80211(params->flags);
6118         upd.set = upd.mask;
6119         wpa_printf(MSG_DEBUG, "  * flags set=0x%x mask=0x%x",
6120                    upd.set, upd.mask);
6121         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
6122
6123         if (params->flags & WPA_STA_WMM) {
6124                 struct nlattr *wme = nla_nest_start(msg, NL80211_ATTR_STA_WME);
6125
6126                 if (!wme)
6127                         goto nla_put_failure;
6128
6129                 wpa_printf(MSG_DEBUG, "  * qosinfo=0x%x", params->qosinfo);
6130                 NLA_PUT_U8(msg, NL80211_STA_WME_UAPSD_QUEUES,
6131                                 params->qosinfo & WMM_QOSINFO_STA_AC_MASK);
6132                 NLA_PUT_U8(msg, NL80211_STA_WME_MAX_SP,
6133                                 (params->qosinfo >> WMM_QOSINFO_STA_SP_SHIFT) &
6134                                 WMM_QOSINFO_STA_SP_MASK);
6135                 nla_nest_end(msg, wme);
6136         }
6137
6138         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6139         msg = NULL;
6140         if (ret)
6141                 wpa_printf(MSG_DEBUG, "nl80211: NL80211_CMD_%s_STATION "
6142                            "result: %d (%s)", params->set ? "SET" : "NEW", ret,
6143                            strerror(-ret));
6144         if (ret == -EEXIST)
6145                 ret = 0;
6146  nla_put_failure:
6147         nlmsg_free(msg);
6148         return ret;
6149 }
6150
6151
6152 static int wpa_driver_nl80211_sta_remove(struct i802_bss *bss, const u8 *addr)
6153 {
6154         struct wpa_driver_nl80211_data *drv = bss->drv;
6155         struct nl_msg *msg;
6156         int ret;
6157
6158         msg = nlmsg_alloc();
6159         if (!msg)
6160                 return -ENOMEM;
6161
6162         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
6163
6164         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
6165                     if_nametoindex(bss->ifname));
6166         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
6167
6168         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6169         if (ret == -ENOENT)
6170                 return 0;
6171         return ret;
6172  nla_put_failure:
6173         nlmsg_free(msg);
6174         return -ENOBUFS;
6175 }
6176
6177
6178 static void nl80211_remove_iface(struct wpa_driver_nl80211_data *drv,
6179                                  int ifidx)
6180 {
6181         struct nl_msg *msg;
6182
6183         wpa_printf(MSG_DEBUG, "nl80211: Remove interface ifindex=%d", ifidx);
6184
6185         /* stop listening for EAPOL on this interface */
6186         del_ifidx(drv, ifidx);
6187
6188         msg = nlmsg_alloc();
6189         if (!msg)
6190                 goto nla_put_failure;
6191
6192         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_INTERFACE);
6193         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifidx);
6194
6195         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
6196                 return;
6197         msg = NULL;
6198  nla_put_failure:
6199         nlmsg_free(msg);
6200         wpa_printf(MSG_ERROR, "Failed to remove interface (ifidx=%d)", ifidx);
6201 }
6202
6203
6204 static const char * nl80211_iftype_str(enum nl80211_iftype mode)
6205 {
6206         switch (mode) {
6207         case NL80211_IFTYPE_ADHOC:
6208                 return "ADHOC";
6209         case NL80211_IFTYPE_STATION:
6210                 return "STATION";
6211         case NL80211_IFTYPE_AP:
6212                 return "AP";
6213         case NL80211_IFTYPE_MONITOR:
6214                 return "MONITOR";
6215         case NL80211_IFTYPE_P2P_CLIENT:
6216                 return "P2P_CLIENT";
6217         case NL80211_IFTYPE_P2P_GO:
6218                 return "P2P_GO";
6219         default:
6220                 return "unknown";
6221         }
6222 }
6223
6224
6225 static int nl80211_create_iface_once(struct wpa_driver_nl80211_data *drv,
6226                                      const char *ifname,
6227                                      enum nl80211_iftype iftype,
6228                                      const u8 *addr, int wds)
6229 {
6230         struct nl_msg *msg;
6231         int ifidx;
6232         int ret = -ENOBUFS;
6233
6234         wpa_printf(MSG_DEBUG, "nl80211: Create interface iftype %d (%s)",
6235                    iftype, nl80211_iftype_str(iftype));
6236
6237         msg = nlmsg_alloc();
6238         if (!msg)
6239                 return -1;
6240
6241         nl80211_cmd(drv, msg, 0, NL80211_CMD_NEW_INTERFACE);
6242         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6243         NLA_PUT_STRING(msg, NL80211_ATTR_IFNAME, ifname);
6244         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, iftype);
6245
6246         if (iftype == NL80211_IFTYPE_MONITOR) {
6247                 struct nlattr *flags;
6248
6249                 flags = nla_nest_start(msg, NL80211_ATTR_MNTR_FLAGS);
6250                 if (!flags)
6251                         goto nla_put_failure;
6252
6253                 NLA_PUT_FLAG(msg, NL80211_MNTR_FLAG_COOK_FRAMES);
6254
6255                 nla_nest_end(msg, flags);
6256         } else if (wds) {
6257                 NLA_PUT_U8(msg, NL80211_ATTR_4ADDR, wds);
6258         }
6259
6260         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6261         msg = NULL;
6262         if (ret) {
6263  nla_put_failure:
6264                 nlmsg_free(msg);
6265                 wpa_printf(MSG_ERROR, "Failed to create interface %s: %d (%s)",
6266                            ifname, ret, strerror(-ret));
6267                 return ret;
6268         }
6269
6270         ifidx = if_nametoindex(ifname);
6271         wpa_printf(MSG_DEBUG, "nl80211: New interface %s created: ifindex=%d",
6272                    ifname, ifidx);
6273
6274         if (ifidx <= 0)
6275                 return -1;
6276
6277         /* start listening for EAPOL on this interface */
6278         add_ifidx(drv, ifidx);
6279
6280         if (addr && iftype != NL80211_IFTYPE_MONITOR &&
6281             linux_set_ifhwaddr(drv->global->ioctl_sock, ifname, addr)) {
6282                 nl80211_remove_iface(drv, ifidx);
6283                 return -1;
6284         }
6285
6286         return ifidx;
6287 }
6288
6289
6290 static int nl80211_create_iface(struct wpa_driver_nl80211_data *drv,
6291                                 const char *ifname, enum nl80211_iftype iftype,
6292                                 const u8 *addr, int wds)
6293 {
6294         int ret;
6295
6296         ret = nl80211_create_iface_once(drv, ifname, iftype, addr, wds);
6297
6298         /* if error occurred and interface exists already */
6299         if (ret == -ENFILE && if_nametoindex(ifname)) {
6300                 wpa_printf(MSG_INFO, "Try to remove and re-create %s", ifname);
6301
6302                 /* Try to remove the interface that was already there. */
6303                 nl80211_remove_iface(drv, if_nametoindex(ifname));
6304
6305                 /* Try to create the interface again */
6306                 ret = nl80211_create_iface_once(drv, ifname, iftype, addr,
6307                                                 wds);
6308         }
6309
6310         if (ret >= 0 && is_p2p_interface(iftype))
6311                 nl80211_disable_11b_rates(drv, ret, 1);
6312
6313         return ret;
6314 }
6315
6316
6317 static void handle_tx_callback(void *ctx, u8 *buf, size_t len, int ok)
6318 {
6319         struct ieee80211_hdr *hdr;
6320         u16 fc;
6321         union wpa_event_data event;
6322
6323         hdr = (struct ieee80211_hdr *) buf;
6324         fc = le_to_host16(hdr->frame_control);
6325
6326         os_memset(&event, 0, sizeof(event));
6327         event.tx_status.type = WLAN_FC_GET_TYPE(fc);
6328         event.tx_status.stype = WLAN_FC_GET_STYPE(fc);
6329         event.tx_status.dst = hdr->addr1;
6330         event.tx_status.data = buf;
6331         event.tx_status.data_len = len;
6332         event.tx_status.ack = ok;
6333         wpa_supplicant_event(ctx, EVENT_TX_STATUS, &event);
6334 }
6335
6336
6337 static void from_unknown_sta(struct wpa_driver_nl80211_data *drv,
6338                              u8 *buf, size_t len)
6339 {
6340         struct ieee80211_hdr *hdr = (void *)buf;
6341         u16 fc;
6342         union wpa_event_data event;
6343
6344         if (len < sizeof(*hdr))
6345                 return;
6346
6347         fc = le_to_host16(hdr->frame_control);
6348
6349         os_memset(&event, 0, sizeof(event));
6350         event.rx_from_unknown.bssid = get_hdr_bssid(hdr, len);
6351         event.rx_from_unknown.addr = hdr->addr2;
6352         event.rx_from_unknown.wds = (fc & (WLAN_FC_FROMDS | WLAN_FC_TODS)) ==
6353                 (WLAN_FC_FROMDS | WLAN_FC_TODS);
6354         wpa_supplicant_event(drv->ctx, EVENT_RX_FROM_UNKNOWN, &event);
6355 }
6356
6357
6358 static void handle_frame(struct wpa_driver_nl80211_data *drv,
6359                          u8 *buf, size_t len, int datarate, int ssi_signal)
6360 {
6361         struct ieee80211_hdr *hdr;
6362         u16 fc;
6363         union wpa_event_data event;
6364
6365         hdr = (struct ieee80211_hdr *) buf;
6366         fc = le_to_host16(hdr->frame_control);
6367
6368         switch (WLAN_FC_GET_TYPE(fc)) {
6369         case WLAN_FC_TYPE_MGMT:
6370                 os_memset(&event, 0, sizeof(event));
6371                 event.rx_mgmt.frame = buf;
6372                 event.rx_mgmt.frame_len = len;
6373                 event.rx_mgmt.datarate = datarate;
6374                 event.rx_mgmt.ssi_signal = ssi_signal;
6375                 wpa_supplicant_event(drv->ctx, EVENT_RX_MGMT, &event);
6376                 break;
6377         case WLAN_FC_TYPE_CTRL:
6378                 /* can only get here with PS-Poll frames */
6379                 wpa_printf(MSG_DEBUG, "CTRL");
6380                 from_unknown_sta(drv, buf, len);
6381                 break;
6382         case WLAN_FC_TYPE_DATA:
6383                 from_unknown_sta(drv, buf, len);
6384                 break;
6385         }
6386 }
6387
6388
6389 static void handle_monitor_read(int sock, void *eloop_ctx, void *sock_ctx)
6390 {
6391         struct wpa_driver_nl80211_data *drv = eloop_ctx;
6392         int len;
6393         unsigned char buf[3000];
6394         struct ieee80211_radiotap_iterator iter;
6395         int ret;
6396         int datarate = 0, ssi_signal = 0;
6397         int injected = 0, failed = 0, rxflags = 0;
6398
6399         len = recv(sock, buf, sizeof(buf), 0);
6400         if (len < 0) {
6401                 perror("recv");
6402                 return;
6403         }
6404
6405         if (ieee80211_radiotap_iterator_init(&iter, (void*)buf, len)) {
6406                 printf("received invalid radiotap frame\n");
6407                 return;
6408         }
6409
6410         while (1) {
6411                 ret = ieee80211_radiotap_iterator_next(&iter);
6412                 if (ret == -ENOENT)
6413                         break;
6414                 if (ret) {
6415                         printf("received invalid radiotap frame (%d)\n", ret);
6416                         return;
6417                 }
6418                 switch (iter.this_arg_index) {
6419                 case IEEE80211_RADIOTAP_FLAGS:
6420                         if (*iter.this_arg & IEEE80211_RADIOTAP_F_FCS)
6421                                 len -= 4;
6422                         break;
6423                 case IEEE80211_RADIOTAP_RX_FLAGS:
6424                         rxflags = 1;
6425                         break;
6426                 case IEEE80211_RADIOTAP_TX_FLAGS:
6427                         injected = 1;
6428                         failed = le_to_host16((*(uint16_t *) iter.this_arg)) &
6429                                         IEEE80211_RADIOTAP_F_TX_FAIL;
6430                         break;
6431                 case IEEE80211_RADIOTAP_DATA_RETRIES:
6432                         break;
6433                 case IEEE80211_RADIOTAP_CHANNEL:
6434                         /* TODO: convert from freq/flags to channel number */
6435                         break;
6436                 case IEEE80211_RADIOTAP_RATE:
6437                         datarate = *iter.this_arg * 5;
6438                         break;
6439                 case IEEE80211_RADIOTAP_DBM_ANTSIGNAL:
6440                         ssi_signal = (s8) *iter.this_arg;
6441                         break;
6442                 }
6443         }
6444
6445         if (rxflags && injected)
6446                 return;
6447
6448         if (!injected)
6449                 handle_frame(drv, buf + iter.max_length,
6450                              len - iter.max_length, datarate, ssi_signal);
6451         else
6452                 handle_tx_callback(drv->ctx, buf + iter.max_length,
6453                                    len - iter.max_length, !failed);
6454 }
6455
6456
6457 /*
6458  * we post-process the filter code later and rewrite
6459  * this to the offset to the last instruction
6460  */
6461 #define PASS    0xFF
6462 #define FAIL    0xFE
6463
6464 static struct sock_filter msock_filter_insns[] = {
6465         /*
6466          * do a little-endian load of the radiotap length field
6467          */
6468         /* load lower byte into A */
6469         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 2),
6470         /* put it into X (== index register) */
6471         BPF_STMT(BPF_MISC| BPF_TAX, 0),
6472         /* load upper byte into A */
6473         BPF_STMT(BPF_LD  | BPF_B | BPF_ABS, 3),
6474         /* left-shift it by 8 */
6475         BPF_STMT(BPF_ALU | BPF_LSH | BPF_K, 8),
6476         /* or with X */
6477         BPF_STMT(BPF_ALU | BPF_OR | BPF_X, 0),
6478         /* put result into X */
6479         BPF_STMT(BPF_MISC| BPF_TAX, 0),
6480
6481         /*
6482          * Allow management frames through, this also gives us those
6483          * management frames that we sent ourselves with status
6484          */
6485         /* load the lower byte of the IEEE 802.11 frame control field */
6486         BPF_STMT(BPF_LD  | BPF_B | BPF_IND, 0),
6487         /* mask off frame type and version */
6488         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0xF),
6489         /* accept frame if it's both 0, fall through otherwise */
6490         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0, PASS, 0),
6491
6492         /*
6493          * TODO: add a bit to radiotap RX flags that indicates
6494          * that the sending station is not associated, then
6495          * add a filter here that filters on our DA and that flag
6496          * to allow us to deauth frames to that bad station.
6497          *
6498          * For now allow all To DS data frames through.
6499          */
6500         /* load the IEEE 802.11 frame control field */
6501         BPF_STMT(BPF_LD  | BPF_H | BPF_IND, 0),
6502         /* mask off frame type, version and DS status */
6503         BPF_STMT(BPF_ALU | BPF_AND | BPF_K, 0x0F03),
6504         /* accept frame if version 0, type 2 and To DS, fall through otherwise
6505          */
6506         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0801, PASS, 0),
6507
6508 #if 0
6509         /*
6510          * drop non-data frames
6511          */
6512         /* load the lower byte of the frame control field */
6513         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
6514         /* mask off QoS bit */
6515         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x0c),
6516         /* drop non-data frames */
6517         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 8, 0, FAIL),
6518 #endif
6519         /* load the upper byte of the frame control field */
6520         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 1),
6521         /* mask off toDS/fromDS */
6522         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x03),
6523         /* accept WDS frames */
6524         BPF_JUMP(BPF_JMP  | BPF_JEQ | BPF_K, 3, PASS, 0),
6525
6526         /*
6527          * add header length to index
6528          */
6529         /* load the lower byte of the frame control field */
6530         BPF_STMT(BPF_LD   | BPF_B | BPF_IND, 0),
6531         /* mask off QoS bit */
6532         BPF_STMT(BPF_ALU  | BPF_AND | BPF_K, 0x80),
6533         /* right shift it by 6 to give 0 or 2 */
6534         BPF_STMT(BPF_ALU  | BPF_RSH | BPF_K, 6),
6535         /* add data frame header length */
6536         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_K, 24),
6537         /* add index, was start of 802.11 header */
6538         BPF_STMT(BPF_ALU  | BPF_ADD | BPF_X, 0),
6539         /* move to index, now start of LL header */
6540         BPF_STMT(BPF_MISC | BPF_TAX, 0),
6541
6542         /*
6543          * Accept empty data frames, we use those for
6544          * polling activity.
6545          */
6546         BPF_STMT(BPF_LD  | BPF_W | BPF_LEN, 0),
6547         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_X, 0, PASS, 0),
6548
6549         /*
6550          * Accept EAPOL frames
6551          */
6552         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 0),
6553         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0xAAAA0300, 0, FAIL),
6554         BPF_STMT(BPF_LD  | BPF_W | BPF_IND, 4),
6555         BPF_JUMP(BPF_JMP | BPF_JEQ | BPF_K, 0x0000888E, PASS, FAIL),
6556
6557         /* keep these last two statements or change the code below */
6558         /* return 0 == "DROP" */
6559         BPF_STMT(BPF_RET | BPF_K, 0),
6560         /* return ~0 == "keep all" */
6561         BPF_STMT(BPF_RET | BPF_K, ~0),
6562 };
6563
6564 static struct sock_fprog msock_filter = {
6565         .len = sizeof(msock_filter_insns)/sizeof(msock_filter_insns[0]),
6566         .filter = msock_filter_insns,
6567 };
6568
6569
6570 static int add_monitor_filter(int s)
6571 {
6572         int idx;
6573
6574         /* rewrite all PASS/FAIL jump offsets */
6575         for (idx = 0; idx < msock_filter.len; idx++) {
6576                 struct sock_filter *insn = &msock_filter_insns[idx];
6577
6578                 if (BPF_CLASS(insn->code) == BPF_JMP) {
6579                         if (insn->code == (BPF_JMP|BPF_JA)) {
6580                                 if (insn->k == PASS)
6581                                         insn->k = msock_filter.len - idx - 2;
6582                                 else if (insn->k == FAIL)
6583                                         insn->k = msock_filter.len - idx - 3;
6584                         }
6585
6586                         if (insn->jt == PASS)
6587                                 insn->jt = msock_filter.len - idx - 2;
6588                         else if (insn->jt == FAIL)
6589                                 insn->jt = msock_filter.len - idx - 3;
6590
6591                         if (insn->jf == PASS)
6592                                 insn->jf = msock_filter.len - idx - 2;
6593                         else if (insn->jf == FAIL)
6594                                 insn->jf = msock_filter.len - idx - 3;
6595                 }
6596         }
6597
6598         if (setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER,
6599                        &msock_filter, sizeof(msock_filter))) {
6600                 perror("SO_ATTACH_FILTER");
6601                 return -1;
6602         }
6603
6604         return 0;
6605 }
6606
6607
6608 static void nl80211_remove_monitor_interface(
6609         struct wpa_driver_nl80211_data *drv)
6610 {
6611         drv->monitor_refcount--;
6612         if (drv->monitor_refcount > 0)
6613                 return;
6614
6615         if (drv->monitor_ifidx >= 0) {
6616                 nl80211_remove_iface(drv, drv->monitor_ifidx);
6617                 drv->monitor_ifidx = -1;
6618         }
6619         if (drv->monitor_sock >= 0) {
6620                 eloop_unregister_read_sock(drv->monitor_sock);
6621                 close(drv->monitor_sock);
6622                 drv->monitor_sock = -1;
6623         }
6624 }
6625
6626
6627 static int
6628 nl80211_create_monitor_interface(struct wpa_driver_nl80211_data *drv)
6629 {
6630         char buf[IFNAMSIZ];
6631         struct sockaddr_ll ll;
6632         int optval;
6633         socklen_t optlen;
6634
6635         if (drv->monitor_ifidx >= 0) {
6636                 drv->monitor_refcount++;
6637                 return 0;
6638         }
6639
6640         if (os_strncmp(drv->first_bss.ifname, "p2p-", 4) == 0) {
6641                 /*
6642                  * P2P interface name is of the format p2p-%s-%d. For monitor
6643                  * interface name corresponding to P2P GO, replace "p2p-" with
6644                  * "mon-" to retain the same interface name length and to
6645                  * indicate that it is a monitor interface.
6646                  */
6647                 snprintf(buf, IFNAMSIZ, "mon-%s", drv->first_bss.ifname + 4);
6648         } else {
6649                 /* Non-P2P interface with AP functionality. */
6650                 snprintf(buf, IFNAMSIZ, "mon.%s", drv->first_bss.ifname);
6651         }
6652
6653         buf[IFNAMSIZ - 1] = '\0';
6654
6655         drv->monitor_ifidx =
6656                 nl80211_create_iface(drv, buf, NL80211_IFTYPE_MONITOR, NULL,
6657                                      0);
6658
6659         if (drv->monitor_ifidx == -EOPNOTSUPP) {
6660                 /*
6661                  * This is backward compatibility for a few versions of
6662                  * the kernel only that didn't advertise the right
6663                  * attributes for the only driver that then supported
6664                  * AP mode w/o monitor -- ath6kl.
6665                  */
6666                 wpa_printf(MSG_DEBUG, "nl80211: Driver does not support "
6667                            "monitor interface type - try to run without it");
6668                 drv->device_ap_sme = 1;
6669         }
6670
6671         if (drv->monitor_ifidx < 0)
6672                 return -1;
6673
6674         if (linux_set_iface_flags(drv->global->ioctl_sock, buf, 1))
6675                 goto error;
6676
6677         memset(&ll, 0, sizeof(ll));
6678         ll.sll_family = AF_PACKET;
6679         ll.sll_ifindex = drv->monitor_ifidx;
6680         drv->monitor_sock = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
6681         if (drv->monitor_sock < 0) {
6682                 perror("socket[PF_PACKET,SOCK_RAW]");
6683                 goto error;
6684         }
6685
6686         if (add_monitor_filter(drv->monitor_sock)) {
6687                 wpa_printf(MSG_INFO, "Failed to set socket filter for monitor "
6688                            "interface; do filtering in user space");
6689                 /* This works, but will cost in performance. */
6690         }
6691
6692         if (bind(drv->monitor_sock, (struct sockaddr *) &ll, sizeof(ll)) < 0) {
6693                 perror("monitor socket bind");
6694                 goto error;
6695         }
6696
6697         optlen = sizeof(optval);
6698         optval = 20;
6699         if (setsockopt
6700             (drv->monitor_sock, SOL_SOCKET, SO_PRIORITY, &optval, optlen)) {
6701                 perror("Failed to set socket priority");
6702                 goto error;
6703         }
6704
6705         if (eloop_register_read_sock(drv->monitor_sock, handle_monitor_read,
6706                                      drv, NULL)) {
6707                 printf("Could not register monitor read socket\n");
6708                 goto error;
6709         }
6710
6711         return 0;
6712  error:
6713         nl80211_remove_monitor_interface(drv);
6714         return -1;
6715 }
6716
6717
6718 static int nl80211_setup_ap(struct i802_bss *bss)
6719 {
6720         struct wpa_driver_nl80211_data *drv = bss->drv;
6721
6722         wpa_printf(MSG_DEBUG, "nl80211: Setup AP - device_ap_sme=%d "
6723                    "use_monitor=%d", drv->device_ap_sme, drv->use_monitor);
6724
6725         /*
6726          * Disable Probe Request reporting unless we need it in this way for
6727          * devices that include the AP SME, in the other case (unless using
6728          * monitor iface) we'll get it through the nl_mgmt socket instead.
6729          */
6730         if (!drv->device_ap_sme)
6731                 wpa_driver_nl80211_probe_req_report(bss, 0);
6732
6733         if (!drv->device_ap_sme && !drv->use_monitor)
6734                 if (nl80211_mgmt_subscribe_ap(bss))
6735                         return -1;
6736
6737         if (drv->device_ap_sme && !drv->use_monitor)
6738                 if (nl80211_mgmt_subscribe_ap_dev_sme(bss))
6739                         return -1;
6740
6741         if (!drv->device_ap_sme && drv->use_monitor &&
6742             nl80211_create_monitor_interface(drv) &&
6743             !drv->device_ap_sme)
6744                 return -1;
6745
6746         if (drv->device_ap_sme &&
6747             wpa_driver_nl80211_probe_req_report(bss, 1) < 0) {
6748                 wpa_printf(MSG_DEBUG, "nl80211: Failed to enable "
6749                            "Probe Request frame reporting in AP mode");
6750                 /* Try to survive without this */
6751         }
6752
6753         return 0;
6754 }
6755
6756
6757 static void nl80211_teardown_ap(struct i802_bss *bss)
6758 {
6759         struct wpa_driver_nl80211_data *drv = bss->drv;
6760
6761         if (drv->device_ap_sme) {
6762                 wpa_driver_nl80211_probe_req_report(bss, 0);
6763                 if (!drv->use_monitor)
6764                         nl80211_mgmt_unsubscribe(bss, "AP teardown (dev SME)");
6765         } else if (drv->use_monitor)
6766                 nl80211_remove_monitor_interface(drv);
6767         else
6768                 nl80211_mgmt_unsubscribe(bss, "AP teardown");
6769
6770         bss->beacon_set = 0;
6771 }
6772
6773
6774 static int nl80211_send_eapol_data(struct i802_bss *bss,
6775                                    const u8 *addr, const u8 *data,
6776                                    size_t data_len)
6777 {
6778         struct sockaddr_ll ll;
6779         int ret;
6780
6781         if (bss->drv->eapol_tx_sock < 0) {
6782                 wpa_printf(MSG_DEBUG, "nl80211: No socket to send EAPOL");
6783                 return -1;
6784         }
6785
6786         os_memset(&ll, 0, sizeof(ll));
6787         ll.sll_family = AF_PACKET;
6788         ll.sll_ifindex = bss->ifindex;
6789         ll.sll_protocol = htons(ETH_P_PAE);
6790         ll.sll_halen = ETH_ALEN;
6791         os_memcpy(ll.sll_addr, addr, ETH_ALEN);
6792         ret = sendto(bss->drv->eapol_tx_sock, data, data_len, 0,
6793                      (struct sockaddr *) &ll, sizeof(ll));
6794         if (ret < 0)
6795                 wpa_printf(MSG_ERROR, "nl80211: EAPOL TX: %s",
6796                            strerror(errno));
6797
6798         return ret;
6799 }
6800
6801
6802 static const u8 rfc1042_header[6] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
6803
6804 static int wpa_driver_nl80211_hapd_send_eapol(
6805         void *priv, const u8 *addr, const u8 *data,
6806         size_t data_len, int encrypt, const u8 *own_addr, u32 flags)
6807 {
6808         struct i802_bss *bss = priv;
6809         struct wpa_driver_nl80211_data *drv = bss->drv;
6810         struct ieee80211_hdr *hdr;
6811         size_t len;
6812         u8 *pos;
6813         int res;
6814         int qos = flags & WPA_STA_WMM;
6815
6816         if (drv->device_ap_sme || !drv->use_monitor)
6817                 return nl80211_send_eapol_data(bss, addr, data, data_len);
6818
6819         len = sizeof(*hdr) + (qos ? 2 : 0) + sizeof(rfc1042_header) + 2 +
6820                 data_len;
6821         hdr = os_zalloc(len);
6822         if (hdr == NULL) {
6823                 printf("malloc() failed for i802_send_data(len=%lu)\n",
6824                        (unsigned long) len);
6825                 return -1;
6826         }
6827
6828         hdr->frame_control =
6829                 IEEE80211_FC(WLAN_FC_TYPE_DATA, WLAN_FC_STYPE_DATA);
6830         hdr->frame_control |= host_to_le16(WLAN_FC_FROMDS);
6831         if (encrypt)
6832                 hdr->frame_control |= host_to_le16(WLAN_FC_ISWEP);
6833         if (qos) {
6834                 hdr->frame_control |=
6835                         host_to_le16(WLAN_FC_STYPE_QOS_DATA << 4);
6836         }
6837
6838         memcpy(hdr->IEEE80211_DA_FROMDS, addr, ETH_ALEN);
6839         memcpy(hdr->IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
6840         memcpy(hdr->IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
6841         pos = (u8 *) (hdr + 1);
6842
6843         if (qos) {
6844                 /* Set highest priority in QoS header */
6845                 pos[0] = 7;
6846                 pos[1] = 0;
6847                 pos += 2;
6848         }
6849
6850         memcpy(pos, rfc1042_header, sizeof(rfc1042_header));
6851         pos += sizeof(rfc1042_header);
6852         WPA_PUT_BE16(pos, ETH_P_PAE);
6853         pos += 2;
6854         memcpy(pos, data, data_len);
6855
6856         res = wpa_driver_nl80211_send_frame(bss, (u8 *) hdr, len, encrypt, 0,
6857                                             0, 0, 0, 0);
6858         if (res < 0) {
6859                 wpa_printf(MSG_ERROR, "i802_send_eapol - packet len: %lu - "
6860                            "failed: %d (%s)",
6861                            (unsigned long) len, errno, strerror(errno));
6862         }
6863         os_free(hdr);
6864
6865         return res;
6866 }
6867
6868
6869 static int wpa_driver_nl80211_sta_set_flags(void *priv, const u8 *addr,
6870                                             int total_flags,
6871                                             int flags_or, int flags_and)
6872 {
6873         struct i802_bss *bss = priv;
6874         struct wpa_driver_nl80211_data *drv = bss->drv;
6875         struct nl_msg *msg;
6876         struct nlattr *flags;
6877         struct nl80211_sta_flag_update upd;
6878
6879         msg = nlmsg_alloc();
6880         if (!msg)
6881                 return -ENOMEM;
6882
6883         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
6884
6885         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
6886                     if_nametoindex(bss->ifname));
6887         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
6888
6889         /*
6890          * Backwards compatibility version using NL80211_ATTR_STA_FLAGS. This
6891          * can be removed eventually.
6892          */
6893         flags = nla_nest_start(msg, NL80211_ATTR_STA_FLAGS);
6894         if (!flags)
6895                 goto nla_put_failure;
6896         if (total_flags & WPA_STA_AUTHORIZED)
6897                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_AUTHORIZED);
6898
6899         if (total_flags & WPA_STA_WMM)
6900                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_WME);
6901
6902         if (total_flags & WPA_STA_SHORT_PREAMBLE)
6903                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_SHORT_PREAMBLE);
6904
6905         if (total_flags & WPA_STA_MFP)
6906                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_MFP);
6907
6908         if (total_flags & WPA_STA_TDLS_PEER)
6909                 NLA_PUT_FLAG(msg, NL80211_STA_FLAG_TDLS_PEER);
6910
6911         nla_nest_end(msg, flags);
6912
6913         os_memset(&upd, 0, sizeof(upd));
6914         upd.mask = sta_flags_nl80211(flags_or | ~flags_and);
6915         upd.set = sta_flags_nl80211(flags_or);
6916         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
6917
6918         return send_and_recv_msgs(drv, msg, NULL, NULL);
6919  nla_put_failure:
6920         nlmsg_free(msg);
6921         return -ENOBUFS;
6922 }
6923
6924
6925 static int wpa_driver_nl80211_ap(struct wpa_driver_nl80211_data *drv,
6926                                  struct wpa_driver_associate_params *params)
6927 {
6928         enum nl80211_iftype nlmode, old_mode;
6929         struct hostapd_freq_params freq = {
6930                 .freq = params->freq,
6931         };
6932
6933         if (params->p2p) {
6934                 wpa_printf(MSG_DEBUG, "nl80211: Setup AP operations for P2P "
6935                            "group (GO)");
6936                 nlmode = NL80211_IFTYPE_P2P_GO;
6937         } else
6938                 nlmode = NL80211_IFTYPE_AP;
6939
6940         old_mode = drv->nlmode;
6941         if (wpa_driver_nl80211_set_mode(&drv->first_bss, nlmode)) {
6942                 nl80211_remove_monitor_interface(drv);
6943                 return -1;
6944         }
6945
6946         if (wpa_driver_nl80211_set_freq(&drv->first_bss, &freq)) {
6947                 if (old_mode != nlmode)
6948                         wpa_driver_nl80211_set_mode(&drv->first_bss, old_mode);
6949                 nl80211_remove_monitor_interface(drv);
6950                 return -1;
6951         }
6952
6953         return 0;
6954 }
6955
6956
6957 static int nl80211_leave_ibss(struct wpa_driver_nl80211_data *drv)
6958 {
6959         struct nl_msg *msg;
6960         int ret = -1;
6961
6962         msg = nlmsg_alloc();
6963         if (!msg)
6964                 return -1;
6965
6966         nl80211_cmd(drv, msg, 0, NL80211_CMD_LEAVE_IBSS);
6967         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
6968         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
6969         msg = NULL;
6970         if (ret) {
6971                 wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS failed: ret=%d "
6972                            "(%s)", ret, strerror(-ret));
6973                 goto nla_put_failure;
6974         }
6975
6976         ret = 0;
6977         wpa_printf(MSG_DEBUG, "nl80211: Leave IBSS request sent successfully");
6978
6979 nla_put_failure:
6980         nlmsg_free(msg);
6981         return ret;
6982 }
6983
6984
6985 static int wpa_driver_nl80211_ibss(struct wpa_driver_nl80211_data *drv,
6986                                    struct wpa_driver_associate_params *params)
6987 {
6988         struct nl_msg *msg;
6989         int ret = -1;
6990         int count = 0;
6991
6992         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS (ifindex=%d)", drv->ifindex);
6993
6994         if (wpa_driver_nl80211_set_mode(&drv->first_bss,
6995                                         NL80211_IFTYPE_ADHOC)) {
6996                 wpa_printf(MSG_INFO, "nl80211: Failed to set interface into "
6997                            "IBSS mode");
6998                 return -1;
6999         }
7000
7001 retry:
7002         msg = nlmsg_alloc();
7003         if (!msg)
7004                 return -1;
7005
7006         nl80211_cmd(drv, msg, 0, NL80211_CMD_JOIN_IBSS);
7007         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7008
7009         if (params->ssid == NULL || params->ssid_len > sizeof(drv->ssid))
7010                 goto nla_put_failure;
7011
7012         wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
7013                           params->ssid, params->ssid_len);
7014         NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
7015                 params->ssid);
7016         os_memcpy(drv->ssid, params->ssid, params->ssid_len);
7017         drv->ssid_len = params->ssid_len;
7018
7019         wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
7020         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
7021
7022         ret = nl80211_set_conn_keys(params, msg);
7023         if (ret)
7024                 goto nla_put_failure;
7025
7026         if (params->bssid && params->fixed_bssid) {
7027                 wpa_printf(MSG_DEBUG, "  * BSSID=" MACSTR,
7028                            MAC2STR(params->bssid));
7029                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
7030         }
7031
7032         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
7033             params->key_mgmt_suite == KEY_MGMT_PSK ||
7034             params->key_mgmt_suite == KEY_MGMT_802_1X_SHA256 ||
7035             params->key_mgmt_suite == KEY_MGMT_PSK_SHA256) {
7036                 wpa_printf(MSG_DEBUG, "  * control port");
7037                 NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
7038         }
7039
7040         if (params->wpa_ie) {
7041                 wpa_hexdump(MSG_DEBUG,
7042                             "  * Extra IEs for Beacon/Probe Response frames",
7043                             params->wpa_ie, params->wpa_ie_len);
7044                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
7045                         params->wpa_ie);
7046         }
7047
7048         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7049         msg = NULL;
7050         if (ret) {
7051                 wpa_printf(MSG_DEBUG, "nl80211: Join IBSS failed: ret=%d (%s)",
7052                            ret, strerror(-ret));
7053                 count++;
7054                 if (ret == -EALREADY && count == 1) {
7055                         wpa_printf(MSG_DEBUG, "nl80211: Retry IBSS join after "
7056                                    "forced leave");
7057                         nl80211_leave_ibss(drv);
7058                         nlmsg_free(msg);
7059                         goto retry;
7060                 }
7061
7062                 goto nla_put_failure;
7063         }
7064         ret = 0;
7065         wpa_printf(MSG_DEBUG, "nl80211: Join IBSS request sent successfully");
7066
7067 nla_put_failure:
7068         nlmsg_free(msg);
7069         return ret;
7070 }
7071
7072
7073 static int wpa_driver_nl80211_try_connect(
7074         struct wpa_driver_nl80211_data *drv,
7075         struct wpa_driver_associate_params *params)
7076 {
7077         struct nl_msg *msg;
7078         enum nl80211_auth_type type;
7079         int ret = 0;
7080         int algs;
7081
7082         msg = nlmsg_alloc();
7083         if (!msg)
7084                 return -1;
7085
7086         wpa_printf(MSG_DEBUG, "nl80211: Connect (ifindex=%d)", drv->ifindex);
7087         nl80211_cmd(drv, msg, 0, NL80211_CMD_CONNECT);
7088
7089         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7090         if (params->bssid) {
7091                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
7092                            MAC2STR(params->bssid));
7093                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
7094         }
7095         if (params->freq) {
7096                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
7097                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
7098         }
7099         if (params->bg_scan_period >= 0) {
7100                 wpa_printf(MSG_DEBUG, "  * bg scan period=%d",
7101                            params->bg_scan_period);
7102                 NLA_PUT_U16(msg, NL80211_ATTR_BG_SCAN_PERIOD,
7103                             params->bg_scan_period);
7104         }
7105         if (params->ssid) {
7106                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
7107                                   params->ssid, params->ssid_len);
7108                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
7109                         params->ssid);
7110                 if (params->ssid_len > sizeof(drv->ssid))
7111                         goto nla_put_failure;
7112                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
7113                 drv->ssid_len = params->ssid_len;
7114         }
7115         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
7116         if (params->wpa_ie)
7117                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
7118                         params->wpa_ie);
7119
7120         algs = 0;
7121         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
7122                 algs++;
7123         if (params->auth_alg & WPA_AUTH_ALG_SHARED)
7124                 algs++;
7125         if (params->auth_alg & WPA_AUTH_ALG_LEAP)
7126                 algs++;
7127         if (algs > 1) {
7128                 wpa_printf(MSG_DEBUG, "  * Leave out Auth Type for automatic "
7129                            "selection");
7130                 goto skip_auth_type;
7131         }
7132
7133         if (params->auth_alg & WPA_AUTH_ALG_OPEN)
7134                 type = NL80211_AUTHTYPE_OPEN_SYSTEM;
7135         else if (params->auth_alg & WPA_AUTH_ALG_SHARED)
7136                 type = NL80211_AUTHTYPE_SHARED_KEY;
7137         else if (params->auth_alg & WPA_AUTH_ALG_LEAP)
7138                 type = NL80211_AUTHTYPE_NETWORK_EAP;
7139         else if (params->auth_alg & WPA_AUTH_ALG_FT)
7140                 type = NL80211_AUTHTYPE_FT;
7141         else
7142                 goto nla_put_failure;
7143
7144         wpa_printf(MSG_DEBUG, "  * Auth Type %d", type);
7145         NLA_PUT_U32(msg, NL80211_ATTR_AUTH_TYPE, type);
7146
7147 skip_auth_type:
7148         if (params->wpa_proto) {
7149                 enum nl80211_wpa_versions ver = 0;
7150
7151                 if (params->wpa_proto & WPA_PROTO_WPA)
7152                         ver |= NL80211_WPA_VERSION_1;
7153                 if (params->wpa_proto & WPA_PROTO_RSN)
7154                         ver |= NL80211_WPA_VERSION_2;
7155
7156                 wpa_printf(MSG_DEBUG, "  * WPA Versions 0x%x", ver);
7157                 NLA_PUT_U32(msg, NL80211_ATTR_WPA_VERSIONS, ver);
7158         }
7159
7160         if (params->pairwise_suite != CIPHER_NONE) {
7161                 int cipher;
7162
7163                 switch (params->pairwise_suite) {
7164                 case CIPHER_SMS4:
7165                         cipher = WLAN_CIPHER_SUITE_SMS4;
7166                         break;
7167                 case CIPHER_WEP40:
7168                         cipher = WLAN_CIPHER_SUITE_WEP40;
7169                         break;
7170                 case CIPHER_WEP104:
7171                         cipher = WLAN_CIPHER_SUITE_WEP104;
7172                         break;
7173                 case CIPHER_CCMP:
7174                         cipher = WLAN_CIPHER_SUITE_CCMP;
7175                         break;
7176                 case CIPHER_GCMP:
7177                         cipher = WLAN_CIPHER_SUITE_GCMP;
7178                         break;
7179                 case CIPHER_TKIP:
7180                 default:
7181                         cipher = WLAN_CIPHER_SUITE_TKIP;
7182                         break;
7183                 }
7184                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
7185         }
7186
7187         if (params->group_suite != CIPHER_NONE) {
7188                 int cipher;
7189
7190                 switch (params->group_suite) {
7191                 case CIPHER_SMS4:
7192                         cipher = WLAN_CIPHER_SUITE_SMS4;
7193                         break;
7194                 case CIPHER_WEP40:
7195                         cipher = WLAN_CIPHER_SUITE_WEP40;
7196                         break;
7197                 case CIPHER_WEP104:
7198                         cipher = WLAN_CIPHER_SUITE_WEP104;
7199                         break;
7200                 case CIPHER_CCMP:
7201                         cipher = WLAN_CIPHER_SUITE_CCMP;
7202                         break;
7203                 case CIPHER_GCMP:
7204                         cipher = WLAN_CIPHER_SUITE_GCMP;
7205                         break;
7206                 case CIPHER_TKIP:
7207                 default:
7208                         cipher = WLAN_CIPHER_SUITE_TKIP;
7209                         break;
7210                 }
7211                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
7212         }
7213
7214         if (params->key_mgmt_suite == KEY_MGMT_802_1X ||
7215             params->key_mgmt_suite == KEY_MGMT_PSK ||
7216             params->key_mgmt_suite == KEY_MGMT_FT_802_1X ||
7217             params->key_mgmt_suite == KEY_MGMT_FT_PSK ||
7218             params->key_mgmt_suite == KEY_MGMT_CCKM) {
7219                 int mgmt = WLAN_AKM_SUITE_PSK;
7220
7221                 switch (params->key_mgmt_suite) {
7222                 case KEY_MGMT_CCKM:
7223                         mgmt = WLAN_AKM_SUITE_CCKM;
7224                         break;
7225                 case KEY_MGMT_802_1X:
7226                         mgmt = WLAN_AKM_SUITE_8021X;
7227                         break;
7228                 case KEY_MGMT_FT_802_1X:
7229                         mgmt = WLAN_AKM_SUITE_FT_8021X;
7230                         break;
7231                 case KEY_MGMT_FT_PSK:
7232                         mgmt = WLAN_AKM_SUITE_FT_PSK;
7233                         break;
7234                 case KEY_MGMT_PSK:
7235                 default:
7236                         mgmt = WLAN_AKM_SUITE_PSK;
7237                         break;
7238                 }
7239                 NLA_PUT_U32(msg, NL80211_ATTR_AKM_SUITES, mgmt);
7240         }
7241
7242 #ifdef CONFIG_IEEE80211W
7243         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
7244                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
7245 #endif /* CONFIG_IEEE80211W */
7246
7247         if (params->disable_ht)
7248                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
7249
7250         if (params->htcaps && params->htcaps_mask) {
7251                 int sz = sizeof(struct ieee80211_ht_capabilities);
7252                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
7253                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
7254                         params->htcaps_mask);
7255         }
7256
7257 #ifdef CONFIG_VHT_OVERRIDES
7258         if (params->disable_vht) {
7259                 wpa_printf(MSG_DEBUG, "  * VHT disabled");
7260                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_VHT);
7261         }
7262
7263         if (params->vhtcaps && params->vhtcaps_mask) {
7264                 int sz = sizeof(struct ieee80211_vht_capabilities);
7265                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY, sz, params->vhtcaps);
7266                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY_MASK, sz,
7267                         params->vhtcaps_mask);
7268         }
7269 #endif /* CONFIG_VHT_OVERRIDES */
7270
7271         ret = nl80211_set_conn_keys(params, msg);
7272         if (ret)
7273                 goto nla_put_failure;
7274
7275         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7276         msg = NULL;
7277         if (ret) {
7278                 wpa_printf(MSG_DEBUG, "nl80211: MLME connect failed: ret=%d "
7279                            "(%s)", ret, strerror(-ret));
7280                 goto nla_put_failure;
7281         }
7282         ret = 0;
7283         wpa_printf(MSG_DEBUG, "nl80211: Connect request send successfully");
7284
7285 nla_put_failure:
7286         nlmsg_free(msg);
7287         return ret;
7288
7289 }
7290
7291
7292 static int wpa_driver_nl80211_connect(
7293         struct wpa_driver_nl80211_data *drv,
7294         struct wpa_driver_associate_params *params)
7295 {
7296         int ret = wpa_driver_nl80211_try_connect(drv, params);
7297         if (ret == -EALREADY) {
7298                 /*
7299                  * cfg80211 does not currently accept new connections if
7300                  * we are already connected. As a workaround, force
7301                  * disconnection and try again.
7302                  */
7303                 wpa_printf(MSG_DEBUG, "nl80211: Explicitly "
7304                            "disconnecting before reassociation "
7305                            "attempt");
7306                 if (wpa_driver_nl80211_disconnect(
7307                             drv, WLAN_REASON_PREV_AUTH_NOT_VALID))
7308                         return -1;
7309                 /* Ignore the next local disconnect message. */
7310                 drv->ignore_next_local_disconnect = 1;
7311                 ret = wpa_driver_nl80211_try_connect(drv, params);
7312         }
7313         return ret;
7314 }
7315
7316
7317 static int wpa_driver_nl80211_associate(
7318         void *priv, struct wpa_driver_associate_params *params)
7319 {
7320         struct i802_bss *bss = priv;
7321         struct wpa_driver_nl80211_data *drv = bss->drv;
7322         int ret = -1;
7323         struct nl_msg *msg;
7324
7325         if (params->mode == IEEE80211_MODE_AP)
7326                 return wpa_driver_nl80211_ap(drv, params);
7327
7328         if (params->mode == IEEE80211_MODE_IBSS)
7329                 return wpa_driver_nl80211_ibss(drv, params);
7330
7331         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_SME)) {
7332                 enum nl80211_iftype nlmode = params->p2p ?
7333                         NL80211_IFTYPE_P2P_CLIENT : NL80211_IFTYPE_STATION;
7334
7335                 if (wpa_driver_nl80211_set_mode(priv, nlmode) < 0)
7336                         return -1;
7337                 return wpa_driver_nl80211_connect(drv, params);
7338         }
7339
7340         drv->associated = 0;
7341
7342         msg = nlmsg_alloc();
7343         if (!msg)
7344                 return -1;
7345
7346         wpa_printf(MSG_DEBUG, "nl80211: Associate (ifindex=%d)",
7347                    drv->ifindex);
7348         nl80211_cmd(drv, msg, 0, NL80211_CMD_ASSOCIATE);
7349
7350         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7351         if (params->bssid) {
7352                 wpa_printf(MSG_DEBUG, "  * bssid=" MACSTR,
7353                            MAC2STR(params->bssid));
7354                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, params->bssid);
7355         }
7356         if (params->freq) {
7357                 wpa_printf(MSG_DEBUG, "  * freq=%d", params->freq);
7358                 NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, params->freq);
7359                 drv->assoc_freq = params->freq;
7360         } else
7361                 drv->assoc_freq = 0;
7362         if (params->bg_scan_period >= 0) {
7363                 wpa_printf(MSG_DEBUG, "  * bg scan period=%d",
7364                            params->bg_scan_period);
7365                 NLA_PUT_U16(msg, NL80211_ATTR_BG_SCAN_PERIOD,
7366                             params->bg_scan_period);
7367         }
7368         if (params->ssid) {
7369                 wpa_hexdump_ascii(MSG_DEBUG, "  * SSID",
7370                                   params->ssid, params->ssid_len);
7371                 NLA_PUT(msg, NL80211_ATTR_SSID, params->ssid_len,
7372                         params->ssid);
7373                 if (params->ssid_len > sizeof(drv->ssid))
7374                         goto nla_put_failure;
7375                 os_memcpy(drv->ssid, params->ssid, params->ssid_len);
7376                 drv->ssid_len = params->ssid_len;
7377         }
7378         wpa_hexdump(MSG_DEBUG, "  * IEs", params->wpa_ie, params->wpa_ie_len);
7379         if (params->wpa_ie)
7380                 NLA_PUT(msg, NL80211_ATTR_IE, params->wpa_ie_len,
7381                         params->wpa_ie);
7382
7383         if (params->pairwise_suite != CIPHER_NONE) {
7384                 int cipher;
7385
7386                 switch (params->pairwise_suite) {
7387                 case CIPHER_WEP40:
7388                         cipher = WLAN_CIPHER_SUITE_WEP40;
7389                         break;
7390                 case CIPHER_WEP104:
7391                         cipher = WLAN_CIPHER_SUITE_WEP104;
7392                         break;
7393                 case CIPHER_CCMP:
7394                         cipher = WLAN_CIPHER_SUITE_CCMP;
7395                         break;
7396                 case CIPHER_GCMP:
7397                         cipher = WLAN_CIPHER_SUITE_GCMP;
7398                         break;
7399                 case CIPHER_TKIP:
7400                 default:
7401                         cipher = WLAN_CIPHER_SUITE_TKIP;
7402                         break;
7403                 }
7404                 wpa_printf(MSG_DEBUG, "  * pairwise=0x%x", cipher);
7405                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITES_PAIRWISE, cipher);
7406         }
7407
7408         if (params->group_suite != CIPHER_NONE) {
7409                 int cipher;
7410
7411                 switch (params->group_suite) {
7412                 case CIPHER_WEP40:
7413                         cipher = WLAN_CIPHER_SUITE_WEP40;
7414                         break;
7415                 case CIPHER_WEP104:
7416                         cipher = WLAN_CIPHER_SUITE_WEP104;
7417                         break;
7418                 case CIPHER_CCMP:
7419                         cipher = WLAN_CIPHER_SUITE_CCMP;
7420                         break;
7421                 case CIPHER_GCMP:
7422                         cipher = WLAN_CIPHER_SUITE_GCMP;
7423                         break;
7424                 case CIPHER_TKIP:
7425                 default:
7426                         cipher = WLAN_CIPHER_SUITE_TKIP;
7427                         break;
7428                 }
7429                 wpa_printf(MSG_DEBUG, "  * group=0x%x", cipher);
7430                 NLA_PUT_U32(msg, NL80211_ATTR_CIPHER_SUITE_GROUP, cipher);
7431         }
7432
7433 #ifdef CONFIG_IEEE80211W
7434         if (params->mgmt_frame_protection == MGMT_FRAME_PROTECTION_REQUIRED)
7435                 NLA_PUT_U32(msg, NL80211_ATTR_USE_MFP, NL80211_MFP_REQUIRED);
7436 #endif /* CONFIG_IEEE80211W */
7437
7438         NLA_PUT_FLAG(msg, NL80211_ATTR_CONTROL_PORT);
7439
7440         if (params->prev_bssid) {
7441                 wpa_printf(MSG_DEBUG, "  * prev_bssid=" MACSTR,
7442                            MAC2STR(params->prev_bssid));
7443                 NLA_PUT(msg, NL80211_ATTR_PREV_BSSID, ETH_ALEN,
7444                         params->prev_bssid);
7445         }
7446
7447         if (params->disable_ht)
7448                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_HT);
7449
7450         if (params->htcaps && params->htcaps_mask) {
7451                 int sz = sizeof(struct ieee80211_ht_capabilities);
7452                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY, sz, params->htcaps);
7453                 NLA_PUT(msg, NL80211_ATTR_HT_CAPABILITY_MASK, sz,
7454                         params->htcaps_mask);
7455         }
7456
7457 #ifdef CONFIG_VHT_OVERRIDES
7458         if (params->disable_vht) {
7459                 wpa_printf(MSG_DEBUG, "  * VHT disabled");
7460                 NLA_PUT_FLAG(msg, NL80211_ATTR_DISABLE_VHT);
7461         }
7462
7463         if (params->vhtcaps && params->vhtcaps_mask) {
7464                 int sz = sizeof(struct ieee80211_vht_capabilities);
7465                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY, sz, params->vhtcaps);
7466                 NLA_PUT(msg, NL80211_ATTR_VHT_CAPABILITY_MASK, sz,
7467                         params->vhtcaps_mask);
7468         }
7469 #endif /* CONFIG_VHT_OVERRIDES */
7470
7471         if (params->p2p)
7472                 wpa_printf(MSG_DEBUG, "  * P2P group");
7473
7474         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7475         msg = NULL;
7476         if (ret) {
7477                 wpa_dbg(drv->ctx, MSG_DEBUG,
7478                         "nl80211: MLME command failed (assoc): ret=%d (%s)",
7479                         ret, strerror(-ret));
7480                 nl80211_dump_scan(drv);
7481                 goto nla_put_failure;
7482         }
7483         ret = 0;
7484         wpa_printf(MSG_DEBUG, "nl80211: Association request send "
7485                    "successfully");
7486
7487 nla_put_failure:
7488         nlmsg_free(msg);
7489         return ret;
7490 }
7491
7492
7493 static int nl80211_set_mode(struct wpa_driver_nl80211_data *drv,
7494                             int ifindex, enum nl80211_iftype mode)
7495 {
7496         struct nl_msg *msg;
7497         int ret = -ENOBUFS;
7498
7499         wpa_printf(MSG_DEBUG, "nl80211: Set mode ifindex %d iftype %d (%s)",
7500                    ifindex, mode, nl80211_iftype_str(mode));
7501
7502         msg = nlmsg_alloc();
7503         if (!msg)
7504                 return -ENOMEM;
7505
7506         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_INTERFACE);
7507         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
7508         NLA_PUT_U32(msg, NL80211_ATTR_IFTYPE, mode);
7509
7510         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7511         msg = NULL;
7512         if (!ret)
7513                 return 0;
7514 nla_put_failure:
7515         nlmsg_free(msg);
7516         wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface %d to mode %d:"
7517                    " %d (%s)", ifindex, mode, ret, strerror(-ret));
7518         return ret;
7519 }
7520
7521
7522 static int wpa_driver_nl80211_set_mode(struct i802_bss *bss,
7523                                        enum nl80211_iftype nlmode)
7524 {
7525         struct wpa_driver_nl80211_data *drv = bss->drv;
7526         int ret = -1;
7527         int i;
7528         int was_ap = is_ap_interface(drv->nlmode);
7529         int res;
7530
7531         res = nl80211_set_mode(drv, drv->ifindex, nlmode);
7532         if (res == 0) {
7533                 drv->nlmode = nlmode;
7534                 ret = 0;
7535                 goto done;
7536         }
7537
7538         if (res == -ENODEV)
7539                 return -1;
7540
7541         if (nlmode == drv->nlmode) {
7542                 wpa_printf(MSG_DEBUG, "nl80211: Interface already in "
7543                            "requested mode - ignore error");
7544                 ret = 0;
7545                 goto done; /* Already in the requested mode */
7546         }
7547
7548         /* mac80211 doesn't allow mode changes while the device is up, so
7549          * take the device down, try to set the mode again, and bring the
7550          * device back up.
7551          */
7552         wpa_printf(MSG_DEBUG, "nl80211: Try mode change after setting "
7553                    "interface down");
7554         for (i = 0; i < 10; i++) {
7555                 res = linux_set_iface_flags(drv->global->ioctl_sock,
7556                                             bss->ifname, 0);
7557                 if (res == -EACCES || res == -ENODEV)
7558                         break;
7559                 if (res == 0) {
7560                         /* Try to set the mode again while the interface is
7561                          * down */
7562                         ret = nl80211_set_mode(drv, drv->ifindex, nlmode);
7563                         if (ret == -EACCES)
7564                                 break;
7565                         res = linux_set_iface_flags(drv->global->ioctl_sock,
7566                                                     bss->ifname, 1);
7567                         if (res && !ret)
7568                                 ret = -1;
7569                         else if (ret != -EBUSY)
7570                                 break;
7571                 } else
7572                         wpa_printf(MSG_DEBUG, "nl80211: Failed to set "
7573                                    "interface down");
7574                 os_sleep(0, 100000);
7575         }
7576
7577         if (!ret) {
7578                 wpa_printf(MSG_DEBUG, "nl80211: Mode change succeeded while "
7579                            "interface is down");
7580                 drv->nlmode = nlmode;
7581                 drv->ignore_if_down_event = 1;
7582         }
7583
7584 done:
7585         if (ret) {
7586                 wpa_printf(MSG_DEBUG, "nl80211: Interface mode change to %d "
7587                            "from %d failed", nlmode, drv->nlmode);
7588                 return ret;
7589         }
7590
7591         if (is_p2p_interface(nlmode))
7592                 nl80211_disable_11b_rates(drv, drv->ifindex, 1);
7593         else if (drv->disabled_11b_rates)
7594                 nl80211_disable_11b_rates(drv, drv->ifindex, 0);
7595
7596         if (is_ap_interface(nlmode)) {
7597                 nl80211_mgmt_unsubscribe(bss, "start AP");
7598                 /* Setup additional AP mode functionality if needed */
7599                 if (nl80211_setup_ap(bss))
7600                         return -1;
7601         } else if (was_ap) {
7602                 /* Remove additional AP mode functionality */
7603                 nl80211_teardown_ap(bss);
7604         } else {
7605                 nl80211_mgmt_unsubscribe(bss, "mode change");
7606         }
7607
7608         if (!bss->in_deinit && !is_ap_interface(nlmode) &&
7609             nl80211_mgmt_subscribe_non_ap(bss) < 0)
7610                 wpa_printf(MSG_DEBUG, "nl80211: Failed to register Action "
7611                            "frame processing - ignore for now");
7612
7613         return 0;
7614 }
7615
7616
7617 static int wpa_driver_nl80211_get_capa(void *priv,
7618                                        struct wpa_driver_capa *capa)
7619 {
7620         struct i802_bss *bss = priv;
7621         struct wpa_driver_nl80211_data *drv = bss->drv;
7622         if (!drv->has_capability)
7623                 return -1;
7624         os_memcpy(capa, &drv->capa, sizeof(*capa));
7625         if (drv->extended_capa && drv->extended_capa_mask) {
7626                 capa->extended_capa = drv->extended_capa;
7627                 capa->extended_capa_mask = drv->extended_capa_mask;
7628                 capa->extended_capa_len = drv->extended_capa_len;
7629         }
7630         return 0;
7631 }
7632
7633
7634 static int wpa_driver_nl80211_set_operstate(void *priv, int state)
7635 {
7636         struct i802_bss *bss = priv;
7637         struct wpa_driver_nl80211_data *drv = bss->drv;
7638
7639         wpa_printf(MSG_DEBUG, "%s: operstate %d->%d (%s)",
7640                    __func__, drv->operstate, state, state ? "UP" : "DORMANT");
7641         drv->operstate = state;
7642         return netlink_send_oper_ifla(drv->global->netlink, drv->ifindex, -1,
7643                                       state ? IF_OPER_UP : IF_OPER_DORMANT);
7644 }
7645
7646
7647 static int wpa_driver_nl80211_set_supp_port(void *priv, int authorized)
7648 {
7649         struct i802_bss *bss = priv;
7650         struct wpa_driver_nl80211_data *drv = bss->drv;
7651         struct nl_msg *msg;
7652         struct nl80211_sta_flag_update upd;
7653
7654         msg = nlmsg_alloc();
7655         if (!msg)
7656                 return -ENOMEM;
7657
7658         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
7659
7660         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7661                     if_nametoindex(bss->ifname));
7662         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, drv->bssid);
7663
7664         os_memset(&upd, 0, sizeof(upd));
7665         upd.mask = BIT(NL80211_STA_FLAG_AUTHORIZED);
7666         if (authorized)
7667                 upd.set = BIT(NL80211_STA_FLAG_AUTHORIZED);
7668         NLA_PUT(msg, NL80211_ATTR_STA_FLAGS2, sizeof(upd), &upd);
7669
7670         return send_and_recv_msgs(drv, msg, NULL, NULL);
7671  nla_put_failure:
7672         nlmsg_free(msg);
7673         return -ENOBUFS;
7674 }
7675
7676
7677 /* Set kernel driver on given frequency (MHz) */
7678 static int i802_set_freq(void *priv, struct hostapd_freq_params *freq)
7679 {
7680         struct i802_bss *bss = priv;
7681         return wpa_driver_nl80211_set_freq(bss, freq);
7682 }
7683
7684
7685 #if defined(HOSTAPD) || defined(CONFIG_AP)
7686
7687 static inline int min_int(int a, int b)
7688 {
7689         if (a < b)
7690                 return a;
7691         return b;
7692 }
7693
7694
7695 static int get_key_handler(struct nl_msg *msg, void *arg)
7696 {
7697         struct nlattr *tb[NL80211_ATTR_MAX + 1];
7698         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7699
7700         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7701                   genlmsg_attrlen(gnlh, 0), NULL);
7702
7703         /*
7704          * TODO: validate the key index and mac address!
7705          * Otherwise, there's a race condition as soon as
7706          * the kernel starts sending key notifications.
7707          */
7708
7709         if (tb[NL80211_ATTR_KEY_SEQ])
7710                 memcpy(arg, nla_data(tb[NL80211_ATTR_KEY_SEQ]),
7711                        min_int(nla_len(tb[NL80211_ATTR_KEY_SEQ]), 6));
7712         return NL_SKIP;
7713 }
7714
7715
7716 static int i802_get_seqnum(const char *iface, void *priv, const u8 *addr,
7717                            int idx, u8 *seq)
7718 {
7719         struct i802_bss *bss = priv;
7720         struct wpa_driver_nl80211_data *drv = bss->drv;
7721         struct nl_msg *msg;
7722
7723         msg = nlmsg_alloc();
7724         if (!msg)
7725                 return -ENOMEM;
7726
7727         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_KEY);
7728
7729         if (addr)
7730                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7731         NLA_PUT_U8(msg, NL80211_ATTR_KEY_IDX, idx);
7732         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(iface));
7733
7734         memset(seq, 0, 6);
7735
7736         return send_and_recv_msgs(drv, msg, get_key_handler, seq);
7737  nla_put_failure:
7738         nlmsg_free(msg);
7739         return -ENOBUFS;
7740 }
7741
7742
7743 static int i802_set_rts(void *priv, int rts)
7744 {
7745         struct i802_bss *bss = priv;
7746         struct wpa_driver_nl80211_data *drv = bss->drv;
7747         struct nl_msg *msg;
7748         int ret = -ENOBUFS;
7749         u32 val;
7750
7751         msg = nlmsg_alloc();
7752         if (!msg)
7753                 return -ENOMEM;
7754
7755         if (rts >= 2347)
7756                 val = (u32) -1;
7757         else
7758                 val = rts;
7759
7760         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7761         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7762         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD, val);
7763
7764         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7765         msg = NULL;
7766         if (!ret)
7767                 return 0;
7768 nla_put_failure:
7769         nlmsg_free(msg);
7770         wpa_printf(MSG_DEBUG, "nl80211: Failed to set RTS threshold %d: "
7771                    "%d (%s)", rts, ret, strerror(-ret));
7772         return ret;
7773 }
7774
7775
7776 static int i802_set_frag(void *priv, int frag)
7777 {
7778         struct i802_bss *bss = priv;
7779         struct wpa_driver_nl80211_data *drv = bss->drv;
7780         struct nl_msg *msg;
7781         int ret = -ENOBUFS;
7782         u32 val;
7783
7784         msg = nlmsg_alloc();
7785         if (!msg)
7786                 return -ENOMEM;
7787
7788         if (frag >= 2346)
7789                 val = (u32) -1;
7790         else
7791                 val = frag;
7792
7793         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7794         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
7795         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD, val);
7796
7797         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
7798         msg = NULL;
7799         if (!ret)
7800                 return 0;
7801 nla_put_failure:
7802         nlmsg_free(msg);
7803         wpa_printf(MSG_DEBUG, "nl80211: Failed to set fragmentation threshold "
7804                    "%d: %d (%s)", frag, ret, strerror(-ret));
7805         return ret;
7806 }
7807
7808
7809 static int i802_flush(void *priv)
7810 {
7811         struct i802_bss *bss = priv;
7812         struct wpa_driver_nl80211_data *drv = bss->drv;
7813         struct nl_msg *msg;
7814         int res;
7815
7816         msg = nlmsg_alloc();
7817         if (!msg)
7818                 return -1;
7819
7820         nl80211_cmd(drv, msg, 0, NL80211_CMD_DEL_STATION);
7821
7822         /*
7823          * XXX: FIX! this needs to flush all VLANs too
7824          */
7825         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7826                     if_nametoindex(bss->ifname));
7827
7828         res = send_and_recv_msgs(drv, msg, NULL, NULL);
7829         if (res) {
7830                 wpa_printf(MSG_DEBUG, "nl80211: Station flush failed: ret=%d "
7831                            "(%s)", res, strerror(-res));
7832         }
7833         return res;
7834  nla_put_failure:
7835         nlmsg_free(msg);
7836         return -ENOBUFS;
7837 }
7838
7839 #endif /* HOSTAPD || CONFIG_AP */
7840
7841
7842 static int get_sta_handler(struct nl_msg *msg, void *arg)
7843 {
7844         struct nlattr *tb[NL80211_ATTR_MAX + 1];
7845         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
7846         struct hostap_sta_driver_data *data = arg;
7847         struct nlattr *stats[NL80211_STA_INFO_MAX + 1];
7848         static struct nla_policy stats_policy[NL80211_STA_INFO_MAX + 1] = {
7849                 [NL80211_STA_INFO_INACTIVE_TIME] = { .type = NLA_U32 },
7850                 [NL80211_STA_INFO_RX_BYTES] = { .type = NLA_U32 },
7851                 [NL80211_STA_INFO_TX_BYTES] = { .type = NLA_U32 },
7852                 [NL80211_STA_INFO_RX_PACKETS] = { .type = NLA_U32 },
7853                 [NL80211_STA_INFO_TX_PACKETS] = { .type = NLA_U32 },
7854                 [NL80211_STA_INFO_TX_FAILED] = { .type = NLA_U32 },
7855         };
7856
7857         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
7858                   genlmsg_attrlen(gnlh, 0), NULL);
7859
7860         /*
7861          * TODO: validate the interface and mac address!
7862          * Otherwise, there's a race condition as soon as
7863          * the kernel starts sending station notifications.
7864          */
7865
7866         if (!tb[NL80211_ATTR_STA_INFO]) {
7867                 wpa_printf(MSG_DEBUG, "sta stats missing!");
7868                 return NL_SKIP;
7869         }
7870         if (nla_parse_nested(stats, NL80211_STA_INFO_MAX,
7871                              tb[NL80211_ATTR_STA_INFO],
7872                              stats_policy)) {
7873                 wpa_printf(MSG_DEBUG, "failed to parse nested attributes!");
7874                 return NL_SKIP;
7875         }
7876
7877         if (stats[NL80211_STA_INFO_INACTIVE_TIME])
7878                 data->inactive_msec =
7879                         nla_get_u32(stats[NL80211_STA_INFO_INACTIVE_TIME]);
7880         if (stats[NL80211_STA_INFO_RX_BYTES])
7881                 data->rx_bytes = nla_get_u32(stats[NL80211_STA_INFO_RX_BYTES]);
7882         if (stats[NL80211_STA_INFO_TX_BYTES])
7883                 data->tx_bytes = nla_get_u32(stats[NL80211_STA_INFO_TX_BYTES]);
7884         if (stats[NL80211_STA_INFO_RX_PACKETS])
7885                 data->rx_packets =
7886                         nla_get_u32(stats[NL80211_STA_INFO_RX_PACKETS]);
7887         if (stats[NL80211_STA_INFO_TX_PACKETS])
7888                 data->tx_packets =
7889                         nla_get_u32(stats[NL80211_STA_INFO_TX_PACKETS]);
7890         if (stats[NL80211_STA_INFO_TX_FAILED])
7891                 data->tx_retry_failed =
7892                         nla_get_u32(stats[NL80211_STA_INFO_TX_FAILED]);
7893
7894         return NL_SKIP;
7895 }
7896
7897 static int i802_read_sta_data(struct i802_bss *bss,
7898                               struct hostap_sta_driver_data *data,
7899                               const u8 *addr)
7900 {
7901         struct wpa_driver_nl80211_data *drv = bss->drv;
7902         struct nl_msg *msg;
7903
7904         os_memset(data, 0, sizeof(*data));
7905         msg = nlmsg_alloc();
7906         if (!msg)
7907                 return -ENOMEM;
7908
7909         nl80211_cmd(drv, msg, 0, NL80211_CMD_GET_STATION);
7910
7911         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7912         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7913
7914         return send_and_recv_msgs(drv, msg, get_sta_handler, data);
7915  nla_put_failure:
7916         nlmsg_free(msg);
7917         return -ENOBUFS;
7918 }
7919
7920
7921 #if defined(HOSTAPD) || defined(CONFIG_AP)
7922
7923 static int i802_set_tx_queue_params(void *priv, int queue, int aifs,
7924                                     int cw_min, int cw_max, int burst_time)
7925 {
7926         struct i802_bss *bss = priv;
7927         struct wpa_driver_nl80211_data *drv = bss->drv;
7928         struct nl_msg *msg;
7929         struct nlattr *txq, *params;
7930
7931         msg = nlmsg_alloc();
7932         if (!msg)
7933                 return -1;
7934
7935         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_WIPHY);
7936
7937         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
7938
7939         txq = nla_nest_start(msg, NL80211_ATTR_WIPHY_TXQ_PARAMS);
7940         if (!txq)
7941                 goto nla_put_failure;
7942
7943         /* We are only sending parameters for a single TXQ at a time */
7944         params = nla_nest_start(msg, 1);
7945         if (!params)
7946                 goto nla_put_failure;
7947
7948         switch (queue) {
7949         case 0:
7950                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VO);
7951                 break;
7952         case 1:
7953                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_VI);
7954                 break;
7955         case 2:
7956                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BE);
7957                 break;
7958         case 3:
7959                 NLA_PUT_U8(msg, NL80211_TXQ_ATTR_QUEUE, NL80211_TXQ_Q_BK);
7960                 break;
7961         }
7962         /* Burst time is configured in units of 0.1 msec and TXOP parameter in
7963          * 32 usec, so need to convert the value here. */
7964         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_TXOP, (burst_time * 100 + 16) / 32);
7965         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMIN, cw_min);
7966         NLA_PUT_U16(msg, NL80211_TXQ_ATTR_CWMAX, cw_max);
7967         NLA_PUT_U8(msg, NL80211_TXQ_ATTR_AIFS, aifs);
7968
7969         nla_nest_end(msg, params);
7970
7971         nla_nest_end(msg, txq);
7972
7973         if (send_and_recv_msgs(drv, msg, NULL, NULL) == 0)
7974                 return 0;
7975         msg = NULL;
7976  nla_put_failure:
7977         nlmsg_free(msg);
7978         return -1;
7979 }
7980
7981
7982 static int i802_set_sta_vlan(struct i802_bss *bss, const u8 *addr,
7983                              const char *ifname, int vlan_id)
7984 {
7985         struct wpa_driver_nl80211_data *drv = bss->drv;
7986         struct nl_msg *msg;
7987         int ret = -ENOBUFS;
7988
7989         msg = nlmsg_alloc();
7990         if (!msg)
7991                 return -ENOMEM;
7992
7993         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_STATION);
7994
7995         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX,
7996                     if_nametoindex(bss->ifname));
7997         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
7998         NLA_PUT_U32(msg, NL80211_ATTR_STA_VLAN,
7999                     if_nametoindex(ifname));
8000
8001         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8002         msg = NULL;
8003         if (ret < 0) {
8004                 wpa_printf(MSG_ERROR, "nl80211: NL80211_ATTR_STA_VLAN (addr="
8005                            MACSTR " ifname=%s vlan_id=%d) failed: %d (%s)",
8006                            MAC2STR(addr), ifname, vlan_id, ret,
8007                            strerror(-ret));
8008         }
8009  nla_put_failure:
8010         nlmsg_free(msg);
8011         return ret;
8012 }
8013
8014
8015 static int i802_get_inact_sec(void *priv, const u8 *addr)
8016 {
8017         struct hostap_sta_driver_data data;
8018         int ret;
8019
8020         data.inactive_msec = (unsigned long) -1;
8021         ret = i802_read_sta_data(priv, &data, addr);
8022         if (ret || data.inactive_msec == (unsigned long) -1)
8023                 return -1;
8024         return data.inactive_msec / 1000;
8025 }
8026
8027
8028 static int i802_sta_clear_stats(void *priv, const u8 *addr)
8029 {
8030 #if 0
8031         /* TODO */
8032 #endif
8033         return 0;
8034 }
8035
8036
8037 static int i802_sta_deauth(void *priv, const u8 *own_addr, const u8 *addr,
8038                            int reason)
8039 {
8040         struct i802_bss *bss = priv;
8041         struct wpa_driver_nl80211_data *drv = bss->drv;
8042         struct ieee80211_mgmt mgmt;
8043
8044         if (drv->device_ap_sme)
8045                 return wpa_driver_nl80211_sta_remove(bss, addr);
8046
8047         memset(&mgmt, 0, sizeof(mgmt));
8048         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
8049                                           WLAN_FC_STYPE_DEAUTH);
8050         memcpy(mgmt.da, addr, ETH_ALEN);
8051         memcpy(mgmt.sa, own_addr, ETH_ALEN);
8052         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
8053         mgmt.u.deauth.reason_code = host_to_le16(reason);
8054         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
8055                                             IEEE80211_HDRLEN +
8056                                             sizeof(mgmt.u.deauth), 0, 0, 0, 0,
8057                                             0);
8058 }
8059
8060
8061 static int i802_sta_disassoc(void *priv, const u8 *own_addr, const u8 *addr,
8062                              int reason)
8063 {
8064         struct i802_bss *bss = priv;
8065         struct wpa_driver_nl80211_data *drv = bss->drv;
8066         struct ieee80211_mgmt mgmt;
8067
8068         if (drv->device_ap_sme)
8069                 return wpa_driver_nl80211_sta_remove(bss, addr);
8070
8071         memset(&mgmt, 0, sizeof(mgmt));
8072         mgmt.frame_control = IEEE80211_FC(WLAN_FC_TYPE_MGMT,
8073                                           WLAN_FC_STYPE_DISASSOC);
8074         memcpy(mgmt.da, addr, ETH_ALEN);
8075         memcpy(mgmt.sa, own_addr, ETH_ALEN);
8076         memcpy(mgmt.bssid, own_addr, ETH_ALEN);
8077         mgmt.u.disassoc.reason_code = host_to_le16(reason);
8078         return wpa_driver_nl80211_send_mlme(bss, (u8 *) &mgmt,
8079                                             IEEE80211_HDRLEN +
8080                                             sizeof(mgmt.u.disassoc), 0, 0, 0, 0,
8081                                             0);
8082 }
8083
8084 #endif /* HOSTAPD || CONFIG_AP */
8085
8086 #ifdef HOSTAPD
8087
8088 static void add_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
8089 {
8090         int i;
8091         int *old;
8092
8093         wpa_printf(MSG_DEBUG, "nl80211: Add own interface ifindex %d",
8094                    ifidx);
8095         for (i = 0; i < drv->num_if_indices; i++) {
8096                 if (drv->if_indices[i] == 0) {
8097                         drv->if_indices[i] = ifidx;
8098                         return;
8099                 }
8100         }
8101
8102         if (drv->if_indices != drv->default_if_indices)
8103                 old = drv->if_indices;
8104         else
8105                 old = NULL;
8106
8107         drv->if_indices = os_realloc_array(old, drv->num_if_indices + 1,
8108                                            sizeof(int));
8109         if (!drv->if_indices) {
8110                 if (!old)
8111                         drv->if_indices = drv->default_if_indices;
8112                 else
8113                         drv->if_indices = old;
8114                 wpa_printf(MSG_ERROR, "Failed to reallocate memory for "
8115                            "interfaces");
8116                 wpa_printf(MSG_ERROR, "Ignoring EAPOL on interface %d", ifidx);
8117                 return;
8118         } else if (!old)
8119                 os_memcpy(drv->if_indices, drv->default_if_indices,
8120                           sizeof(drv->default_if_indices));
8121         drv->if_indices[drv->num_if_indices] = ifidx;
8122         drv->num_if_indices++;
8123 }
8124
8125
8126 static void del_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
8127 {
8128         int i;
8129
8130         for (i = 0; i < drv->num_if_indices; i++) {
8131                 if (drv->if_indices[i] == ifidx) {
8132                         drv->if_indices[i] = 0;
8133                         break;
8134                 }
8135         }
8136 }
8137
8138
8139 static int have_ifidx(struct wpa_driver_nl80211_data *drv, int ifidx)
8140 {
8141         int i;
8142
8143         for (i = 0; i < drv->num_if_indices; i++)
8144                 if (drv->if_indices[i] == ifidx)
8145                         return 1;
8146
8147         return 0;
8148 }
8149
8150
8151 static int i802_set_wds_sta(void *priv, const u8 *addr, int aid, int val,
8152                             const char *bridge_ifname)
8153 {
8154         struct i802_bss *bss = priv;
8155         struct wpa_driver_nl80211_data *drv = bss->drv;
8156         char name[IFNAMSIZ + 1];
8157
8158         os_snprintf(name, sizeof(name), "%s.sta%d", bss->ifname, aid);
8159         wpa_printf(MSG_DEBUG, "nl80211: Set WDS STA addr=" MACSTR
8160                    " aid=%d val=%d name=%s", MAC2STR(addr), aid, val, name);
8161         if (val) {
8162                 if (!if_nametoindex(name)) {
8163                         if (nl80211_create_iface(drv, name,
8164                                                  NL80211_IFTYPE_AP_VLAN,
8165                                                  bss->addr, 1) < 0)
8166                                 return -1;
8167                         if (bridge_ifname &&
8168                             linux_br_add_if(drv->global->ioctl_sock,
8169                                             bridge_ifname, name) < 0)
8170                                 return -1;
8171                 }
8172                 if (linux_set_iface_flags(drv->global->ioctl_sock, name, 1)) {
8173                         wpa_printf(MSG_ERROR, "nl80211: Failed to set WDS STA "
8174                                    "interface %s up", name);
8175                 }
8176                 return i802_set_sta_vlan(priv, addr, name, 0);
8177         } else {
8178                 if (bridge_ifname)
8179                         linux_br_del_if(drv->global->ioctl_sock, bridge_ifname,
8180                                         name);
8181
8182                 i802_set_sta_vlan(priv, addr, bss->ifname, 0);
8183                 return wpa_driver_nl80211_if_remove(priv, WPA_IF_AP_VLAN,
8184                                                     name);
8185         }
8186 }
8187
8188
8189 static void handle_eapol(int sock, void *eloop_ctx, void *sock_ctx)
8190 {
8191         struct wpa_driver_nl80211_data *drv = eloop_ctx;
8192         struct sockaddr_ll lladdr;
8193         unsigned char buf[3000];
8194         int len;
8195         socklen_t fromlen = sizeof(lladdr);
8196
8197         len = recvfrom(sock, buf, sizeof(buf), 0,
8198                        (struct sockaddr *)&lladdr, &fromlen);
8199         if (len < 0) {
8200                 perror("recv");
8201                 return;
8202         }
8203
8204         if (have_ifidx(drv, lladdr.sll_ifindex))
8205                 drv_event_eapol_rx(drv->ctx, lladdr.sll_addr, buf, len);
8206 }
8207
8208
8209 static int i802_check_bridge(struct wpa_driver_nl80211_data *drv,
8210                              struct i802_bss *bss,
8211                              const char *brname, const char *ifname)
8212 {
8213         int ifindex;
8214         char in_br[IFNAMSIZ];
8215
8216         os_strlcpy(bss->brname, brname, IFNAMSIZ);
8217         ifindex = if_nametoindex(brname);
8218         if (ifindex == 0) {
8219                 /*
8220                  * Bridge was configured, but the bridge device does
8221                  * not exist. Try to add it now.
8222                  */
8223                 if (linux_br_add(drv->global->ioctl_sock, brname) < 0) {
8224                         wpa_printf(MSG_ERROR, "nl80211: Failed to add the "
8225                                    "bridge interface %s: %s",
8226                                    brname, strerror(errno));
8227                         return -1;
8228                 }
8229                 bss->added_bridge = 1;
8230                 add_ifidx(drv, if_nametoindex(brname));
8231         }
8232
8233         if (linux_br_get(in_br, ifname) == 0) {
8234                 if (os_strcmp(in_br, brname) == 0)
8235                         return 0; /* already in the bridge */
8236
8237                 wpa_printf(MSG_DEBUG, "nl80211: Removing interface %s from "
8238                            "bridge %s", ifname, in_br);
8239                 if (linux_br_del_if(drv->global->ioctl_sock, in_br, ifname) <
8240                     0) {
8241                         wpa_printf(MSG_ERROR, "nl80211: Failed to "
8242                                    "remove interface %s from bridge "
8243                                    "%s: %s",
8244                                    ifname, brname, strerror(errno));
8245                         return -1;
8246                 }
8247         }
8248
8249         wpa_printf(MSG_DEBUG, "nl80211: Adding interface %s into bridge %s",
8250                    ifname, brname);
8251         if (linux_br_add_if(drv->global->ioctl_sock, brname, ifname) < 0) {
8252                 wpa_printf(MSG_ERROR, "nl80211: Failed to add interface %s "
8253                            "into bridge %s: %s",
8254                            ifname, brname, strerror(errno));
8255                 return -1;
8256         }
8257         bss->added_if_into_bridge = 1;
8258
8259         return 0;
8260 }
8261
8262
8263 static void *i802_init(struct hostapd_data *hapd,
8264                        struct wpa_init_params *params)
8265 {
8266         struct wpa_driver_nl80211_data *drv;
8267         struct i802_bss *bss;
8268         size_t i;
8269         char brname[IFNAMSIZ];
8270         int ifindex, br_ifindex;
8271         int br_added = 0;
8272
8273         bss = wpa_driver_nl80211_init(hapd, params->ifname,
8274                                       params->global_priv);
8275         if (bss == NULL)
8276                 return NULL;
8277
8278         drv = bss->drv;
8279         drv->nlmode = NL80211_IFTYPE_AP;
8280         drv->eapol_sock = -1;
8281
8282         if (linux_br_get(brname, params->ifname) == 0) {
8283                 wpa_printf(MSG_DEBUG, "nl80211: Interface %s is in bridge %s",
8284                            params->ifname, brname);
8285                 br_ifindex = if_nametoindex(brname);
8286         } else {
8287                 brname[0] = '\0';
8288                 br_ifindex = 0;
8289         }
8290
8291         drv->num_if_indices = sizeof(drv->default_if_indices) / sizeof(int);
8292         drv->if_indices = drv->default_if_indices;
8293         for (i = 0; i < params->num_bridge; i++) {
8294                 if (params->bridge[i]) {
8295                         ifindex = if_nametoindex(params->bridge[i]);
8296                         if (ifindex)
8297                                 add_ifidx(drv, ifindex);
8298                         if (ifindex == br_ifindex)
8299                                 br_added = 1;
8300                 }
8301         }
8302         if (!br_added && br_ifindex &&
8303             (params->num_bridge == 0 || !params->bridge[0]))
8304                 add_ifidx(drv, br_ifindex);
8305
8306         /* start listening for EAPOL on the default AP interface */
8307         add_ifidx(drv, drv->ifindex);
8308
8309         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 0))
8310                 goto failed;
8311
8312         if (params->bssid) {
8313                 if (linux_set_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
8314                                        params->bssid))
8315                         goto failed;
8316         }
8317
8318         if (wpa_driver_nl80211_set_mode(bss, drv->nlmode)) {
8319                 wpa_printf(MSG_ERROR, "nl80211: Failed to set interface %s "
8320                            "into AP mode", bss->ifname);
8321                 goto failed;
8322         }
8323
8324         if (params->num_bridge && params->bridge[0] &&
8325             i802_check_bridge(drv, bss, params->bridge[0], params->ifname) < 0)
8326                 goto failed;
8327
8328         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1))
8329                 goto failed;
8330
8331         drv->eapol_sock = socket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_PAE));
8332         if (drv->eapol_sock < 0) {
8333                 perror("socket(PF_PACKET, SOCK_DGRAM, ETH_P_PAE)");
8334                 goto failed;
8335         }
8336
8337         if (eloop_register_read_sock(drv->eapol_sock, handle_eapol, drv, NULL))
8338         {
8339                 printf("Could not register read socket for eapol\n");
8340                 goto failed;
8341         }
8342
8343         if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
8344                                params->own_addr))
8345                 goto failed;
8346
8347         memcpy(bss->addr, params->own_addr, ETH_ALEN);
8348
8349         return bss;
8350
8351 failed:
8352         wpa_driver_nl80211_deinit(bss);
8353         return NULL;
8354 }
8355
8356
8357 static void i802_deinit(void *priv)
8358 {
8359         struct i802_bss *bss = priv;
8360         wpa_driver_nl80211_deinit(bss);
8361 }
8362
8363 #endif /* HOSTAPD */
8364
8365
8366 static enum nl80211_iftype wpa_driver_nl80211_if_type(
8367         enum wpa_driver_if_type type)
8368 {
8369         switch (type) {
8370         case WPA_IF_STATION:
8371                 return NL80211_IFTYPE_STATION;
8372         case WPA_IF_P2P_CLIENT:
8373         case WPA_IF_P2P_GROUP:
8374                 return NL80211_IFTYPE_P2P_CLIENT;
8375         case WPA_IF_AP_VLAN:
8376                 return NL80211_IFTYPE_AP_VLAN;
8377         case WPA_IF_AP_BSS:
8378                 return NL80211_IFTYPE_AP;
8379         case WPA_IF_P2P_GO:
8380                 return NL80211_IFTYPE_P2P_GO;
8381         }
8382         return -1;
8383 }
8384
8385
8386 #ifdef CONFIG_P2P
8387
8388 static int nl80211_addr_in_use(struct nl80211_global *global, const u8 *addr)
8389 {
8390         struct wpa_driver_nl80211_data *drv;
8391         dl_list_for_each(drv, &global->interfaces,
8392                          struct wpa_driver_nl80211_data, list) {
8393                 if (os_memcmp(addr, drv->first_bss.addr, ETH_ALEN) == 0)
8394                         return 1;
8395         }
8396         return 0;
8397 }
8398
8399
8400 static int nl80211_p2p_interface_addr(struct wpa_driver_nl80211_data *drv,
8401                                       u8 *new_addr)
8402 {
8403         unsigned int idx;
8404
8405         if (!drv->global)
8406                 return -1;
8407
8408         os_memcpy(new_addr, drv->first_bss.addr, ETH_ALEN);
8409         for (idx = 0; idx < 64; idx++) {
8410                 new_addr[0] = drv->first_bss.addr[0] | 0x02;
8411                 new_addr[0] ^= idx << 2;
8412                 if (!nl80211_addr_in_use(drv->global, new_addr))
8413                         break;
8414         }
8415         if (idx == 64)
8416                 return -1;
8417
8418         wpa_printf(MSG_DEBUG, "nl80211: Assigned new P2P Interface Address "
8419                    MACSTR, MAC2STR(new_addr));
8420
8421         return 0;
8422 }
8423
8424 #endif /* CONFIG_P2P */
8425
8426
8427 static int wpa_driver_nl80211_if_add(void *priv, enum wpa_driver_if_type type,
8428                                      const char *ifname, const u8 *addr,
8429                                      void *bss_ctx, void **drv_priv,
8430                                      char *force_ifname, u8 *if_addr,
8431                                      const char *bridge)
8432 {
8433         struct i802_bss *bss = priv;
8434         struct wpa_driver_nl80211_data *drv = bss->drv;
8435         int ifidx;
8436 #ifdef HOSTAPD
8437         struct i802_bss *new_bss = NULL;
8438
8439         if (type == WPA_IF_AP_BSS) {
8440                 new_bss = os_zalloc(sizeof(*new_bss));
8441                 if (new_bss == NULL)
8442                         return -1;
8443         }
8444 #endif /* HOSTAPD */
8445
8446         if (addr)
8447                 os_memcpy(if_addr, addr, ETH_ALEN);
8448         ifidx = nl80211_create_iface(drv, ifname,
8449                                      wpa_driver_nl80211_if_type(type), addr,
8450                                      0);
8451         if (ifidx < 0) {
8452 #ifdef HOSTAPD
8453                 os_free(new_bss);
8454 #endif /* HOSTAPD */
8455                 return -1;
8456         }
8457
8458         if (!addr &&
8459             linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
8460                                if_addr) < 0) {
8461                 nl80211_remove_iface(drv, ifidx);
8462                 return -1;
8463         }
8464
8465 #ifdef CONFIG_P2P
8466         if (!addr &&
8467             (type == WPA_IF_P2P_CLIENT || type == WPA_IF_P2P_GROUP ||
8468              type == WPA_IF_P2P_GO)) {
8469                 /* Enforce unique P2P Interface Address */
8470                 u8 new_addr[ETH_ALEN], own_addr[ETH_ALEN];
8471
8472                 if (linux_get_ifhwaddr(drv->global->ioctl_sock, bss->ifname,
8473                                        own_addr) < 0 ||
8474                     linux_get_ifhwaddr(drv->global->ioctl_sock, ifname,
8475                                        new_addr) < 0) {
8476                         nl80211_remove_iface(drv, ifidx);
8477                         return -1;
8478                 }
8479                 if (os_memcmp(own_addr, new_addr, ETH_ALEN) == 0) {
8480                         wpa_printf(MSG_DEBUG, "nl80211: Allocate new address "
8481                                    "for P2P group interface");
8482                         if (nl80211_p2p_interface_addr(drv, new_addr) < 0) {
8483                                 nl80211_remove_iface(drv, ifidx);
8484                                 return -1;
8485                         }
8486                         if (linux_set_ifhwaddr(drv->global->ioctl_sock, ifname,
8487                                                new_addr) < 0) {
8488                                 nl80211_remove_iface(drv, ifidx);
8489                                 return -1;
8490                         }
8491                 }
8492                 os_memcpy(if_addr, new_addr, ETH_ALEN);
8493         }
8494 #endif /* CONFIG_P2P */
8495
8496 #ifdef HOSTAPD
8497         if (bridge &&
8498             i802_check_bridge(drv, new_bss, bridge, ifname) < 0) {
8499                 wpa_printf(MSG_ERROR, "nl80211: Failed to add the new "
8500                            "interface %s to a bridge %s", ifname, bridge);
8501                 nl80211_remove_iface(drv, ifidx);
8502                 os_free(new_bss);
8503                 return -1;
8504         }
8505
8506         if (type == WPA_IF_AP_BSS) {
8507                 if (linux_set_iface_flags(drv->global->ioctl_sock, ifname, 1))
8508                 {
8509                         nl80211_remove_iface(drv, ifidx);
8510                         os_free(new_bss);
8511                         return -1;
8512                 }
8513                 os_strlcpy(new_bss->ifname, ifname, IFNAMSIZ);
8514                 os_memcpy(new_bss->addr, if_addr, ETH_ALEN);
8515                 new_bss->ifindex = ifidx;
8516                 new_bss->drv = drv;
8517                 new_bss->next = drv->first_bss.next;
8518                 new_bss->freq = drv->first_bss.freq;
8519                 new_bss->ctx = bss_ctx;
8520                 drv->first_bss.next = new_bss;
8521                 if (drv_priv)
8522                         *drv_priv = new_bss;
8523                 nl80211_init_bss(new_bss);
8524
8525                 /* Subscribe management frames for this WPA_IF_AP_BSS */
8526                 if (nl80211_setup_ap(new_bss))
8527                         return -1;
8528         }
8529 #endif /* HOSTAPD */
8530
8531         if (drv->global)
8532                 drv->global->if_add_ifindex = ifidx;
8533
8534         return 0;
8535 }
8536
8537
8538 static int wpa_driver_nl80211_if_remove(struct i802_bss *bss,
8539                                         enum wpa_driver_if_type type,
8540                                         const char *ifname)
8541 {
8542         struct wpa_driver_nl80211_data *drv = bss->drv;
8543         int ifindex = if_nametoindex(ifname);
8544
8545         wpa_printf(MSG_DEBUG, "nl80211: %s(type=%d ifname=%s) ifindex=%d",
8546                    __func__, type, ifname, ifindex);
8547         if (ifindex <= 0)
8548                 return -1;
8549
8550         nl80211_remove_iface(drv, ifindex);
8551
8552 #ifdef HOSTAPD
8553         if (type != WPA_IF_AP_BSS)
8554                 return 0;
8555
8556         if (bss->added_if_into_bridge) {
8557                 if (linux_br_del_if(drv->global->ioctl_sock, bss->brname,
8558                                     bss->ifname) < 0)
8559                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
8560                                    "interface %s from bridge %s: %s",
8561                                    bss->ifname, bss->brname, strerror(errno));
8562         }
8563         if (bss->added_bridge) {
8564                 if (linux_br_del(drv->global->ioctl_sock, bss->brname) < 0)
8565                         wpa_printf(MSG_INFO, "nl80211: Failed to remove "
8566                                    "bridge %s: %s",
8567                                    bss->brname, strerror(errno));
8568         }
8569
8570         if (bss != &drv->first_bss) {
8571                 struct i802_bss *tbss;
8572
8573                 for (tbss = &drv->first_bss; tbss; tbss = tbss->next) {
8574                         if (tbss->next == bss) {
8575                                 tbss->next = bss->next;
8576                                 /* Unsubscribe management frames */
8577                                 nl80211_teardown_ap(bss);
8578                                 nl80211_destroy_bss(bss);
8579                                 os_free(bss);
8580                                 bss = NULL;
8581                                 break;
8582                         }
8583                 }
8584                 if (bss)
8585                         wpa_printf(MSG_INFO, "nl80211: %s - could not find "
8586                                    "BSS %p in the list", __func__, bss);
8587         }
8588 #endif /* HOSTAPD */
8589
8590         return 0;
8591 }
8592
8593
8594 static int cookie_handler(struct nl_msg *msg, void *arg)
8595 {
8596         struct nlattr *tb[NL80211_ATTR_MAX + 1];
8597         struct genlmsghdr *gnlh = nlmsg_data(nlmsg_hdr(msg));
8598         u64 *cookie = arg;
8599         nla_parse(tb, NL80211_ATTR_MAX, genlmsg_attrdata(gnlh, 0),
8600                   genlmsg_attrlen(gnlh, 0), NULL);
8601         if (tb[NL80211_ATTR_COOKIE])
8602                 *cookie = nla_get_u64(tb[NL80211_ATTR_COOKIE]);
8603         return NL_SKIP;
8604 }
8605
8606
8607 static int nl80211_send_frame_cmd(struct i802_bss *bss,
8608                                   unsigned int freq, unsigned int wait,
8609                                   const u8 *buf, size_t buf_len,
8610                                   u64 *cookie_out, int no_cck, int no_ack,
8611                                   int offchanok)
8612 {
8613         struct wpa_driver_nl80211_data *drv = bss->drv;
8614         struct nl_msg *msg;
8615         u64 cookie;
8616         int ret = -1;
8617
8618         msg = nlmsg_alloc();
8619         if (!msg)
8620                 return -1;
8621
8622         wpa_printf(MSG_DEBUG, "nl80211: CMD_FRAME freq=%u wait=%u no_cck=%d "
8623                    "no_ack=%d offchanok=%d",
8624                    freq, wait, no_cck, no_ack, offchanok);
8625         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME);
8626
8627         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
8628         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
8629         if (wait)
8630                 NLA_PUT_U32(msg, NL80211_ATTR_DURATION, wait);
8631         if (offchanok && (drv->capa.flags & WPA_DRIVER_FLAGS_OFFCHANNEL_TX))
8632                 NLA_PUT_FLAG(msg, NL80211_ATTR_OFFCHANNEL_TX_OK);
8633         if (no_cck)
8634                 NLA_PUT_FLAG(msg, NL80211_ATTR_TX_NO_CCK_RATE);
8635         if (no_ack)
8636                 NLA_PUT_FLAG(msg, NL80211_ATTR_DONT_WAIT_FOR_ACK);
8637
8638         NLA_PUT(msg, NL80211_ATTR_FRAME, buf_len, buf);
8639
8640         cookie = 0;
8641         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
8642         msg = NULL;
8643         if (ret) {
8644                 wpa_printf(MSG_DEBUG, "nl80211: Frame command failed: ret=%d "
8645                            "(%s) (freq=%u wait=%u)", ret, strerror(-ret),
8646                            freq, wait);
8647                 goto nla_put_failure;
8648         }
8649         wpa_printf(MSG_DEBUG, "nl80211: Frame TX command accepted%s; "
8650                    "cookie 0x%llx", no_ack ? " (no ACK)" : "",
8651                    (long long unsigned int) cookie);
8652
8653         if (cookie_out)
8654                 *cookie_out = no_ack ? (u64) -1 : cookie;
8655
8656 nla_put_failure:
8657         nlmsg_free(msg);
8658         return ret;
8659 }
8660
8661
8662 static int wpa_driver_nl80211_send_action(struct i802_bss *bss,
8663                                           unsigned int freq,
8664                                           unsigned int wait_time,
8665                                           const u8 *dst, const u8 *src,
8666                                           const u8 *bssid,
8667                                           const u8 *data, size_t data_len,
8668                                           int no_cck)
8669 {
8670         struct wpa_driver_nl80211_data *drv = bss->drv;
8671         int ret = -1;
8672         u8 *buf;
8673         struct ieee80211_hdr *hdr;
8674
8675         wpa_printf(MSG_DEBUG, "nl80211: Send Action frame (ifindex=%d, "
8676                    "freq=%u MHz wait=%d ms no_cck=%d)",
8677                    drv->ifindex, freq, wait_time, no_cck);
8678
8679         buf = os_zalloc(24 + data_len);
8680         if (buf == NULL)
8681                 return ret;
8682         os_memcpy(buf + 24, data, data_len);
8683         hdr = (struct ieee80211_hdr *) buf;
8684         hdr->frame_control =
8685                 IEEE80211_FC(WLAN_FC_TYPE_MGMT, WLAN_FC_STYPE_ACTION);
8686         os_memcpy(hdr->addr1, dst, ETH_ALEN);
8687         os_memcpy(hdr->addr2, src, ETH_ALEN);
8688         os_memcpy(hdr->addr3, bssid, ETH_ALEN);
8689
8690         if (is_ap_interface(drv->nlmode))
8691                 ret = wpa_driver_nl80211_send_mlme(bss, buf, 24 + data_len,
8692                                                    0, freq, no_cck, 1,
8693                                                    wait_time);
8694         else
8695                 ret = nl80211_send_frame_cmd(bss, freq, wait_time, buf,
8696                                              24 + data_len,
8697                                              &drv->send_action_cookie,
8698                                              no_cck, 0, 1);
8699
8700         os_free(buf);
8701         return ret;
8702 }
8703
8704
8705 static void wpa_driver_nl80211_send_action_cancel_wait(void *priv)
8706 {
8707         struct i802_bss *bss = priv;
8708         struct wpa_driver_nl80211_data *drv = bss->drv;
8709         struct nl_msg *msg;
8710         int ret;
8711
8712         msg = nlmsg_alloc();
8713         if (!msg)
8714                 return;
8715
8716         wpa_printf(MSG_DEBUG, "nl80211: Cancel TX frame wait: cookie=0x%llx",
8717                    (long long unsigned int) drv->send_action_cookie);
8718         nl80211_cmd(drv, msg, 0, NL80211_CMD_FRAME_WAIT_CANCEL);
8719
8720         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8721         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->send_action_cookie);
8722
8723         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8724         msg = NULL;
8725         if (ret)
8726                 wpa_printf(MSG_DEBUG, "nl80211: wait cancel failed: ret=%d "
8727                            "(%s)", ret, strerror(-ret));
8728
8729  nla_put_failure:
8730         nlmsg_free(msg);
8731 }
8732
8733
8734 static int wpa_driver_nl80211_remain_on_channel(void *priv, unsigned int freq,
8735                                                 unsigned int duration)
8736 {
8737         struct i802_bss *bss = priv;
8738         struct wpa_driver_nl80211_data *drv = bss->drv;
8739         struct nl_msg *msg;
8740         int ret;
8741         u64 cookie;
8742
8743         msg = nlmsg_alloc();
8744         if (!msg)
8745                 return -1;
8746
8747         nl80211_cmd(drv, msg, 0, NL80211_CMD_REMAIN_ON_CHANNEL);
8748
8749         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8750         NLA_PUT_U32(msg, NL80211_ATTR_WIPHY_FREQ, freq);
8751         NLA_PUT_U32(msg, NL80211_ATTR_DURATION, duration);
8752
8753         cookie = 0;
8754         ret = send_and_recv_msgs(drv, msg, cookie_handler, &cookie);
8755         msg = NULL;
8756         if (ret == 0) {
8757                 wpa_printf(MSG_DEBUG, "nl80211: Remain-on-channel cookie "
8758                            "0x%llx for freq=%u MHz duration=%u",
8759                            (long long unsigned int) cookie, freq, duration);
8760                 drv->remain_on_chan_cookie = cookie;
8761                 drv->pending_remain_on_chan = 1;
8762                 return 0;
8763         }
8764         wpa_printf(MSG_DEBUG, "nl80211: Failed to request remain-on-channel "
8765                    "(freq=%d duration=%u): %d (%s)",
8766                    freq, duration, ret, strerror(-ret));
8767 nla_put_failure:
8768         nlmsg_free(msg);
8769         return -1;
8770 }
8771
8772
8773 static int wpa_driver_nl80211_cancel_remain_on_channel(void *priv)
8774 {
8775         struct i802_bss *bss = priv;
8776         struct wpa_driver_nl80211_data *drv = bss->drv;
8777         struct nl_msg *msg;
8778         int ret;
8779
8780         if (!drv->pending_remain_on_chan) {
8781                 wpa_printf(MSG_DEBUG, "nl80211: No pending remain-on-channel "
8782                            "to cancel");
8783                 return -1;
8784         }
8785
8786         wpa_printf(MSG_DEBUG, "nl80211: Cancel remain-on-channel with cookie "
8787                    "0x%llx",
8788                    (long long unsigned int) drv->remain_on_chan_cookie);
8789
8790         msg = nlmsg_alloc();
8791         if (!msg)
8792                 return -1;
8793
8794         nl80211_cmd(drv, msg, 0, NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL);
8795
8796         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
8797         NLA_PUT_U64(msg, NL80211_ATTR_COOKIE, drv->remain_on_chan_cookie);
8798
8799         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8800         msg = NULL;
8801         if (ret == 0)
8802                 return 0;
8803         wpa_printf(MSG_DEBUG, "nl80211: Failed to cancel remain-on-channel: "
8804                    "%d (%s)", ret, strerror(-ret));
8805 nla_put_failure:
8806         nlmsg_free(msg);
8807         return -1;
8808 }
8809
8810
8811 static int wpa_driver_nl80211_probe_req_report(struct i802_bss *bss, int report)
8812 {
8813         struct wpa_driver_nl80211_data *drv = bss->drv;
8814
8815         if (!report) {
8816                 if (bss->nl_preq && drv->device_ap_sme &&
8817                     is_ap_interface(drv->nlmode)) {
8818                         /*
8819                          * Do not disable Probe Request reporting that was
8820                          * enabled in nl80211_setup_ap().
8821                          */
8822                         wpa_printf(MSG_DEBUG, "nl80211: Skip disabling of "
8823                                    "Probe Request reporting nl_preq=%p while "
8824                                    "in AP mode", bss->nl_preq);
8825                 } else if (bss->nl_preq) {
8826                         wpa_printf(MSG_DEBUG, "nl80211: Disable Probe Request "
8827                                    "reporting nl_preq=%p", bss->nl_preq);
8828                         eloop_unregister_read_sock(
8829                                 nl_socket_get_fd(bss->nl_preq));
8830                         nl_destroy_handles(&bss->nl_preq);
8831                 }
8832                 return 0;
8833         }
8834
8835         if (bss->nl_preq) {
8836                 wpa_printf(MSG_DEBUG, "nl80211: Probe Request reporting "
8837                            "already on! nl_preq=%p", bss->nl_preq);
8838                 return 0;
8839         }
8840
8841         bss->nl_preq = nl_create_handle(drv->global->nl_cb, "preq");
8842         if (bss->nl_preq == NULL)
8843                 return -1;
8844         wpa_printf(MSG_DEBUG, "nl80211: Enable Probe Request "
8845                    "reporting nl_preq=%p", bss->nl_preq);
8846
8847         if (nl80211_register_frame(bss, bss->nl_preq,
8848                                    (WLAN_FC_TYPE_MGMT << 2) |
8849                                    (WLAN_FC_STYPE_PROBE_REQ << 4),
8850                                    NULL, 0) < 0)
8851                 goto out_err;
8852
8853         eloop_register_read_sock(nl_socket_get_fd(bss->nl_preq),
8854                                  wpa_driver_nl80211_event_receive, bss->nl_cb,
8855                                  bss->nl_preq);
8856
8857         return 0;
8858
8859  out_err:
8860         nl_destroy_handles(&bss->nl_preq);
8861         return -1;
8862 }
8863
8864
8865 static int nl80211_disable_11b_rates(struct wpa_driver_nl80211_data *drv,
8866                                      int ifindex, int disabled)
8867 {
8868         struct nl_msg *msg;
8869         struct nlattr *bands, *band;
8870         int ret;
8871
8872         msg = nlmsg_alloc();
8873         if (!msg)
8874                 return -1;
8875
8876         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_TX_BITRATE_MASK);
8877         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, ifindex);
8878
8879         bands = nla_nest_start(msg, NL80211_ATTR_TX_RATES);
8880         if (!bands)
8881                 goto nla_put_failure;
8882
8883         /*
8884          * Disable 2 GHz rates 1, 2, 5.5, 11 Mbps by masking out everything
8885          * else apart from 6, 9, 12, 18, 24, 36, 48, 54 Mbps from non-MCS
8886          * rates. All 5 GHz rates are left enabled.
8887          */
8888         band = nla_nest_start(msg, NL80211_BAND_2GHZ);
8889         if (!band)
8890                 goto nla_put_failure;
8891         if (disabled) {
8892                 NLA_PUT(msg, NL80211_TXRATE_LEGACY, 8,
8893                         "\x0c\x12\x18\x24\x30\x48\x60\x6c");
8894         }
8895         nla_nest_end(msg, band);
8896
8897         nla_nest_end(msg, bands);
8898
8899         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
8900         msg = NULL;
8901         if (ret) {
8902                 wpa_printf(MSG_DEBUG, "nl80211: Set TX rates failed: ret=%d "
8903                            "(%s)", ret, strerror(-ret));
8904         } else
8905                 drv->disabled_11b_rates = disabled;
8906
8907         return ret;
8908
8909 nla_put_failure:
8910         nlmsg_free(msg);
8911         return -1;
8912 }
8913
8914
8915 static int wpa_driver_nl80211_deinit_ap(void *priv)
8916 {
8917         struct i802_bss *bss = priv;
8918         struct wpa_driver_nl80211_data *drv = bss->drv;
8919         if (!is_ap_interface(drv->nlmode))
8920                 return -1;
8921         wpa_driver_nl80211_del_beacon(drv);
8922         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
8923 }
8924
8925
8926 static int wpa_driver_nl80211_deinit_p2p_cli(void *priv)
8927 {
8928         struct i802_bss *bss = priv;
8929         struct wpa_driver_nl80211_data *drv = bss->drv;
8930         if (drv->nlmode != NL80211_IFTYPE_P2P_CLIENT)
8931                 return -1;
8932         return wpa_driver_nl80211_set_mode(priv, NL80211_IFTYPE_STATION);
8933 }
8934
8935
8936 static void wpa_driver_nl80211_resume(void *priv)
8937 {
8938         struct i802_bss *bss = priv;
8939         struct wpa_driver_nl80211_data *drv = bss->drv;
8940         if (linux_set_iface_flags(drv->global->ioctl_sock, bss->ifname, 1)) {
8941                 wpa_printf(MSG_DEBUG, "nl80211: Failed to set interface up on "
8942                            "resume event");
8943         }
8944 }
8945
8946
8947 static int nl80211_send_ft_action(void *priv, u8 action, const u8 *target_ap,
8948                                   const u8 *ies, size_t ies_len)
8949 {
8950         struct i802_bss *bss = priv;
8951         struct wpa_driver_nl80211_data *drv = bss->drv;
8952         int ret;
8953         u8 *data, *pos;
8954         size_t data_len;
8955         const u8 *own_addr = bss->addr;
8956
8957         if (action != 1) {
8958                 wpa_printf(MSG_ERROR, "nl80211: Unsupported send_ft_action "
8959                            "action %d", action);
8960                 return -1;
8961         }
8962
8963         /*
8964          * Action frame payload:
8965          * Category[1] = 6 (Fast BSS Transition)
8966          * Action[1] = 1 (Fast BSS Transition Request)
8967          * STA Address
8968          * Target AP Address
8969          * FT IEs
8970          */
8971
8972         data_len = 2 + 2 * ETH_ALEN + ies_len;
8973         data = os_malloc(data_len);
8974         if (data == NULL)
8975                 return -1;
8976         pos = data;
8977         *pos++ = 0x06; /* FT Action category */
8978         *pos++ = action;
8979         os_memcpy(pos, own_addr, ETH_ALEN);
8980         pos += ETH_ALEN;
8981         os_memcpy(pos, target_ap, ETH_ALEN);
8982         pos += ETH_ALEN;
8983         os_memcpy(pos, ies, ies_len);
8984
8985         ret = wpa_driver_nl80211_send_action(bss, drv->assoc_freq, 0,
8986                                              drv->bssid, own_addr, drv->bssid,
8987                                              data, data_len, 0);
8988         os_free(data);
8989
8990         return ret;
8991 }
8992
8993
8994 static int nl80211_signal_monitor(void *priv, int threshold, int hysteresis)
8995 {
8996         struct i802_bss *bss = priv;
8997         struct wpa_driver_nl80211_data *drv = bss->drv;
8998         struct nl_msg *msg;
8999         struct nlattr *cqm;
9000         int ret = -1;
9001
9002         wpa_printf(MSG_DEBUG, "nl80211: Signal monitor threshold=%d "
9003                    "hysteresis=%d", threshold, hysteresis);
9004
9005         msg = nlmsg_alloc();
9006         if (!msg)
9007                 return -1;
9008
9009         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_CQM);
9010
9011         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
9012
9013         cqm = nla_nest_start(msg, NL80211_ATTR_CQM);
9014         if (cqm == NULL)
9015                 goto nla_put_failure;
9016
9017         NLA_PUT_U32(msg, NL80211_ATTR_CQM_RSSI_THOLD, threshold);
9018         NLA_PUT_U32(msg, NL80211_ATTR_CQM_RSSI_HYST, hysteresis);
9019         nla_nest_end(msg, cqm);
9020
9021         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9022         msg = NULL;
9023
9024 nla_put_failure:
9025         nlmsg_free(msg);
9026         return ret;
9027 }
9028
9029
9030 static int nl80211_signal_poll(void *priv, struct wpa_signal_info *si)
9031 {
9032         struct i802_bss *bss = priv;
9033         struct wpa_driver_nl80211_data *drv = bss->drv;
9034         int res;
9035
9036         os_memset(si, 0, sizeof(*si));
9037         res = nl80211_get_link_signal(drv, si);
9038         if (res != 0)
9039                 return res;
9040
9041         return nl80211_get_link_noise(drv, si);
9042 }
9043
9044
9045 static int wpa_driver_nl80211_shared_freq(void *priv)
9046 {
9047         struct i802_bss *bss = priv;
9048         struct wpa_driver_nl80211_data *drv = bss->drv;
9049         struct wpa_driver_nl80211_data *driver;
9050         int freq = 0;
9051
9052         /*
9053          * If the same PHY is in connected state with some other interface,
9054          * then retrieve the assoc freq.
9055          */
9056         wpa_printf(MSG_DEBUG, "nl80211: Get shared freq for PHY %s",
9057                    drv->phyname);
9058
9059         dl_list_for_each(driver, &drv->global->interfaces,
9060                          struct wpa_driver_nl80211_data, list) {
9061                 if (drv == driver ||
9062                     os_strcmp(drv->phyname, driver->phyname) != 0 ||
9063                     !driver->associated)
9064                         continue;
9065
9066                 wpa_printf(MSG_DEBUG, "nl80211: Found a match for PHY %s - %s "
9067                            MACSTR,
9068                            driver->phyname, driver->first_bss.ifname,
9069                            MAC2STR(driver->first_bss.addr));
9070                 if (is_ap_interface(driver->nlmode))
9071                         freq = driver->first_bss.freq;
9072                 else
9073                         freq = nl80211_get_assoc_freq(driver);
9074                 wpa_printf(MSG_DEBUG, "nl80211: Shared freq for PHY %s: %d",
9075                            drv->phyname, freq);
9076         }
9077
9078         if (!freq)
9079                 wpa_printf(MSG_DEBUG, "nl80211: No shared interface for "
9080                            "PHY (%s) in associated state", drv->phyname);
9081
9082         return freq;
9083 }
9084
9085
9086 static int nl80211_send_frame(void *priv, const u8 *data, size_t data_len,
9087                               int encrypt)
9088 {
9089         struct i802_bss *bss = priv;
9090         return wpa_driver_nl80211_send_frame(bss, data, data_len, encrypt, 0,
9091                                              0, 0, 0, 0);
9092 }
9093
9094
9095 static int nl80211_set_param(void *priv, const char *param)
9096 {
9097         wpa_printf(MSG_DEBUG, "nl80211: driver param='%s'", param);
9098         if (param == NULL)
9099                 return 0;
9100
9101 #ifdef CONFIG_P2P
9102         if (os_strstr(param, "use_p2p_group_interface=1")) {
9103                 struct i802_bss *bss = priv;
9104                 struct wpa_driver_nl80211_data *drv = bss->drv;
9105
9106                 wpa_printf(MSG_DEBUG, "nl80211: Use separate P2P group "
9107                            "interface");
9108                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_CONCURRENT;
9109                 drv->capa.flags |= WPA_DRIVER_FLAGS_P2P_MGMT_AND_NON_P2P;
9110         }
9111 #endif /* CONFIG_P2P */
9112
9113         return 0;
9114 }
9115
9116
9117 static void * nl80211_global_init(void)
9118 {
9119         struct nl80211_global *global;
9120         struct netlink_config *cfg;
9121
9122         global = os_zalloc(sizeof(*global));
9123         if (global == NULL)
9124                 return NULL;
9125         global->ioctl_sock = -1;
9126         dl_list_init(&global->interfaces);
9127         global->if_add_ifindex = -1;
9128
9129         cfg = os_zalloc(sizeof(*cfg));
9130         if (cfg == NULL)
9131                 goto err;
9132
9133         cfg->ctx = global;
9134         cfg->newlink_cb = wpa_driver_nl80211_event_rtm_newlink;
9135         cfg->dellink_cb = wpa_driver_nl80211_event_rtm_dellink;
9136         global->netlink = netlink_init(cfg);
9137         if (global->netlink == NULL) {
9138                 os_free(cfg);
9139                 goto err;
9140         }
9141
9142         if (wpa_driver_nl80211_init_nl_global(global) < 0)
9143                 goto err;
9144
9145         global->ioctl_sock = socket(PF_INET, SOCK_DGRAM, 0);
9146         if (global->ioctl_sock < 0) {
9147                 perror("socket(PF_INET,SOCK_DGRAM)");
9148                 goto err;
9149         }
9150
9151         return global;
9152
9153 err:
9154         nl80211_global_deinit(global);
9155         return NULL;
9156 }
9157
9158
9159 static void nl80211_global_deinit(void *priv)
9160 {
9161         struct nl80211_global *global = priv;
9162         if (global == NULL)
9163                 return;
9164         if (!dl_list_empty(&global->interfaces)) {
9165                 wpa_printf(MSG_ERROR, "nl80211: %u interface(s) remain at "
9166                            "nl80211_global_deinit",
9167                            dl_list_len(&global->interfaces));
9168         }
9169
9170         if (global->netlink)
9171                 netlink_deinit(global->netlink);
9172
9173         nl_destroy_handles(&global->nl);
9174
9175         if (global->nl_event) {
9176                 eloop_unregister_read_sock(
9177                         nl_socket_get_fd(global->nl_event));
9178                 nl_destroy_handles(&global->nl_event);
9179         }
9180
9181         nl_cb_put(global->nl_cb);
9182
9183         if (global->ioctl_sock >= 0)
9184                 close(global->ioctl_sock);
9185
9186         os_free(global);
9187 }
9188
9189
9190 static const char * nl80211_get_radio_name(void *priv)
9191 {
9192         struct i802_bss *bss = priv;
9193         struct wpa_driver_nl80211_data *drv = bss->drv;
9194         return drv->phyname;
9195 }
9196
9197
9198 static int nl80211_pmkid(struct i802_bss *bss, int cmd, const u8 *bssid,
9199                          const u8 *pmkid)
9200 {
9201         struct nl_msg *msg;
9202
9203         msg = nlmsg_alloc();
9204         if (!msg)
9205                 return -ENOMEM;
9206
9207         nl80211_cmd(bss->drv, msg, 0, cmd);
9208
9209         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, if_nametoindex(bss->ifname));
9210         if (pmkid)
9211                 NLA_PUT(msg, NL80211_ATTR_PMKID, 16, pmkid);
9212         if (bssid)
9213                 NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid);
9214
9215         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
9216  nla_put_failure:
9217         nlmsg_free(msg);
9218         return -ENOBUFS;
9219 }
9220
9221
9222 static int nl80211_add_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
9223 {
9224         struct i802_bss *bss = priv;
9225         wpa_printf(MSG_DEBUG, "nl80211: Add PMKID for " MACSTR, MAC2STR(bssid));
9226         return nl80211_pmkid(bss, NL80211_CMD_SET_PMKSA, bssid, pmkid);
9227 }
9228
9229
9230 static int nl80211_remove_pmkid(void *priv, const u8 *bssid, const u8 *pmkid)
9231 {
9232         struct i802_bss *bss = priv;
9233         wpa_printf(MSG_DEBUG, "nl80211: Delete PMKID for " MACSTR,
9234                    MAC2STR(bssid));
9235         return nl80211_pmkid(bss, NL80211_CMD_DEL_PMKSA, bssid, pmkid);
9236 }
9237
9238
9239 static int nl80211_flush_pmkid(void *priv)
9240 {
9241         struct i802_bss *bss = priv;
9242         wpa_printf(MSG_DEBUG, "nl80211: Flush PMKIDs");
9243         return nl80211_pmkid(bss, NL80211_CMD_FLUSH_PMKSA, NULL, NULL);
9244 }
9245
9246
9247 static void nl80211_set_rekey_info(void *priv, const u8 *kek, const u8 *kck,
9248                                    const u8 *replay_ctr)
9249 {
9250         struct i802_bss *bss = priv;
9251         struct wpa_driver_nl80211_data *drv = bss->drv;
9252         struct nlattr *replay_nested;
9253         struct nl_msg *msg;
9254
9255         msg = nlmsg_alloc();
9256         if (!msg)
9257                 return;
9258
9259         nl80211_cmd(drv, msg, 0, NL80211_CMD_SET_REKEY_OFFLOAD);
9260
9261         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
9262
9263         replay_nested = nla_nest_start(msg, NL80211_ATTR_REKEY_DATA);
9264         if (!replay_nested)
9265                 goto nla_put_failure;
9266
9267         NLA_PUT(msg, NL80211_REKEY_DATA_KEK, NL80211_KEK_LEN, kek);
9268         NLA_PUT(msg, NL80211_REKEY_DATA_KCK, NL80211_KCK_LEN, kck);
9269         NLA_PUT(msg, NL80211_REKEY_DATA_REPLAY_CTR, NL80211_REPLAY_CTR_LEN,
9270                 replay_ctr);
9271
9272         nla_nest_end(msg, replay_nested);
9273
9274         send_and_recv_msgs(drv, msg, NULL, NULL);
9275         return;
9276  nla_put_failure:
9277         nlmsg_free(msg);
9278 }
9279
9280
9281 static void nl80211_send_null_frame(struct i802_bss *bss, const u8 *own_addr,
9282                                     const u8 *addr, int qos)
9283 {
9284         /* send data frame to poll STA and check whether
9285          * this frame is ACKed */
9286         struct {
9287                 struct ieee80211_hdr hdr;
9288                 u16 qos_ctl;
9289         } STRUCT_PACKED nulldata;
9290         size_t size;
9291
9292         /* Send data frame to poll STA and check whether this frame is ACKed */
9293
9294         os_memset(&nulldata, 0, sizeof(nulldata));
9295
9296         if (qos) {
9297                 nulldata.hdr.frame_control =
9298                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
9299                                      WLAN_FC_STYPE_QOS_NULL);
9300                 size = sizeof(nulldata);
9301         } else {
9302                 nulldata.hdr.frame_control =
9303                         IEEE80211_FC(WLAN_FC_TYPE_DATA,
9304                                      WLAN_FC_STYPE_NULLFUNC);
9305                 size = sizeof(struct ieee80211_hdr);
9306         }
9307
9308         nulldata.hdr.frame_control |= host_to_le16(WLAN_FC_FROMDS);
9309         os_memcpy(nulldata.hdr.IEEE80211_DA_FROMDS, addr, ETH_ALEN);
9310         os_memcpy(nulldata.hdr.IEEE80211_BSSID_FROMDS, own_addr, ETH_ALEN);
9311         os_memcpy(nulldata.hdr.IEEE80211_SA_FROMDS, own_addr, ETH_ALEN);
9312
9313         if (wpa_driver_nl80211_send_mlme(bss, (u8 *) &nulldata, size, 0, 0, 0,
9314                                          0, 0) < 0)
9315                 wpa_printf(MSG_DEBUG, "nl80211_send_null_frame: Failed to "
9316                            "send poll frame");
9317 }
9318
9319 static void nl80211_poll_client(void *priv, const u8 *own_addr, const u8 *addr,
9320                                 int qos)
9321 {
9322         struct i802_bss *bss = priv;
9323         struct wpa_driver_nl80211_data *drv = bss->drv;
9324         struct nl_msg *msg;
9325
9326         if (!drv->poll_command_supported) {
9327                 nl80211_send_null_frame(bss, own_addr, addr, qos);
9328                 return;
9329         }
9330
9331         msg = nlmsg_alloc();
9332         if (!msg)
9333                 return;
9334
9335         nl80211_cmd(drv, msg, 0, NL80211_CMD_PROBE_CLIENT);
9336
9337         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
9338         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, addr);
9339
9340         send_and_recv_msgs(drv, msg, NULL, NULL);
9341         return;
9342  nla_put_failure:
9343         nlmsg_free(msg);
9344 }
9345
9346
9347 static int nl80211_set_power_save(struct i802_bss *bss, int enabled)
9348 {
9349         struct nl_msg *msg;
9350
9351         msg = nlmsg_alloc();
9352         if (!msg)
9353                 return -ENOMEM;
9354
9355         nl80211_cmd(bss->drv, msg, 0, NL80211_CMD_SET_POWER_SAVE);
9356         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, bss->ifindex);
9357         NLA_PUT_U32(msg, NL80211_ATTR_PS_STATE,
9358                     enabled ? NL80211_PS_ENABLED : NL80211_PS_DISABLED);
9359         return send_and_recv_msgs(bss->drv, msg, NULL, NULL);
9360 nla_put_failure:
9361         nlmsg_free(msg);
9362         return -ENOBUFS;
9363 }
9364
9365
9366 static int nl80211_set_p2p_powersave(void *priv, int legacy_ps, int opp_ps,
9367                                      int ctwindow)
9368 {
9369         struct i802_bss *bss = priv;
9370
9371         wpa_printf(MSG_DEBUG, "nl80211: set_p2p_powersave (legacy_ps=%d "
9372                    "opp_ps=%d ctwindow=%d)", legacy_ps, opp_ps, ctwindow);
9373
9374         if (opp_ps != -1 || ctwindow != -1)
9375                 return -1; /* Not yet supported */
9376
9377         if (legacy_ps == -1)
9378                 return 0;
9379         if (legacy_ps != 0 && legacy_ps != 1)
9380                 return -1; /* Not yet supported */
9381
9382         return nl80211_set_power_save(bss, legacy_ps);
9383 }
9384
9385
9386 #ifdef CONFIG_TDLS
9387
9388 static int nl80211_send_tdls_mgmt(void *priv, const u8 *dst, u8 action_code,
9389                                   u8 dialog_token, u16 status_code,
9390                                   const u8 *buf, size_t len)
9391 {
9392         struct i802_bss *bss = priv;
9393         struct wpa_driver_nl80211_data *drv = bss->drv;
9394         struct nl_msg *msg;
9395
9396         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
9397                 return -EOPNOTSUPP;
9398
9399         if (!dst)
9400                 return -EINVAL;
9401
9402         msg = nlmsg_alloc();
9403         if (!msg)
9404                 return -ENOMEM;
9405
9406         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_MGMT);
9407         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9408         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, dst);
9409         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_ACTION, action_code);
9410         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_DIALOG_TOKEN, dialog_token);
9411         NLA_PUT_U16(msg, NL80211_ATTR_STATUS_CODE, status_code);
9412         NLA_PUT(msg, NL80211_ATTR_IE, len, buf);
9413
9414         return send_and_recv_msgs(drv, msg, NULL, NULL);
9415
9416 nla_put_failure:
9417         nlmsg_free(msg);
9418         return -ENOBUFS;
9419 }
9420
9421
9422 static int nl80211_tdls_oper(void *priv, enum tdls_oper oper, const u8 *peer)
9423 {
9424         struct i802_bss *bss = priv;
9425         struct wpa_driver_nl80211_data *drv = bss->drv;
9426         struct nl_msg *msg;
9427         enum nl80211_tdls_operation nl80211_oper;
9428
9429         if (!(drv->capa.flags & WPA_DRIVER_FLAGS_TDLS_SUPPORT))
9430                 return -EOPNOTSUPP;
9431
9432         switch (oper) {
9433         case TDLS_DISCOVERY_REQ:
9434                 nl80211_oper = NL80211_TDLS_DISCOVERY_REQ;
9435                 break;
9436         case TDLS_SETUP:
9437                 nl80211_oper = NL80211_TDLS_SETUP;
9438                 break;
9439         case TDLS_TEARDOWN:
9440                 nl80211_oper = NL80211_TDLS_TEARDOWN;
9441                 break;
9442         case TDLS_ENABLE_LINK:
9443                 nl80211_oper = NL80211_TDLS_ENABLE_LINK;
9444                 break;
9445         case TDLS_DISABLE_LINK:
9446                 nl80211_oper = NL80211_TDLS_DISABLE_LINK;
9447                 break;
9448         case TDLS_ENABLE:
9449                 return 0;
9450         case TDLS_DISABLE:
9451                 return 0;
9452         default:
9453                 return -EINVAL;
9454         }
9455
9456         msg = nlmsg_alloc();
9457         if (!msg)
9458                 return -ENOMEM;
9459
9460         nl80211_cmd(drv, msg, 0, NL80211_CMD_TDLS_OPER);
9461         NLA_PUT_U8(msg, NL80211_ATTR_TDLS_OPERATION, nl80211_oper);
9462         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9463         NLA_PUT(msg, NL80211_ATTR_MAC, ETH_ALEN, peer);
9464
9465         return send_and_recv_msgs(drv, msg, NULL, NULL);
9466
9467 nla_put_failure:
9468         nlmsg_free(msg);
9469         return -ENOBUFS;
9470 }
9471
9472 #endif /* CONFIG TDLS */
9473
9474
9475 #ifdef ANDROID
9476
9477 typedef struct android_wifi_priv_cmd {
9478         char *buf;
9479         int used_len;
9480         int total_len;
9481 } android_wifi_priv_cmd;
9482
9483 static int drv_errors = 0;
9484
9485 static void wpa_driver_send_hang_msg(struct wpa_driver_nl80211_data *drv)
9486 {
9487         drv_errors++;
9488         if (drv_errors > DRV_NUMBER_SEQUENTIAL_ERRORS) {
9489                 drv_errors = 0;
9490                 wpa_msg(drv->ctx, MSG_INFO, WPA_EVENT_DRIVER_STATE "HANGED");
9491         }
9492 }
9493
9494
9495 static int android_priv_cmd(struct i802_bss *bss, const char *cmd)
9496 {
9497         struct wpa_driver_nl80211_data *drv = bss->drv;
9498         struct ifreq ifr;
9499         android_wifi_priv_cmd priv_cmd;
9500         char buf[MAX_DRV_CMD_SIZE];
9501         int ret;
9502
9503         os_memset(&ifr, 0, sizeof(ifr));
9504         os_memset(&priv_cmd, 0, sizeof(priv_cmd));
9505         os_strlcpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
9506
9507         os_memset(buf, 0, sizeof(buf));
9508         os_strlcpy(buf, cmd, sizeof(buf));
9509
9510         priv_cmd.buf = buf;
9511         priv_cmd.used_len = sizeof(buf);
9512         priv_cmd.total_len = sizeof(buf);
9513         ifr.ifr_data = &priv_cmd;
9514
9515         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
9516         if (ret < 0) {
9517                 wpa_printf(MSG_ERROR, "%s: failed to issue private commands",
9518                            __func__);
9519                 wpa_driver_send_hang_msg(drv);
9520                 return ret;
9521         }
9522
9523         drv_errors = 0;
9524         return 0;
9525 }
9526
9527
9528 static int android_pno_start(struct i802_bss *bss,
9529                              struct wpa_driver_scan_params *params)
9530 {
9531         struct wpa_driver_nl80211_data *drv = bss->drv;
9532         struct ifreq ifr;
9533         android_wifi_priv_cmd priv_cmd;
9534         int ret = 0, i = 0, bp;
9535         char buf[WEXT_PNO_MAX_COMMAND_SIZE];
9536
9537         bp = WEXT_PNOSETUP_HEADER_SIZE;
9538         os_memcpy(buf, WEXT_PNOSETUP_HEADER, bp);
9539         buf[bp++] = WEXT_PNO_TLV_PREFIX;
9540         buf[bp++] = WEXT_PNO_TLV_VERSION;
9541         buf[bp++] = WEXT_PNO_TLV_SUBVERSION;
9542         buf[bp++] = WEXT_PNO_TLV_RESERVED;
9543
9544         while (i < WEXT_PNO_AMOUNT && (size_t) i < params->num_ssids) {
9545                 /* Check that there is enough space needed for 1 more SSID, the
9546                  * other sections and null termination */
9547                 if ((bp + WEXT_PNO_SSID_HEADER_SIZE + MAX_SSID_LEN +
9548                      WEXT_PNO_NONSSID_SECTIONS_SIZE + 1) >= (int) sizeof(buf))
9549                         break;
9550                 wpa_hexdump_ascii(MSG_DEBUG, "For PNO Scan",
9551                                   params->ssids[i].ssid,
9552                                   params->ssids[i].ssid_len);
9553                 buf[bp++] = WEXT_PNO_SSID_SECTION;
9554                 buf[bp++] = params->ssids[i].ssid_len;
9555                 os_memcpy(&buf[bp], params->ssids[i].ssid,
9556                           params->ssids[i].ssid_len);
9557                 bp += params->ssids[i].ssid_len;
9558                 i++;
9559         }
9560
9561         buf[bp++] = WEXT_PNO_SCAN_INTERVAL_SECTION;
9562         os_snprintf(&buf[bp], WEXT_PNO_SCAN_INTERVAL_LENGTH + 1, "%x",
9563                     WEXT_PNO_SCAN_INTERVAL);
9564         bp += WEXT_PNO_SCAN_INTERVAL_LENGTH;
9565
9566         buf[bp++] = WEXT_PNO_REPEAT_SECTION;
9567         os_snprintf(&buf[bp], WEXT_PNO_REPEAT_LENGTH + 1, "%x",
9568                     WEXT_PNO_REPEAT);
9569         bp += WEXT_PNO_REPEAT_LENGTH;
9570
9571         buf[bp++] = WEXT_PNO_MAX_REPEAT_SECTION;
9572         os_snprintf(&buf[bp], WEXT_PNO_MAX_REPEAT_LENGTH + 1, "%x",
9573                     WEXT_PNO_MAX_REPEAT);
9574         bp += WEXT_PNO_MAX_REPEAT_LENGTH + 1;
9575
9576         memset(&ifr, 0, sizeof(ifr));
9577         memset(&priv_cmd, 0, sizeof(priv_cmd));
9578         os_strncpy(ifr.ifr_name, bss->ifname, IFNAMSIZ);
9579
9580         priv_cmd.buf = buf;
9581         priv_cmd.used_len = bp;
9582         priv_cmd.total_len = bp;
9583         ifr.ifr_data = &priv_cmd;
9584
9585         ret = ioctl(drv->global->ioctl_sock, SIOCDEVPRIVATE + 1, &ifr);
9586
9587         if (ret < 0) {
9588                 wpa_printf(MSG_ERROR, "ioctl[SIOCSIWPRIV] (pnosetup): %d",
9589                            ret);
9590                 wpa_driver_send_hang_msg(drv);
9591                 return ret;
9592         }
9593
9594         drv_errors = 0;
9595
9596         return android_priv_cmd(bss, "PNOFORCE 1");
9597 }
9598
9599
9600 static int android_pno_stop(struct i802_bss *bss)
9601 {
9602         return android_priv_cmd(bss, "PNOFORCE 0");
9603 }
9604
9605 #endif /* ANDROID */
9606
9607
9608 static int driver_nl80211_set_key(const char *ifname, void *priv,
9609                                   enum wpa_alg alg, const u8 *addr,
9610                                   int key_idx, int set_tx,
9611                                   const u8 *seq, size_t seq_len,
9612                                   const u8 *key, size_t key_len)
9613 {
9614         struct i802_bss *bss = priv;
9615         return wpa_driver_nl80211_set_key(ifname, bss, alg, addr, key_idx,
9616                                           set_tx, seq, seq_len, key, key_len);
9617 }
9618
9619
9620 static int driver_nl80211_scan2(void *priv,
9621                                 struct wpa_driver_scan_params *params)
9622 {
9623         struct i802_bss *bss = priv;
9624         return wpa_driver_nl80211_scan(bss, params);
9625 }
9626
9627
9628 static int driver_nl80211_deauthenticate(void *priv, const u8 *addr,
9629                                          int reason_code)
9630 {
9631         struct i802_bss *bss = priv;
9632         return wpa_driver_nl80211_deauthenticate(bss, addr, reason_code);
9633 }
9634
9635
9636 static int driver_nl80211_authenticate(void *priv,
9637                                        struct wpa_driver_auth_params *params)
9638 {
9639         struct i802_bss *bss = priv;
9640         return wpa_driver_nl80211_authenticate(bss, params);
9641 }
9642
9643
9644 static void driver_nl80211_deinit(void *priv)
9645 {
9646         struct i802_bss *bss = priv;
9647         wpa_driver_nl80211_deinit(bss);
9648 }
9649
9650
9651 static int driver_nl80211_if_remove(void *priv, enum wpa_driver_if_type type,
9652                                     const char *ifname)
9653 {
9654         struct i802_bss *bss = priv;
9655         return wpa_driver_nl80211_if_remove(bss, type, ifname);
9656 }
9657
9658
9659 static int driver_nl80211_send_mlme(void *priv, const u8 *data,
9660                                     size_t data_len, int noack)
9661 {
9662         struct i802_bss *bss = priv;
9663         return wpa_driver_nl80211_send_mlme(bss, data, data_len, noack,
9664                                             0, 0, 0, 0);
9665 }
9666
9667
9668 static int driver_nl80211_sta_remove(void *priv, const u8 *addr)
9669 {
9670         struct i802_bss *bss = priv;
9671         return wpa_driver_nl80211_sta_remove(bss, addr);
9672 }
9673
9674
9675 #if defined(HOSTAPD) || defined(CONFIG_AP)
9676 static int driver_nl80211_set_sta_vlan(void *priv, const u8 *addr,
9677                                        const char *ifname, int vlan_id)
9678 {
9679         struct i802_bss *bss = priv;
9680         return i802_set_sta_vlan(bss, addr, ifname, vlan_id);
9681 }
9682 #endif /* HOSTAPD || CONFIG_AP */
9683
9684
9685 static int driver_nl80211_read_sta_data(void *priv,
9686                                         struct hostap_sta_driver_data *data,
9687                                         const u8 *addr)
9688 {
9689         struct i802_bss *bss = priv;
9690         return i802_read_sta_data(bss, data, addr);
9691 }
9692
9693
9694 static int driver_nl80211_send_action(void *priv, unsigned int freq,
9695                                       unsigned int wait_time,
9696                                       const u8 *dst, const u8 *src,
9697                                       const u8 *bssid,
9698                                       const u8 *data, size_t data_len,
9699                                       int no_cck)
9700 {
9701         struct i802_bss *bss = priv;
9702         return wpa_driver_nl80211_send_action(bss, freq, wait_time, dst, src,
9703                                               bssid, data, data_len, no_cck);
9704 }
9705
9706
9707 static int driver_nl80211_probe_req_report(void *priv, int report)
9708 {
9709         struct i802_bss *bss = priv;
9710         return wpa_driver_nl80211_probe_req_report(bss, report);
9711 }
9712
9713
9714 static int wpa_driver_nl80211_update_ft_ies(void *priv, const u8 *md,
9715                                             const u8 *ies, size_t ies_len)
9716 {
9717         int ret;
9718         struct nl_msg *msg;
9719         struct i802_bss *bss = priv;
9720         struct wpa_driver_nl80211_data *drv = bss->drv;
9721         u16 mdid = WPA_GET_LE16(md);
9722
9723         msg = nlmsg_alloc();
9724         if (!msg)
9725                 return -ENOMEM;
9726
9727         wpa_printf(MSG_DEBUG, "nl80211: Updating FT IEs");
9728         nl80211_cmd(drv, msg, 0, NL80211_CMD_UPDATE_FT_IES);
9729         NLA_PUT_U32(msg, NL80211_ATTR_IFINDEX, drv->ifindex);
9730         NLA_PUT(msg, NL80211_ATTR_IE, ies_len, ies);
9731         NLA_PUT_U16(msg, NL80211_ATTR_MDID, mdid);
9732
9733         ret = send_and_recv_msgs(drv, msg, NULL, NULL);
9734         if (ret) {
9735                 wpa_printf(MSG_DEBUG, "nl80211: update_ft_ies failed "
9736                            "err=%d (%s)", ret, strerror(-ret));
9737         }
9738
9739         return ret;
9740
9741 nla_put_failure:
9742         nlmsg_free(msg);
9743         return -ENOBUFS;
9744 }
9745
9746
9747 const struct wpa_driver_ops wpa_driver_nl80211_ops = {
9748         .name = "nl80211",
9749         .desc = "Linux nl80211/cfg80211",
9750         .get_bssid = wpa_driver_nl80211_get_bssid,
9751         .get_ssid = wpa_driver_nl80211_get_ssid,
9752         .set_key = driver_nl80211_set_key,
9753         .scan2 = driver_nl80211_scan2,
9754         .sched_scan = wpa_driver_nl80211_sched_scan,
9755         .stop_sched_scan = wpa_driver_nl80211_stop_sched_scan,
9756         .get_scan_results2 = wpa_driver_nl80211_get_scan_results,
9757         .deauthenticate = driver_nl80211_deauthenticate,
9758         .authenticate = driver_nl80211_authenticate,
9759         .associate = wpa_driver_nl80211_associate,
9760         .global_init = nl80211_global_init,
9761         .global_deinit = nl80211_global_deinit,
9762         .init2 = wpa_driver_nl80211_init,
9763         .deinit = driver_nl80211_deinit,
9764         .get_capa = wpa_driver_nl80211_get_capa,
9765         .set_operstate = wpa_driver_nl80211_set_operstate,
9766         .set_supp_port = wpa_driver_nl80211_set_supp_port,
9767         .set_country = wpa_driver_nl80211_set_country,
9768         .set_ap = wpa_driver_nl80211_set_ap,
9769         .if_add = wpa_driver_nl80211_if_add,
9770         .if_remove = driver_nl80211_if_remove,
9771         .send_mlme = driver_nl80211_send_mlme,
9772         .get_hw_feature_data = wpa_driver_nl80211_get_hw_feature_data,
9773         .sta_add = wpa_driver_nl80211_sta_add,
9774         .sta_remove = driver_nl80211_sta_remove,
9775         .hapd_send_eapol = wpa_driver_nl80211_hapd_send_eapol,
9776         .sta_set_flags = wpa_driver_nl80211_sta_set_flags,
9777 #ifdef HOSTAPD
9778         .hapd_init = i802_init,
9779         .hapd_deinit = i802_deinit,
9780         .set_wds_sta = i802_set_wds_sta,
9781 #endif /* HOSTAPD */
9782 #if defined(HOSTAPD) || defined(CONFIG_AP)
9783         .get_seqnum = i802_get_seqnum,
9784         .flush = i802_flush,
9785         .get_inact_sec = i802_get_inact_sec,
9786         .sta_clear_stats = i802_sta_clear_stats,
9787         .set_rts = i802_set_rts,
9788         .set_frag = i802_set_frag,
9789         .set_tx_queue_params = i802_set_tx_queue_params,
9790         .set_sta_vlan = driver_nl80211_set_sta_vlan,
9791         .sta_deauth = i802_sta_deauth,
9792         .sta_disassoc = i802_sta_disassoc,
9793 #endif /* HOSTAPD || CONFIG_AP */
9794         .read_sta_data = driver_nl80211_read_sta_data,
9795         .set_freq = i802_set_freq,
9796         .send_action = driver_nl80211_send_action,
9797         .send_action_cancel_wait = wpa_driver_nl80211_send_action_cancel_wait,
9798         .remain_on_channel = wpa_driver_nl80211_remain_on_channel,
9799         .cancel_remain_on_channel =
9800         wpa_driver_nl80211_cancel_remain_on_channel,
9801         .probe_req_report = driver_nl80211_probe_req_report,
9802         .deinit_ap = wpa_driver_nl80211_deinit_ap,
9803         .deinit_p2p_cli = wpa_driver_nl80211_deinit_p2p_cli,
9804         .resume = wpa_driver_nl80211_resume,
9805         .send_ft_action = nl80211_send_ft_action,
9806         .signal_monitor = nl80211_signal_monitor,
9807         .signal_poll = nl80211_signal_poll,
9808         .send_frame = nl80211_send_frame,
9809         .shared_freq = wpa_driver_nl80211_shared_freq,
9810         .set_param = nl80211_set_param,
9811         .get_radio_name = nl80211_get_radio_name,
9812         .add_pmkid = nl80211_add_pmkid,
9813         .remove_pmkid = nl80211_remove_pmkid,
9814         .flush_pmkid = nl80211_flush_pmkid,
9815         .set_rekey_info = nl80211_set_rekey_info,
9816         .poll_client = nl80211_poll_client,
9817         .set_p2p_powersave = nl80211_set_p2p_powersave,
9818 #ifdef CONFIG_TDLS
9819         .send_tdls_mgmt = nl80211_send_tdls_mgmt,
9820         .tdls_oper = nl80211_tdls_oper,
9821 #endif /* CONFIG_TDLS */
9822         .update_ft_ies = wpa_driver_nl80211_update_ft_ies,
9823 };