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