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