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