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