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