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