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