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