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