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