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