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