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