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