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