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