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