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