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