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