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